/**
   * Makes REST call to Crowd to get user's groups
   *
   * @param username
   * @return Set<JAASRole>
   * @throws RemoteException
   * @throws UnsupportedEncodingException
   */
  private Set<JAASRole> getUserGroups(String username)
      throws RemoteException, UnsupportedEncodingException {
    if (LOG.isDebugEnabled()) LOG.debug("get groups for '" + String.valueOf(username) + "'");

    WebResource r =
        client.resource(
            crowdServer.resolve(
                "user/group/nested?username="******"UTF-8")));

    GroupsResponse response = r.get(GroupsResponse.class);
    if (LOG.isDebugEnabled()) LOG.debug(response.toString());

    Set<JAASRole> results = new HashSet<JAASRole>();
    for (GroupResponse group : response.group) {
      // check if group is active
      r =
          client.resource(
              crowdServer.resolve("group?groupname=" + URLEncoder.encode(group.name, "UTF-8")));
      GroupResponse groupResponse = r.get(GroupResponse.class);

      if (groupResponse.active) {
        results.add(new JAASRole(group.name));
        if (LOG.isDebugEnabled()) LOG.debug("Adding Group: " + group.name);
      }
    }

    // Add the specified supplemental roles to the user
    results.addAll(getSupplementalRoles());

    return results;
  }
 private ClientResponse put(final String uri, final String body) {
   ClientResponse clientResp = _client.put_json(_baseUrl.resolve(uri), authToken, body);
   if (clientResp.getStatus() == 401) {
     getAuthToken();
     clientResp = _client.put_json(_baseUrl.resolve(uri), authToken, body);
   }
   return clientResp;
 }
 private ClientResponse get(final String uri) {
   ClientResponse clientResp = _client.get_json(_baseUrl.resolve(uri), authToken);
   if (clientResp != null && clientResp.getStatus() == 401) {
     getAuthToken();
     clientResp = _client.get_json(_baseUrl.resolve(uri), authToken);
   }
   return clientResp;
 }
 @Test
 public void testZipInputStreamToResearchObject() {
   URI id = URI.create("http://www.example.com/ROs/simple/");
   ResearchObjectSerializable ro =
       IO.toResearchObject(id, getClass().getClassLoader().getResourceAsStream("simple.zip"));
   // check the content of the returned ro
   for (ResearchObjectComponentSerializable component : ro.getSerializables().values()) {
     System.out.println(component.getUri());
   }
   Assert.assertNotNull(ro.getSerializables().get(id.resolve("1.txt")));
   Assert.assertNotNull(ro.getSerializables().get(id.resolve("2.txt")));
   Assert.assertNotNull(ro.getSerializables().get(id.resolve(".ro/manifest.rdf")));
   Assert.assertNotNull(ro.getSerializables().get(id.resolve(".ro/evo_info.ttl")));
 }
 private void sendMail(
     HttpServletRequest request, BlogAuthor blogAuthor, Entity blog, Settings settings)
     throws IOException {
   if (settings.dontSendEmail()) {
     return;
   }
   try {
     String digest = DS.getBlogDigest(blog);
     MailService mailService = MailServiceFactory.getMailService();
     Message reply = new Message();
     reply.setSender(blogAuthor.toString());
     Email sender = (Email) blog.getProperty(SenderProperty);
     reply.setTo(sender.getEmail());
     String subject = (String) blog.getProperty(SubjectProperty);
     reply.setSubject("Blog: " + subject + " received");
     StringBuilder sb = new StringBuilder();
     URI reqUri = new URI(request.getScheme(), NamespaceManager.get(), "", "");
     if (!settings.isPublishImmediately()) {
       sb.append("<div>");
       sb.append(
           "<p>Blog is not yet published because it was sent from untrusted email address "
               + sender.getEmail()
               + ". </p>");
       URI publishUri =
           reqUri.resolve(
               "/blog?action=publish&blog="
                   + KeyFactory.keyToString(blog.getKey())
                   + "&auth="
                   + digest);
       sb.append("<a href=\"" + publishUri.toASCIIString() + "\">Publish Blog</a>");
       sb.append("</div>");
     }
     sb.append("<div>");
     sb.append("<p>If blog is not ok, you can delete and then resend it.</p>");
     URI deleteUri =
         reqUri.resolve(
             "/blog?action=remove&blog="
                 + KeyFactory.keyToString(blog.getKey())
                 + "&auth="
                 + digest);
     sb.append("<a href=\"" + deleteUri.toASCIIString() + "\">Delete Blog</a>");
     sb.append("</div>");
     reply.setHtmlBody(sb.toString());
     mailService.send(reply);
   } catch (URISyntaxException ex) {
     throw new IOException(ex);
   }
 }
