Example usage for java.net URI isAbsolute

List of usage examples for java.net URI isAbsolute

Introduction

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

Prototype

public boolean isAbsolute() 

Source Link

Document

Tells whether or not this URI is absolute.

Usage

From source file:org.apache.http.HC4.impl.nio.client.MainClientExec.java

private void prepareRequest(final InternalState state, final AbstractClientExchangeHandler<?> handler)
        throws IOException, HttpException {
    final HttpClientContext localContext = state.getLocalContext();
    final HttpRequestWrapper currentRequest = handler.getCurrentRequest();
    final HttpRoute route = handler.getRoute();

    final HttpRequest original = currentRequest.getOriginal();
    URI uri = null;
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {//from  w w w .ja va  2 s  .  com
        final String uriString = original.getRequestLine().getUri();
        try {
            uri = URI.create(uriString);
        } catch (final IllegalArgumentException ex) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Unable to parse '" + uriString + "' as a valid URI; "
                        + "request URI and Host header may be inconsistent", ex);
            }
        }

    }
    currentRequest.setURI(uri);

    // Re-write request URI if needed
    rewriteRequestURI(currentRequest, route);

    HttpHost target = null;
    if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
        target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    }
    if (target == null) {
        target = route.getTargetHost();
    }

    // Get user info from the URI
    if (uri != null) {
        final String userinfo = uri.getUserInfo();
        if (userinfo != null) {
            final CredentialsProvider credsProvider = localContext.getCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
        }
    }

    localContext.setAttribute(HttpClientContext.HTTP_REQUEST, currentRequest);
    localContext.setAttribute(HttpClientContext.HTTP_TARGET_HOST, target);
    localContext.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    this.httpProcessor.process(currentRequest, localContext);
}

From source file:org.apache.http.impl.nio.client.MainClientExec.java

private void prepareRequest(final InternalState state, final AbstractClientExchangeHandler<?> handler)
        throws IOException, HttpException {
    final HttpClientContext localContext = state.getLocalContext();
    final HttpRequestWrapper currentRequest = handler.getCurrentRequest();
    final HttpRoute route = handler.getRoute();

    final HttpRequest original = currentRequest.getOriginal();
    URI uri = null;
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {/*w  w  w  .  ja va  2 s .c om*/
        final String uriString = original.getRequestLine().getUri();
        try {
            uri = URI.create(uriString);
        } catch (final IllegalArgumentException ex) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Unable to parse '" + uriString + "' as a valid URI; "
                        + "request URI and Host header may be inconsistent", ex);
            }
        }

    }
    currentRequest.setURI(uri);

    // Re-write request URI if needed
    rewriteRequestURI(currentRequest, route);

    HttpHost target = null;
    if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
        target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    }
    if (target == null) {
        target = route.getTargetHost();
    }

    // Get user info from the URI
    if (uri != null) {
        final String userinfo = uri.getUserInfo();
        if (userinfo != null) {
            final CredentialsProvider credsProvider = localContext.getCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
        }
    }

    localContext.setAttribute(HttpCoreContext.HTTP_REQUEST, currentRequest);
    localContext.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    localContext.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    this.httpProcessor.process(currentRequest, localContext);
}

From source file:net.sf.iqser.plugin.csv.CsvContentProvider.java

/**
 * Initializes the content provider.//  w  w  w  . j ava2  s. c o m
 * 
 * @see com.iqser.core.plugin.AbstractContentProvider#init()
 */
