/**
   * Method that s if two elements of an ontology are subsumes.
   *
   * @param requestParameter - A request parameter.
   * @param serviceParameter - A service parameter.
   * @param typoOfParameter - It informs if the parameters are inputs or outputs.
   * @return true/false - return true if they are the same and false if they are different.
   */
  @SuppressWarnings("unchecked")
  private boolean isSubsumesMatching(
      URI requestParameter, URI serviceParameter, char typeOfParameter) {
    Iterator iter = null;
    OntClass ontClass = null;

    loadOntology(
        requestParameter.getScheme() + ":" + requestParameter.getSchemeSpecificPart() + "#");

    if (typeOfParameter == FunctionalMatcher.INPUT) {
      ontClass = model.getOntClass(serviceParameter.toString());
      iter = ontClass.listSubClasses();
      while (iter.hasNext()) {
        if (requestParameter.toString().equals(iter.next().toString())) {
          return true;
        }
      }
    } else if (typeOfParameter == FunctionalMatcher.OUTPUT) {
      ontClass = model.getOntClass(requestParameter.toString());
      iter = ontClass.listSubClasses();
      while (iter.hasNext()) {
        if (serviceParameter.toString().equals(iter.next().toString())) {
          return true;
        }
      }
    }

    return false;
  }
  @Test
  public void testUriBuilderTemplatesNotEncodedSlash() {
    URI uri =
        new UriBuilderImpl()
            .uri("http://localhost:8080/{path}")
            .build(new Object[] {"a/b/c"}, false);
    assertEquals("http://localhost:8080/a/b/c", uri.toString());

    uri =
        new UriBuilderImpl()
            .uri("http://{host}:8080/{path}")
            .build(new Object[] {"l", "a/b/c"}, false);
    assertEquals("http://l:8080/a/b/c", uri.toString());

    Map<String, Object> values = new HashMap<String, Object>();
    values.put("scheme", "s");
    values.put("host", "h");
    values.put("port", new Integer(1));
    values.put("path", "p/p");
    values.put("query", "q");
    values.put("fragment", "f");

    uri =
        new UriBuilderImpl()
            .uri("{scheme}://{host}:{port}/{path}?{query}#{fragment}")
            .buildFromMap(values, false);
    assertEquals("s://h:1/p/p?q#f", uri.toString());
  }
  private void loadURL(URL url) {
    boolean verbose = cmCheck_verbose.isSelected();

    universe = new SVGUniverse();
    universe.setVerbose(verbose);
    SVGDiagram diagram = null;

    if (!CheckBoxMenuItem_anonInputStream.isSelected()) {
      // Load from a disk with a valid URL
      URI uri = universe.loadSVG(url);

      if (verbose) System.err.println(uri.toString());

      diagram = universe.getDiagram(uri);
    } else {
      // Load from a stream with no particular valid URL
      try {
        InputStream is = url.openStream();
        URI uri = universe.loadSVG(is, "defaultName");

        if (verbose) System.err.println(uri.toString());

        diagram = universe.getDiagram(uri);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    svgDisplayPanel.setDiagram(diagram);
    repaint();
  }
 private static String createCssFileInjectionScript(URI uri) {
   return "if(document.createStyleSheet){document.createStyleSheet(\""
       + uri.toString()
       + "\")}else{var link=document.createElement(\"link\"); link.rel=\"stylesheet\"; link.type=\"text/css\"; link.href=\""
       + uri.toString()
       + "\"; document.getElementsByTagName(\"head\")[0].appendChild(link); }";
 }
Exemple #5
0
 private URI pruneFragment(URI uri) throws URISyntaxException {
   if (uri.getFragment() != null) {
     int hashIndex = uri.toString().indexOf("#");
     return new URI(uri.toString().substring(0, hashIndex));
   }
   return uri;
 }
  /*
   * (non-Javadoc)
   *
   * @see net.xeoh.plugins.base.impl.loader.AbstractLoader#loadFrom(java.net.URI)
   */
  @Override
  public void loadFrom(URI url, AddPluginsFromOption[] options) {
    // Special handler to load files from the local classpath
    if (url.toString().contains("*")) {
      if (url.toString().equals("classpath://*")) {
        loadAllClasspathPluginClasses(null, options);
      } else {
        String pattern = url.toString();
        pattern = pattern.replace("**", ".+");
        pattern = pattern.replace("*", "[^\\.]*");
        pattern = pattern.replace("classpath://", "");
        loadAllClasspathPluginClasses(pattern, options);
      }
      return;
    }

    // Special handler to load files from the local classpath, specified by name.
    // Please note that this is a very bad solution and should only be used in special
    // cases,
    // as when invoking from applets that don't have permission to access the
    // classpath (is this so)
    if (url.toString().startsWith("classpath://")) {
      // Obtain the fq-classname to load
      final String toLoad = url.toString().substring("classpath://".length());

      // Try to load all plugins, might cause memory problems due to Issue #20.
      try {
        loadClassFromClasspathByName(toLoad);
      } catch (OutOfMemoryError error) {
        this.logger.severe(
            "Due to a bug, JSPF ran low on memory. Please increase your memory by (e.g., -Xmx1024m) or specify a 'classpath.filter.default.pattern' options. We hope to fix this bux in some future release. We are sorry for the inconvenience this might cause and we can understand if you hate us now :-(");
      }
      return;
    }
  }
  /**
   * Verify the RP consistency group and its volumes have been properly migrated.
   *
   * @throws Exception
   */
  private void verifyRpConsistencyGroupMigration() throws Exception {
    log.info("Verifying RP BlockConsistencyGroup and associated volume migration.");

    BlockConsistencyGroup rpCg =
        _dbClient.queryObject(BlockConsistencyGroup.class, rpConsistencyGroupURI);

    Assert.assertNotNull(
        "The RP+VPlex BlockConsistencyGroup.systemConsistencyGroups field should be populated.",
        rpCg.getSystemConsistencyGroups());
    Assert.assertTrue(
        "The RP+VPlex BlockConsistencyGroup.systemConsistencyGroups field should contain a mapping for "
            + protectionSystemURI.toString()
            + "-> ViPR-"
            + rpCg.getLabel(),
        rpCg.getSystemConsistencyGroups()
            .get(protectionSystemURI.toString())
            .contains("ViPR-" + rpCg.getLabel()));

    Iterator<Volume> rpVolumeItr = _dbClient.queryIterativeObjects(Volume.class, rpVolumeURIs);

    // Verify the RP consistency group was properly migrated
    verifyConsistencyGroupMigration(rpCg, Types.RP.name());

    // Verify the volume migration took place correctly
    List<BlockObject> blockObjects = new ArrayList<BlockObject>();
    while (rpVolumeItr.hasNext()) {
      blockObjects.add(rpVolumeItr.next());
    }

    verifyBlockObjects(blockObjects);
  }
Exemple #8
0
  public static int loadURIResource(URI uri, CPU cpu, int addr) {
    int i;

    System.out.println("loadURL: " + uri.toString());

    try {
      DataInputStream s = new DataInputStream(new BufferedInputStream(uri.toURL().openStream()));

      i = 0;
      try {
        while (true) {
          cpu.write8_a32(addr + i, s.readByte());
          i++;
        }
      } catch (EOFException e) {
        // end
      }
    } catch (IOException e) {
      e.printStackTrace(System.err);
      throw new IllegalArgumentException(e);
    }

    System.out.printf("loadURL: '%s' done, %dbytes.\n", uri.toString(), i);

    return i;
  }
Exemple #9
0
  /**
   * Appends the XML representation of the given <code>OutputFormatType</code> (as FormatType[]) to
   * the passed <code>Element</code>.
   *
   * @param root
   * @param formats
   */
  public static void appendOutputFormats(Element root, FormatType[] formats) {
    LOG.entering();

    Element outputFormatsNode = XMLTools.appendElement(root, WFS, "wfs:OutputFormats");
    for (int i = 0; i < formats.length; i++) {
      Element formatNode =
          XMLTools.appendElement(outputFormatsNode, WFS, "wfs:Format", formats[i].getValue());
      if (formats[i].getInFilter() != null) {
        formatNode.setAttributeNS(
            DEEGREEWFS.toString(), "deegree:inFilter", formats[i].getInFilter().toString());
      }
      if (formats[i].getOutFilter() != null) {
        formatNode.setAttributeNS(
            DEEGREEWFS.toString(), "deegree:outFilter", formats[i].getOutFilter().toString());
      }
      if (formats[i].getSchemaLocation() != null) {
        formatNode.setAttributeNS(
            DEEGREEWFS.toString(),
            "deegree:schemaLocation",
            formats[i].getSchemaLocation().toString());
      }
    }

    LOG.exiting();
  }
  private ICredentials getAuthorizationInfo(URI link, String realm) throws CredentialsException {
    ISecurePreferences securePreferences = getSecurePreferences();

    /* Check if Bundle is Stopped */
    if (securePreferences == null) return null;

    /* Return from Equinox Security Storage */
    if (securePreferences.nodeExists(SECURE_FEED_NODE)) { // Global Feed Node
      ISecurePreferences allFeedsPreferences = securePreferences.node(SECURE_FEED_NODE);
      if (allFeedsPreferences.nodeExists(
          EncodingUtils.encodeSlashes(link.toString()))) { // Feed Node
        ISecurePreferences feedPreferences =
            allFeedsPreferences.node(EncodingUtils.encodeSlashes(link.toString()));
        if (feedPreferences.nodeExists(
            EncodingUtils.encodeSlashes(realm != null ? realm : REALM))) { // Realm Node
          ISecurePreferences realmPreferences =
              feedPreferences.node(EncodingUtils.encodeSlashes(realm != null ? realm : REALM));

          try {
            String username = realmPreferences.get(USERNAME, null);
            String password = realmPreferences.get(PASSWORD, null);
            String domain = realmPreferences.get(DOMAIN, null);

            if (username != null && password != null)
              return new Credentials(username, password, domain);
          } catch (StorageException e) {
            throw new CredentialsException(
                Activator.getDefault().createErrorStatus(e.getMessage(), e));
          }
        }
      }
    }

    return null;
  }
  @Override
  protected int checkResponse(URI uri, ClientResponse response) {
    ClientResponse.Status status = response.getClientResponseStatus();
    int errorCode = status.getStatusCode();
    if (errorCode >= 300) {
      JSONObject obj = null;
      int code = 0;
      try {
        obj = response.getEntity(JSONObject.class);
        code = obj.getInt(ScaleIOConstants.ERROR_CODE);
      } catch (Exception e) {
        log.error("Parsing the failure response object failed", e);
      }

      if (code == 404 || code == 410) {
        throw ScaleIOException.exceptions.resourceNotFound(uri.toString());
      } else if (code == 401) {
        throw ScaleIOException.exceptions.authenticationFailure(uri.toString());
      } else {
        throw ScaleIOException.exceptions.internalError(uri.toString(), obj.toString());
      }
    } else {
      return errorCode;
    }
  }
 /**
  * (non-Javadoc)
  *
  * @see
  *     org.objectweb.proactive.extensions.webservices.WebServicesFactory#getWebServices(java.lang.String)
  */
 public final WebServices getWebServices(String url) throws WebServicesException {
   URI uriKey = null;
   try {
     URI uri = new URI(url);
     uriKey =
         URIBuilder.buildURI(uri.getHost(), null, uri.toURL().getProtocol(), uri.getPort(), true);
   } catch (Exception e) {
     throw new WebServicesException("An exception occured while reading the web service url", e);
   }
   WebServices ws = activatedWebServices.get(uriKey);
   if (ws != null) {
     logger.debug("Getting the WebServices instance from the hashmap");
     logger.debug(
         "the new WebServices instance has been put into the HashMap using the uri key: "
             + uriKey.toString());
     return ws;
   } else {
     logger.debug("Creating a new WebServices instance");
     ws = newWebServices(url);
     activatedWebServices.put(uriKey, ws);
     logger.debug(
         "The new WebServices instance has been put into the HashMap using the uri key: "
             + uriKey.toString());
     return ws;
   }
 }
  private String generateRedirectLocation(Context context, Request request, String path) {
    // Rules
    // 1. Given absolute URL use it
    // 2. Given Starting Slash prepend public facing domain:port if provided if not use base URL of
    // request
    // 3. Given relative URL prepend public facing domain:port plus parent path of request URL
    // otherwise full parent path

    PublicAddress publicAddress = context.get(PublicAddress.class);
    String generatedPath;
    URI host = publicAddress.getAddress(context);

    if (ABSOLUTE_PATTERN.matcher(path).matches()) {
      // Rule 1 - Path is absolute
      generatedPath = path;
    } else {
      if (path.charAt(0) == '/') {
        // Rule 2 - Starting Slash
        generatedPath = host.toString() + path;
      } else {
        // Rule 3
        generatedPath = host.toString() + getParentPath(request.getUri()) + path;
      }
    }

    return generatedPath;
  }
  /**
   * Method that s if two elements of an ontology are siblings.
   *
   * @param requestParameter - A request parameter.
   * @param serviceParameter - A service parameter.
   * @param typoOfParameter - It informs if the parameters are inputs or outputs.
   * @return true/false - return true if they are the same and false if they are different.
   */
  @SuppressWarnings("unchecked")
  private boolean isSiblingMatching(
      URI requestParameter, URI serviceParameter, char typeOfParameter) {

    boolean gotSuperClass = false;
    OntClass ontClass = null;
    Iterator iter = null;

    loadOntology(
        requestParameter.getScheme() + ":" + requestParameter.getSchemeSpecificPart() + "#");

    ontClass = model.getOntClass(serviceParameter.toString());
    iter = ontClass.listSuperClasses(true);
    if (iter.hasNext()) {
      ontClass = (OntClass) iter.next();
      gotSuperClass = true;
    }
    if (gotSuperClass) {
      iter = ontClass.listSubClasses(true);
    }
    while (iter.hasNext()) {
      String next = iter.next().toString();
      if (requestParameter.toString().equals(next)) {
        return true;
      }
    }
    return false;
  }
 @Override
 public void downloadFinished(URI uri) {
   if (!TiResponseCache.peek(uri)) {
     // The requested image did not make it into our TiResponseCache,
     // possibly because it had a header forbidding that. Now get it
     // via the "old way" (not relying on cache).
     synchronized (imageTokenGenerator) {
       token = imageTokenGenerator.incrementAndGet();
       if (uri.toString().equals(currentUrl)) {
         makeImageSource(uri.toString())
             .getBitmapAsync(new BgImageLoader(requestedWidth, requestedHeight, token));
       }
     }
   } else {
     firedLoad = false;
     if (uri.toString().equals(currentUrl)) {
       ImageArgs imageArgs =
           new ImageArgs(
               makeImageSource(uri.toString()),
               getParentView(),
               requestedWidth,
               requestedHeight,
               true,
               false);
       BackgroundImageTask task = new BackgroundImageTask();
       try {
         task.execute(imageArgs);
       } catch (RejectedExecutionException e) {
         Log.e(TAG, "Cannot load the image. Loading too many images at the same time.");
       }
     }
   }
 }
Exemple #16
0
  /**
   * Builds an URI from an URI and a suffix.
   *
   * <p>This suffix can be an absolute URL, or a relative path with respect to the first URI. In
   * this case, the suffix is resolved with respect to the URI.
   *
   * <p>If the suffix is already an URL, its is returned.<br>
   * If the suffix is a relative file path and cannot be resolved, an exception is thrown.
   *
   * <p>The returned URI is normalized.
   *
   * @param referenceUri the reference URI (can be null)
   * @param uriSuffix the URI suffix (not null)
   * @return the new URI
   * @throws URISyntaxException if the resolution failed
   */
  public static URI buildNewURI(URI referenceUri, String uriSuffix) throws URISyntaxException {

    if (uriSuffix == null) throw new NullPointerException("The URI suffix cannot be null.");

    uriSuffix = uriSuffix.replaceAll("\\\\", "/");
    URI importUri = null;
    try {
      // Absolute URL ?
      importUri = urlToUri(new URL(uriSuffix));

    } catch (Exception e) {
      try {
        // Relative URL ?
        if (!referenceUri.toString().endsWith("/") && !uriSuffix.startsWith("/"))
          referenceUri = new URI(referenceUri.toString() + "/");

        importUri = referenceUri.resolve(new URI(null, uriSuffix, null));

      } catch (Exception e2) {
        String msg =
            "An URI could not be built from the URI "
                + referenceUri.toString()
                + " and the suffix "
                + uriSuffix
                + ".";
        throw new URISyntaxException(msg, e2.getMessage());
      }
    }

    return importUri.normalize();
  }
  @SuppressWarnings({"unchecked"})
  @Override
  public Resource convert(Object source) {
    if (null == repositoryMetadata || null == source) {
      return new Resource<Object>(source);
    }

    Serializable id = (Serializable) repositoryMetadata.entityMetadata().idAttribute().get(source);
    URI selfUri = buildUri(config.getBaseUri(), repositoryMetadata.name(), id.toString());

    Set<Link> links = new HashSet<Link>();
    for (Object attrName : entityMetadata.linkedAttributes().keySet()) {
      URI uri = buildUri(selfUri, attrName.toString());
      String rel =
          repositoryMetadata.rel() + "." + source.getClass().getSimpleName() + "." + attrName;
      links.add(new Link(uri.toString(), rel));
    }
    links.add(new Link(selfUri.toString(), "self"));

    Map<String, Object> entityDto = new HashMap<String, Object>();
    for (Map.Entry<String, AttributeMetadata> attrMeta :
        ((Map<String, AttributeMetadata>) entityMetadata.embeddedAttributes()).entrySet()) {
      String name = attrMeta.getKey();
      Object val;
      if (null != (val = attrMeta.getValue().get(source))) {
        entityDto.put(name, val);
      }
    }

    return new EntityResource(entityDto, links);
  }
  /**
   * Call recurly API.
   *
   * @param <T> the generic type
   * @param <E> the element type
   * @param path the path
   * @param payload the payload
   * @param responseClass the response class
   * @param method the method
   * @param headers the headers
   * @return the t
   * @throws RecurlyException the recurly exception
   */
  protected <T, E> T call(
      String path, E payload, Class<T> responseClass, HttpMethod method, HttpHeaders headers)
      throws RecurlyException {

    URI uri = null;
    ResponseEntity<T> responseEntity = null;
    T reponse = null;
    HttpEntity<?> entity = null;
    try {
      if (headers == null) {
        entity = new HttpEntity<>(payload, recurly.getRecurlyHeaders());
      } else {
        entity = new HttpEntity<>(payload, headers);
      }
      uri = new URI(URIUtil.encodeQuery(recurly.getRecurlyServerURL() + path, "UTF-8"));
      getLogger().debug("Calling Recurly URL {}, method: {}", uri.toString(), method.toString());
      responseEntity = restTemplate.exchange(uri, method, entity, responseClass);
      if (responseEntity != null) reponse = responseEntity.getBody();

    } catch (URIException | UnsupportedEncodingException | URISyntaxException e) {
      throw new RecurlyException("Not able to reach recurly. Please check the URL.", e);
    } catch (RestClientException e) {
      String err = ((HttpStatusCodeException) e).getResponseBodyAsString();
      int code = ((HttpStatusCodeException) e).getStatusCode().value();
      publishError(uri.toString(), err, code);
      RecurlyException ex = handleError(err, code, e);
      throw ex;
    }
    return reponse;
  }
  /**
   * Prepare the RecoverPoint only volumes and associated consistency group data.
   *
   * @throws Exception
   */
  private void prepareRPConsistencyGroupDataWithStaleVolumes() throws Exception {
    String cg2Name = "rpCg2";
    // Create the RecoverPoint BlockConsistencyGroup that will be shared by all the
    // RP volumes.
    BlockConsistencyGroup rpCg = createBlockConsistencyGroup(cg2Name, null, Types.RP.name(), true);
    // Save the CG references for migration verification.
    rpConsistencyGroupURI2 = rpCg.getId();

    // Create the ProtectionSet that the RP volumes will belong to.
    ProtectionSet cg2ps = createProtectionSet("rpCg2ProtectionSet", projectURI);

    // Create all the RP volumes
    List<Volume> rpCg2Volumes = createRpVolumes("rpCg2VolumeA", 2, cg2ps, false);
    rpCg2Volumes.addAll(createRpVolumes("rpCg2VolumeB", 2, cg2ps, false));

    // Add the RP volumes to the RP consistency group
    addVolumesToBlockConsistencyGroup(rpCg.getId(), rpCg2Volumes);
    // Add the RP volumes to the protection set
    addVolumesToProtectionSet(cg2ps.getId(), rpCg2Volumes);

    // Add stale volume references
    URI staleVolumeURI1 = URIUtil.createId(Volume.class);
    URI staleVolumeURI2 = URIUtil.createId(Volume.class);

    ProtectionSet ps = _dbClient.queryObject(ProtectionSet.class, cg2ps.getId());
    StringSet vols = ps.getVolumes();
    vols.add(staleVolumeURI1.toString());
    vols.add(staleVolumeURI2.toString());

    staleProtectionSetURI2 = cg2ps.getId();
    staleProtectionSetVolumeURIs.add(staleVolumeURI1.toString());
    staleProtectionSetVolumeURIs.add(staleVolumeURI2.toString());

    _dbClient.persistObject(ps);
  }
 public final URI toUri() {
   URI zdirURI = this.getArchiveURI();
   try {
     // Optimistic try and see
     return new URI("jar:" + zdirURI.toString() + "!/" + resName); // NOI18N
   } catch (URISyntaxException e) {
     // Need to encode the resName part (slower)
     final StringBuilder sb = new StringBuilder();
     final String[] elements = resName.split("/"); // NOI18N
     try {
       for (int i = 0; i < elements.length; i++) {
         String element = elements[i];
         element = URLEncoder.encode(element, "UTF-8"); // NOI18N
         element = element.replace("+", "%20"); // NOI18N
         sb.append(element);
         if (i < elements.length - 1) {
           sb.append('/'); // NOI18N
         }
       }
       return new URI("jar:" + zdirURI.toString() + "!/" + sb.toString()); // NOI18N
     } catch (final UnsupportedEncodingException e2) {
       final IllegalStateException ne = new IllegalStateException();
       ne.initCause(e2);
       throw ne;
     } catch (final URISyntaxException e2) {
       final IllegalStateException ne = new IllegalStateException();
       ne.initCause(e2);
       throw ne;
     }
   }
 }
Exemple #21
0
  /*
   * (non-Javadoc)
   * @see net.java.treaty.ContractVocabulary#getDomain(java.net.URI)
   */
  public URI getDomain(URI relationshipOrProperty) throws TreatyException {

    OntModel model;
    model = getOntology();

    ObjectProperty property;
    property = model.getObjectProperty(relationshipOrProperty.toString());

    if (property != null) {

      try {
        return new URI(property.getDomain().getURI());
      } catch (URISyntaxException e) {
        throw new TreatyException(e);
      }
      // and catch.
    }
    // no else.

    DatatypeProperty dataProperty = model.getDatatypeProperty(relationshipOrProperty.toString());

    if (dataProperty != null) {

      try {
        return new URI(dataProperty.getDomain().getURI());
      } catch (URISyntaxException e) {
        throw new TreatyException(e);
      }
      // end catch.
    }
    // no else.

    return null;
  }
  /**
   * Process the buffer transition to check if the current buffer is visiting a file and if that
   * file is different from the file visited by the buffer during the last wakeup. Its element
   * consists of the the (absolute) file name (or last-time-visited file name) from which an user is
   * visiting, the (absolute) file name (or current-visiting file name) to which the user is
   * visiting, and the modification status of the last-time-visited file.
   */
  public void processBuffTrans() {
    // check if BufferTran property is enable
    if (this.activeTextEditor == null || (this.previousTextEditor == null)) {
      return;
    }
    URI toFile = this.getFileResource(this.activeTextEditor);
    URI fromFile = this.getFileResource(this.previousTextEditor);
    if (fromFile != null && toFile != null && !toFile.equals(fromFile)) {
      String buffTrans = fromFile.toString() + "->" + toFile.toString();
      // :RESOVED: 5/21/04 ISSUE:HACK109
      if (!latestBuffTrans.equals(buffTrans)) {
        HashMap<String, String> buffTranKeyValuePairs = new HashMap<String, String>();

        buffTranKeyValuePairs.put(EclipseSensorConstants.SUBTYPE, "BufferTransition");
        buffTranKeyValuePairs.put("From-Buff-Name", fromFile.toString());
        buffTranKeyValuePairs.put("To-Buff-Name", toFile.toString());
        buffTranKeyValuePairs.put("Modified", String.valueOf(this.isModifiedFromFile));

        String message =
            "BuffTrans : "
                + this.extractFileName(fromFile)
                + " --> "
                + this.extractFileName(toFile);

        this.addDevEvent(
            EclipseSensorConstants.DEVEVENT_EDIT, toFile, buffTranKeyValuePairs, message);
        latestBuffTrans = buffTrans;
      }
    }
  }
 /**
  * Sets the "uri" element on the underlying model.
  *
  * @param uri The Camel Component URI
  * @return {@link CamelBindingModel} to support method chaining.
  */
 public V1CamelBindingModel setConfigURI(URI uri) {
   if (_configURI == null) {
     setModelAttribute(CONFIG_URI, uri.toString());
     _configURI = ConfigURIFactory.newConfigURI(uri.toString(), getSocketAddr());
   }
   return this;
 }
 /**
  * Provides manipulation of browser part brought-to-top status due to implement <code>
  * IPartListener</code>. This method must not be called by client because it is called by
  * platform. Whenever part is closing, check whether or not part is the instance of <code>
  * IEditorPart</code>, if so, set process activity as <code>ActivityType.CLOSE_FILE</code> with
  * its absolute path.
  *
  * @param part An IWorkbenchPart instance to be triggered when a part is closed.
  */
 public void partClosed(IWorkbenchPart part) {
   if (part instanceof ITextEditor) {
     URI fileResource = EclipseSensor.this.getFileResource((ITextEditor) part);
     Map<String, String> keyValueMap = new HashMap<String, String>();
     keyValueMap.put(EclipseSensorConstants.SUBTYPE, "Close");
     if (fileResource != null
         && fileResource.toString().endsWith(EclipseSensorConstants.JAVA_EXT)) {
       keyValueMap.put("Language", "java");
     }
     if (fileResource != null) {
       keyValueMap.put(EclipseSensorConstants.UNIT_TYPE, EclipseSensorConstants.FILE);
       keyValueMap.put(
           EclipseSensorConstants.UNIT_NAME, EclipseSensor.this.extractFileName(fileResource));
       EclipseSensor.this.addDevEvent(
           EclipseSensorConstants.DEVEVENT_EDIT,
           fileResource,
           keyValueMap,
           fileResource.toString());
     }
     IEditorPart activeEditorPart = part.getSite().getPage().getActiveEditor();
     if (activeEditorPart == null) {
       EclipseSensor.this.activeTextEditor = null;
     }
   }
 }
Exemple #25
0
  /** 创建/更新/删除任务. */
  @Test
  @Category(Smoke.class)
  public void createUpdateAndDeleteTask() {

    // create
    Task task = TaskData.randomTask();

    URI createdTaskUri = restTemplate.postForLocation(resourceUrl, task);
    System.out.println(createdTaskUri.toString());
    Task createdTask = restTemplate.getForObject(createdTaskUri, Task.class);
    assertThat(createdTask.getTitle()).isEqualTo(task.getTitle());

    // update
    String id = StringUtils.substringAfterLast(createdTaskUri.toString(), "/");
    task.setId(new Long(id));
    task.setTitle(TaskData.randomTitle());

    restTemplate.put(createdTaskUri, task);

    Task updatedTask = restTemplate.getForObject(createdTaskUri, Task.class);
    assertThat(updatedTask.getTitle()).isEqualTo(task.getTitle());

    // delete
    restTemplate.delete(createdTaskUri);

    try {
      restTemplate.getForObject(createdTaskUri, Task.class);
      fail("Get should fail while feth a deleted task");
    } catch (HttpStatusCodeException e) {
      assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
    }
  }
  /*
   * Analyze the schema at the given URI, the schema is parsed and stored in
   * XMLObjectInfos.
   */
  private void analyzeXSD(URI uri) {

    uri = uri.normalize();

    // already seen this xsd, skip it
    if (xmlObjectInfos.containsKey(uri.toString())) return;

    XSDSchema xsdSchema = XSDSchemaImpl.getSchemaForSchema(uri.toString());

    String encoding = null;
    // if schema is not cached, parse it
    if (xsdSchema == null) {
      XSDParser p = new XSDParser(null);
      InputStream is = NetUtils.getURLInputStream(uri.toString());

      if (is != null) {
        p.parse(is);
        xsdSchema = p.getSchema();
        encoding = p.getEncoding();
      }
    } else encoding = xsdSchema.getDocument().getXmlEncoding();

    if (xsdSchema != null) {

      if (encoding == null) encoding = "UTF-8";

      XMLObjectInfo info = new XMLObjectInfo(new Path(uri.getPath()), xsdSchema, encoding);
      xmlObjectInfos.put(uri.toString(), info);
      updatePathPrefix(info);

      // analyze its imports and includes
      analyzeXSD(uri, xsdSchema);
    }
  }
  private void testStartStop2(final String filename) throws Exception {
    FileDeploymentManager fdm = new FileDeploymentManager(Long.MAX_VALUE);

    FileDeploymentManagerTest.log.debug("Filename is " + filename);

    File file = new File("target/test-classes/");

    file.mkdirs();

    file = new File("target/test-classes/" + filename);

    FileDeploymentManagerTest.log.debug(file.getAbsoluteFile());

    file.createNewFile();

    FakeDeployer deployer = new FakeDeployer(filename);

    fdm.start();

    try {
      fdm.registerDeployer(deployer);
      URI expected = file.toURI();
      URI deployedUrl = deployer.deployedUri;
      Assert.assertTrue(expected.toString().equalsIgnoreCase(deployedUrl.toString()));
      deployer.deployedUri = null;
      fdm.start();
      Assert.assertNull(deployer.deployedUri);
      fdm.stop();
    } finally {
      file.delete();
      fdm.stop();
    }
  }
  public static void main(String[] args) {

    URI uriAmazon =
        UriBuilder.fromUri("http://free.apisigning.com/onca/xml")
            .queryParam("Service", "AWSECommerceService")
            .queryParam("AWSAccessKeyId", "AKIAIYNLC7WME6YSY66A")
            .build();
    URI uriSearch = UriBuilder.fromUri(uriAmazon).queryParam("Operation", "ItemSearch").build();
    URI uriSearchBooks = UriBuilder.fromUri(uriSearch).queryParam("SearchIndex", "Books").build();
    Client client = ClientBuilder.newClient();

    URI uriSearchBooksByKeyword =
        UriBuilder.fromUri(uriSearchBooks).queryParam("Keywords", "Java EE 7").build();
    URI uriSearchBooksWithImages =
        UriBuilder.fromUri(uriSearchBooks)
            .queryParam("Condition", "All")
            .queryParam("ResponseGroup", "Images")
            .queryParam("Title", "Java EE 7")
            .build();

    System.out.println(uriSearchBooksByKeyword.toString());
    System.out.println(uriSearchBooksWithImages.toString());

    Response response = client.target(uriSearchBooksByKeyword).request().get();
    System.out.println(response.getStatus());
    response = client.target(uriSearchBooksWithImages).request().get();
    System.out.println(response.getStatus());
  }
  @Override
  public DDF loadSpecialFormat(DataFormat format, URI fileURI, Boolean flatten)
      throws DDFException {
    SparkDDFManager sparkDDFManager = (SparkDDFManager) mDDFManager;
    HiveContext sqlContext = sparkDDFManager.getHiveContext();
    DataFrame jdf = null;
    switch (format) {
      case JSON:
        jdf = sqlContext.jsonFile(fileURI.toString());
        break;
      case PQT:
        jdf = sqlContext.parquetFile(fileURI.toString());
        break;
      default:
        throw new DDFException(String.format("Unsupported data format: %s", format.toString()));
    }

    DataFrame df = SparkUtils.getDataFrameWithValidColnames(jdf);
    DDF ddf =
        sparkDDFManager.newDDF(
            sparkDDFManager,
            df,
            new Class<?>[] {DataFrame.class},
            null,
            SparkUtils.schemaFromDataFrame(df));

    if (flatten == true) return ddf.getFlattenedDDF();
    else return ddf;
  }
Exemple #30
0
  private DetectedSource getSource(URI uri) {
    DetectedSource source = null;
    synchronized (detectedSources) {
      source = detectedSources.get(uri.toString());
      if (source == null) {
        if (detectedSources.size() > MAX_SOURCE_BUFFER_SIZE) {
          int i = MAX_SOURCE_BUFFER_SIZE / 2;
          List<String> remove = new ArrayList<String>();
          for (String key : detectedSources.keySet()) {
            remove.add(key);
            if (i-- < 0) {
              break;
            }
          }
          for (String key : remove) {
            detectedSources.remove(key);
          }
        }

        source = new DetectedSource(uri);
        detectedSources.put(uri.toString(), source);
      }
    }
    return source;
  }