Beispiel #6
0
 private Set<URI> parse(Change addition, URI base) {
   Set<URI> uris = new LinkedHashSet<URI>();
   for (Resource r : addition.getRelatedResource()) {
     uris.add(base.resolve(r.getResource()));
   }
   return uris;
 }
Beispiel #7
0
  public static URI build(URI prefix, URI localName) throws NamingAuthorityConfigurationException {
    try {
      verifyPrefix(prefix);
    } catch (Exception e) {
      throw new NamingAuthorityConfigurationException(e.getMessage());
    }

    if (localName == null) {
      throw new IllegalArgumentException("Localname must not be null.");
    } else if (localName.isAbsolute()) {
      throw new IllegalArgumentException("Localname must be a relative URI.");
    }

    // request.getPathInfo() strips required "/" from identifier URL, replace it
    String scheme = localName.getScheme();
    String path = localName.getPath();
    // trim off any leading / so the URI resolving doesn't treat it as an
    // absolute path
    if (path.startsWith("/")) {
      path = path.substring(1);
    }
    String url = path;
    if (scheme != null) {
      url = scheme + ":/" + path;
    }
    localName = URI.create(url);

    return prefix.resolve(localName);
  }
Beispiel #8
0
 @Override
 void parse(XdmNode node) {
   String hr = XProcUtil.getAttrString(node, "href");
   URI base = node.getBaseURI();
   if (base != null) href = base.resolve(hr).toString();
   else href = hr;
 }
  public static String join(String source, String fragment) {
    try {
      boolean isRelative = false;
      if (source.startsWith("/") || source.startsWith(".")) {
        isRelative = true;
      }
      URI uri = new URI(source);

      if (!source.endsWith("/") && (fragment.startsWith("./") && "".equals(uri.getPath()))) {
        uri = new URI(source + "/");
      } else if ("".equals(uri.getPath()) && !fragment.startsWith("/")) {
        uri = new URI(source + "/");
      }
      URI f = new URI(fragment);

      URI resolved = uri.resolve(f);

      URI normalized = resolved.normalize();
      if (Character.isAlphabetic(normalized.toString().charAt(0)) && isRelative) {
        return "./" + normalized.toString();
      }
      return normalized.toString();
    } catch (Exception e) {
      return source;
    }
  }
