Example usage for java.net URI getFragment

List of usage examples for java.net URI getFragment

Introduction

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

Prototype

public String getFragment() 

Source Link

Document

Returns the decoded fragment component of this URI.

Usage

From source file:org.devnexus.aerogear.RestRunner.java

private URL appendQuery(String query, URL baseURL) {
    try {//  w w  w .  j a v a  2 s .c  o  m
        URI baseURI = baseURL.toURI();
        String baseQuery = baseURI.getQuery();
        if (baseQuery == null || baseQuery.isEmpty()) {
            baseQuery = query;
        } else {
            if (query != null && !query.isEmpty()) {
                baseQuery = baseQuery + "&" + query;
            }
        }

        if (baseQuery.isEmpty()) {
            baseQuery = null;
        }

        return new URI(baseURI.getScheme(), baseURI.getUserInfo(), baseURI.getHost(), baseURI.getPort(),
                baseURI.getPath(), baseQuery, baseURI.getFragment()).toURL();
    } catch (MalformedURLException ex) {
        Log.e(TAG, "The URL could not be created from " + baseURL.toString(), ex);
        throw new RuntimeException(ex);
    } catch (URISyntaxException ex) {
        Log.e(TAG, "Error turning " + query + " into URI query.", ex);
        throw new RuntimeException(ex);
    }
}

From source file:org.soyatec.windowsazure.blob.internal.Blob.java

