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:org.opendatakit.api.odktables.RealizedTableService.java

/**
 * There is already a row-by-row manifest at attachments/{rowId}/manifest This shows the list of
 * attachments for a table, similar to what you see in the aggregate interface This was ported
 * from Open Data Kit Aggregate's ServerDataServiceImpl.getInstanceFileInfoContents
 * // w w w  .  j a v a  2s. c  o m
 * @param httpHeaders
 * @return
 * @throws IOException
 * @throws ODKTaskLockException
 * @throws PermissionDeniedException
 * @throws ODKDatastoreException
 */
@GET
@Path("attachments/manifest")
@Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
        ApiConstants.MEDIA_APPLICATION_XML_UTF8 })
public Response getManifest(@Context HttpHeaders httpHeaders)
        throws IOException, ODKTaskLockException, PermissionDeniedException, ODKDatastoreException {
    UriBuilder ub = info.getBaseUriBuilder();
    ub.path(OdkTables.class);
    ub.path(OdkTables.class, "getTablesService");

    DbTableInstanceFiles blobStore = new DbTableInstanceFiles(tableId, cc);
    List<BinaryContent> contents = blobStore.getAllBinaryContents(cc);

    ArrayList<OdkTablesFileManifestEntry> completedSummaries = new ArrayList<OdkTablesFileManifestEntry>();
    for (BinaryContent entry : contents) {
        if (entry.getUnrootedFilePath() == null) {
            continue;
        }
        String rowId = entry.getTopLevelAuri();
        UriBuilder tmp = ub.clone().path(TableService.class, "getRealizedTable")
                .path(RealizedTableService.class, "getInstanceFiles")
                .path(InstanceFileService.class, "getFile");
        URI getFile = tmp.build(appId, tableId, schemaETag, rowId, entry.getUnrootedFilePath());
        String downloadUrl = getFile.toASCIIString() + "?" + FileService.PARAM_AS_ATTACHMENT + "=true";
        OdkTablesFileManifestEntry manifestEntry = new OdkTablesFileManifestEntry();
        manifestEntry.downloadUrl = downloadUrl;
        manifestEntry.contentLength = entry.getContentLength();
        manifestEntry.contentType = entry.getContentType();
        manifestEntry.filename = entry.getUnrootedFilePath();
        manifestEntry.md5hash = entry.getContentHash();
        completedSummaries.add(manifestEntry);

    }

    OdkTablesFileManifest manifest = new OdkTablesFileManifest(completedSummaries);

    ResponseBuilder rBuild = Response.ok(manifest).header(HttpHeaders.ETAG, "test")
            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
            .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true");
    return rBuild.build();

}

From source file:com.almende.eve.transport.ws.WsServerTransport.java

@Override
public void send(final URI receiverUri, final byte[] message, final String tag) throws IOException {
    if (remotes.containsKey(receiverUri)) {
        final Async remote = remotes.get(receiverUri);
        remote.sendBinary(ByteBuffer.wrap(message));
        remote.flushBatch();/*from  w  w  w  .  j a v a  2 s.  c o m*/
    } else {
        throw new IOException("Remote: " + receiverUri.toASCIIString() + " is currently not connected.");
    }
}

From source file:org.apache.olingo.ext.proxy.commons.AbstractInvocationHandler.java

protected ComplexType<?> getComplex(final String name, final ClientValue value, final Class<?> ref,
        final EntityInvocationHandler handler, final URI baseURI, final boolean collectionItem) {

    final URIBuilder targetURI;
    if (collectionItem) {
        targetURI = null;//from   ww  w . ja  v a2 s  .c o  m
    } else {
        targetURI = baseURI == null ? null
                : getClient().newURIBuilder(baseURI.toASCIIString()).appendPropertySegment(name);
    }

    final ComplexInvocationHandler complexHandler;
    Class<?> actualRef = ref;
    if (value == null) {
        complexHandler = ComplexInvocationHandler.getInstance(actualRef, service, targetURI);
    } else {
        actualRef = CoreUtils.getComplexTypeRef(service, value); // handle derived types
        complexHandler = ComplexInvocationHandler.getInstance(value.asComplex(), actualRef, service, targetURI);
    }

    complexHandler.setEntityHandler(handler);

    final ComplexType<?> res = ComplexType.class.cast(Proxy.newProxyInstance(
            Thread.currentThread().getContextClassLoader(), new Class<?>[] { actualRef }, complexHandler));

    return res;
}

From source file:org.callimachusproject.client.HttpUriClient.java

public HttpUriResponse getAnyResponse(HttpUriRequest request) throws IOException, ResponseException {
    HttpClientContext ctx = HttpClientContext.create();
    ctx.setCookieStore(new BasicCookieStore());
    CloseableHttpResponse response = execute(request, ctx);
    URI systemId;
    if (response instanceof HttpUriResponse) {
        systemId = ((HttpUriResponse) response).getURI();
    } else {// ww  w. ja  v  a  2  s  . com
        systemId = getSystemId(ctx);
    }
    if (response instanceof HttpUriResponse) {
        return (HttpUriResponse) response;
    } else {
        return new HttpUriResponse(systemId.toASCIIString(), response);
    }
}

From source file:com.epam.ta.reportportal.ws.controller.impl.UserController.java