@Override
public void init() {
    LOG.info(String.format("Invoking %s#init() ...", this.getClass().getSimpleName()));

    // Setting the file's name.
    String filename = getInitParams().getProperty(CSV_PROPERTY_FILE, "").trim();
    if ("".equals(filename)) {
        LOG.error("No csv file specified in configuration!");
        filename = null;
    }

    // Setting the file
    if (null != filename && !"".equals(filename.trim())) {

        URI fileUri = null;
        try {
            fileUri = new URI(filename);
            LOG.info("CSV filename: " + filename);
            LOG.info("URI of CSV file: " + fileUri + ". URI is absolute? " + fileUri.isAbsolute());
        } catch (URISyntaxException e) {
            if (LOG.isDebugEnabled()) {
                LOG.warn(filename + " is no valid URI.", e);
            } else {
                LOG.warn(filename + " is no valid URI.");
            }
        }

        if (null == fileUri || !fileUri.isAbsolute()) {
            file = new File(filename);
        } else {
            file = new File(fileUri.getPath());
        }
    }

    // Setting the content type
    contentType = getInitParams().getProperty(CSV_PROPERTY_CONTENT_TYPE, CSV_DEFAULT_TYPE).trim();
    LOG.debug("Init param: contentType = " + contentType);

    // Setting the file's delimeter.
    try {
        delimeter = getInitParams().getProperty(CSV_PROPERTY_DELIMETER, CSV_DEFAULT_DELIMETER).trim().charAt(0);
    } catch (IndexOutOfBoundsException ioobe) {
        LOG.warn(String.format("'%s' is an illegal delimeter. Default delimeter (%s) will be used.", delimeter,
                CSV_DEFAULT_DELIMETER));
        delimeter = CSV_DEFAULT_DELIMETER.charAt(0);
    }
    LOG.debug("Init param: delimeter = " + delimeter);

    // Setting the file's charset.
    String charsetParamValue = getInitParams().getProperty(CSV_PROPERTY_CHARSET, CSV_DEFAULT_CHARSET);
    try {
        charset = Charset.forName(charsetParamValue);
        LOG.debug("Init param: charset = " + charsetParamValue);
    } catch (IllegalCharsetNameException e) {
        charset = Charset.defaultCharset();
        LOG.warn(String.format("'%s' is an illegal chaset name. Default charset (%s) of the JVM will be used.",
                charsetParamValue, charset.displayName()));
    }

    contenUrlAsHashFromRecord = Boolean.parseBoolean(getInitParams()
            .getProperty(CSV_PROPERTY_CONTENTURLASHASHEDRECORD, CSV_DEFAULT_CONTENTURLASHASHEDRECORD));
    LOG.debug("Init param: contenUrlAsHashFromRecord = " + contenUrlAsHashFromRecord);

    if (contenUrlAsHashFromRecord) {
        String digestAlgorithmParam = getInitParams().getProperty(
                CSV_PROPERTY_DIGESTALGORITHMFORCONTENTURLASHASHEDRECORD,
                CSV_DEFAULT_DIGESTALGORITHMFORCONTENTURLASHASHEDRECORD);
        LOG.debug("Init param: contenUrlAsHashFromRecordDigestAlgorithm = " + digestAlgorithmParam);
        try {
            digestForContenUrlAsHashFromRecord = MessageDigest.getInstance(digestAlgorithmParam);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(
                    "Digest algorithm for content url computation could not be instantiated", e);
        }
        idColumns = Collections.emptyList();
    } else {
        // Setting the zero-based list of numbers of the id-columns.
        String idColumnsParamValue = getInitParams().getProperty(CSV_PROPERTY_IDCOLUMNS);
        if (StringUtils.isBlank(idColumnsParamValue)) {
            idColumnsParamValue = getInitParams().getProperty(CSV_PROPERTY_IDCOLUMN, CSV_DEFAULT_IDCOLUMN);
        }
        if (StringUtils.isBlank(idColumnsParamValue)) {
            idColumnsParamValue = CSV_DEFAULT_IDCOLUMN;
        }
        String[] idColumnStrings = idColumnsParamValue.split(",");
        idColumns = new ArrayList<Integer>();
        for (int i = 0; i < idColumnStrings.length; i++) {
            try {
                if (StringUtils.isNotBlank(idColumnStrings[i])) {
                    idColumns.add(i, Integer.parseInt(idColumnStrings[i].trim()));
                }
            } catch (NumberFormatException e) {
                LOG.error("Could not identify id column for value: '" + idColumnStrings[i]
                        + "'\nList of id columns is corrupted!", e);
                throw e;
            }
        }
        LOG.debug("Init param: idColumns = " + idColumnsParamValue);
    }
    // Setting the boolean idAsContentUrl-flag.
    idAsContentUrl = Boolean
            .parseBoolean(getInitParams().getProperty(CSV_PROPERTY_IDASCONTENTURL, CSV_DEFAULT_IDASCONTENTURL));
    LOG.debug("Init param: idAsContentUrl = " + idAsContentUrl);

    // Setting the boolean recordAsFulltext-flag.
    recordAsFulltext = Boolean.parseBoolean(
            getInitParams().getProperty(CSV_PROPERTY_RECORDASFULLTEXT, CSV_DEFAULT_RECORDASFULLTEXT));
    LOG.debug("Init param: recordAsFulltext = " + idAsContentUrl);

    // Setting the zero-based number of the fulltext-column.
    String fulltextColumnValue = getInitParams().getProperty(CSV_PROPERTY_FULLTEXTCOLUMN,
            CSV_DEFAULT_FULLTEXTCOLUMN);
    fulltextColumn = Integer.parseInt(StringUtils.isNotBlank(fulltextColumnValue) ? fulltextColumnValue.trim()
            : CSV_DEFAULT_FULLTEXTCOLUMN);
    LOG.debug("Init param: fulltextColumn = " + fulltextColumn);

    fullTextColumnAsAdditionalAttribute = Boolean.parseBoolean(getInitParams().getProperty(
            CSV_PROPERTY_FULLTEXTCOLUMNASADDITIONALATTRIBUTE, CSV_DEFAULT_FULLTEXTCOLUMNASADDITIONALATTRIBUTE));
    LOG.debug("Init param: fullTextColumnAsAdditionalAttribute = " + fullTextColumnAsAdditionalAttribute);

    // Setting the zero-based number of the name-column.
    String nameColumnValue = getInitParams().getProperty(CSV_PROPERTY_NAMECOLUMN, CSV_DEFAULT_NAMECOLUMN);
    nameColumn = Integer.parseInt(
            StringUtils.isNotBlank(nameColumnValue) ? nameColumnValue.trim() : CSV_DEFAULT_NAMECOLUMN);
    LOG.debug("Init param: nameColumn = " + nameColumn);

    // Setting the timestamp columns' type.
    String timestampColumnParamValue = getInitParams().getProperty(CSV_PROPERTY_TIMESTAMPCOLUMNS,
            CSV_DEFAULT_TIMESTAMPCOLUMNS);
    if (StringUtils.isBlank(timestampColumnParamValue)) {
        timestampColumnParamValue = CSV_DEFAULT_TIMESTAMPCOLUMNS;
    }
    String[] timestampColumnStrings = timestampColumnParamValue.split(",");
    timestampColumns = new ArrayList<Integer>();
    for (int i = 0; i < timestampColumnStrings.length; i++) {
        try {
            if (!(null == timestampColumnStrings[i] || "".equals(timestampColumnStrings[i].trim()))) {
                timestampColumns.add(i, Integer.parseInt(timestampColumnStrings[i].trim()));
            }
        } catch (NumberFormatException e) {
            LOG.error("Could not identify key column for value: '" + timestampColumnStrings[i]
                    + "'\nList of key columns is corrupted!", e);
            throw e;
        }
    }
    LOG.debug("Init param: columns.type.date = " + timestampColumnStrings);

    // Setting the key columns.
    String keyColumnParamValue = getInitParams().getProperty(CSV_PROPERTY_KEYCOLUMNS, CSV_DEFAULT_KEYCOLUMNS);
    if (StringUtils.isBlank(keyColumnParamValue)) {
        keyColumnParamValue = CSV_DEFAULT_KEYCOLUMNS;
    }
    String[] keyColumnStrings = keyColumnParamValue.split(",");
    keyColumns = new ArrayList<Integer>();
    for (int i = 0; i < keyColumnStrings.length; i++) {
        try {
            if (StringUtils.isNotBlank(keyColumnStrings[i])) {
                keyColumns.add(i, Integer.parseInt(keyColumnStrings[i].trim()));
            }
        } catch (NumberFormatException e) {
            LOG.error("Could not identify key column for value: '" + keyColumnStrings[i]
                    + "'\nList of key columns is corrupted!", e);
            throw e;
        }
    }
    LOG.debug("Init param: keyColumns = " + keyColumnParamValue);

    // Setting the columns that will be ignored while creating the content
    // objects.
    String ignoreColumnParamValue = getInitParams().getProperty(CSV_PROPERTY_IGNORECOLUMNS,
            CSV_DEFAULT_IGNORECOLUMNS);
    if (StringUtils.isBlank(ignoreColumnParamValue)) {
        ignoreColumnParamValue = CSV_DEFAULT_IGNORECOLUMNS;
    }
    String[] ignoreColumnStrings = ignoreColumnParamValue.split(",");
    ignoreColumns = new ArrayList<Integer>();
    for (int i = 0; i < ignoreColumnStrings.length; i++) {
        try {
            if (StringUtils.isNotBlank(ignoreColumnStrings[i])) {
                ignoreColumns.add(i, Integer.parseInt(ignoreColumnStrings[i].trim()));
            }
        } catch (NumberFormatException e) {
            LOG.error("Could not identify key column for value: '" + ignoreColumnStrings[i]
                    + "'\nList of key columns is incomplete!", e);
            throw e;
        }
    }
    LOG.debug("Init param: ignoreColumnStrings = " + ignoreColumnStrings);

    // Setting the zero-based number of the modificationDate-column.
    String modificationDateColumnValue = getInitParams().getProperty(CSV_PROPERTY_MODIFICATIONDATECOLUMN,
            CSV_DEFAULT_MODIFICATIONDATECOLUMN);
    modificationDateColumn = Integer
            .parseInt(StringUtils.isNotBlank(modificationDateColumnValue) ? modificationDateColumnValue.trim()
                    : CSV_DEFAULT_NAMECOLUMN);
    LOG.debug("Init param: modificationDateColumn = " + modificationDateColumn);

    modified = true;
    contentMap = new HashMap<String, Content>();

    String multiValueDelimitersParam = getInitParams().getProperty(CSV_PROPERTY_MULTIVALUEDELIMITERS);
    LOG.debug("Init param: multiValueDelimiters = " + multiValueDelimitersParam);

    if (StringUtils.isNotBlank(multiValueDelimitersParam)) {
        try {
            @SuppressWarnings("unchecked")
            Map<String, String> multiValueDelimitersAsStrings = new ObjectMapper()
                    .readValue(multiValueDelimitersParam, Map.class);
            multiValueDelimiters = new HashMap<Integer, Pattern>();
            for (Entry<String, String> entry : multiValueDelimitersAsStrings.entrySet()) {
                Integer columnNumber = Integer.valueOf(entry.getKey());
                Pattern delimiter = Pattern.compile(entry.getValue());
                multiValueDelimiters.put(columnNumber, delimiter);
            }
        } catch (JsonParseException e) {
            throw new IllegalArgumentException("Could not read multiValueDelimiters", e);
        } catch (JsonMappingException e) {
            throw new IllegalArgumentException("Could not read multiValueDelimiters", e);
        } catch (IOException e) {
            throw new IllegalArgumentException("Could not read multiValueDelimiters", e);
        }
    }
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * Adjusts the given artifact template to conform with the repository format
 * //w w  w  . ja  v  a 2  s  .co m
 * We import the files given at the artifact references
 * 
 * @throws InvalidCSARException
 * @throws IOException
 */
private void adjustArtifactTemplate(Path rootPath, TOSCAMetaFile tmf, ArtifactTemplateId atid,
        TArtifactTemplate ci, final List<String> errors) throws IOException {
    ArtifactReferences refs = ci.getArtifactReferences();
    if (refs == null) {
        // no references stored - break
        return;
    }
    List<TArtifactReference> refList = refs.getArtifactReference();
    Iterator<TArtifactReference> iterator = refList.iterator();
    while (iterator.hasNext()) {
        TArtifactReference ref = iterator.next();
        String reference = ref.getReference();
        // URLs are stored encoded -> undo the encoding
        reference = Util.URLdecode(reference);

        URI refURI;
        try {
            refURI = new URI(reference);
        } catch (URISyntaxException e) {
            errors.add(String.format("Invalid URI %1$s", ref));
            continue;
        }
        if (refURI.isAbsolute()) {
            // Points to somewhere external
            // We have to do nothing
            continue;
        }

        // we remove the current element as it will be handled during the export
        iterator.remove();

        Path path = rootPath.resolve(reference);
        if (!Files.exists(path)) {
            errors.add(String.format("Reference %1$s not found", reference));
            return;
        }
        Set<Path> allFiles;
        if (Files.isRegularFile(path)) {
            allFiles = new HashSet<Path>();
            allFiles.add(path);
        } else {
            assert (Files.isDirectory(path));
            Path localRoot = rootPath.resolve(path);
            List<Object> includeOrExclude = ref.getIncludeOrExclude();

            if (includeOrExclude.get(0) instanceof TArtifactReference.Exclude) {
                // Implicit semantics of an exclude listed first:
                // include all files and then exclude the files matched by the pattern
                allFiles = this.getAllFiles(localRoot);
            } else {
                // semantics if include lited as first:
                // same as listed at other places
                allFiles = new HashSet<>();
            }

            for (Object object : includeOrExclude) {
                if (object instanceof TArtifactReference.Include) {
                    this.handleInclude((TArtifactReference.Include) object, localRoot, allFiles);
                } else {
                    assert (object instanceof TArtifactReference.Exclude);
                    this.handleExclude((TArtifactReference.Exclude) object, localRoot, allFiles);
                }
            }
        }
        this.importAllFiles(allFiles, atid, tmf, rootPath, errors);
    }

    if (refList.isEmpty()) {
        // everything is imported and is a file stored locally
        // we don't need the references stored locally: they are generated on the fly when exporting
        ci.setArtifactReferences(null);
    }
}

From source file:org.opencms.staticexport.CmsDefaultLinkSubstitutionHandler.java

/**
 * @see org.opencms.staticexport.I_CmsLinkSubstitutionHandler#getRootPath(org.opencms.file.CmsObject, java.lang.String, java.lang.String)
 *///ww  w.jav a2  s .  com
public String getRootPath(CmsObject cms, String targetUri, String basePath) {

    if (cms == null) {
        // required by unit test cases
        return targetUri;
    }

    URI uri;
    String path;
    String fragment;
    String query;
    String suffix;

    // malformed uri
    try {
        uri = new URI(targetUri);
        path = uri.getPath();

        fragment = uri.getFragment();
        if (fragment != null) {
            fragment = "#" + fragment;
        } else {
            fragment = "";
        }

        query = uri.getQuery();
        if (query != null) {
            query = "?" + query;
        } else {
            query = "";
        }
    } catch (Exception e) {
        if (LOG.isWarnEnabled()) {
            LOG.warn(Messages.get().getBundle().key(Messages.LOG_MALFORMED_URI_1, targetUri), e);
        }
        return null;
    }

    // concatenate query and fragment 
    suffix = query.concat(fragment);

    // opaque URI
    if (uri.isOpaque()) {
        return null;
    }

    // absolute URI (i.e. URI has a scheme component like http:// ...)
    if (uri.isAbsolute()) {
        CmsSiteMatcher matcher = new CmsSiteMatcher(targetUri);
        if (OpenCms.getSiteManager().isMatching(matcher)) {
            if (path.startsWith(OpenCms.getSystemInfo().getOpenCmsContext())) {
                path = path.substring(OpenCms.getSystemInfo().getOpenCmsContext().length());
            }
            boolean isWorkplaceServer = OpenCms.getSiteManager().isWorkplaceRequest(matcher);
            if (isWorkplaceServer) {
                String pathForCurrentSite = cms.getRequestContext().addSiteRoot(path);
                String pathForMatchedSite = cms.getRequestContext()
                        .addSiteRoot(OpenCms.getSiteManager().matchSite(matcher).getSiteRoot(), path);
                String originalSiteRoot = cms.getRequestContext().getSiteRoot();
                String selectedPath = pathForCurrentSite;
                try {
                    cms.getRequestContext().setSiteRoot("");
                    // the path for the current site normally is preferred, but if it doesn't exist and the path for the matched site
                    // does exist, then use the path for the matched site 
                    if (!cms.existsResource(pathForCurrentSite, CmsResourceFilter.ALL)
                            && cms.existsResource(pathForMatchedSite, CmsResourceFilter.ALL)) {
                        selectedPath = pathForMatchedSite;
                    }
                } finally {
                    cms.getRequestContext().setSiteRoot(originalSiteRoot);
                }
                return selectedPath + suffix;
            } else {
                // add the site root of the matching site
                return cms.getRequestContext()
                        .addSiteRoot(OpenCms.getSiteManager().matchSite(matcher).getSiteRoot(), path + suffix);
            }
        } else {
            return null;
        }
    }

    // relative URI (i.e. no scheme component, but filename can still start with "/") 
    String context = OpenCms.getSystemInfo().getOpenCmsContext();
    if ((context != null) && path.startsWith(context)) {
        // URI is starting with opencms context
        String siteRoot = null;
        if (basePath != null) {
            siteRoot = OpenCms.getSiteManager().getSiteRoot(basePath);
        }

        // cut context from path
        path = path.substring(context.length());

        if (siteRoot != null) {
            // special case: relative path contains a site root, i.e. we are in the root site                
            if (!path.startsWith(siteRoot)) {
                // path does not already start with the site root, we have to add this path as site prefix
                return cms.getRequestContext().addSiteRoot(siteRoot, path + suffix);
            } else {
                // since path already contains the site root, we just leave it unchanged
                return path + suffix;
            }
        } else {
            // site root is added with standard mechanism
            return cms.getRequestContext().addSiteRoot(path + suffix);
        }
    }

    // URI with relative path is relative to the given relativePath if available and in a site, 
    // otherwise invalid
    if (CmsStringUtil.isNotEmpty(path) && (path.charAt(0) != '/')) {
        if (basePath != null) {
            String absolutePath;
            int pos = path.indexOf("../../galleries/pics/");
            if (pos >= 0) {
                // HACK: mixed up editor path to system gallery image folder
                return CmsWorkplace.VFS_PATH_SYSTEM + path.substring(pos + 6) + suffix;
            }
            absolutePath = CmsLinkManager.getAbsoluteUri(path, cms.getRequestContext().addSiteRoot(basePath));
            if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
                return absolutePath + suffix;
            }
            // HACK: some editor components (e.g. HtmlArea) mix up the editor URL with the current request URL 
            absolutePath = CmsLinkManager.getAbsoluteUri(path,
                    cms.getRequestContext().getSiteRoot() + CmsWorkplace.VFS_PATH_EDITORS);
            if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
                return absolutePath + suffix;
            }
            // HACK: same as above, but XmlContent editor has one path element more
            absolutePath = CmsLinkManager.getAbsoluteUri(path,
                    cms.getRequestContext().getSiteRoot() + CmsWorkplace.VFS_PATH_EDITORS + "xmlcontent/");
            if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
                return absolutePath + suffix;
            }
        }

        return null;
    }

    // relative URI (= VFS path relative to currently selected site root)
    if (CmsStringUtil.isNotEmpty(path)) {
        return cms.getRequestContext().addSiteRoot(path) + suffix;
    }

    // URI without path (typically local link)
    return suffix;
}

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

