Example usage for java.net URI toString

List of usage examples for java.net URI toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns the content of this URI as a string.

Usage

From source file:com.tactfactory.harmony.utils.TactFileUtils.java

/**
 * Converts an absolute path to a path relative to working dir.
 * @param absolute The absolute path//  www . ja  v a2 s. c om
 * @param relative The relative path to use
 * @return The relative path
 */
public static String absoluteToRelativePath(final String absolute, final String relative) {
    String result = ".";

    final File abs = new File(absolute);
    final File workingDir = new File(relative);

    final URI resultString = workingDir.toURI().relativize(abs.toURI());

    if (!resultString.toString().equals("")) {
        result = resultString.toString();
    }

    if (result.startsWith("file:")) {
        result = result.substring("file:".length());

    }

    return result;
}

From source file:com.google.caja.ancillary.servlet.UploadPage.java

static void doUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Process the uploaded items
    List<ObjectConstructor> uploads = Lists.newArrayList();

    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        int maxUploadSizeBytes = 1 << 18;
        factory.setSizeThreshold(maxUploadSizeBytes); // In-memory threshold
        factory.setRepository(new File("/dev/null")); // Do not store on disk
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxUploadSizeBytes);

        writeHeader(resp);/*w ww  .  ja va 2s.com*/

        // Parse the request
        List<?> items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            resp.getWriter().write(Nodes.encode(ex.getMessage()));
            return;
        }

        for (Object fileItemObj : items) {
            FileItem item = (FileItem) fileItemObj; // Written for pre-generic java.
            if (!item.isFormField()) { // Then is a file
                FilePosition unk = FilePosition.UNKNOWN;
                String ct = item.getContentType();
                uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                        StringLiteral.valueOf(unk, item.getString()), "ip",
                        StringLiteral.valueOf(unk, item.getName()), "it",
                        ct != null ? StringLiteral.valueOf(unk, ct) : null));
            }
        }
    } else if (req.getParameter("url") != null) {
        List<URI> toFetch = Lists.newArrayList();
        boolean failed = false;
        for (String value : req.getParameterValues("url")) {
            try {
                toFetch.add(new URI(value));
            } catch (URISyntaxException ex) {
                if (!failed) {
                    failed = true;
                    resp.setStatus(500);
                    resp.setContentType("text/html;charset=UTF-8");
                }
                resp.getWriter().write("<p>Bad URI: " + Nodes.encode(ex.getMessage()));
            }
        }
        if (failed) {
            return;
        }
        writeHeader(resp);
        FilePosition unk = FilePosition.UNKNOWN;
        for (URI uri : toFetch) {
            try {
                Content c = UriFetcher.fetch(uri);
                if (c.isText()) {
                    uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                            StringLiteral.valueOf(unk, c.getText()), "ip",
                            StringLiteral.valueOf(unk, uri.toString()), "it",
                            StringLiteral.valueOf(unk, c.type.mimeType)));
                }
            } catch (IOException ex) {
                resp.getWriter()
                        .write("<p>" + Nodes.encode("Failed to fetch URI: " + uri + " : " + ex.getMessage()));
            }
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("Content not multipart");
        return;
    }

    Expression notifyParent = (Expression) QuasiBuilder.substV(
            "window.parent.uploaded([@uploads*], window.name)", "uploads", new ParseTreeNodeContainer(uploads));
    StringBuilder jsBuf = new StringBuilder();
    RenderContext rc = new RenderContext(new JsMinimalPrinter(new Concatenator(jsBuf))).withEmbeddable(true);
    notifyParent.render(rc);
    rc.getOut().noMoreTokens();

    HtmlQuasiBuilder b = HtmlQuasiBuilder.getBuilder(DomParser.makeDocument(null, null));

    Writer out = resp.getWriter();
    out.write(Nodes.render(b.substV("<script>@js</script>", "js", jsBuf.toString())));
}

From source file:com.ibm.stocator.fs.common.Utils.java

