Example usage for java.net URI toURL

List of usage examples for java.net URI toURL

Introduction

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

Prototype

public URL toURL() throws MalformedURLException 

Source Link

Document

Constructs a URL from this URI.

Usage

From source file:org.apache.nifi.processors.aws.wag.AbstractAWSGatewayApiProcessor.java

protected void logRequest(ComponentLog logger, URI endpoint, GenericApiGatewayRequest request) {
    try {/*from   w  w w.ja  v a2 s  . c  om*/
        logger.debug("\nRequest to remote service:\n\t{}\t{}\t\n{}",
                new Object[] { endpoint.toURL().toExternalForm(), request.getHttpMethod(),
                        getLogString(request.getHeaders()) });
    } catch (MalformedURLException e) {
        logger.debug(e.getMessage());
    }
}

From source file:com.liferay.maven.plugins.AbstractLiferayMojo.java

protected List<String> getToolsClassPath() throws Exception {
    List<String> toolsClassPath = new ArrayList<String>();

    if ((appServerLibGlobalDir != null) && appServerLibGlobalDir.exists()) {
        Collection<File> globalJarFiles = FileUtils.listFiles(appServerLibGlobalDir, new String[] { "jar" },
                false);/*from   w ww.j  av a  2 s . c  o m*/

        for (File file : globalJarFiles) {
            URI uri = file.toURI();

            URL url = uri.toURL();

            toolsClassPath.add(url.toString());
        }

        Dependency jalopyDependency = createDependency("jalopy", "jalopy", "1.5rc3", "", "jar");

        addDependencyToClassPath(toolsClassPath, jalopyDependency);

        Dependency qdoxDependency = createDependency("com.thoughtworks.qdox", "qdox", "1.12", "", "jar");

        addDependencyToClassPath(toolsClassPath, qdoxDependency);

        ClassLoader globalClassLoader = toClassLoader(toolsClassPath);

        try {
            globalClassLoader.loadClass("javax.activation.MimeType");
        } catch (ClassNotFoundException cnfe) {
            Dependency activationDependency = createDependency("javax.activation", "activation", "1.1", "",
                    "jar");

            addDependencyToClassPath(toolsClassPath, activationDependency);
        }

        try {
            globalClassLoader.loadClass("javax.mail.Message");
        } catch (ClassNotFoundException cnfe) {
            Dependency mailDependency = createDependency("javax.mail", "mail", "1.4", "", "jar");

            addDependencyToClassPath(toolsClassPath, mailDependency);
        }

        try {
            globalClassLoader.loadClass("com.liferay.portal.kernel.util.ReleaseInfo");
        } catch (ClassNotFoundException cnfe) {
            Dependency portalServiceDependency = createDependency("com.liferay.portal", "portal-service",
                    liferayVersion, "", "jar");

            addDependencyToClassPath(toolsClassPath, portalServiceDependency);
        }

        try {
            globalClassLoader.loadClass("javax.portlet.Portlet");
        } catch (ClassNotFoundException cnfe) {
            Dependency portletApiDependency = createDependency("javax.portlet", "portlet-api", "2.0", "",
                    "jar");

            addDependencyToClassPath(toolsClassPath, portletApiDependency);
        }

        try {
            globalClassLoader.loadClass("javax.servlet.ServletRequest");
        } catch (ClassNotFoundException cnfe) {
            Dependency servletApiDependency = createDependency("javax.servlet", "servlet-api", "2.5", "",
                    "jar");

            addDependencyToClassPath(toolsClassPath, servletApiDependency);
        }

        try {
            globalClassLoader.loadClass("javax.servlet.jsp.JspPage");
        } catch (ClassNotFoundException cnfe) {
            Dependency jspApiDependency = createDependency("javax.servlet.jsp", "jsp-api", "2.1", "", "jar");

            addDependencyToClassPath(toolsClassPath, jspApiDependency);
        }
    } else {
        Dependency jalopyDependency = createDependency("jalopy", "jalopy", "1.5rc3", "", "jar");

        addDependencyToClassPath(toolsClassPath, jalopyDependency);

        Dependency qdoxDependency = createDependency("com.thoughtworks.qdox", "qdox", "1.12", "", "jar");

        addDependencyToClassPath(toolsClassPath, qdoxDependency);

        Dependency activationDependency = createDependency("javax.activation", "activation", "1.1", "", "jar");

        addDependencyToClassPath(toolsClassPath, activationDependency);

        Dependency mailDependency = createDependency("javax.mail", "mail", "1.4", "", "jar");

        addDependencyToClassPath(toolsClassPath, mailDependency);

        Dependency portalServiceDependency = createDependency("com.liferay.portal", "portal-service",
                liferayVersion, "", "jar");

        addDependencyToClassPath(toolsClassPath, portalServiceDependency);

        Dependency portletApiDependency = createDependency("javax.portlet", "portlet-api", "2.0", "", "jar");

        addDependencyToClassPath(toolsClassPath, portletApiDependency);

        Dependency servletApiDependency = createDependency("javax.servlet", "servlet-api", "2.5", "", "jar");

        addDependencyToClassPath(toolsClassPath, servletApiDependency);

        Dependency jspApiDependency = createDependency("javax.servlet.jsp", "jsp-api", "2.1", "", "jar");

        addDependencyToClassPath(toolsClassPath, jspApiDependency);
    }

    Collection<File> portalJarFiles = FileUtils.listFiles(appServerLibPortalDir, new String[] { "jar" }, false);

    for (File file : portalJarFiles) {
        URI uri = file.toURI();

        URL url = uri.toURL();

        toolsClassPath.add(url.toString());
    }

    getLog().debug("Tools class path:");

    for (String path : toolsClassPath) {
        getLog().debug("\t" + path);
    }

    return toolsClassPath;
}