@Override
public IResource newResource(URI uri) {
    final String sourceMethod = "newResource"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[] { uri });
    }/*from w ww.ja va  2 s . c o m*/
    if (!uri.isAbsolute()) {
        // URI is not absolute, so make it absolute.
        try {
            uri = getPlatformServices().getAppContextURI().resolve(uri.getPath());
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e);
        }
    }

    IResourceFactory factory = null;
    String scheme = uri.getScheme();

    for (IAggregatorExtension extension : getExtensions(IResourceFactoryExtensionPoint.ID)) {
        if (scheme.equals(extension.getAttribute(IResourceFactoryExtensionPoint.SCHEME_ATTRIBUTE))) {
            IResourceFactory test = (IResourceFactory) extension.getInstance();
            if (test.handles(uri)) {
                factory = test;
                break;
            }
        }
    }
    if (factory == null) {
        throw new UnsupportedOperationException("No resource factory for " + uri.toString() //$NON-NLS-1$
        );
    }

    IResource result = factory.newResource(uri);
    if (isTraceLogging) {
        log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, result);
    }
    return result;
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * In case plans are provided, the plans are imported into Winery's storage
 * /*  ww  w  . j a  v  a  2  s. c  o  m*/
 * @param rootPath the root path of the extracted csar
 * @param tmf the TOSCAMetaFile object used to determine the mime type of the plan
 * @param wid Winery's internal id of the service template
 * @param st the the service template to be imported {@inheritDoc}
 * 
 * @throws InvalidCSARException
 */