/**
 * Extract host name from the URI/*w  ww. ja  va2 s .  c o m*/
 *
 * @param uri object store uri
 * @return host name
 */
public static String getHost(URI uri) {
    String host = uri.getHost();
    if (host != null) {
        return host;
    }
    host = uri.toString();
    int sInd = host.indexOf("//") + 2;
    host = host.substring(sInd);
    int eInd = host.indexOf("/");
    host = host.substring(0, eInd);
    return host;
}

From source file:com.microsoft.alm.common.utils.UrlHelper.java

public static URI getMyWorkItemsURI(final URI projectUri) {
    // The default query when you navigate to the work items section is the "Assigned to me" query results
    return UrlHelper.createUri(projectUri.toString().concat(URL_SEPARATOR).concat(URL_WIT_PATH_SEGMENT));
}

From source file:eu.esdihumboldt.hale.io.haleconnect.HaleConnectUrnBuilder.java

private static String[] splitProjectUrn(URI urn) {
    if (urn == null) {
        throw new NullPointerException("URN must not be null");
    } else if (!SCHEME_HALECONNECT.equals(urn.getScheme().toLowerCase())) {
        throw new IllegalArgumentException(
                MessageFormat.format("URN must have scheme \"{0}\"", SCHEME_HALECONNECT));
    }/*from  w  ww . j  av  a 2  s .c om*/

    if (StringUtils.isEmpty(urn.getSchemeSpecificPart())) {
        throw new IllegalArgumentException(MessageFormat.format("Malformed URN: {0}", urn.toString()));
    }

    String[] parts = urn.getSchemeSpecificPart().split(":");
    if (parts.length != 4) {
        throw new IllegalArgumentException(MessageFormat.format("Malformed URN: {0}", urn.toString()));
    } else if (!"project".equals(parts[0])) {
        throw new IllegalArgumentException(MessageFormat.format("No a project URN: {0}", urn.toString()));
    }
    return parts;
}

From source file:eu.planets_project.tb.gui.backing.data.DigitalObjectBrowser.java

/**
 * adds the selected data to the design experiment stage (i.e. inputData)
 * @return//  w  ww .j  a va2  s  .c  o  m
 */
private static String addToDesignExperiment() {
    DigitalObjectBrowser fb = (DigitalObjectBrowser) JSFUtil.getManagedObject("DobBrowser");
    ExperimentBean expBean = (ExperimentBean) JSFUtil.getManagedObject("ExperimentBean");
    if (expBean == null)
        return "failure";
    // Add each of the selected items to the experiment:
    for (URI uri : fb.getSelectedUris()) {
        //add reference to the new experiment's backing bean
        expBean.addExperimentInputData(uri.toString());
    }
    // Clear any selection:
    fb.clearSelection();
    // Return: gotoStage2 in the browse new experiment wizard
    //return "goToStage2";
    NewExpWizardController.redirectToExpStage(expBean.getID(), 2);
    return "success";
}

From source file:eu.planets_project.tb.gui.backing.data.DigitalObjectBrowser.java

/**
 * adds the selected data to the evaluation stage. i.e. external evaluation data
 * @return/*from ww w  . ja va  2  s . co m*/
 */
private static String addToEvaluateExperiment() {
    DigitalObjectBrowser fb = (DigitalObjectBrowser) JSFUtil.getManagedObject("DobBrowser");
    ExperimentBean expBean = (ExperimentBean) JSFUtil.getManagedObject("ExperimentBean");
    if (expBean == null)
        return "failure";
    // Add each of the selected items to the experiment:
    for (URI uri : fb.getSelectedUris()) {
        //add reference to the new experiment's backing bean
        expBean.addEvaluationExternalDigoRef(uri.toString());
    }
    // Clear any selection:
    fb.clearSelection();
    // Return: gotoStage6 in the browse new experiment wizard
    //return "goToStage2";
    NewExpWizardController.redirectToExpStage(expBean.getID(), 6);
    return "success";
}