Beispiel #10
0
      private String lastURL() throws URISyntaxException {
        try {
          Address adr = getAddress();
          String scheme = decode(getScheme()).toString();
          int port = adr.getPort();
          if ((scheme.equals("http") && port == 80) || (scheme.equals("https") && port == 443)) {
            port = -1;
          }

          URI uri = new URI(scheme, null, adr.getHost(), port, null, null, null);

          uri = uri.resolve(getRequestURI());
          return uri.toString();
        }
        // URI can also throw IllegalArgumentException wrapping
        // a URISyntaxException. Unwrap it.
        catch (IllegalArgumentException x) {
          Throwable cause = x.getCause();
          if ((cause != null) && (cause instanceof URISyntaxException)) {
            throw (URISyntaxException) cause;
          } else {
            throw x;
          }
        }
      }
  private ServerStatus getSpaces(List<Space> spaces, JSONObject orgJSON) throws Exception {
    URI targetURI = URIUtil.toURI(target.getUrl());
    URI spaceURI = targetURI.resolve(orgJSON.getJSONObject("entity").getString("spaces_url"));

    GetMethod getDomainsMethod = new GetMethod(spaceURI.toString());
    HttpUtil.configureHttpMethod(getDomainsMethod, target);
    getDomainsMethod.setQueryString("inline-relations-depth=1"); // $NON-NLS-1$

    ServerStatus status = HttpUtil.executeMethod(getDomainsMethod);
    if (!status.isOK()) return status;

    /* extract available spaces */
    JSONObject orgs = status.getJsonData();

    if (orgs.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1) {
      return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
    }

    /* look if the domain is available */
    int resources = orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).length();
    for (int k = 0; k < resources; ++k) {
      JSONObject spaceJSON =
          orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).getJSONObject(k);
      spaces.add(new Space().setCFJSON(spaceJSON));
    }

    return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
  }
Beispiel #12
0
 @Override
 public boolean load(BuildCacheKey key, BuildCacheEntryReader reader) throws BuildCacheException {
   final URI uri = root.resolve("./" + key.getHashCode());
   HttpGet httpGet = new HttpGet(uri);
   CloseableHttpResponse response = null;
   try {
     response = httpClient.execute(httpGet);
     StatusLine statusLine = response.getStatusLine();
     if (LOGGER.isDebugEnabled()) {
       LOGGER.debug("Response for GET {}: {}", uri, statusLine);
     }
     int statusCode = statusLine.getStatusCode();
     if (statusCode >= 200 && statusCode < 300) {
       reader.readFrom(response.getEntity().getContent());
       return true;
     } else if (statusCode == 404) {
       return false;
     } else {
       throw new BuildCacheException(
           String.format(
               "HTTP cache returned status %d: %s for key '%s' from %s",
               statusCode, statusLine.getReasonPhrase(), key, getDescription()));
     }
   } catch (IOException e) {
     throw new BuildCacheException(
         String.format("loading key '%s' from %s", key, getDescription()), e);
   } finally {
     HttpClientUtils.closeQuietly(response);
   }
 }
 protected Properties loadPropertyFile(URI projectDirectory, String propertyFile) {
   // Read the properties file.
   Properties props = new Properties();
   InputStream is = null;
   try {
     File pFile = new File(propertyFile);
     if (!pFile.isAbsolute()) {
       is =
           projectDirectory
               .resolve(propertyFile.toString())
               .toURL()
               .openConnection()
               .getInputStream();
     } else {
       is = pFile.toURI().toURL().openConnection().getInputStream();
     }
     props.load(is);
     is.close();
   } catch (MalformedURLException ex) {
     System.err.print("Main: " + ex);
     return null;
   } catch (FileNotFoundException ex) {
     // Ignore file not found.
   } catch (Exception ex) {
     System.err.append("Main: Error loading properties from ").println(propertyFile);
     System.err.println("Main: " + ex);
     try {
       if (is != null) is.close();
     } catch (IOException ex2) {
       // Nothing we can do.
     }
     return null;
   }
   return props;
 }