From source file:ddf.catalog.resource.impl.URLResourceReader.java

private ResourceResponse retrieveFileProduct(URI resourceURI, String productName, String bytesToSkip)
        throws ResourceNotFoundException {
    URLConnection connection = null;
    try {//  w ww  .  j a v  a 2s  .  c om
        LOGGER.debug("Opening connection to: {}", resourceURI.toString());
        connection = resourceURI.toURL().openConnection();

        productName = StringUtils.defaultIfBlank(
                handleContentDispositionHeader(connection.getHeaderField(HttpHeaders.CONTENT_DISPOSITION)),
                productName);

        String mimeType = getMimeType(resourceURI, productName);

        InputStream is = connection.getInputStream();

        skipBytes(is, bytesToSkip);

        return new ResourceResponseImpl(
                new ResourceImpl(new BufferedInputStream(is), mimeType, FilenameUtils.getName(productName)));
    } catch (MimeTypeResolutionException | IOException e) {
        LOGGER.error("Error retrieving resource", e);
        throw new ResourceNotFoundException("Unable to retrieve resource at: " + resourceURI.toString(), e);
    }
}

From source file:org.apache.taverna.component.profile.ComponentProfileImpl.java

public ComponentProfileImpl(Registry registry, URI profileURI, BaseProfileLocator base)
        throws ComponentException, MalformedURLException {
    this(registry, profileURI.toURL(), base);
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestAuditLogger.java

@Test
public void testWebHdfsAuditLogger() throws IOException, URISyntaxException {
    Configuration conf = new HdfsConfiguration();
    conf.set(DFS_NAMENODE_AUDIT_LOGGERS_KEY, DummyAuditLogger.class.getName());
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();

    GetOpParam.Op op = GetOpParam.Op.GETFILESTATUS;
    try {//w ww  .  j  av a 2 s . c o  m
        cluster.waitClusterUp();
        assertTrue(DummyAuditLogger.initialized);
        URI uri = new URI("http", NetUtils.getHostPortString(cluster.getNameNode().getHttpAddress()),
                "/webhdfs/v1/", op.toQueryString(), null);

        // non-proxy request
        HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
        conn.setRequestMethod(op.getType().toString());
        conn.connect();
        assertEquals(200, conn.getResponseCode());
        conn.disconnect();
        assertEquals(1, DummyAuditLogger.logCount);
        assertEquals("127.0.0.1", DummyAuditLogger.remoteAddr);

        // non-trusted proxied request
        conn = (HttpURLConnection) uri.toURL().openConnection();
        conn.setRequestMethod(op.getType().toString());
        conn.setRequestProperty("X-Forwarded-For", "1.1.1.1");
        conn.connect();
        assertEquals(200, conn.getResponseCode());
        conn.disconnect();
        assertEquals(2, DummyAuditLogger.logCount);
        assertEquals("127.0.0.1", DummyAuditLogger.remoteAddr);

        // trusted proxied request
        conf.set(ProxyServers.CONF_HADOOP_PROXYSERVERS, "127.0.0.1");
        ProxyUsers.refreshSuperUserGroupsConfiguration(conf);
        conn = (HttpURLConnection) uri.toURL().openConnection();
        conn.setRequestMethod(op.getType().toString());
        conn.setRequestProperty("X-Forwarded-For", "1.1.1.1");
        conn.connect();
        assertEquals(200, conn.getResponseCode());
        conn.disconnect();
        assertEquals(3, DummyAuditLogger.logCount);
        assertEquals("1.1.1.1", DummyAuditLogger.remoteAddr);
    } finally {
        cluster.shutdown();
    }
}

From source file:de.dfki.km.perspecting.obie.corpus.LabeledTextCorpus.java

public Reader getGroundTruth(final URI uri) throws Exception {
    if (labelFileMediaType == MediaType.DIRECTORY) {
        return new StringReader(FileUtils.readFileToString(new File(uri)));
    } else if (labelFileMediaType == MediaType.ZIP) {
        ZipFile zipFile = new ZipFile(labelFolder);
        String[] entryName = uri.toURL().getFile().split("/");
        ZipEntry entry = zipFile.getEntry(URLDecoder.decode(entryName[entryName.length - 1], "utf-8"));

        if (entry != null) {
            log.info("found labels for: " + uri.toString());
        } else {/*  ww w .j a  v a  2s . c o  m*/
            throw new Exception("did not found labels for: " + uri.toString());
        }
        return new InputStreamReader(zipFile.getInputStream(entry));
    } else {
        throw new Exception("Unsupported media format for labels: " + labelFileMediaType + ". "
                + "Please use zip or plain directories instead.");
    }
}

From source file:io.apiman.gateway.engine.impl.DefaultPluginRegistry.java

/**
 * Tries to download the plugin from the given remote maven repository.
 *//*from   ww w . j a v a 2  s. c  o  m*/
protected void downloadFromMavenRepo(PluginCoordinates coordinates, URI mavenRepoUrl,
        IAsyncResultHandler<File> handler) {
    String artifactSubPath = PluginUtils.getMavenPath(coordinates);
    try {
        File tempArtifactFile = File.createTempFile("_plugin", "dwn"); //$NON-NLS-1$ //$NON-NLS-2$
        URL artifactUrl = new URL(mavenRepoUrl.toURL(), artifactSubPath);
        downloadArtifactTo(artifactUrl, tempArtifactFile, handler);
    } catch (Exception e) {
        handler.handle(AsyncResultImpl.<File>create(e));
    }
}

From source file:com.spotify.helios.client.DefaultHttpConnector.java

private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
        final Map<String, List<String>> headers, final String endpointHost) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
                Joiner.on(',').withKeyValueSeparator("=").join(headers), entity.length,
                Json.asPrettyStringUnchecked(entity));
    } else {//from w w w.  j  a v a2s .  c  o  m
        log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
    }

    final HttpURLConnection connection = (HttpURLConnection) ipUri.toURL().openConnection();
    handleHttps(connection, endpointHost, hostnameVerifierProvider, extraHttpsHandler);

    connection.setRequestProperty("Accept-Encoding", "gzip");
    connection.setInstanceFollowRedirects(false);
    connection.setConnectTimeout(httpTimeoutMillis);
    connection.setReadTimeout(httpTimeoutMillis);
    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        for (final String value : header.getValue()) {
            connection.addRequestProperty(header.getKey(), value);
        }
    }
    if (entity.length > 0) {
        connection.setDoOutput(true);
        connection.getOutputStream().write(entity);
    }

    setRequestMethod(connection, method, connection instanceof HttpsURLConnection);

    return connection;
}