From source file:de.betterform.agent.web.WebUtil.java

/**
 * this method is responsible for passing all context information needed by the Adapter and Processor from
 * ServletRequest to Context. Will be called only once when the form-session is inited (GET).
 * <p/>//from w  w  w .j  a v a2 s. c  o m
 * <p/>
 * todo: better logging of context params
 *
 * @param request     the Servlet request to fetch params from
 * @param httpSession the Http Session context
 * @param processor   the XFormsProcessor which receives the context params
 * @param sessionkey  the key to identify the XFormsSession
 */
public static void setContextParams(HttpServletRequest request, HttpSession httpSession,
        XFormsProcessor processor, String sessionkey) throws XFormsConfigException {
    Map servletMap = new HashMap();
    servletMap.put(WebProcessor.SESSION_ID, sessionkey);
    processor.setContextParam(XFormsProcessor.SUBMISSION_RESPONSE, servletMap);

    //adding requestURI to context
    processor.setContextParam(WebProcessor.REQUEST_URI, WebUtil.getRequestURI(request));

    //adding request URL to context
    String requestURL = request.getRequestURL().toString();
    processor.setContextParam(WebProcessor.REQUEST_URL, requestURL);

    // the web app name with an '/' prepended e.g. '/betterform' by default
    String contextRoot = WebUtil.getContextRoot(request);
    processor.setContextParam(WebProcessor.CONTEXTROOT, contextRoot);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("context root of webapp: " + processor.getContextParam(WebProcessor.CONTEXTROOT));
    }

    String requestPath = "";
    URL url = null;
    String plainPath = "";
    try {
        url = new URL(requestURL);
        requestPath = url.getPath();
    } catch (MalformedURLException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    if (requestPath.length() != 0) {
        //adding request path e.g. '/betterform/forms/demo/registration.xhtml'
        processor.setContextParam(WebProcessor.REQUEST_PATH, requestPath);

        //adding filename of requested doc to context
        String fileName = requestPath.substring(requestPath.lastIndexOf('/') + 1, requestPath.length());//FILENAME xforms
        processor.setContextParam(FILENAME, fileName);

        if (requestURL.contains(contextRoot)) { //case1: contextRoot is a part of the URL
            //adding plainPath which is the part between contextroot and filename e.g. '/forms' for a requestPath of '/betterform/forms/Status.xhtml'
            plainPath = requestPath.substring(contextRoot.length() + 1,
                    requestPath.length() - fileName.length());
            processor.setContextParam(PLAIN_PATH, plainPath);
        } else {//case2: contextRoot is not a part of the URL take the part previous the filename.
            String[] urlParts = requestURL.split("/");
            plainPath = urlParts[urlParts.length - 2];
        }

        //adding contextPath - requestPath without the filename
        processor.setContextParam(CONTEXT_PATH, contextRoot + "/" + plainPath);
    }

    //adding session id to context
    processor.setContextParam(HTTP_SESSION_ID, httpSession.getId());
    //adding context absolute path to context

    //EXIST-WORKAROUND: TODO triple check ...
    //TODO: triple check where this is used.
    if (request.isRequestedSessionIdValid()) {
        processor.setContextParam(EXISTDB_USER, httpSession.getAttribute(EXISTDB_USER));
    }

    //adding pathInfo to context - attention: this is only available when a servlet is requested
    String s1 = request.getPathInfo();
    if (s1 != null) {
        processor.setContextParam(WebProcessor.PATH_INFO, s1);
    }
    processor.setContextParam(WebProcessor.QUERY_STRING,
            (request.getQueryString() != null ? request.getQueryString() : ""));

    //storing the realpath for webapp

    String realPath = WebFactory.getRealPath(".", httpSession.getServletContext());
    File f = new File(realPath);
    URI fileURI = f.toURI();

    processor.setContextParam(WebProcessor.REALPATH, fileURI.toString());
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("real path of webapp: " + realPath);
    }

    //storing the TransformerService
    processor.setContextParam(TransformerService.TRANSFORMER_SERVICE,
            httpSession.getServletContext().getAttribute(TransformerService.TRANSFORMER_SERVICE));
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("TransformerService: "
                + httpSession.getServletContext().getAttribute(TransformerService.TRANSFORMER_SERVICE));
    }

    //[2] read any request params that are *not* betterForm params and pass them into the context map
    Enumeration params = request.getParameterNames();
    String s;
    while (params.hasMoreElements()) {
        s = (String) params.nextElement();
        //store all request-params we don't use in the context map of XFormsProcessorImpl
        String value = request.getParameter(s);
        processor.setContextParam(s, value);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("added request param '" + s + "' added to context");
            LOGGER.debug("param value'" + value);
        }
    }

}

