Example usage for java.net URI toURL

List of usage examples for java.net URI toURL

Introduction

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

Prototype

public URL toURL() throws MalformedURLException 

Source Link

Document

Constructs a URL from this URI.

Usage

From source file:com.tomagoyaky.jdwp.IOUtils.java

/**
 * Gets the contents of a <code>URI</code> as a <code>byte[]</code>.
 *
 * @param uri the <code>URI</code> to read
 * @return the requested byte array/*from w w w  .  j  a v a  2  s  .  c om*/
 * @throws NullPointerException if the uri is null
 * @throws IOException          if an I/O exception occurs
 * @since 2.4
 */
public static byte[] toByteArray(final URI uri) throws IOException {
    return IOUtils.toByteArray(uri.toURL());
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    if (log.isDebugEnabled()) {
        log.debug("Start : sample " + url.toString());
        log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth);
    }/* w w w  .  j a  v  a 2 s.co  m*/

    HTTPSampleResult res = createSampleResult(url, method);

    HttpClient httpClient = setupClient(url, res);

    HttpRequestBase httpRequest = null;
    try {
        URI uri = url.toURI();
        if (method.equals(HTTPConstants.POST)) {
            httpRequest = new HttpPost(uri);
        } else if (method.equals(HTTPConstants.GET)) {
            httpRequest = new HttpGet(uri);
        } else if (method.equals(HTTPConstants.PUT)) {
            httpRequest = new HttpPut(uri);
        } else if (method.equals(HTTPConstants.HEAD)) {
            httpRequest = new HttpHead(uri);
        } else if (method.equals(HTTPConstants.TRACE)) {
            httpRequest = new HttpTrace(uri);
        } else if (method.equals(HTTPConstants.OPTIONS)) {
            httpRequest = new HttpOptions(uri);
        } else if (method.equals(HTTPConstants.DELETE)) {
            httpRequest = new HttpDelete(uri);
        } else if (method.equals(HTTPConstants.PATCH)) {
            httpRequest = new HttpPatch(uri);
        } else if (HttpWebdav.isWebdavMethod(method)) {
            httpRequest = new HttpWebdav(method, uri);
        } else {
            throw new IllegalArgumentException("Unexpected method: '" + method + "'");
        }
        setupRequest(url, httpRequest, res); // can throw IOException
    } catch (Exception e) {
        res.sampleStart();
        res.sampleEnd();
        errorResult(e, res);
        return res;
    }

    HttpContext localContext = new BasicHttpContext();
    setupClientContextBeforeSample(localContext);

    res.sampleStart();

    final CacheManager cacheManager = getCacheManager();
    if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
        if (cacheManager.inCache(url)) {
            return updateSampleResultForResourceInCache(res);
        }
    }

    try {
        currentRequest = httpRequest;
        handleMethod(method, res, httpRequest, localContext);
        // store the SampleResult in LocalContext to compute connect time
        localContext.setAttribute(SAMPLER_RESULT_TOKEN, res);
        // perform the sample
        HttpResponse httpResponse = executeRequest(httpClient, httpRequest, localContext, url);

        // Needs to be done after execute to pick up all the headers
        final HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
        extractClientContextAfterSample(localContext);
        // We've finished with the request, so we can add the LocalAddress to it for display
        final InetAddress localAddr = (InetAddress) httpRequest.getParams()
                .getParameter(ConnRoutePNames.LOCAL_ADDRESS);
        if (localAddr != null) {
            request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
        }
        res.setRequestHeaders(getConnectionHeaders(request));

        Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (contentType != null) {
            String ct = contentType.getValue();
            res.setContentType(ct);
            res.setEncodingAndType(ct);
        }
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            res.setResponseData(readResponse(res, entity.getContent(), (int) entity.getContentLength()));
        }

        res.sampleEnd(); // Done with the sampling proper.
        currentRequest = null;

        // Now collect the results into the HTTPSampleResult:
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        res.setResponseCode(Integer.toString(statusCode));
        res.setResponseMessage(statusLine.getReasonPhrase());
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseHeaders(getResponseHeaders(httpResponse, localContext));
        if (res.isRedirect()) {
            final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException(
                        "Missing location header in redirect for " + httpRequest.getRequestLine());
            }
            String redirectLocation = headerLocation.getValue();
            res.setRedirectLocation(redirectLocation);
        }

        // record some sizes to allow HTTPSampleResult.getBytes() with different options
        HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_METRICS);
        long headerBytes = res.getResponseHeaders().length() // condensed length (without \r)
                + httpResponse.getAllHeaders().length // Add \r for each header
                + 1 // Add \r for initial header
                + 2; // final \r\n before data
        long totalBytes = metrics.getReceivedBytesCount();
        res.setHeadersSize((int) headerBytes);
        res.setBodySize((int) (totalBytes - headerBytes));
        if (log.isDebugEnabled()) {
            log.debug("ResponseHeadersSize=" + res.getHeadersSize() + " Content-Length=" + res.getBodySize()
                    + " Total=" + (res.getHeadersSize() + res.getBodySize()));
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
            HttpHost target = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            URI redirectURI = req.getURI();
            if (redirectURI.isAbsolute()) {
                res.setURL(redirectURI.toURL());
            } else {
                res.setURL(new URL(new URL(target.toURI()), redirectURI.toString()));
            }
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpResponse, res.getURL(), getCookieManager());

        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(httpResponse, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

    } catch (IOException e) {
        log.debug("IOException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        // pick up headers if failed to execute the request
        if (res.getRequestHeaders() != null) {
            log.debug("Overwriting request old headers: " + res.getRequestHeaders());
        }
        res.setRequestHeaders(
                getConnectionHeaders((HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST)));
        errorResult(e, res);
        return res;
    } catch (RuntimeException e) {
        log.debug("RuntimeException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        errorResult(e, res);
        return res;
    } finally {
        currentRequest = null;
        JMeterContextService.getContext().getSamplerContext().remove(HTTPCLIENT_TOKEN);
    }
    return res;
}

From source file:nl.mpi.lamus.workspace.exporting.implementation.AddedNodeExporterTest.java

private WorkspaceNode getParentNode(boolean isInArchive, String parentNodeName, String basepath)
        throws MalformedURLException, URISyntaxException {

    final int parentNodeWsID = 1;
    final String parentFilename = parentNodeName + FilenameUtils.EXTENSION_SEPARATOR_STR + metadataExtension;
    final URL parentNodeWsURL = new URL(
            "file:/workspace/" + testWorkspace.getWorkspaceID() + File.separator + parentFilename);
    final URI parentNodeOriginURI = URI.create(basepath + parentFilename);
    final URL parentNodeArchiveURL = parentNodeOriginURI.toURL();
    final URI parentNodeArchiveURI;
    if (isInArchive) {
        parentNodeArchiveURI = new URI(UUID.randomUUID().toString());
    } else {/*  ww w .j  av  a  2s  . com*/
        parentNodeArchiveURI = null;
    }
    final WorkspaceNodeType parentNodeType = WorkspaceNodeType.METADATA;
    final WorkspaceNodeStatus parentNodeStatus = WorkspaceNodeStatus.ARCHIVE_COPY;
    final boolean parentNodeProtected = Boolean.FALSE;
    final String parentNodeFormat = "text/x-cmdi+xml";
    final URI nodeSchemaLocation = new URI("http://some.location");

    return new LamusWorkspaceNode(parentNodeWsID, testWorkspace.getWorkspaceID(), nodeSchemaLocation,
            parentNodeName, "", parentNodeType, parentNodeWsURL, parentNodeArchiveURI, parentNodeArchiveURL,
            parentNodeOriginURI, parentNodeStatus, parentNodeProtected, parentNodeFormat);
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.css.CSSModuleBuilder.java

/**
 * Processes the input CSS to replace &#064;import statements with the
 * contents of the imported CSS.  The imported CSS is minified, image
 * URLs in-lined, and this method recursively called to in-line nested
 * &#064;imports./*  www  .j  a  va  2 s  .com*/
 *
 * @param req
 *            The request associated with the call.
 * @param css
 *            The current CSS containing &#064;import statements to be
 *            processed
 * @param res
 *            The resource for the CSS file.
 * @param path
 *            The path, as specified in the &#064;import statement used to
 *            import the current CSS, or null if this is the top level CSS.
 *
 * @return The input CSS with &#064;import statements replaced with the
 *         contents of the imported files.
 *
 * @throws IOException
 */
protected String inlineImports(HttpServletRequest req, String css, IResource res, String path)
        throws IOException {

    // In-lining of imports can be disabled by request parameter for debugging
    if (!TypeUtil.asBoolean(req.getParameter(INLINEIMPORTS_REQPARAM_NAME), true)) {
        return css;
    }

    StringBuffer buf = new StringBuffer();
    IAggregator aggregator = (IAggregator) req.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME);
    IOptions options = aggregator.getOptions();
    /*
     * True if we should include the name of imported CSS files in a comment at
     * the beginning of the file.
     */
    boolean includePreamble = TypeUtil.asBoolean(req.getAttribute(IHttpTransport.SHOWFILENAMES_REQATTRNAME))
            && (options.isDebugMode() || options.isDevelopmentMode());
    if (includePreamble && path != null && path.length() > 0) {
        buf.append("/* @import " + path + " */\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    Matcher m = importPattern.matcher(css);
    while (m.find()) {
        String fullMatch = m.group(0);
        String importNameMatch = m.group(2);
        String mediaTypes = m.group(4);
        /*
         * CSS rules require that all @import statements appear before any
         * style definitions within a document. Most browsers simply ignore
         * @import statements which appear following any styles definitions.
         * This means that once we've inlined an @import, then we can't not
         * inline any subsequent @imports. The implication is that all
         * @imports which cannot be inlined (i.e. non-relative url or device
         * specific media types) MUST appear before any @import that is
         * inlined. For this reason, we throw an error if we encounter an
         * @import which we cannot inline if we have already inlined a
         * previous @import.
         */

        //Only process media type "all" or empty media type rules.
        if (mediaTypes.length() > 0 && !"all".equals(StringUtils.trim(mediaTypes))) { //$NON-NLS-1$
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
            continue;
        }
        // remove quotes.
        importNameMatch = dequote(importNameMatch);
        importNameMatch = forwardSlashPattern.matcher(importNameMatch).replaceAll("/"); //$NON-NLS-1$

        if (importNameMatch.startsWith("/") || protocolPattern.matcher(importNameMatch).find()) { //$NON-NLS-1$
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
            continue;
        }

        IResource importRes = res.resolve(importNameMatch);
        URI uri = null;
        if (importRes.exists()) {
            uri = importRes.getURI();
        } else if (includeAMDPaths && importNameMatch.contains("/") && !importNameMatch.startsWith(".")) { //$NON-NLS-1$ //$NON-NLS-2$
            // Resource not found using relative path to res.  If path is not relative (starts with .)
            // then try to find the resource using config paths and packages.
            uri = aggregator.getConfig().locateModuleResource(importNameMatch);
            if (uri != null) {
                uri = aggregator.newResource(uri).getURI();
            }
        }
        if (uri == null) {
            throw new NotFoundException(importNameMatch);
        }

        String importCss = null;
        importCss = readToString(
                new CommentStrippingReader(new InputStreamReader(uri.toURL().openStream(), "UTF-8" //$NON-NLS-1$
                )));
        importCss = minify(importCss, importRes);
        // Inline images
        importCss = inlineImageUrls(req, importCss, importRes);

        if (inlineImports) {
            importCss = inlineImports(req, importCss, importRes, importNameMatch);
        }
        m.appendReplacement(buf, ""); //$NON-NLS-1$
        buf.append(importCss);
    }
    m.appendTail(buf);

    css = buf.toString();
    /*
     * Now re-write all relative URLs in url(...) statements to make them relative
     * to the importing CSS
     */
    if (path != null && path.length() > 0) {
        int idx = path.lastIndexOf("/"); //$NON-NLS-1$
        //Make a file path based on the last slash.
        //If no slash, so must be just a file name. Use empty string then.
        path = (idx != -1) ? path.substring(0, idx + 1) : ""; //$NON-NLS-1$
        buf = new StringBuffer();
        m = urlPattern.matcher(css);
        while (m.find()) {
            String fullMatch = m.group(0);
            String urlMatch = m.group(1);

            urlMatch = StringUtils.trim(urlMatch.replace("\\", "/")); //$NON-NLS-1$ //$NON-NLS-2$
            String quoted = ""; //$NON-NLS-1$
            if (urlMatch.charAt(0) == '"' && urlMatch.charAt(urlMatch.length() - 1) == '"') {
                quoted = "\""; //$NON-NLS-1$
                urlMatch = urlMatch.substring(1, urlMatch.length() - 1);
            } else if (urlMatch.charAt(0) == '\'' && urlMatch.charAt(urlMatch.length() - 1) == '\'') {
                quoted = "'"; //$NON-NLS-1$
                urlMatch = urlMatch.substring(1, urlMatch.length() - 1);
            }

            // Don't modify non-relative URLs
            if (urlMatch.startsWith("/") || urlMatch.startsWith("#") //$NON-NLS-1$//$NON-NLS-2$
                    || protocolPattern.matcher(urlMatch).find()) {
                m.appendReplacement(buf, ""); //$NON-NLS-1$
                buf.append(fullMatch);
                continue;
            }

            String fixedUrl = path + ((path.endsWith("/") || path.length() == 0) ? "" : "/") + urlMatch; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            //Collapse '..' and '.'
            String[] parts = fixedUrl.split("/"); //$NON-NLS-1$
            for (int i = parts.length - 1; i > 0; i--) {
                if (".".equals(parts[i])) { //$NON-NLS-1$
                    parts = (String[]) ArrayUtils.remove(parts, i);
                } else if ("..".equals(parts[i])) { //$NON-NLS-1$
                    if (i != 0 && !"..".equals(parts[i - 1])) { //$NON-NLS-1$
                        parts = (String[]) ArrayUtils.remove(parts, i - 1);
                        parts = (String[]) ArrayUtils.remove(parts, i - 1);
                    }
                }
            }
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append("url(") //$NON-NLS-1$
                    .append(quoted).append(StringUtils.join(parts, "/")) //$NON-NLS-1$
                    .append(quoted).append(")"); //$NON-NLS-1$
        }
        m.appendTail(buf);
        css = buf.toString();
    }
    return css;
}

From source file:com.ibm.jaggr.service.impl.modulebuilder.css.CSSModuleBuilder.java

/**
 * Replace <code>url(&lt;<i>relative-path</i>&gt;)</code> references in the
 * input CSS with/*from   www  . j  a va  2  s  .  c o  m*/
 * <code>url(data:&lt;<i>mime-type</i>&gt;;&lt;<i>base64-encoded-data</i>&gt;</code>
 * ). The conversion is controlled by option settings as described in
 * {@link CSSModuleBuilder}.
 * 
 * @param css
 *            The input CSS
 * @param uri
 *            The URI for the input CSS
 * @return The transformed CSS with images in-lined as determined by option
 *         settings.
 */
protected String inlineImageUrls(HttpServletRequest req, String css, IResource res) {
    if (imageSizeThreshold == 0 && inlinedImageIncludeList.size() == 0) {
        // nothing to do
        return css;
    }

    // In-lining of imports can be disabled by request parameter for debugging
    if (!TypeUtil.asBoolean(req.getParameter(INLINEIMAGES_REQPARAM_NAME), true)) {
        return css;
    }

    StringBuffer buf = new StringBuffer();
    Matcher m = urlPattern.matcher(css);
    while (m.find()) {
        String fullMatch = m.group(0);
        String urlMatch = m.group(1);

        // remove quotes.
        urlMatch = quotedStringPattern.matcher(urlMatch).replaceAll(""); //$NON-NLS-1$
        urlMatch = forwardSlashPattern.matcher(urlMatch).replaceAll("/"); //$NON-NLS-1$

        // Don't do anything with non-relative URLs
        if (urlMatch.startsWith("/") || urlMatch.startsWith("#") || protocolPattern.matcher(urlMatch).find()) { //$NON-NLS-1$ //$NON-NLS-2$
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
            continue;
        }

        URI imageUri = res.getURI().resolve(urlMatch);
        boolean exclude = false, include = false;

        // Determine if this image is in the include list
        for (Pattern regex : inlinedImageIncludeList) {
            if (regex.matcher(imageUri.getPath()).find()) {
                include = true;
                break;
            }
        }

        // Determine if this image is in the exclude list
        for (Pattern regex : inlinedImageExcludeList) {
            if (regex.matcher(imageUri.getPath()).find()) {
                exclude = true;
                break;
            }
        }
        // If there's an include list, then only the files in the include list
        // will be inlined
        if (inlinedImageIncludeList.size() > 0 && !include || exclude) {
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
            continue;
        }

        boolean imageInlined = false;
        InputStream in = null;
        try {
            // In-line the image.
            URLConnection connection = imageUri.toURL().openConnection();
            in = connection.getInputStream();
            int size = connection.getContentLength();
            String type = connection.getContentType();
            if (type == null) {
                type = "content/unknown"; //$NON-NLS-1$
            }
            if (include || inlineableImageTypes.contains(type) && size <= imageSizeThreshold) {
                String base64 = getBase64(connection);
                m.appendReplacement(buf, ""); //$NON-NLS-1$
                buf.append("url('data:" + type + //$NON-NLS-1$
                        ";base64," + base64 + "')"); //$NON-NLS-1$ //$NON-NLS-2$
                imageInlined = true;
            }
        } catch (IOException ex) {
            if (log.isLoggable(Level.WARNING)) {
                log.log(Level.WARNING,
                        MessageFormat.format(Messages.CSSModuleBuilder_0, new Object[] { imageUri }), ex);
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignore) {
                }
            }
        }
        if (!imageInlined) {
            // Image not in-lined.  Write the original URL
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
        }
    }
    m.appendTail(buf);
    return buf.toString();
}

From source file:ddf.catalog.resource.impl.URLResourceReader.java

private String getMimeType(URI resourceURI, String productName)
        throws MimeTypeResolutionException, IOException {
    // Determine the mime type in a hierarchical fashion. The hierarchy is based on the
    // most accurate mime type resolution being used and lesser accurate approaches being
    // used//from   w  w  w . jav  a 2 s  . c  om
    // if a mime type is not resolved.

    // The approaches, in order, are:
    // 1. Try using the DDF MimeTypeMapper so that custom MimeTypeResolvers are used
    // 2. Try using Apache Tika directly on the URL

    String mimeType = null;
    if (mimeTypeMapper == null) {
        LOGGER.warn("mimeTypeMapper is NULL");
    } else {
        // Extract the file extension (if any) from the URL's filename
        String fileExtension = FilenameUtils.getExtension(productName);
        mimeType = mimeTypeMapper.getMimeTypeForFileExtension(fileExtension);
    }

    // If MimeTypeMapper was null or did not yield a mime type, or if default
    // mime type was returned, try using Apache Tika to inspect the file for better
    // mime type resolution than just file extension mime type mapping
    if ((mimeType == null || mimeType.isEmpty() || mimeType.equals(DEFAULT_MIME_TYPE))
            && URL_FILE_SCHEME.equalsIgnoreCase(resourceURI.getScheme())) {
        // Use Apache Tika to detect mime type from URL
        Tika tika = new Tika();
        mimeType = tika.detect(resourceURI.toURL());
        LOGGER.debug("Tika determined mimeType for url = {}", mimeType);
    } else {
        LOGGER.debug("mimeType = {} set by MimeTypeMapper", mimeType);
    }

    // Legacy default is application/unknown but URLConnection returns content/unknown
    // as default when mime type does not map to a file extension. To maintain legacy
    // compatibility, change content/unknown to application/unknown

    // With switching to use MimeTypeMapper vs. URLConnection.getContentType() and
    // guessContentTypeFromName()
    // the underlying TikaMimeTypeResolver will always return at least
    // application/octet-stream as the default
    // mime type for an unknown file extension. Hence, application/unknown will probably
    // never be returned.
    if (mimeType == null || mimeType.equals("content/unknown")) {
        mimeType = "application/unknown";
    }

    LOGGER.debug("mimeType set to: {}", mimeType);
    return mimeType;
}

From source file:org.dkpro.lab.engine.impl.DefaultTaskContext.java

public StorageKey resolve(String aKey, AccessMode aMode, boolean aAllowMissing) {
    StorageService storage = getStorageService();
    Map<String, String> imports = getMetadata().getImports();

    if (storage.containsKey(getId(), aKey)) {
        // If the context contains the key, we do nothing. Locally available data always
        // supersedes imported data.
        return new StorageKey(getId(), aKey);
    } else if (imports.containsKey(aKey)) {
        URI uri;
        try {//from  w w w. ja va2 s.  c o m
            uri = new URI(imports.get(aKey));
        } catch (URISyntaxException e) {
            throw new DataAccessResourceFailureException(
                    "Imported key [" + aKey + "] resolves to illegal URL [" + imports.get(aKey) + "]", e);
        }

        // Try resolving by ID or by type/constraints
        StorageKey key = null;
        if (CONTEXT_ID_SCHEME.equals(uri.getScheme()) || LATEST_CONTEXT_SCHEME.equals(uri.getScheme())) {
            TaskContextMetadata meta = resolve(uri);
            key = new StorageKey(meta.getId(), uri.getPath());
        }

        // If the resource is imported from another context and will be modified it has to
        // be copied into the current context. The storage may decide though not to copy
        // data at this point if it can assure a copy-on-write behavior. E.g. it may copy
        // imported storage folders now but imported stream-access (files) keys later.
        if (key != null) {
            switch (aMode) {
            case ADD_ONLY:
            case READWRITE:
                storage.copy(getId(), aKey, key, aMode);
                return new StorageKey(getId(), aKey);
            case READONLY:
                return key;
            }
        }

        // If this is an external URL, copy it to the current context and then return a location
        // in the current context.
        InputStream is = null;
        try {
            is = uri.toURL().openStream();
            storage.storeBinary(getId(), aKey, is);
            return new StorageKey(getId(), aKey);
        } catch (MalformedURLException e) {
            throw new DataAccessResourceFailureException(
                    "Imported external key [" + aKey + "] resolves to illegal URL [" + uri + "]", e);
        } catch (IOException e) {
            throw new DataAccessResourceFailureException(
                    "Unable to read data for external key [" + aKey + "] from [" + uri + "]", e);
        } finally {
            close(is);
        }
    } else if (aAllowMissing) {
        return new StorageKey(getId(), aKey);
    }

    throw new DataAccessResourceFailureException("No resource bound to key [" + aKey + "]");
}

From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java

protected void processAggregatorRequest(HttpServletRequest req, HttpServletResponse resp) {
    final String sourceMethod = "processAggregatorRequest"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[] { req, resp });
    }/*from  w  w  w .  j av  a  2s  .  c  o m*/
    req.setAttribute(AGGREGATOR_REQATTRNAME, this);
    ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<String, Object>();
    req.setAttribute(CONCURRENTMAP_REQATTRNAME, concurrentMap);

    try {
        // Validate config last-modified if development mode is enabled
        if (getOptions().isDevelopmentMode()) {
            long lastModified = -1;
            URI configUri = getConfig().getConfigUri();
            if (configUri != null) {
                try {
                    // try to get platform URI from IResource in case uri specifies
                    // aggregator specific scheme like namedbundleresource
                    configUri = newResource(configUri).getURI();
                } catch (UnsupportedOperationException e) {
                    // Not fatal.  Just use uri as specified.
                }
                lastModified = configUri.toURL().openConnection().getLastModified();
            }
            if (lastModified > getConfig().lastModified()) {
                if (reloadConfig()) {
                    // If the config has been modified, then dependencies will be revalidated
                    // asynchronously.  Rather than forcing the current request to wait, return
                    // a response that will display an alert informing the user of what is
                    // happening and asking them to reload the page.
                    String content = "alert('" + //$NON-NLS-1$
                            StringUtil.escapeForJavaScript(Messages.ConfigModified) + "');"; //$NON-NLS-1$
                    resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
                    CopyUtil.copy(new StringReader(content), resp.getOutputStream());
                    return;
                }
            }
        }

        getTransport().decorateRequest(req);
        notifyRequestListeners(RequestNotifierAction.start, req, resp);

        ILayer layer = getLayer(req);
        long modifiedSince = req.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
        long lastModified = (Math.max(getCacheManager().getCache().getCreated(), layer.getLastModified(req))
                / 1000) * 1000;
        if (modifiedSince >= lastModified) {
            if (log.isLoggable(Level.FINER)) {
                log.finer("Returning Not Modified response for layer in servlet" + //$NON-NLS-1$
                        getName() + ":" //$NON-NLS-1$
                        + req.getAttribute(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME).toString());
            }
            resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        } else {
            // Get the InputStream for the response.  This call sets the Content-Type,
            // Content-Length and Content-Encoding headers in the response.
            InputStream in = layer.getInputStream(req, resp);
            // if any of the readers included an error response, then don't cache the layer.
            if (req.getAttribute(ILayer.NOCACHE_RESPONSE_REQATTRNAME) != null) {
                resp.addHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
            } else {
                resp.setDateHeader("Last-Modified", lastModified); //$NON-NLS-1$
                int expires = getConfig().getExpires();
                resp.addHeader("Cache-Control", //$NON-NLS-1$
                        "public" + (expires > 0 ? (", max-age=" + expires) : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                );
            }
            CopyUtil.copy(in, resp.getOutputStream());
        }
        notifyRequestListeners(RequestNotifierAction.end, req, resp);
    } catch (DependencyVerificationException e) {
        // clear the cache now even though it will be cleared when validateDeps has
        // finished (asynchronously) so that any new requests will be forced to wait
        // until dependencies have been validated.
        getCacheManager().clearCache();
        getDependencies().validateDeps(false);

        resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
        if (getOptions().isDevelopmentMode()) {
            String msg = StringUtil.escapeForJavaScript(MessageFormat.format(Messages.DepVerificationFailed,
                    new Object[] { e.getMessage(), "aggregator " + //$NON-NLS-1$
                            "validatedeps " + //$NON-NLS-1$
                            getName() + " clean", //$NON-NLS-1$
                            getWorkingDirectory().toString().replace("\\", "\\\\") //$NON-NLS-1$ //$NON-NLS-2$
                    }));
            String content = "alert('" + msg + "');"; //$NON-NLS-1$ //$NON-NLS-2$
            try {
                CopyUtil.copy(new StringReader(content), resp.getOutputStream());
            } catch (IOException e1) {
                if (log.isLoggable(Level.SEVERE)) {
                    log.log(Level.SEVERE, e1.getMessage(), e1);
                }
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (ProcessingDependenciesException e) {
        resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
        if (getOptions().isDevelopmentMode()) {
            String content = "alert('" + StringUtil.escapeForJavaScript(Messages.Busy) + "');"; //$NON-NLS-1$ //$NON-NLS-2$
            try {
                CopyUtil.copy(new StringReader(content), resp.getOutputStream());
            } catch (IOException e1) {
                if (log.isLoggable(Level.SEVERE)) {
                    log.log(Level.SEVERE, e1.getMessage(), e1);
                }
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (BadRequestException e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_BAD_REQUEST);
    } catch (NotFoundException e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_NOT_FOUND);
    } catch (Exception e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        concurrentMap.clear();
    }
    if (isTraceLogging) {
        log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
    }
}

From source file:org.apache.woden.internal.DOMWSDLReader.java

protected DescriptionElement getWSDLFromLocation(String locationURI, DescriptionElement desc, Map wsdlModules)
        throws WSDLException {
    DescriptionElement referencedDesc = null;
    Element docEl;/*from w  w w  . ja  v  a 2s  .c om*/
    URL locationURL = null;
    URI contextURI = null;

    try {
        /*
         * For simple resolvers, we resolve the parent (Description) URI
         * to be used as the context. This allows for relative locationURIs
         * to be resolved implicitly - they are considered to be located 
         * relative to the resolved parent. Therefore, relative URIs such as these
         * need not be listed in the catalog file.
         */

        /* TODO
         * OASIS-style catalogs have a convenience notation to define root URIs
         * thus grouping related URLs together. In this case the context URI here
         * should be left alone, but the resultant locationURL resolved instead.
         * 
         * Implement a boolean system property like org.apache.woden.resolver.useRelativeURLs
         * (set by the resolver ctor). SimpleURIResolver (et al) should set this to true,
         * OASISCatalogResolver should set to false. 
         */
        // contextURI = desc.getDocumentBaseURI();
        contextURI = resolveURI(desc.getDocumentBaseURI());
        URL contextURL = (contextURI != null) ? contextURI.toURL() : null;
        locationURL = StringUtils.getURL(contextURL, locationURI);
    } catch (MalformedURLException e) {
        String baseURI = contextURI != null ? contextURI.toString() : null;

        getErrorReporter().reportError(new ErrorLocatorImpl(), //TODO line&col nos.
                "WSDL502", new Object[] { baseURI, locationURI }, ErrorReporter.SEVERITY_ERROR);

        //can't continue import with a bad URL.
        return null;
    }

    String locationStr = locationURL.toString();

    //Check if WSDL imported or included previously from this location.
    referencedDesc = (DescriptionElement) wsdlModules.get(locationStr);

    if (referencedDesc == null) {
        //not previously imported or included, so retrieve the WSDL.
        try {
            Document doc = getDocument(new InputSource(locationStr), locationStr);
            docEl = doc.getDocumentElement();
        } catch (IOException e) {
            //document retrieval failed (e.g. 'not found')
            getErrorReporter().reportError(new ErrorLocatorImpl(), //TODO line&col nos.
                    "WSDL503", new Object[] { locationStr }, ErrorReporter.SEVERITY_WARNING, e);

            //cannot continue without the referenced document
            return null;
        }

        //The referenced document should contain a WSDL <description>
        QName docElQN = new QName(docEl.getNamespaceURI(), docEl.getLocalName());

        if (!Constants.Q_ELEM_DESCRIPTION.equals(docElQN)) {
            getErrorReporter().reportError(new ErrorLocatorImpl(), //TODO line&col nos.
                    "WSDL501", new Object[] { Constants.Q_ELEM_DESCRIPTION, docElQN },
                    ErrorReporter.SEVERITY_ERROR);

            //cannot continue without a <description> element
            return null;
        }

        XMLElement descEl = createXMLElement(docEl);

        referencedDesc = parseDescription(locationStr, descEl, wsdlModules);

        if (!wsdlModules.containsKey(locationStr)) {
            wsdlModules.put(locationStr, referencedDesc);
        }
    }

    return referencedDesc;
}

From source file:it.infn.ct.futuregateway.apiserver.inframanager.SessionBuilder.java

/**
 * Read the proxy certificate from a remote location.
 * The location is retrieved from the parameters.
 *
 * @return A string representation of the proxy
 * @throws InfrastructureException If the proxy for the infrastructure
 * cannot be retrieved for problems with the parameters
 *///from  w  w w.  ja v a2  s  .c om
protected final String readRemoteProxy() throws InfrastructureException {
    URL proxy;
    if (params.getProperty("proxyurl") == null && params.getProperty("etokenserverurl") == null) {
        throw new InfrastructureException(
                "No proxy location in " + "configuration parameters for " + infrastructure.getId());
    }
    if (params.getProperty("proxyurl") != null) {
        try {
            proxy = new URL(params.getProperty("proxyurl"));
        } catch (MalformedURLException mue) {
            throw new InfrastructureException("URL for the proxy is not " + "valid, infrastructure "
                    + infrastructure.getId() + " is not accessible");
        }
    } else {
        try {
            URI etokenurl = new URI(params.getProperty("etokenserverurl"));
            StringBuilder queryURI = new StringBuilder();
            StringBuilder pathURI = new StringBuilder();
            String oldPath = etokenurl.getPath();
            if (oldPath != null) {
                pathURI.append(oldPath);
                if (!oldPath.endsWith("/")) {
                    pathURI.append('/');
                }
                pathURI.append(params.getProperty("etokenid", ""));
            } else {
                pathURI.append('/').append(params.getProperty("etokenid", ""));
            }
            String oldQuery = etokenurl.getQuery();
            if (oldQuery != null) {
                queryURI.append(oldQuery).append('&');
            }
            queryURI.append("voms=").append(params.getProperty("vo", "")).append(':')
                    .append(params.getProperty("voroles", "")).append('&');
            queryURI.append("proxy-renewal=").append(params.getProperty("proxyrenewal", Defaults.PROXYRENEWAL))
                    .append('&');
            queryURI.append("disable-voms-proxy=")
                    .append(params.getProperty("disablevomsproxy", Defaults.DISABLEVOMSPROXY)).append('&');
            queryURI.append("rfc-proxy=").append(params.getProperty("rfcproxy", Defaults.RFCPROXY)).append('&');
            queryURI.append("cn-label=");
            if (user != null) {
                queryURI.append("eToken:").append(user);
            }
            etokenurl = new URI(etokenurl.getScheme(), etokenurl.getUserInfo(), etokenurl.getHost(),
                    etokenurl.getPort(), pathURI.toString(), queryURI.toString(), etokenurl.getFragment());
            proxy = etokenurl.toURL();
        } catch (MalformedURLException | URISyntaxException use) {
            throw new InfrastructureException("etokenserverurl not " + "properly configured for infrastructure "
                    + getInfrastructure().getId());
        }
    }
    StringBuilder strProxy = new StringBuilder();
    log.debug("Accessing the proxy " + proxy.toString());
    try {
        String lnProxy;
        BufferedReader fileProxy = new BufferedReader(new InputStreamReader(proxy.openStream()));
        while ((lnProxy = fileProxy.readLine()) != null) {
            strProxy.append(lnProxy);
            strProxy.append("\n");
        }
    } catch (IOException ioer) {
        log.error("Impossible to retrieve the remote proxy certificate from" + ": " + proxy.toString());
    }
    log.debug("Proxy:\n\n" + strProxy.toString() + "\n\n");
    return strProxy.toString();
}