Example usage for java.net URI toASCIIString

List of usage examples for java.net URI toASCIIString

Introduction

In this page you can find the example usage for java.net URI toASCIIString.

Prototype

public String toASCIIString() 

Source Link

Document

Returns the content of this URI as a US-ASCII string.

Usage

From source file:edu.harvard.hms.dbmi.scidb.SciDB.java

public InputStream readLines(String sessionID) throws NotConnectedException {
    if (!this.connected) {
        throw new NotConnectedException();
    }/*from   ww w .  j av a2 s . co m*/

    try {
        URIBuilder uriBuilder = new URIBuilder(this.url + "/read_lines").addParameter("id", sessionID);

        URI uri = uriBuilder.build();
        System.out.println(uri.toASCIIString());

        HttpGet runQuery = new HttpGet(uri);
        HttpResponse response = client.execute(runQuery);
        return response.getEntity().getContent();
    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:eu.esdihumboldt.hale.common.core.io.project.impl.ArchiveProjectWriter.java

/**
 * Update the resources and copy them into the target directory
 * /*from   w  ww  .j  av  a  2 s.  com*/
 * @param targetDirectory target directory
 * @param includeWebResources whether to include web resources in the copy
 * @param progress the progress indicator
 * @param reporter the reporter to use for the execution report
 * @throws IOException if an I/O operation fails
 */
protected void updateResources(File targetDirectory, boolean includeWebResources, ProgressIndicator progress,
        IOReporter reporter) throws IOException {
    progress.begin("Copy resources", ProgressIndicator.UNKNOWN);
    try {
        List<IOConfiguration> resources = getProject().getResources();
        // every resource needs his own directory
        int count = 1;
        // true if excluded files should be skipped; false is default
        boolean excludeDataFiles = getParameter(EXLUDE_DATA_FILES).as(Boolean.class, false);

        // resource locations mapped to new resource path
        Map<URI, String> handledResources = new HashMap<>();

        Iterator<IOConfiguration> iter = resources.iterator();
        while (iter.hasNext()) {
            IOConfiguration resource = iter.next();

            // check if ActionId is equal to
            // eu.esdihumboldt.hale.common.instance.io.InstanceIO.ACTION_LOAD_SOURCE_DATA
            // import not possible due to cycle errors
            if (excludeDataFiles
                    && resource.getActionId().equals("eu.esdihumboldt.hale.io.instance.read.source")) {
                // delete reference in project file
                iter.remove();
                continue;
            }

            // get resource path
            Map<String, Value> providerConfig = resource.getProviderConfiguration();
            String path = providerConfig.get(ImportProvider.PARAM_SOURCE).toString();

            URI pathUri;
            try {
                pathUri = new URI(path);
            } catch (URISyntaxException e1) {
                reporter.error(new IOMessageImpl("Skipped resource because of invalid URI: " + path, e1));
                continue;
            }
            if (!pathUri.isAbsolute()) {
                if (getPreviousTarget() != null) {
                    pathUri = getPreviousTarget().resolve(pathUri);
                } else {
                    log.warn("Could not resolve relative path " + pathUri.toString());
                }
            }

            // check if path was already handled
            if (handledResources.containsKey(pathUri)) {
                providerConfig.put(ImportProvider.PARAM_SOURCE, Value.of(handledResources.get(pathUri)));
                // skip copying the resource
                continue;
            }

            String scheme = pathUri.getScheme();
            LocatableInputSupplier<? extends InputStream> input = null;
            if (scheme != null) {
                if (scheme.equals("http") || scheme.equals("https")) {
                    // web resource
                    if (includeWebResources) {
                        input = new DefaultInputSupplier(pathUri);
                    } else {
                        // web resource that should not be included this
                        // time

                        // but the resolved URI should be stored
                        // nevertheless
                        // otherwise the URI may be invalid if it was
                        // relative
                        providerConfig.put(ImportProvider.PARAM_SOURCE, Value.of(pathUri.toASCIIString()));

                        continue;
                    }
                } else if (scheme.equals("file") || scheme.equals("platform") || scheme.equals("bundle")
                        || scheme.equals("jar")) {
                    // files need always to be included
                    // platform resources (or other internal resources)
                    // should be included as well
                    input = new DefaultInputSupplier(pathUri);
                } else {
                    // other type of URI, e.g. JDBC
                    // not to be included

                    providerConfig.put(ImportProvider.PARAM_SOURCE, Value.of(pathUri.toASCIIString()));

                    continue;
                }
            } else {
                // now can't open that, can we?
                reporter.error(new IOMessageImpl(
                        "Skipped resource because it cannot be loaded from " + pathUri.toString(), null));
                continue;
            }

            progress.setCurrentTask("Copying resource at " + path);

            // every resource file is copied into an own resource
            // directory in the target directory
            String resourceFolder = "resource" + count;
            File newDirectory = new File(targetDirectory, resourceFolder);
            try {
                newDirectory.mkdir();
            } catch (SecurityException e) {
                throw new IOException("Can not create directory " + newDirectory.toString(), e);
            }

            // Extract the file name from pathUri.getPath().
            // This will produce a non-URL-encoded file name to be used in
            // the File(File parent, String child) constructor below
            String fileName = FilenameUtils.getName(pathUri.getPath().toString());

            if (path.isEmpty()) {
                fileName = "file";
            }

            File newFile = new File(newDirectory, fileName);
            Path target = newFile.toPath();

            // retrieve the resource advisor
            Value ct = providerConfig.get(ImportProvider.PARAM_CONTENT_TYPE);
            IContentType contentType = null;
            if (ct != null) {
                contentType = HalePlatform.getContentTypeManager().getContentType(ct.as(String.class));
            }
            ResourceAdvisor ra = ResourceAdvisorExtension.getInstance().getAdvisor(contentType);

            // copy the resource
            progress.setCurrentTask("Copying resource at " + path);

            // Extract the URL-encoded file name of the copied resource and
            // build the new relative resource path
            String resourceName = FilenameUtils.getName(target.toUri().toString());
            String newPath = resourceFolder + "/" + resourceName;

            boolean skipCopy = getParameter(EXCLUDE_CACHED_RESOURCES).as(Boolean.class, false)
                    && !resource.getCache().isEmpty();
            if (!skipCopy) {
                ra.copyResource(input, target, contentType, includeWebResources, reporter);

                // store new path for resource
                handledResources.put(pathUri, newPath);
            }

            // update the provider configuration
            providerConfig.put(ImportProvider.PARAM_SOURCE, Value.of(newPath));
            count++;
        }
    } finally {
        progress.end();
    }
}

From source file:edu.harvard.hms.dbmi.scidb.SciDB.java

/**
 * Connect to a SciDB instance at the given URL
 * //from  w w w .j  a v  a  2 s .  c om
 * @param client HTTP Client
 * @param url SciDB URL
 * @return Operation Status
 */
public boolean connect(HttpClient client, String url) {
    this.client = client;
    this.url = url;

    try {
        URIBuilder uriBuilder = new URIBuilder(this.url + "/new_session");

        URI uri = uriBuilder.build();
        System.out.println(uri.toASCIIString());

        HttpResponse response = client.execute(new HttpGet(uri));

        this.sessionId = inputStreamToString(response.getEntity().getContent());
        this.connected = true;
        return true;
    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:edu.harvard.hms.dbmi.scidb.SciDB.java

public String executeQuery(SciDBCommand operation, String save) throws NotConnectedException {
    if (!this.connected) {
        throw new NotConnectedException();
    }//from  w w  w .  ja v a 2 s. com

    try {
        URIBuilder uriBuilder = new URIBuilder(this.url + "/execute_query");
        uriBuilder.addParameter("id", this.sessionId);
        uriBuilder.addParameter("query", operation.toAFLQueryString());
        if (save != null) {
            uriBuilder.addParameter("save", save);
        }

        URI uri = uriBuilder.build();
        System.out.println(uri.toASCIIString());
        HttpGet runQuery = new HttpGet(uri);
        HttpResponse response = client.execute(runQuery);
        return inputStreamToString(response.getEntity().getContent());
    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.paxle.core.doc.impl.CommandTracker.java

/**
 * @see Thread#run()//from  ww w. j  a v  a 2 s . c o m
 */
@Override
public void run() {
    try {
        while (!this.isInterrupted()) {
            try {
                /* Check for unreferenced ICommands.
                 * 
                 * Command that are accessible via this queue are not referenced 
                 * anywhere in the runtime.
                 * 
                 * This should only occur if a component has forgotten to call
                 * ICommandTracker.commandDestroyed(...)
                 */
                Reference<? extends ICommand> commandRef = this.refQueue.remove(CLEANUP_DELAY.longValue());
                if (commandRef != null) {
                    this.logger.error(
                            "Command was destroyed without calling ICommandTracker.commandDestroyed(...)");

                    ICommand command = commandRef.get();
                    if (command != null) {
                        // we should never get in here ...
                        this.logger.error("Unexpected stat. commandRef.get() returned not null");
                    } else {
                        Long commandID = null;
                        URI commandURI = null;
                        try {
                            w.lock();
                            Iterator<Map.Entry<Long, WeakReference<ICommand>>> commandIDIter = this.commandIDTable
                                    .entrySet().iterator();
                            while (commandIDIter.hasNext()) {
                                Map.Entry<Long, WeakReference<ICommand>> entry = commandIDIter.next();
                                if (entry.getValue().equals(commandRef)) {
                                    commandID = entry.getKey();
                                    commandIDIter.remove();
                                    break;
                                }
                            }

                            Iterator<Map.Entry<URI, WeakReference<ICommand>>> commandURIIter = this.commandLocationTable
                                    .entrySet().iterator();
                            while (commandIDIter.hasNext()) {
                                Map.Entry<URI, WeakReference<ICommand>> entry = commandURIIter.next();
                                if (entry.getValue().equals(commandRef)) {
                                    commandURI = entry.getKey();
                                    commandURIIter.remove();
                                    break;
                                }
                            }
                        } finally {
                            w.unlock();
                        }

                        this.logger.warn(String.format("Command [%06d] removed without calling destroy: %s",
                                commandID, (commandURI == null) ? "unknown" : commandURI.toASCIIString()));
                    }
                }

                /* Check for to old destroyed ICommands.
                 * 
                 */
                if (!this.destroyedCommandMap.isEmpty()) {
                    long maxage = System.currentTimeMillis() - MAX_HOLDBACK_TIME.longValue();

                    synchronized (this.destroyedCommandMap) {

                        while (!this.destroyedCommandMap.isEmpty()
                                && this.destroyedCommandMap.getFirst().destroyedTime.longValue() < maxage) {
                            // remove the next command
                            DestroyedCommandData destoryedCommand = this.destroyedCommandMap.removeFirst();

                            ICommand command = destoryedCommand.command;
                            Long commandID = Long.valueOf(command.getOID());
                            URI commandURI = command.getLocation();

                            // removing the outdated command from all lists
                            WeakReference<ICommand> cmdRef = null;
                            this.commandLocationTable.remove(commandURI);
                            cmdRef = this.commandIDTable.remove(commandID);
                            if (cmdRef != null)
                                cmdRef.clear();

                            this.logger.debug(String.format("Command [%06d] removed from destroyed map: %s",
                                    commandID, (commandURI == null) ? "unknown" : commandURI.toASCIIString()));
                        }
                    }
                }
            } catch (Throwable e) {
                if (e instanceof InterruptedException)
                    throw (InterruptedException) e;
                this.logger.error(String.format("Unexpected '%s' while cleaning up destroyed commands.",
                        e.getClass().getName()), e);
            }
        }
    } catch (InterruptedException e) {
        this.logger.info("Thread was interrupted");
    }
}

From source file:org.paxle.filter.robots.impl.RobotsTxtManager.java

/**
 * Check a list of {@link URI URI} against the robots.txt file of the specified server.
 * @param baseUri the base-URI of the server hosting the {@link URI URIs}
 * @param uriList a list of {@link URI}. Each {@link URI} must belong to the specified <code>hostname:port</code>
 * //  w  w  w.  ja  v  a 2s .c  o  m
 * @return all {@link URI} that are blocked by the specified server
 */
private Collection<URI> isDisallowed(URI baseUri, Collection<URI> uriList) {
    if (baseUri == null)
        throw new NullPointerException("The base-URI is null.");
    if (uriList == null)
        throw new NullPointerException("The URI-list is null.");
    if (!baseUri.getScheme().startsWith("http"))
        throw new IllegalArgumentException("Only http(s) resources are allowed.");
    if (baseUri.getPath().length() > 1)
        throw new IllegalArgumentException("Invalid base-URI.");

    ArrayList<URI> disallowedList = new ArrayList<URI>();

    try {
        String hostPort = this.getHostPort(baseUri);

        // getting the RobotsTxt-info for this host[:port]
        RobotsTxt robotsTxt = this.getRobotsTxt(baseUri);

        // loop through each URI and check against the robots.txt
        for (URI location : uriList) {
            assert (this.getHostPort(location).equals(hostPort));
            String path = location.getPath();

            if (robotsTxt.isDisallowed(this.userAgent, path)) {
                disallowedList.add(location);
            }
        }
    } catch (Exception e) {
        this.logger.error(
                String.format("Unexpected '%s' while checking URIs against the robots.txt hosted on '%s'.",
                        e.getClass().getName(), baseUri.toASCIIString()),
                e);
    }

    return disallowedList;
}

From source file:com.liferay.mobile.android.http.file.DownloadFileTest.java

@Test
public void getDownloadURL() throws Exception {
    DownloadUtil.encoder = new DownloadUtil.URLEncoder() {

        @Override/*from   w  w  w.  j av a2s.  c  o  m*/
        public String encode(String path) throws Exception {
            URI URI = new URI("http", "localhost", path, null);

            path = URI.toASCIIString();
            path = path.replaceAll("http://localhost", "");

            return path;
        }

    };

    String expectedURL = "http://localhost:8080/webdav/guest" + "/document_library" + "/folder%20with%20spaces"
            + "/file%20%C3%A1%C3%A9%C3%AD%C3%B2%C3%BA%C3%B1.txt";

    String downloadURL = DownloadUtil.getWebDAVFileURL(session, PortalVersion.V_6_2, "/guest",
            "/folder with spaces", "file .txt");

    assertEquals(expectedURL, downloadURL);

    downloadURL = DownloadUtil.getWebDAVFileURL(session, PortalVersion.V_6_2, "guest", "folder with spaces",
            "/file .txt");

    assertEquals(expectedURL, downloadURL);

    expectedURL = "http://localhost:8080/webdav/guest" + "/document_library"
            + "/file%20%C3%A1%C3%A9%C3%AD%C3%B2%C3%BA%C3%B1.txt";

    downloadURL = DownloadUtil.getWebDAVFileURL(session, PortalVersion.V_6_2, "guest", "",
            "file .txt");

    assertEquals(expectedURL, downloadURL);
}

From source file:org.paxle.data.db.impl.CommandDB.java

boolean isKnownInDB(URI location, String queueName) {
    boolean known = false;

    Session session = null;/*from   w  w w. j  av a  2s  .  c  o m*/
    Transaction transaction = null;
    try {
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        Query query = session
                .createQuery(
                        String.format("SELECT count(location) FROM %s as cmd WHERE location = ?", queueName))
                .setParameter(0, location);
        Long result = (Long) query.setReadOnly(true).uniqueResult();
        known = (result != null && result.longValue() > 0);

        transaction.commit();
    } catch (Exception e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error(String.format("Unexpected '%s' while testing if location '%s' is known.",
                e.getClass().getName(), location.toASCIIString()), e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return known;
}

From source file:org.apache.ode.bpel.compiler.v1.BpelCompilerImpl.java

public void addWsdlImport(URI from, URI wsdlImport, SourceLocation sloc) {
    Definition4BPEL def;//from  w  w w . j av a 2  s  .c o m
    try {
        WSDLReader r = _wsdlFactory.newWSDLReader();
        WSDLLocatorImpl locator = new WSDLLocatorImpl(_resourceFinder, from.resolve(wsdlImport));
        def = (Definition4BPEL) r.readWSDL(locator);
    } catch (WSDLException e) {
        recoveredFromError(sloc, new CompilationException(
                __cmsgs.errWsdlParseError(e.getFaultCode(), e.getLocation(), e.getMessage())));
        throw new CompilationException(
                __cmsgs.errWsdlImportFailed(wsdlImport.toASCIIString(), e.getFaultCode()).setSource(sloc), e);
    }

    try {
        _wsdlRegistry.addDefinition(def, _resourceFinder, from.resolve(wsdlImport));
        if (__log.isDebugEnabled())
            __log.debug("Added WSDL Definition: " + wsdlImport);
    } catch (CompilationException ce) {
        recoveredFromError(sloc, ce);
    }
}

From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientRemoteStorage.java

/**
 * Executes the HTTP request./*from w ww  .j  a v a2s  .com*/
 * <p/>
 * In case of any exception thrown by HttpClient, it will release the connection. In other cases it
 * is the duty of caller to do it, or process the input stream.
 *
 * @param repository  to execute the HTTP method fpr
 * @param request     resource store request that triggered the HTTP request
 * @param httpRequest HTTP request to be executed
 * @return response of making the request
 * @throws RemoteStorageException If an error occurred during execution of HTTP request
 */
private HttpResponse executeRequest(final ProxyRepository repository, final ResourceStoreRequest request,
        final HttpUriRequest httpRequest) throws RemoteStorageException {
    final URI methodUri = httpRequest.getURI();

    if (getLogger().isDebugEnabled()) {
        getLogger().debug(
                "Invoking HTTP " + httpRequest.getMethod() + " method against remote location " + methodUri);
    }

    final RemoteStorageContext ctx = getRemoteStorageContext(repository);

    final HttpClient httpClient = HttpClientUtil.getHttpClient(CTX_KEY, ctx);

    httpRequest.setHeader("user-agent", formatUserAgentString(ctx, repository));
    httpRequest.setHeader("accept", "*/*");
    httpRequest.setHeader("accept-language", "en-us");
    httpRequest.setHeader("accept-encoding", "gzip,deflate,identity");
    httpRequest.setHeader("cache-control", "no-cache");

    // HTTP keep alive should not be used, except when NTLM is used
    final Boolean isNtlmUsed = HttpClientUtil.isNTLMAuthenticationUsed(CTX_KEY, ctx);
    if (isNtlmUsed == null || !isNtlmUsed) {
        httpRequest.setHeader("Connection", "close");
        httpRequest.setHeader("Proxy-Connection", "close");
    }

    HttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpRequest);
        final int statusCode = httpResponse.getStatusLine().getStatusCode();

        final Header httpServerHeader = httpResponse.getFirstHeader("server");
        checkForRemotePeerAmazonS3Storage(repository,
                httpServerHeader == null ? null : httpServerHeader.getValue());

        Header proxyReturnedErrorHeader = httpResponse.getFirstHeader(NEXUS_MISSING_ARTIFACT_HEADER);
        boolean proxyReturnedError = proxyReturnedErrorHeader != null
                && Boolean.valueOf(proxyReturnedErrorHeader.getValue());

        if (statusCode == HttpStatus.SC_FORBIDDEN) {
            throw new RemoteAccessDeniedException(repository, methodUri.toASCIIString(),
                    httpResponse.getStatusLine().getReasonPhrase());
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new RemoteAuthenticationNeededException(repository,
                    httpResponse.getStatusLine().getReasonPhrase());
        } else if (statusCode == HttpStatus.SC_OK && proxyReturnedError) {
            throw new RemoteStorageException(
                    "Invalid artifact found, most likely a proxy redirected to an HTML error page.");
        }

        return httpResponse;
    } catch (RemoteStorageException ex) {
        release(httpResponse);
        throw ex;
    } catch (ClientProtocolException ex) {
        release(httpResponse);
        throw new RemoteStorageException("Protocol error while executing " + httpRequest.getMethod()
                + " method. [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                + request.getRequestPath() + "\", remoteUrl=\"" + methodUri.toASCIIString() + "\"]", ex);
    } catch (IOException ex) {
        release(httpResponse);
        throw new RemoteStorageException("Transport error while executing " + httpRequest.getMethod()
                + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                + request.getRequestPath() + "\", remoteUrl=\"" + methodUri.toASCIIString() + "\"]", ex);
    }
}