protected BlobProperties downloadData(String blobName, BlobStream stream, String eTagIfNoneMatch,
        String eTagIfMatch, long offset, long length, NameValueCollection nvc,
        OutParameter<Boolean> localModified) throws StorageException {
    String containerName = getContainerName();
    ResourceUriComponents uriComponents = new ResourceUriComponents(container.getAccountName(), containerName,
            blobName);//w  ww .j a  v a2  s . com

    URI blobUri = HttpUtilities.createRequestUri(container.getBaseUri(), container.isUsePathStyleUris(),
            container.getAccountName(), containerName, blobName, container.getTimeout(), nvc, uriComponents,
            container.getCredentials());

    if (SSLProperties.isSSL()) {
        try {
            URI newBlobUri = new URI("https", null, blobUri.getHost(), 443, blobUri.getPath(),
                    blobUri.getQuery(), blobUri.getFragment());
            blobUri = newBlobUri;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    String httpMethod = (stream == null ? HttpMethod.Head : HttpMethod.Get);
    HttpRequest request = createHttpRequestForGetBlob(blobUri, httpMethod, eTagIfNoneMatch, eTagIfMatch);

    if (offset != 0 || length != 0) {
        // Use the blob storage custom header for range since the standard
        // HttpWebRequest.
        // AddRange accepts only 32 bit integers and so does not work for
        // large blobs.
        String rangeHeaderValue = MessageFormat.format(HeaderValues.RangeHeaderFormat, offset,
                offset + length - 1);
        request.addHeader(HeaderNames.StorageRange, rangeHeaderValue);
    }
    request.addHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2009_09_19);
    container.getCredentials().signRequest(request, uriComponents);
    BlobProperties blobProperties;

    try {
        HttpWebResponse response = null;
        if (SSLProperties.isSSL()) {
            SSLSocketFactory factory = SslUtil.createSSLSocketFactory(SSLProperties.getKeyStore(),
                    SSLProperties.getKeyStorePasswd(), SSLProperties.getTrustStore(),
                    SSLProperties.getTrustStorePasswd(), SSLProperties.getKeyAlias());
            response = HttpUtilities.getSSLReponse((HttpUriRequest) request, factory);
        } else {
            response = HttpUtilities.getResponse(request);
        }
        if (response.getStatusCode() == HttpStatus.SC_OK
                || response.getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) {

            blobProperties = blobPropertiesFromResponse(blobName, blobUri, response);
            if (stream != null) {
                InputStream responseStream = response.getStream();
                long byteCopied = Utilities.copyStream(responseStream, stream);
                response.close();
                if (blobProperties.getContentLength() > 0 && byteCopied < blobProperties.getContentLength()) {
                    throw new StorageServerException(StorageErrorCode.ServiceTimeout,
                            "Unable to read complete data from server", HttpStatus.SC_REQUEST_TIMEOUT, null);
                }
            } else {
                response.close();
            }
        } else if (response.getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED
                || response.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {

            if (eTagIfMatch != null)
                localModified.setValue(true);
            else if (eTagIfNoneMatch != null)
                localModified.setValue(false);
            HttpUtilities.processUnexpectedStatusCode(response);
            return null;
        } else if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND && stream == null) {
            return null; // check blob exist
        } else {
            HttpUtilities.processUnexpectedStatusCode(response);
            return null;
        }
        return blobProperties;
    } catch (Exception we) {
        throw HttpUtilities.translateWebException(we);
    }
}

From source file:com.mcxiaoke.next.http.util.URIBuilder.java

private void digestURI(final URI uri) {
    this.scheme = uri.getScheme();
    this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart();
    this.encodedAuthority = uri.getRawAuthority();
    this.host = uri.getHost();
    this.port = uri.getPort();
    this.encodedUserInfo = uri.getRawUserInfo();
    this.userInfo = uri.getUserInfo();
    this.encodedPath = uri.getRawPath();
    this.path = uri.getPath();
    this.encodedQuery = uri.getRawQuery();
    this.queryParams = parseQuery(uri.getRawQuery(), Charsets.UTF_8);
    this.encodedFragment = uri.getRawFragment();
    this.fragment = uri.getFragment();
}

From source file:org.opendatakit.api.filter.ProxyUrlSetFilter.java

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    String forwardedPort = requestContext.getHeaderString("x-forwarded-port");
    String forwardedProto = requestContext.getHeaderString("x-forwarded-proto");
    String host = requestContext.getHeaderString("host");

    UriInfo uriInfo = requestContext.getUriInfo();
    URI requestUri = uriInfo.getRequestUri();
    URI baseUri = uriInfo.getBaseUri();
    int forwardedPortInt = uriInfo.getRequestUri().getPort();

    if (StringUtils.isNotEmpty(forwardedPort) || StringUtils.isNotEmpty(forwardedProto)) {
        if (StringUtils.isNotEmpty(forwardedPort)) {
            try {
                forwardedPortInt = Integer.parseInt(forwardedPort);
            } catch (NumberFormatException e) {
                logger.error("Unable to parse x-forwarded-port number " + forwardedPort
                        + " Generated URLs in JSON responses may be wrong.");
                // Life goes on. Non-fatal.
            }//from   w w  w.  j  a va2 s.  c o m
        }
        if (StringUtils.isEmpty(forwardedProto)) {
            forwardedProto = uriInfo.getRequestUri().getScheme();
        }
        try {
            URI newRequestUri = new URI(forwardedProto, requestUri.getUserInfo(), host, forwardedPortInt,
                    requestUri.getPath(), requestUri.getQuery(), requestUri.getFragment());

            URI newBaseUri = new URI(forwardedProto, baseUri.getUserInfo(), host, forwardedPortInt,
                    baseUri.getPath(), baseUri.getQuery(), baseUri.getFragment());

            requestContext.setRequestUri(newBaseUri, newRequestUri);
        } catch (URISyntaxException e) {
            logger.error("Unable to update requestUri. Generated URLs in JSON responses may be wrong.");
            // Life goes on. Non-fatal.
        }

    }
}

From source file:org.dita.dost.writer.SeparateChunkTopicParser.java