From source file:com.occamlab.te.web.TestServlet.java

public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {//from www . j  av a  2 s .  co  m
        FileItemFactory ffactory;
        ServletFileUpload upload;
        List /* FileItem */ items = null;
        HashMap<String, String> params = new HashMap<String, String>();
        boolean multipart = ServletFileUpload.isMultipartContent(request);
        if (multipart) {
            ffactory = new DiskFileItemFactory();
            upload = new ServletFileUpload(ffactory);
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString());
                }
            }
        } else {
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                params.put(name, request.getParameter(name));
            }
        }
        HttpSession session = request.getSession();
        ServletOutputStream out = response.getOutputStream();
        String operation = params.get("te-operation");
        if (operation.equals("Test")) {
            TestSession s = new TestSession();
            String user = request.getRemoteUser();
            File logdir = new File(conf.getUsersDir(), user);
            String mode = params.get("mode");
            RuntimeOptions opts = new RuntimeOptions();
            opts.setWorkDir(conf.getWorkDir());
            opts.setLogDir(logdir);
            if (mode.equals("retest")) {
                opts.setMode(Test.RETEST_MODE);
                String sessionid = params.get("session");
                String test = params.get("test");
                if (sessionid == null) {
                    int i = test.indexOf("/");
                    sessionid = i > 0 ? test.substring(0, i) : test;
                }
                opts.setSessionId(sessionid);
                if (test == null) {
                    opts.addTestPath(sessionid);
                } else {
                    opts.addTestPath(test);
                }
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        String profileId = entry.getValue();
                        int i = profileId.indexOf("}");
                        opts.addTestPath(sessionid + "/" + profileId.substring(i + 1));
                    }
                }
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else if (mode.equals("resume")) {
                opts.setMode(Test.RESUME_MODE);
                String sessionid = params.get("session");
                opts.setSessionId(sessionid);
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else {
                opts.setMode(Test.TEST_MODE);
                String sessionid = LogUtils.generateSessionId(logdir);
                s.setSessionId(sessionid);
                String sources = params.get("sources");
                s.setSourcesName(sources);
                SuiteEntry suite = conf.getSuites().get(sources);
                s.setSuiteName(suite.getId());
                //                    String suite = params.get("suite");
                //                    s.setSuiteName(suite);
                String description = params.get("description");
                s.setDescription(description);
                opts.setSessionId(sessionid);
                opts.setSourcesName(sources);
                opts.setSuiteName(suite.getId());
                ArrayList<String> profiles = new ArrayList<String>();
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        profiles.add(entry.getValue());
                        opts.addProfile(entry.getValue());
                    }
                }
                s.setProfiles(profiles);
                s.save(logdir);
            }
            String webdir = conf.getWebDirs().get(s.getSourcesName());
            //                String requestURI = request.getRequestURI();
            //                String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1);
            //                URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null);
            URI contextURI = new URI(request.getScheme(), null, request.getServerName(),
                    request.getServerPort(), request.getRequestURI(), null, null);
            opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString());
            //                URI baseURI = new URL(contextURI.toURL(), webdir).toURI();
            //                String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/";
            //                opts.setBaseURI(base);
            //System.out.println(opts.getSourcesName());
            TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts);
            //System.out.println(indexes.get(opts.getSourcesName()).toString());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            core.setOut(ps);
            core.setWeb(true);
            Thread thread = new Thread(core);
            session.setAttribute("testsession", core);
            thread.start();
            response.setContentType("text/xml");
            out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>");
        } else if (operation.equals("Stop")) {
            response.setContentType("text/xml");
            TECore core = (TECore) session.getAttribute("testsession");
            if (core != null) {
                core.stopThread();
                session.removeAttribute("testsession");
                out.println("<stopped/>");
            } else {
                out.println("<message>Could not retrieve core object</message>");
            }
        } else if (operation.equals("GetStatus")) {
            TECore core = (TECore) session.getAttribute("testsession");
            response.setContentType("text/xml");
            out.print("<status");
            if (core.getFormHtml() != null) {
                out.print(" form=\"true\"");
            }
            if (core.isThreadComplete()) {
                out.print(" complete=\"true\"");
                session.removeAttribute("testsession");
            }
            out.println(">");
            out.print("<![CDATA[");
            //                out.print(core.getOutput());
            out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' '));
            out.println("]]>");
            out.println("</status>");
        } else if (operation.equals("GetForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            String html = core.getFormHtml();
            core.setFormHtml(null);
            response.setContentType("text/html");
            out.print(html);
        } else if (operation.equals("SubmitForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            Document doc = DB.newDocument();
            Element root = doc.createElement("values");
            doc.appendChild(root);
            for (String key : params.keySet()) {
                if (!key.startsWith("te-")) {
                    Element valueElement = doc.createElement("value");
                    valueElement.setAttribute("key", key);
                    valueElement.appendChild(doc.createTextNode(params.get(key)));
                    root.appendChild(valueElement);
                }
            }
            if (multipart) {
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (!item.isFormField() && !item.getName().equals("")) {
                        File uploadedFile = new File(core.getLogDir(),
                                StringUtils.getFilenameFromString(item.getName()));
                        item.write(uploadedFile);
                        Element valueElement = doc.createElement("value");
                        String key = item.getFieldName();
                        valueElement.setAttribute("key", key);
                        if (core.getFormParsers().containsKey(key)) {
                            Element parser = core.getFormParsers().get(key);
                            URL url = uploadedFile.toURI().toURL();
                            Element resp = core.parse(url.openConnection(), parser, doc);
                            Element content = DomUtils.getElementByTagName(resp, "content");
                            if (content != null) {
                                Element child = DomUtils.getChildElement(content);
                                if (child != null) {
                                    valueElement.appendChild(child);
                                }
                            }
                        } else {
                            Element fileEntry = doc.createElementNS(CTL_NS, "file-entry");
                            fileEntry.setAttribute("full-path",
                                    uploadedFile.getAbsolutePath().replace('\\', '/'));
                            fileEntry.setAttribute("media-type", item.getContentType());
                            fileEntry.setAttribute("size", String.valueOf(item.getSize()));
                            valueElement.appendChild(fileEntry);
                        }
                        root.appendChild(valueElement);
                    }
                }
            }
            core.setFormResults(doc);
            response.setContentType("text/html");
            out.println("<html>");
            out.println("<head><title>Form Submitted</title></head>");
            out.print("<body onload=\"window.parent.update()\"></body>");
            out.println("</html>");
        }
    } catch (Throwable t) {
        throw new ServletException(t);
    }
}