Beispiel #14
0
  @Override
  public IResource[] getResourcesFromCommand(List<String> cmd, URI buildDirectoryURI) {
    // Start at the back looking for arguments
    List<IResource> resources = new ArrayList<>();
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    for (int i = cmd.size() - 1; i >= 0; --i) {
      String arg = cmd.get(i);
      if (arg.startsWith("-")) { // $NON-NLS-1$
        // ran into an option, we're done.
        break;
      }
      Path srcPath = Paths.get(arg);
      URI uri;
      if (srcPath.isAbsolute()) {
        uri = srcPath.toUri();
      } else {
        try {
          uri = buildDirectoryURI.resolve(arg);
        } catch (IllegalArgumentException e) {
          // Bad URI
          continue;
        }
      }

      for (IFile resource : root.findFilesForLocationURI(uri)) {
        resources.add(resource);
      }
    }

    return resources.toArray(new IResource[resources.size()]);
  }
  /**
   * Gets the destination of a redirection
   *
   * @return absolute URL of new location; null if not available
   */
  static URI getLocation(HttpRequest request, HttpResponse response, HttpContext context) {
    Header locationHdr = response.getFirstHeader("Location");
    if (locationHdr == null) {
      Log.e(TAG, "Received redirection without Location header, ignoring");
      return null;
    }
    try {
      URI location = URIUtils.parseURI(locationHdr.getValue(), false);

      // some servers don't return absolute URLs as required by RFC 2616
      if (!location.isAbsolute()) {
        Log.w(TAG, "Received invalid redirection to relative URL, repairing");
        URI originalURI = URIUtils.parseURI(request.getRequestLine().getUri(), false);
        if (!originalURI.isAbsolute()) {
          final HttpHost target = HttpClientContext.adapt(context).getTargetHost();
          if (target != null)
            originalURI = org.apache.http.client.utils.URIUtilsHC4.rewriteURI(originalURI, target);
          else return null;
        }
        return originalURI.resolve(location);
      }
      return location;
    } catch (URISyntaxException e) {
      Log.e(TAG, "Received redirection from/to invalid URI, ignoring", e);
    }
    return null;
  }
Beispiel #16
0
  @Test
  public void testEchoReturn() throws Exception {
    WSServer wsb = new WSServer(testdir, "app");
    wsb.copyWebInf("empty-web.xml");
    wsb.copyClass(EchoReturnEndpoint.class);

    try {
      wsb.start();
      URI uri = wsb.getServerBaseURI();

      WebAppContext webapp = wsb.createWebAppContext();
      wsb.deployWebapp(webapp);
      wsb.dump();

      WebSocketClient client = new WebSocketClient();
      try {
        client.start();
        JettyEchoSocket clientEcho = new JettyEchoSocket();
        Future<Session> future = client.connect(clientEcho, uri.resolve("echoreturn"));
        // wait for connect
        future.get(1, TimeUnit.SECONDS);
        clientEcho.sendMessage("Hello World");
        Queue<String> msgs = clientEcho.awaitMessages(1);
        Assert.assertEquals("Expected message", "Hello World", msgs.poll());
      } finally {
        client.stop();
      }
    } finally {
      wsb.stop();
    }
  }
Beispiel #17
0
  /**
   * Resolve a child path against a parent path.
   *
   * @param parent the parent path
   * @param child the child path
   */
  public Path(Path parent, Path child) {
    // Add a slash to parent's path so resolution is compatible with URI's
    URI parentUri = parent.uri;
    final String parentPath = parentUri.getPath();
    if (!(parentPath.equals("/") || parentPath.equals(""))) {
      try {
        parentUri =
            new URI(
                parentUri.getScheme(),
                parentUri.getAuthority(),
                parentUri.getPath() + "/",
                null,
                null);
      } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
      }
    }

    if (child.uri.getPath().startsWith(Path.SEPARATOR)) {
      child =
          new Path(
              child.uri.getScheme(), child.uri.getAuthority(), child.uri.getPath().substring(1));
    }

    final URI resolved = parentUri.resolve(child.uri);
    initialize(resolved.getScheme(), resolved.getAuthority(), normalizePath(resolved.getPath()));
  }