@Override
public void write(final URI currentFile) throws DITAOTException {
    this.currentFile = currentFile;
    final URI hrefValue = toURI(getValue(rootTopicref, ATTRIBUTE_NAME_HREF));
    final URI copytoValue = toURI(getValue(rootTopicref, ATTRIBUTE_NAME_COPY_TO));
    final String scopeValue = getCascadeValue(rootTopicref, ATTRIBUTE_NAME_SCOPE);
    // Chimera path, has fragment
    URI parseFilePath;/*ww w  . j  av  a 2s .co  m*/
    final Collection<String> chunkValue = split(getValue(rootTopicref, ATTRIBUTE_NAME_CHUNK));
    final String processRoleValue = getCascadeValue(rootTopicref, ATTRIBUTE_NAME_PROCESSING_ROLE);
    boolean dotchunk = false;

    if (copytoValue != null) {
        if (hrefValue != null && hrefValue.getFragment() != null) {
            parseFilePath = setFragment(copytoValue, hrefValue.getFragment());
        } else {
            parseFilePath = copytoValue;
        }
    } else {
        parseFilePath = hrefValue;
    }

    try {
        // if the path to target file make sense
        currentParsingFile = currentFile.resolve(parseFilePath);
        URI outputFileName;
        /*
         * FIXME: we have code flaws here, references in ditamap need to
         * be updated to new created file.
         */
        String id = null;
        String firstTopicID = null;
        if (parseFilePath.getFragment() != null) {
            id = parseFilePath.getFragment();
            if (chunkValue.contains(CHUNK_SELECT_BRANCH)) {
                outputFileName = resolve(currentFile, id + FILE_EXTENSION_DITA);
                targetTopicId = id;
                startFromFirstTopic = false;
                selectMethod = CHUNK_SELECT_BRANCH;
            } else if (chunkValue.contains(CHUNK_SELECT_DOCUMENT)) {
                firstTopicID = getFirstTopicId(currentFile.resolve(parseFilePath).getPath());

                topicDoc = getTopicDoc(currentFile.resolve(parseFilePath));

                if (firstTopicID != null) {
                    outputFileName = resolve(currentFile, firstTopicID + FILE_EXTENSION_DITA);
                    targetTopicId = firstTopicID;
                } else {
                    outputFileName = resolve(currentParsingFile, null);
                    dotchunk = true;
                    targetTopicId = null;
                }
                selectMethod = CHUNK_SELECT_DOCUMENT;
            } else {
                outputFileName = resolve(currentFile, id + FILE_EXTENSION_DITA);
                targetTopicId = id;
                startFromFirstTopic = false;
                selectMethod = CHUNK_SELECT_TOPIC;
            }
        } else {
            firstTopicID = getFirstTopicId(currentFile.resolve(parseFilePath).getPath());

            topicDoc = getTopicDoc(currentFile.resolve(parseFilePath));

            if (firstTopicID != null) {
                outputFileName = resolve(currentFile, firstTopicID + FILE_EXTENSION_DITA);
                targetTopicId = firstTopicID;
            } else {
                outputFileName = resolve(currentParsingFile, null);
                dotchunk = true;
                targetTopicId = null;
            }
            selectMethod = CHUNK_SELECT_DOCUMENT;
        }
        if (copytoValue != null) {
            // use @copy-to value as the new file name
            outputFileName = resolve(currentFile, copytoValue.toString());
        }

        if (new File(outputFileName).exists()) {
            final URI t = outputFileName;
            outputFileName = resolve(currentFile, generateFilename());
            conflictTable.put(outputFileName, t);
            dotchunk = false;
        }
        output = new OutputStreamWriter(new FileOutputStream(new File(outputFileName)), UTF8);
        outputFile = outputFileName;

        if (!dotchunk) {
            final FileInfo fi = generateFileInfo(outputFile);
            job.add(fi);

            changeTable.put(currentFile.resolve(parseFilePath), setFragment(outputFileName, id));
            // new generated file
            changeTable.put(outputFileName, outputFileName);
        }

        // change the href value
        final URI newHref = setFragment(
                getRelativePath(currentFile.resolve(FILE_NAME_STUB_DITAMAP), outputFileName),
                firstTopicID != null ? firstTopicID : id);
        rootTopicref.setAttribute(ATTRIBUTE_NAME_HREF, newHref.toString());

        include = false;

        addStubElements();

        // Place siblingStub
        if (rootTopicref.getNextSibling() != null) {
            rootTopicref.getParentNode().insertBefore(siblingStub, rootTopicref.getNextSibling());
        } else {
            rootTopicref.getParentNode().appendChild(siblingStub);
        }

        reader.setErrorHandler(new DITAOTXMLErrorHandler(currentParsingFile.getPath(), logger));
        logger.info("Processing " + currentParsingFile);
        reader.parse(currentParsingFile.toString());
        output.flush();

        removeStubElements();
    } catch (final RuntimeException e) {
        throw e;
    } catch (final Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (output != null) {
                output.close();
                output = null;
                if (dotchunk) {
                    final File dst = new File(currentParsingFile);
                    final File src = new File(outputFile);
                    logger.debug("Delete " + currentParsingFile);
                    deleteQuietly(dst);
                    logger.debug("Move " + outputFile + " to " + currentParsingFile);
                    moveFile(src, dst);
                    final FileInfo fi = job.getFileInfo(outputFile);
                    if (fi != null) {
                        job.remove(fi);
                    }
                }
            }
        } catch (final Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
}

From source file:org.structr.rdfs.OWLParserv2.java

private <T extends RDFItem> void filter(final Collection<T> items) {

    for (final Iterator<T> it = items.iterator(); it.hasNext();) {

        final T t = it.next();
        final URI id = t.getId();
        final String idString = id.toString();
        final String fragment = id.getFragment();

        for (final String unwanted : unwantedPrefixes) {

            if (idString.startsWith(unwanted) || fragment.startsWith(unwanted)) {
                it.remove();/*from   w ww . ja v a2s.c  o  m*/
            }
        }
    }
}

From source file:org.dita.dost.module.GenMapAndTopicListModule.java

private FileInfo getOrCreateFileInfo(final Map<URI, FileInfo> fileInfos, final URI file) {
    assert file.getFragment() == null;
    final URI f = file.normalize();
    FileInfo.Builder b;//from  w  ww . j a  v a 2s  .  co m
    if (fileInfos.containsKey(f)) {
        b = new FileInfo.Builder(fileInfos.get(f));
    } else {
        b = new FileInfo.Builder().src(file);
    }
    b = b.uri(tempFileNameScheme.generateTempFileName(file));
    final FileInfo i = b.build();
    fileInfos.put(i.src, i);
    return i;
}

From source file:com.maestrodev.maestrocontinuumplugin.ContinuumWorker.java

private String getPomUrlWithCredentials() throws URISyntaxException {
    String pomUrl = getPomUrl();//from  w ww .j  a  v  a  2  s .co m
    String pomUsername = getPomUsername();
    if (pomUsername != null) {
        URI u = new URI(pomUrl);
        pomUrl = new URI(u.getScheme(), pomUsername + ":" + getPomPassword(), u.getHost(), u.getPort(),
                u.getPath(), u.getQuery(), u.getFragment()).toString();
    }
    return pomUrl;
}

From source file:org.codice.ddf.catalog.content.impl.FileSystemStorageProviderTest.java

@Test
public void testUpdateWithMultipleItems() throws Exception {
    CreateStorageResponse createResponse = assertContentItem(TEST_INPUT_CONTENTS, NITF_MIME_TYPE,
            TEST_INPUT_FILENAME);//from   w  w  w .  ja va 2 s  .c  o m
    URI unqualifiedUri = new URI(createResponse.getCreatedContentItems().get(0).getUri());

    createResponse = assertContentItemWithQualifier(TEST_INPUT_CONTENTS, NITF_MIME_TYPE, TEST_INPUT_FILENAME,
            createResponse.getCreatedContentItems().get(0).getId(), QUALIFIER);

    URI qualifiedUri = new URI(createResponse.getCreatedContentItems().get(0).getUri());

    String id = createResponse.getCreatedContentItems().get(0).getId();
    ByteSource byteSource = new ByteSource() {
        @Override
        public InputStream openStream() throws IOException {
            return IOUtils.toInputStream("Updated NITF");
        }
    };
    ContentItem updateItem = new ContentItemImpl(id, byteSource, NITF_MIME_TYPE, mock(Metacard.class));
    UpdateStorageRequest updateRequest = new UpdateStorageRequestImpl(Collections.singletonList(updateItem),
            null);

    assertUpdateRequest(updateRequest);

    updateItem = new ContentItemImpl(id, qualifiedUri.getFragment(), byteSource, NITF_MIME_TYPE,
            mock(Metacard.class));

    updateRequest = new UpdateStorageRequestImpl(Collections.singletonList(updateItem), null);

    assertUpdateRequest(updateRequest);
}