From source file:org.eclipse.winery.bpmn2bpel.parser.Bpmn4JsonParser.java

@Override
public ManagementFlow parse(URI jsonFileUrl) throws ParseException {

    try {//from   ww w .  j a v  a 2  s.c  o m
        // general method, same as with data binding
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        // (note: can also use more specific type, like ArrayNode or
        // ObjectNode!)
        JsonNode rootNode = mapper.readValue(jsonFileUrl.toURL(), JsonNode.class);

        String prettyPrintedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
        log.debug("Creating management flow from following Json model:" + prettyPrintedJson);

        ManagementFlow managementFlow = new ManagementFlow();
        /* Contains the ids (values) of the target nodes of a certain node
         * (key is node id of this node) */
        Map<String, Set<String>> nodeWithTargetsMap = new HashMap<String, Set<String>>();

        /* Create model objects from Json nodes */
        log.debug("Creating node models...");
        Iterator<JsonNode> iter = rootNode.iterator();
        while (iter.hasNext()) {
            JsonNode jsonNode = (JsonNode) iter.next();

            /*
             * As top level elements just start events, end events and
             * management tasks expected which are transformed to tasks in
             * our management model
             */
            Task task = createTaskFromJson(jsonNode);
            /*
             * Task may be null if it could not be created due to missing or
             * incorrect fields/values in the Json node
             */
            if (task != null) {
                managementFlow.addVertex(task);

                // TODO GATEWAAAAYYYYSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
                // !!!!!!!!!!!!!!!!!!

                /*
                 * To create the links later, relate the id of the created
                 * node with its direct successor nodes
                 */
                nodeWithTargetsMap.put(task.getId(), extractNodeTargetIds(jsonNode));
            } else {
                String ignoredJsonNode = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
                log.warn(
                        "No model element could be created from following node due to missing or invalid keys/values :"
                                + ignoredJsonNode);
            }
        }

        /*
         * Now since all node models are created they can be linked with each other in the management flow
         */
        log.debug("Building management flow by relating node models...");
        Iterator<Map.Entry<String, Set<String>>> nodeWithTargetsMapIter = nodeWithTargetsMap.entrySet()
                .iterator();
        while (nodeWithTargetsMapIter.hasNext()) {
            Map.Entry<String, Set<String>> inputParamEntry = (Map.Entry<String, Set<String>>) nodeWithTargetsMapIter
                    .next();
            String srcNodeId = inputParamEntry.getKey();
            Node srcNode = managementFlow.getNode(srcNodeId);
            if (srcNode == null) {
                throw new Exception(
                        "Node with id '" + srcNodeId + "' could not be found in the management flow.");
            }

            /* Relate the source node with its link targets */
            Iterator<String> nodeTargetIdsIter = inputParamEntry.getValue().iterator();
            while (nodeTargetIdsIter.hasNext()) {
                String targetNodeId = (String) nodeTargetIdsIter.next();
                Node targetNode = managementFlow.getNode(targetNodeId);
                if (targetNode == null) {
                    throw new Exception(
                            "Node with id '" + targetNodeId + "' could not be found in the management flow.");
                }

                log.debug("Creating link between node with id '" + srcNodeId + "' and target node with id '"
                        + targetNodeId + "'");
                managementFlow.addEdge(srcNode, targetNode);
            }
        }

        return managementFlow;

    } catch (Exception e) {
        log.error("Error while creating management flow : " + e.getMessage());
        throw new ParseException(e);
    }

}