@Override
@RequestMapping(value = "/bid", method = POST)
@ResponseBody/*  w  w w .j a v a 2 s . c o m*/
@ResponseStatus(CREATED)
@PreAuthorize("hasPermission(#createUserRQ.getDefaultProject(), 'projectLeadPermission')")
@ApiOperation("Register invitation for user who will be created")
public CreateUserBidRS createUserBid(@RequestBody @Validated CreateUserRQ createUserRQ, Principal principal,
        HttpServletRequest request) {
    /*
     * Use Uri components since they are aware of x-forwarded-host headers
     */
    URI rqUrl = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request)).replacePath(null)
            .replaceQuery(null).build().toUri();
    return createUserMessageHandler.createUserBid(createUserRQ, principal, rqUrl.toASCIIString());
}

From source file:org.ebayopensource.io.netty.http.snoop.HttpSnoopClient.java

public boolean run() throws Exception {
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "localhost" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/*from  ww w .j av  a  2 s.  c om*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        LOGGER.error("Only HTTP(S) is supported.");
        return false;
    }

    boolean ssl = "https".equalsIgnoreCase(scheme);

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(ssl));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        QueryStringEncoder encoder = new QueryStringEncoder(uri.toString());

        URI uriGet = null;
        try {
            uriGet = new URI(encoder.toString());
        } catch (URISyntaxException e) {
            LOGGER.error(e.getMessage());
        }

        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uriGet.toASCIIString());

        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
        return false;
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
    return true;
}

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

public Exchange dispatchAsync(RouteboxEndpoint endpoint, Exchange exchange) throws Exception {
    URI dispatchUri;
    Exchange reply;//from w ww  .j  av  a2 s.com

    if (LOG.isDebugEnabled()) {
        LOG.debug("Dispatching exchange " + exchange + " to endpoint " + endpoint.getEndpointUri());
    }

    dispatchUri = selectDispatchUri(endpoint, exchange);

    if (exchange.getPattern() == ExchangePattern.InOnly) {
        producer.asyncSend(dispatchUri.toASCIIString(), exchange);
        reply = exchange;
    } else {
        Future<Exchange> future = producer.asyncCallback(dispatchUri.toASCIIString(), exchange,
                new SynchronizationAdapter());
        reply = future.get(endpoint.getConfig().getConnectionTimeout(), TimeUnit.MILLISECONDS);
    }

    return reply;
}

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

public Exchange dispatchSync(RouteboxEndpoint endpoint, Exchange exchange) throws Exception {
    URI dispatchUri;
    Exchange reply;/*from  w  w  w .  j a  v a  2 s .  c o  m*/

    if (LOG.isDebugEnabled()) {
        LOG.debug("Dispatching exchange " + exchange + " to endpoint " + endpoint.getEndpointUri());
    }

    dispatchUri = selectDispatchUri(endpoint, exchange);

    if (exchange.getPattern() == ExchangePattern.InOnly) {
        reply = producer.send(dispatchUri.toASCIIString(), exchange);
    } else {
        reply = issueRequest(endpoint, ExchangePattern.InOut, exchange.getIn().getBody(),
                exchange.getIn().getHeaders());
    }

    return reply;
}

From source file:fr.acxio.tools.agia.ftp.FTPUploadTasklet.java

@Override
public RepeatStatus execute(StepContribution sContribution, ChunkContext sChunkContext) throws Exception {
    FTPClient aClient = ftpClientFactory.getFtpClient();

    RegexFilenameFilter aFilter = new RegexFilenameFilter();
    aFilter.setRegex(regexFilename);//from w  ww .  ja  va 2  s. com

    try {
        File aLocalDir = new File(localBaseDir);

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Listing : {} ({}) for upload to [{}]", localBaseDir, regexFilename,
                    aClient.getRemoteAddress().toString());
        }

        File[] aLocalFiles = aLocalDir.listFiles(aFilter);

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("  {} file(s) found", aLocalFiles.length);
        }

        for (File aLocalFile : aLocalFiles) {

            if (sContribution != null) {
                sContribution.incrementReadCount();
            }

            URI aRemoteFile = new URI(remoteBaseDir).resolve(aLocalFile.getName());
            InputStream aInputStream;
            aInputStream = new FileInputStream(aLocalFile);
            try {

                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info(" Uploading : {} => {}", aLocalFile.getAbsolutePath(),
                            aRemoteFile.toASCIIString());
                }

                aClient.storeFile(aRemoteFile.toASCIIString(), aInputStream);

                if (sContribution != null) {
                    sContribution.incrementWriteCount(1);
                }
            } finally {
                aInputStream.close();
            }
        }
    } finally {
        aClient.logout();
        aClient.disconnect();
    }

    return RepeatStatus.FINISHED;
}

From source file:org.apache.taverna.scufl2.translator.t2flow.t23activities.ExternalToolActivityParser.java

@Override
public boolean canHandlePlugin(URI activityURI) {
    String activityUriStr = activityURI.toASCIIString();
    if (activityUriStr.startsWith(usecaseActivityRavenUri.toASCIIString())
            && activityUriStr.endsWith(usecaseActivityClass))
        return true;
    return activityUriStr.startsWith(externalToolRavenUri.toASCIIString())
            && activityUriStr.endsWith(externalToolClass);
}