Beispiel #18
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();
  }
 /*  43:    */
 /*  44:    */ private ModuleSource loadFromPathArray(
     String moduleId, Scriptable paths, Object validator)
     /*  45:    */ throws IOException
       /*  46:    */ {
   /*  47: 60 */ long llength =
       ScriptRuntime.toUint32(ScriptableObject.getProperty(paths, "length"));
   /*  48:    */
   /*  49:    */
   /*  50: 63 */ int ilength = llength > 2147483647L ? 2147483647 : (int) llength;
   /*  51: 66 */ for (int i = 0; i < ilength; i++)
   /*  52:    */ {
     /*  53: 67 */ String path =
         ensureTrailingSlash((String) ScriptableObject.getTypedProperty(paths, i, String.class));
     /*  54:    */ try
     /*  55:    */ {
       /*  56: 70 */ URI uri = new URI(path);
       /*  57: 71 */ if (!uri.isAbsolute()) {
         /*  58: 72 */ uri = new File(path).toURI().resolve("");
         /*  59:    */ }
       /*  60: 74 */ ModuleSource moduleSource =
           loadFromUri(uri.resolve(moduleId), uri, validator);
       /*  61: 76 */ if (moduleSource != null) {
         /*  62: 77 */ return moduleSource;
         /*  63:    */ }
       /*  64:    */ }
     /*  65:    */ catch (URISyntaxException e)
     /*  66:    */ {
       /*  67: 81 */ throw new MalformedURLException(e.getMessage());
       /*  68:    */ }
     /*  69:    */ }
   /*  70: 84 */ return null;
   /*  71:    */ }
 private Uri resolveUri(URI uri) {
   if (uri.isAbsolute() || absoluteUri == null) {
     return convertToAndroidUriAndFixScheme(uri, uri);
   } else {
     return convertToAndroidUriAndFixScheme(absoluteUri.resolve(uri), absoluteUri);
   }
 }
  /**
   * Resolve COLLADA references relative to the COLLADA document. If the reference is relative then
   * it will resolved relative to the .dae file, not the kml file. If the COLLADA document may be
   * contained in a KMZ archive the resources will be resolved relative to the .dae file within the
   * archive. Normally references in a KMZ are resolved relative to the root of the archive, but
   * Model references are an exception. See
   * https://developers.google.com/kml/documentation/kmzarchives and
   * https://developers.google.com/kml/documentation/kmlreference#model
   *
   * <p>{@inheritDoc}.
   */
  public String resolveFilePath(String path) throws IOException {
    KMLLink link = this.model.getLink();

    // Check the resource map to see if an alias is defined for this resource.
    String alias = this.resourceMap.get(path);
    if (alias != null) path = alias;

    // If the path is relative then resolve it relative to the COLLADA file.
    File f = new File(path);
    if (!f.isAbsolute() && link != null && link.getHref() != null) {
      try {
        URI base = new URI(null, link.getHref(), null);
        URI ref = new URI(null, path, null);

        path = base.resolve(ref).getPath();
      } catch (URISyntaxException ignored) {
        // Ignored
      }
    }

    Object o = this.parent.getRoot().resolveReference(path);
    if (o instanceof URL || o instanceof String) return o.toString();

    return null;
  }
Beispiel #22
0
 private static void resolve(String base, String uri, String expected) {
   URI b = URI.create(base);
   URI resolved = b.resolve(uri);
   //        System.out.println("base=" + base + " uri=" + uri
   //                + " resolved=" + resolved);
   assertEquals(expected, resolved.toString());
 }
  @Override
  public JsonRef resolve(final JsonRef other) {
    if (other.uri.isAbsolute()) return other;

    final URI targetPath = pathURI.resolve(other.uri);
    final URI targetURI = URI.create(jarPrefix + targetPath.toString());
    return new JarJsonRef(targetURI, jarPrefix, targetPath);
  }
 /**
  * Retrieves a <CODE>File</CODE> object corresponding to the specified path. If the given path is
  * an absolute path, then it will be used. If the path is relative, then it will be interpreted as
  * if it were relative to the Identity Server root.
  *
  * @param path The path string to be retrieved as a <CODE>File</CODE>
  * @param rootDir the server root to resolve against
  * @return A <CODE>File</CODE> object that corresponds to the specified path.
  */
 public File getFileForPath(String path, URI rootDir) {
   File f = new File(path);
   if (f.isAbsolute()) {
     return f;
   } else {
     return new File(rootDir.resolve(path)).getAbsoluteFile();
   }
 }
