Example usage for java.net URI toASCIIString

List of usage examples for java.net URI toASCIIString

Introduction

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

Prototype

public String toASCIIString() 

Source Link

Document

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

Usage

From source file:com.marklogic.contentpump.CompressedRDFReader.java

@Override
protected void initStream(InputSplit inSplit) throws IOException, InterruptedException {
    setFile(((FileSplit) inSplit).getPath());
    FSDataInputStream fileIn = fs.open(file);
    URI zipURI = file.toUri();
    String codecString = conf.get(ConfigConstants.CONF_INPUT_COMPRESSION_CODEC,
            CompressionCodec.ZIP.toString());
    if (codecString.equalsIgnoreCase(CompressionCodec.ZIP.toString())) {
        zipIn = new ZipInputStream(fileIn);
        codec = CompressionCodec.ZIP;/*w  ww.  ja v  a2s.co m*/
        while (true) {
            try {
                currZipEntry = ((ZipInputStream) zipIn).getNextEntry();
                if (currZipEntry == null) {
                    break;
                }
                if (currZipEntry.getSize() != 0) {
                    subId = currZipEntry.getName();
                    break;
                }
            } catch (IllegalArgumentException e) {
                LOG.warn("Skipped a zip entry in : " + file.toUri() + ", reason: " + e.getMessage());
            }
        }
        if (currZipEntry == null) { // no entry in zip
            LOG.warn("No valid entry in zip:" + file.toUri());
            return;
        }
        ByteArrayOutputStream baos;
        long size = currZipEntry.getSize();
        if (size == -1) {
            baos = new ByteArrayOutputStream();
            // if we don't know the size, assume it's big!
            initParser(zipURI.toASCIIString() + "/" + subId, INMEMORYTHRESHOLD);
        } else {
            baos = new ByteArrayOutputStream((int) size);
            initParser(zipURI.toASCIIString() + "/" + subId, size);
        }
        int nb;
        while ((nb = zipIn.read(buf, 0, buf.length)) != -1) {
            baos.write(buf, 0, nb);
        }
        parse(subId, new ByteArrayInputStream(baos.toByteArray()));
    } else if (codecString.equalsIgnoreCase(CompressionCodec.GZIP.toString())) {
        long size = inSplit.getLength();
        zipIn = new GZIPInputStream(fileIn);
        codec = CompressionCodec.GZIP;
        initParser(zipURI.toASCIIString(), size * COMPRESSIONFACTOR);
        parse(file.getName(), zipIn);
    } else {
        throw new UnsupportedOperationException("Unsupported codec: " + codec.name());
    }
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Transition a delta resource from the Accepted to Committed state.
 *
 * Operation: PUT /api/sense/v1/deltas/{id}/actions/commit
 *
 * @param deltaId The identifier of the delta resource to commit.
 *
 * @return A RESTful response with status NO_CONTENT if successful.
 *///ww w . j  a v a2s.  c  o  m
@ApiOperation(value = "Transition a delta resource from the Accepted to Committed state.", notes = "The Resource Manager must verify the proposed delta commit and will "
        + "confirm success returning (204 No Content).", response = DeltaResource.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.NO_CONTENT_CODE, message = HttpConstants.NO_CONTENT_MSG),
        @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_FOUND_CODE, message = HttpConstants.NOT_FOUND_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_ACCEPTABLE_CODE, message = HttpConstants.NOT_ACCEPTABLE_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), })