private void adjustServiceTemplate(Path rootPath, TOSCAMetaFile tmf, ServiceTemplateId wid, TServiceTemplate st,
        final List<String> errors) {
    TPlans plans = st.getPlans();
    if (plans != null) {
        for (TPlan plan : plans.getPlan()) {
            PlanModelReference refContainer = plan.getPlanModelReference();
            if (refContainer != null) {
                String ref = refContainer.getReference();
                if (ref != null) {
                    // URLs are stored encoded -> undo the encoding
                    ref = Util.URLdecode(ref);
                    URI refURI;
                    try {
                        refURI = new URI(ref);
                    } catch (URISyntaxException e) {
                        errors.add(String.format("Invalid URI %1$s", ref));
                        continue;
                    }
                    if (refURI.isAbsolute()) {
                        // Points to somewhere external
                        // This is a linked plan
                        // We have to do nothing
                        continue;
                    }
                    Path path = rootPath.resolve(ref);
                    if (!Files.exists(path)) {
                        // possibly, the reference is relative to the Definitions subfolder
                        // COS01 does not make any explicit statement how to resolve the reference here
                        path = rootPath.resolve("Definitions").resolve(ref);
                        if (!Files.exists(path)) {
                            errors.add(String.format("Plan reference %1$s not found", ref));
                            // we quickly remove the reference to reflect the not-found in the data
                            refContainer.setReference(null);
                            continue;
                        }
                    }
                    PlansId plansId = new PlansId(wid);
                    PlanId pid = new PlanId(plansId, new XMLId(plan.getId(), false));
                    if (Files.isDirectory(path)) {
                        errors.add(String.format(
                                "Reference %1$s is a directory and Winery currently does not support importing directories",
                                ref));
                        continue;
                    }
                    RepositoryFileReference fref = new RepositoryFileReference(pid,
                            path.getFileName().toString());
                    this.importFile(path, fref, tmf, rootPath, errors);

                    // file is imported
                    // Adjust the reference
                    refContainer.setReference(
                            "../" + Utils.getURLforPathInsideRepo(BackendUtils.getPathInsideRepo(fref)));
                }
            }
        }
    }
}

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);
    }/*from  w w  w. j  a  v  a  2  s  .c o  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:com.googlecode.jdeltasync.DeltaSyncClient.java

/**
 * Slightly modified version of {@link DefaultRedirectStrategy#getLocationURI(HttpRequest, HttpResponse, HttpContext)}
 * which also adds the query string from the original request URI to the new URI.
 *//*  ww w.j  av a 2 s  .co m*/