Beispiel #25
0
  private static URI resolveUri(String uriStr, URI baseUri) throws URISyntaxException {
    URI resolved;

    URI resourceUri = new URI(uriStr);
    if (resourceUri.isAbsolute()) resolved = resourceUri;
    else resolved = baseUri.resolve(resourceUri);

    return resolved;
  }
 /**
  * Create a Base Bucket instance
  *
  * @param bucketName Bucket name
  * @param namespace Namespace where Bucket should reside
  * @param repGroup Volume
  * @return Source ID of the Bucket created
  */
 public String createBucket(String bucketName, String namespace, String repGroup) {
   _log.debug("ECSApi:createBucket Create bucket initiated for : {}", bucketName);
   String id = null;
   ClientResponse clientResp = null;
   String body =
       " { \"name\": \""
           + bucketName
           + "\", "
           + "\"vpool\": \""
           + repGroup
           + "\", \"namespace\": \""
           + namespace
           + "\"}  ";
   try {
     clientResp = post(URI_CREATE_BUCKET, body);
   } catch (Exception e) {
     _log.error("Error occured while bucket base creation : {}", bucketName, e);
   } finally {
     if (null == clientResp) {
       throw ECSException.exceptions.storageAccessFailed(
           _baseUrl.resolve(URI_CREATE_BUCKET), 500, "no response from ECS");
     } else if (clientResp.getStatus() != 200) {
       String response = String.format("%1$s", (clientResp == null) ? "" : clientResp);
       throw ECSException.exceptions.storageAccessFailed(
           _baseUrl.resolve(URI_CREATE_BUCKET), clientResp.getStatus(), response);
     } else {
       // extract bucket id
       JSONObject jObj = clientResp.getEntity(JSONObject.class);
       if (jObj.has("id")) {
         try {
           id = jObj.getString("id");
         } catch (JSONException e) {
           throw ECSException.exceptions.storageAccessFailed(
               _baseUrl.resolve(URI_CREATE_BUCKET),
               clientResp.getStatus(),
               "Unable to extract source ID of the bucket");
         }
       }
     }
     closeResponse(clientResp);
   }
   return id;
 }
  public static void openwebsite(String url) {
    try {
      Desktop dt = Desktop.getDesktop();
      URI uri = new URI(url);
      dt.browse(uri.resolve(uri));

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #28
0
  public static void main(String[] args) throws Exception {
    URI testURI = new URI("http://www.cnn.com/");
    // URI testURI = new URI("file:///W:/temp");
    // System.out.println(new File(testURI).exists());

    HttpURLConnection connecition = (HttpURLConnection) testURI.toURL().openConnection();
    System.out.println(connecition.getResponseCode());

    System.out.println(testURI.resolve("TEST").toString());
  }
Beispiel #29
0
 /**
  * Getter for mulchLevels.
  *
  * @return value for mulchLevels
  */
 @XmlElement
 public MulchLevelConverter getMulchLevel() {
   if (expandLevel > 0) {
     if (entity.getMulchLevel() != null) {
       return new MulchLevelConverter(
           entity.getMulchLevel(), uri.resolve("mulchLevel/"), expandLevel - 1, false);
     }
   }
   return null;
 }
Beispiel #30
0
  protected void checkResponse(HttpResponse response) throws HttpException {
    checkResponse(response.getStatusLine());

    // handle Content-Location header (see RFC 4918 5.2 Collection Resources)
    Header contentLocationHdr = response.getFirstHeader("Content-Location");
    if (contentLocationHdr != null) {
      // Content-Location was set, update location correspondingly
      location = location.resolve(contentLocationHdr.getValue());
      Log.d(TAG, "Set Content-Location to " + location);
    }
  }