From source file:com.net2plan.utils.HTMLUtils.java

/**
 * Opens a browser for the given {@code URI}. It is supposed to avoid issues with KDE systems.
 *
 * @param uri URI to browse/*  w  ww . j a  va2  s.c  om*/
 */
public static void browse(URI uri) {
    try {
        if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
            Desktop.getDesktop().browse(uri);
            return;
        } else if (SystemUtils.IS_OS_UNIX
                && (new File("/usr/bin/xdg-open").exists() || new File("/usr/local/bin/xdg-open").exists())) {
            new ProcessBuilder("xdg-open", uri.toString()).start();
            return;
        }

        throw new UnsupportedOperationException(
                "Your operating system does not support launching browser from Net2Plan");
    } catch (IOException | UnsupportedOperationException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.lyo.client.oslc.samples.DoorsOauthSample.java

/**
 * Find the OSLC Instance Shape URL for a given OSLC resource type.  
 *
 * @param serviceProviderUrl/*w w w  . java 2 s . co  m*/
 * @param oslcDomain
 * @param oslcResourceType - the resource type of the desired query capability.   This may differ from the OSLC artifact type.
 * @return URL of requested Creation Factory or null if not found.
 * @throws IOException
 * @throws OAuthException
 * @throws URISyntaxException
 * @throws ResourceNotFoundException 
 */
public static ResourceShape lookupRequirementsInstanceShapesOLD(final String serviceProviderUrl,
        final String oslcDomain, final String oslcResourceType, OslcOAuthClient client,
        String requiredInstanceShape)
        throws IOException, OAuthException, URISyntaxException, ResourceNotFoundException {

    ClientResponse response = client.getResource(serviceProviderUrl, OSLCConstants.CT_RDF);
    ServiceProvider serviceProvider = response.getEntity(ServiceProvider.class);

    if (serviceProvider != null) {
        for (Service service : serviceProvider.getServices()) {
            URI domain = service.getDomain();
            if (domain != null && domain.toString().equals(oslcDomain)) {
                CreationFactory[] creationFactories = service.getCreationFactories();
                if (creationFactories != null && creationFactories.length > 0) {
                    for (CreationFactory creationFactory : creationFactories) {
                        for (URI resourceType : creationFactory.getResourceTypes()) {

                            //return as soon as domain + resource type are matched
                            if (resourceType.toString() != null
                                    && resourceType.toString().equals(oslcResourceType)) {
                                URI[] instanceShapes = creationFactory.getResourceShapes();
                                if (instanceShapes != null) {
                                    for (URI typeURI : instanceShapes) {
                                        response = client.getResource(typeURI.toString(), OSLCConstants.CT_RDF);
                                        ResourceShape resourceShape = response.getEntity(ResourceShape.class);
                                        String typeTitle = resourceShape.getTitle();
                                        if ((typeTitle != null)
                                                && (typeTitle.equalsIgnoreCase(requiredInstanceShape))) {
                                            return resourceShape;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    throw new ResourceNotFoundException(serviceProviderUrl, "InstanceShapes");
}