@RequestMapping(value = "/deltas/{" + HttpConstants.DELTAID_NAME
        + "}/actions/commit", method = RequestMethod.PUT, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public ResponseEntity<?> commitDelta(
        @PathVariable(HttpConstants.DELTAID_NAME) @ApiParam(value = HttpConstants.DELTAID_MSG, required = true) String deltaId) {

    // Get the requested resource URL.
    final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

    log.info("[SenseRmController] operation = {}, deltaId = {}", location, deltaId);

    DeltaResource d;
    try {
        // We need to return the current location of this resource in the response header.
        final HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Location", location.toASCIIString());

        // Query for the requested delta.
        DeltaResponse response = driver.commitDelta(deltaId).get();
        if (response == null || response.getStatus() != Status.NO_CONTENT) {
            return toResponseEntity(headers, response);
        }

        DeltaResource delta = response.getDelta().get();
        log.info("[SenseRmController] commitDelta deltaId = {}, lastModified = {}", delta.getId(),
                delta.getLastModified());

        return new ResponseEntity<>(headers, HttpStatus.NO_CONTENT);
    } catch (InterruptedException | ExecutionException ex) {
        log.error("getDelta failed, ex = {}", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.keycloak.testsuite.adapter.servlet.DemoServletsAdapterTest.java

@Test
public void testCallURLWithAccessToken() throws Exception {
    // test login to customer-portal which does a bearer request to customer-db
    URI applicationURL = inputPortalNoAccessToken.getUriBuilder().clone()
            .queryParam("access_token", "invalid_token").build();

    driver.navigate().to(applicationURL.toURL());

    assertEquals(applicationURL.toASCIIString(), driver.getCurrentUrl());
    inputPortalNoAccessToken.execute("hello");
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
}

From source file:com.connectsdk.service.DLNAService.java

String encodeURL(String mediaURL)
        throws MalformedURLException, URISyntaxException, UnsupportedEncodingException {
    if (mediaURL == null || mediaURL.isEmpty()) {
        return "";
    }//from  w  w  w  .  jav a  2s. com
    String decodedURL = URLDecoder.decode(mediaURL, "UTF-8");
    if (decodedURL.equals(mediaURL)) {
        URL url = new URL(mediaURL);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        return uri.toASCIIString();
    }
    return mediaURL;
}

From source file:uk.ac.open.kmi.iserve.sal.manager.impl.RegistryManagerImpl.java

private List<Service> getServicesFromRemoteLocation(String mediaType, boolean nativeFormat,
        URI servicesContentLocation) throws ServiceException {
    if (servicesContentLocation == null)
        throw new ServiceException("Unable to parse the saved document. Operation aborted.");

    List<Service> services = null;
    if (nativeFormat) {
        // Parse it directly
        ServiceReader reader = new ServiceReaderImpl();
        Syntax syntax = MediaType.NATIVE_MEDIATYPE_SYNTAX_MAP.get(mediaType);
        try {/*from w  w  w  . ja v  a2s  . co  m*/
            services = reader.parse(servicesContentLocation.toURL().openStream(), null, syntax);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("Unable to retrieve the document");
        }
    } else {
        // Its an external format: use the appropriate importer
        // We should have a suitable importer
        try {
            services = this.serviceTransformationEngine.transform(servicesContentLocation.toURL().openStream(),
                    servicesContentLocation.toASCIIString(), mediaType);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("Unable to retrieve the document");
        } catch (TransformationException e) {
            throw new ServiceException("Errors transforming the service", e);
        }
    }
    log.debug("Services parsed:", services);
    return services;
}

From source file:eu.scape_project.service.ConnectorService.java

private List<String> addFiles(final Session session, final List<File> files, final String repPath)
        throws RepositoryException {
    if (files == null) {
        return Collections.<String>emptyList();
    }/*ww w  .j  ava  2 s . c  om*/
    final List<String> fileUris = new ArrayList<>(files.size());
    final StringBuilder sparql = new StringBuilder("PREFIX scape: <" + SCAPE_NAMESPACE + "> ");
    for (File f : files) {

        final String fileId = (f.getIdentifier() != null) ? f.getIdentifier().getValue()
                : UUID.randomUUID().toString();
        final String filePath = repPath + "/" + fileId;

        URI fileUri = f.getUri();
        if (fileUri.getScheme() == null) {
            fileUri = URI.create("file:" + fileUri.toASCIIString());
        }

        /* create a datastream in fedora for this file */
        final FedoraObject fileObject = this.objectService.createObject(session, filePath);
        fileObject.getNode().addMixin("scape:file");
        final IdentifierTranslator subjects = new DefaultIdentifierTranslator();
        final String uri = subjects.getSubject(fileObject.getPath()).getURI();

        /* add the metadata */
        if (f.getTechnical() != null) {
            addMetadata(session, f.getTechnical(), filePath + "/TECHNICAL");
        }

        /* add all bitstreams as child objects */
        if (f.getBitStreams() != null) {
            for (final String bsUri : addBitStreams(session, f.getBitStreams(), "/" + filePath)) {
                sparql.append("INSERT DATA {<" + uri + "> " + prefix(HAS_BITSTREAM) + " \"" + bsUri + "\"};");
            }
        }
        String fileName = f.getFilename();
        if (fileName == null) {
            fileName = f.getUri().toASCIIString().substring(f.getUri().toASCIIString().lastIndexOf('/') + 1);
        }
        final String mimeType = (f.getMimetype() != null) ? f.getMimetype() : "application/binary";

        sparql.append("INSERT DATA {<" + uri + "> " + prefix(HAS_TYPE) + " \"file\"};");
        sparql.append("INSERT DATA {<" + uri + "> " + prefix(HAS_FILENAME) + " \"" + fileName + "\"};");
        sparql.append("INSERT DATA {<" + uri + "> " + prefix(HAS_MIMETYPE) + " \"" + mimeType + "\"};");
        sparql.append("INSERT DATA {<" + uri + "> " + prefix(HAS_INGEST_SOURCE) + " \"" + f.getUri() + "\"};");

        if (this.referencedContent) {
            /* only write a reference to the file URI as a node property */
            sparql.append(
                    "INSERT DATA {<" + uri + "> " + prefix(HAS_REFERENCED_CONTENT) + " \"" + fileUri + "\"};");
        } else {
            /* load the actual binary data into the repo */
            LOG.info("reading binary from {}", fileUri.toASCIIString());
            try (final InputStream src = fileUri.toURL().openStream()) {
                final Node fileDs = this.datastreamService
                        .createDatastream(session, filePath + "/DATA", f.getMimetype(), null, src)
                        .getContentNode();
            } catch (IOException | InvalidChecksumException e) {
                throw new RepositoryException(e);
            }
        }
        fileUris.add(uri);
        fileObject.updatePropertiesDataset(subjects, sparql.toString());
    }
    return fileUris;
}

From source file:org.apache.camel.component.routebox.strategy.RouteboxDispatcher.java

protected URI selectDispatchUri(RouteboxEndpoint endpoint, Exchange exchange) throws Exception {
    URI dispatchUri;

    List<URI> consumerUris = getInnerContextConsumerList(endpoint.getConfig().getInnerContext());
    if (consumerUris.isEmpty()) {
        throw new CamelExchangeException("No routes found to dispatch in Routebox at " + endpoint, exchange);
    } else if (consumerUris.size() == 1) {
        dispatchUri = consumerUris.get(0);
    } else {//from ww w .j  a va2  s  .  co  m
        if (!endpoint.getConfig().getDispatchMap().isEmpty()) {
            // apply URI string found in dispatch Map
            String key = exchange.getIn().getHeader("ROUTE_DISPATCH_KEY", String.class);
            if (endpoint.getConfig().getDispatchMap().containsKey(key)) {
                dispatchUri = new URI(endpoint.getConfig().getDispatchMap().get(key));
            } else {
                throw new CamelExchangeException(
                        "No matching entry found in Dispatch Map for ROUTE_DISPATCH_KEY: " + key, exchange);
            }
        } else {
            // apply dispatch strategy
            dispatchUri = endpoint.getConfig().getDispatchStrategy().selectDestinationUri(consumerUris,
                    exchange);
            if (dispatchUri == null) {
                throw new CamelExchangeException("No matching inner routes found for Operation", exchange);
            }
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Dispatch URI set to: " + dispatchUri.toASCIIString());
    }

    return dispatchUri;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.TestRMAppAttemptTransitions.java

private String getProxyUrl(RMAppAttempt appAttempt) {
    String url = null;//w  w w.j  a va  2  s.  co m
    final String scheme = WebAppUtils.getHttpSchemePrefix(conf);
    try {
        String proxy = WebAppUtils.getProxyHostAndPort(conf);
        URI proxyUri = ProxyUriUtils.getUriFromAMUrl(scheme, proxy);
        URI result = ProxyUriUtils.getProxyUri(null, proxyUri, appAttempt.getAppAttemptId().getApplicationId());
        url = result.toASCIIString();
    } catch (URISyntaxException ex) {
        Assert.fail();
    }
    return url;
}

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

private RobotsTxt getRobotsTxt(URI baseUri) throws IOException, URISyntaxException {
    String hostPort = this.getHostPort(baseUri);

    synchronized (hostPort.intern()) {
        RobotsTxt robotsTxt = null;//from   w ww. j  a v a  2  s  .c  o m

        // trying to get the robots.txt from cache
        robotsTxt = this.getFromCache(hostPort);

        // trying to get the robots.txt from file
        if (robotsTxt == null) {
            try {
                robotsTxt = this.loader.read(hostPort);
            } catch (Exception e) {
                this.logger.error(String.format(
                        "Unexpected '%s' while trying to load robots.txt file for domain '%s' from DB.",
                        e.getClass().getName(), baseUri.toASCIIString()), e);
            }

            if (robotsTxt != null) {
                this.putIntoCache(hostPort, robotsTxt);
            }
        }

        // trying to download the robots.txt
        boolean newDomain = robotsTxt == null;
        if (newDomain || (System.currentTimeMillis() - robotsTxt.getLoadedDate().getTime() > robotsTxt
                .getReloadInterval())) {
            robotsTxt = this.getFromWeb(URI.create(baseUri.toASCIIString() + "/robots.txt"));
            this.putIntoCache(hostPort, robotsTxt);
            this.loader.write(robotsTxt);
        }

        return robotsTxt;
    }
}

From source file:uk.ac.open.kmi.iserve.rest.sal.resource.DocumentsResource.java

@POST
@ApiOperation(value = "Add a new service document", notes = "Returns a message which contains the URI of the added document")
@ApiResponses(value = { @ApiResponse(code = 201, message = "Created document"),
        @ApiResponse(code = 500, message = "Internal error") })
@Consumes({ MediaType.TEXT_HTML, MediaType.TEXT_XML, MediaType.APPLICATION_XML, "application/rdf+xml",
        "text/turtle", "text/n3", "text/rdf+n3", MediaType.TEXT_PLAIN, "application/json",
        "application/wsdl+xml" })
@Produces({ MediaType.TEXT_HTML, "application/json" })
public Response addDocument(String document,
        @ApiParam(value = "Document location", required = true) @HeaderParam("Content-Location") String locationUri,
        @ApiParam(value = "Document Media type", required = true) @HeaderParam("Content-Type") String contentType,
        @ApiParam(value = "Response message media type", allowableValues = "application/json,text/html") @HeaderParam("Accept") String accept) {

    // TODO: Re add security
    //        if ( security.getUserPrincipal() == null ) {
    //         throw new MappableContainerException(
    //               new AuthenticationException(
    //                     "Authentication credentials are required\r\n",
    //                     "iServe SAL RESTful API"));
    //      }/*from   w w  w .j  a v  a  2s .  c  o  m*/
    //
    //      String userFoafId = security.getUserPrincipal().getName();

    // TODO check the actual encoding
    try {

        URI docUri;
        ServiceTransformationEngine transformationEngine = registryManager.getServiceTransformationEngine();
        if (document != null && !document.equals("")) {
            InputStream is = new ByteArrayInputStream(document.getBytes("UTF-8"));
            docUri = registryManager.getDocumentManager().createDocument(is,
                    transformationEngine.getFileExtension(contentType), contentType);
        } else {
            docUri = registryManager.getDocumentManager().createDocument(new URI(locationUri),
                    transformationEngine.getFileExtension(contentType), contentType);
        }
        String response;
        if (accept.contains(MediaType.TEXT_HTML)) {
            response = "<html>\n  <head>\n    <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n  </head>\n"
                    + "<body>\nA document is created at <a href='" + docUri.toString() + "'>"
                    + docUri.toString() + "</a>\n  </body>\n</html>";
        } else {
            JsonObject message = new JsonObject();
            message.add("message", new JsonPrimitive("A document is created at " + docUri.toString()));
            message.add("uri", new JsonPrimitive(docUri.toASCIIString()));
            response = message.toString();
        }
        return Response.status(Status.CREATED).contentLocation(docUri).entity(response).build();

    } catch (Exception e) {
        String error;
        if (accept.contains(MediaType.TEXT_HTML)) {
            error = "<html>\n  <head>\n    <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n  </head>\n"
                    + "<body>\nThere was an error while creating a document. Contact the system administrator. \n  </body>\n</html>";
        } else {
            JsonObject message = new JsonObject();
            message.add("message", new JsonPrimitive(
                    "There was an error while creating a document. Contact the system administrator."));
            error = message.toString();
        }
        e.printStackTrace();
        logger.error(e.toString());

        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(error).build();
    }

}