private URI getRedirectLocationURI(IDeltaSyncSession session, HttpUriRequest request, HttpResponse response,
        HttpContext context) throws DeltaSyncException {

    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new DeltaSyncException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue();
    if (session.getLogger().isDebugEnabled()) {
        session.getLogger().debug("Redirect requested to location '" + location + "'");
    }

    URI uri = null;
    try {
        uri = new URI(location);
        if (request.getURI().getRawQuery() != null) {
            String query = request.getURI().getRawQuery();
            uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
                    query, uri.getFragment());
        }
    } catch (URISyntaxException ex) {
        throw new DeltaSyncException("Invalid redirect URI: " + location, ex);
    }

    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final RequestConfig config = clientContext.getRequestConfig();

    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    try {
        if (!uri.isAbsolute()) {
            if (config.isRelativeRedirectsAllowed()) {
                throw new DeltaSyncException("Relative redirect location '" + uri + "' not allowed");
            }
            // Adjust location URI
            HttpHost target = clientContext.getTargetHost();
            if (target == null) {
                throw new IllegalStateException("Target host not available " + "in the HTTP context");
            }

            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        }
    } catch (URISyntaxException ex) {
        throw new DeltaSyncException(ex.getMessage(), ex);
    }

    RedirectLocations redirectLocations = (RedirectLocations) clientContext
            .getAttribute("http.protocol.redirect-locations");
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocations();
        context.setAttribute("http.protocol.redirect-locations", redirectLocations);
    }

    if (config.isCircularRedirectsAllowed()) {
        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new DeltaSyncException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new DeltaSyncException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Perform any desired modifications to a link which is <em>not</em> being
 * {@linkplain #rewriteProxiedFileLink(Page.Request, URL, URI, boolean, boolean) rewritten} to point back through this
 * channel.//  www. ja  v a  2  s .  com
 * 
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param proxiedFileURL The {@linkplain #getProxiedFileURL(Page.Request, Channel.Mode, boolean) proxied file URL}.
 * @param linkURI The {@link URI} of the link to rewrite.
 * @param hyperlink Is the <code>linkURI</code> a hyperlink?
 * @param absoluteURLRequired Does the result need to be {@linkplain URI#isAbsolute() absolute}?
 * @param resolvedLinkURL The <code>linkURI</code> after being resolved to it's actual location.
 * @return The rewritten link {@link URI}.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @see #rewriteProxiedFileLink(Page.Request, URL, URI, boolean, boolean)
 */
protected static final URI rewriteProxiedFileLinkOutsideChannel(final Page.Request pageRequest,
        final URL proxiedFileURL, final @Nullable URI linkURI, final boolean hyperlink,
        final boolean absoluteURLRequired, final URL resolvedLinkURL) throws WWWEEEPortal.Exception {
    if ((linkURI != null) && (linkURI.isAbsolute())) {
        return linkURI; // If a document author includes an absolute link, we generally want to just leave that as-is.
    }

    try {

        if ((!absoluteURLRequired) && (equalHostAndPort(proxiedFileURL, pageRequest.getBaseURL()))) {
            // They didn't author an absolute link, we don't require one, and since the resolved link points to our host/port, we have the opportunity to return a nice short non-absolute link...
            final StringBuffer sb = new StringBuffer();
            sb.append(resolvedLinkURL.getPath());
            if (resolvedLinkURL.getQuery() != null) {
                sb.append('?');
                sb.append(resolvedLinkURL.getQuery());
            }
            if (resolvedLinkURL.getRef() != null) {
                sb.append('#');
                sb.append(resolvedLinkURL.getRef());
            }
            return new URI(sb.toString());
        }

        return resolvedLinkURL.toURI();
    } catch (URISyntaxException urise) {
        throw new ContentManager.ContentException("Error constructing resolved link URI", urise);
    }
}