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.efaps.wikiutil.export.latex.WikiPage2Tex.java

/**
 * @param _uri              URI of the input file
 * @param _out              output file/*from   www . j  a  v  a 2 s  .  co  m*/
 * @param _structureLevel   current level of the section
 * @param _title            title of the Wiki page
 * @throws MalformedURLException if the <code>_uri</code> could not be
 *                               converted to an URL
 */
public WikiPage2Tex(final URI _uri, final File _out, final int _structureLevel, final String _title)
        throws MalformedURLException {
    this.url = _uri.toURL();
    this.texOut = _out;
    this.structureLevel = _structureLevel;
    this.title = _title;
}

From source file:de.sub.goobi.helper.tasks.CreatePdfFromServletThread.java

/**
 * Aufruf als Thread./*ww w. j a v a  2s .co m*/
 */
@Override
public void run() {
    setStatusProgress(30);
    if ((this.getProcess() == null) || (this.targetFolder == null) || (this.internalServletPath == null)) {
        setStatusMessage("parameters for temporary and final folder and internal servlet path not defined");
        setStatusProgress(-1);
        return;
    }
    GetMethod method = null;
    try {
        /*
         * define path for mets and pdfs
         */
        URL kitodoContentServerUrl = null;
        String contentServerUrl = ConfigCore.getParameter("kitodoContentServerUrl");
        new File("");
        URI tempPdf = fileService.createResource(this.getProcess().getTitle() + ".pdf");
        URI finalPdf = fileService.createResource(this.targetFolder, this.getProcess().getTitle() + ".pdf");
        Integer contentServerTimeOut = ConfigCore.getIntParameter("kitodoContentServerTimeOut", 60000);

        /*
         * using mets file
         */
        if (new MetadatenVerifizierung().validate(this.getProcess()) && (this.metsURL != null)) {
            /*
             * if no contentserverurl defined use internal
             * goobiContentServerServlet
             */
            if ((contentServerUrl == null) || (contentServerUrl.length() == 0)) {
                contentServerUrl = this.internalServletPath + "/gcs/gcs?action=pdf&metsFile=";
            }
            kitodoContentServerUrl = new URL(contentServerUrl + this.metsURL);

            /*
             * mets data does not exist or is invalid
             */
        } else {
            if ((contentServerUrl == null) || (contentServerUrl.length() == 0)) {
                contentServerUrl = this.internalServletPath + "/cs/cs?action=pdf&images=";
            }
            StringBuilder url = new StringBuilder();
            FilenameFilter filter = Helper.imageNameFilter;
            URI imagesDir = serviceManager.getProcessService().getImagesTifDirectory(true, this.getProcess());
            ArrayList<URI> meta = fileService.getSubUris(filter, imagesDir);
            ArrayList<String> filenames = new ArrayList<>();
            for (URI data : meta) {
                String file = "";
                file += data.toURL();
                filenames.add(file);
            }
            Collections.sort(filenames, new MetadatenHelper(null, null));
            for (String f : filenames) {
                url.append(f);
                url.append("$");
            }
            String imageString = url.substring(0, url.length() - 1);
            String targetFileName = "&targetFileName=" + this.getProcess().getTitle() + ".pdf";
            kitodoContentServerUrl = new URL(contentServerUrl + imageString + targetFileName);
        }

        /*
         * get pdf from servlet and forward response to file
         */

        HttpClient httpclient = new HttpClient();
        if (logger.isDebugEnabled()) {
            logger.debug("Retrieving: " + kitodoContentServerUrl.toString());
        }
        method = new GetMethod(kitodoContentServerUrl.toString());
        try {
            method.getParams().setParameter("http.socket.timeout", contentServerTimeOut);
            int statusCode = httpclient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("HttpStatus not ok");
                if (logger.isDebugEnabled()) {
                    logger.debug("Response is:\n" + method.getResponseBodyAsString());
                }
                return;
            }

            InputStream inStream = method.getResponseBodyAsStream();
            try (BufferedInputStream bis = new BufferedInputStream(inStream);
                    FileOutputStream fos = (FileOutputStream) fileService.write(tempPdf)) {
                byte[] bytes = new byte[8192];
                int count = bis.read(bytes);
                while ((count != -1) && (count <= 8192)) {
                    fos.write(bytes, 0, count);
                    count = bis.read(bytes);
                }
                if (count != -1) {
                    fos.write(bytes, 0, count);
                }
            }
            setStatusProgress(80);
        } finally {
            method.releaseConnection();
        }
        /*
         * copy pdf from temp to final destination
         */
        if (logger.isDebugEnabled()) {
            logger.debug("pdf file created: " + tempPdf + "; now copy it to " + finalPdf);
        }
        fileService.copyFile(tempPdf, finalPdf);
        if (logger.isDebugEnabled()) {
            logger.debug("pdf copied to " + finalPdf + "; now start cleaning up");
        }
        fileService.delete(tempPdf);
        if (this.metsURL != null) {
            File tempMets = new File(this.metsURL.toString());
            tempMets.delete();
        }
    } catch (Exception e) {
        logger.error("Error while creating pdf for " + this.getProcess().getTitle(), e);
        setStatusMessage("error " + e.getClass().getSimpleName() + " while pdf creation: " + e.getMessage());
        setStatusProgress(-1);

        /*
         * report Error to User as Error-Log
         */
        String text = "error while pdf creation: " + e.getMessage();
        URI uri = null;
        try {
            uri = fileService.createResource(this.targetFolder,
                    this.getProcess().getTitle() + ".PDF-ERROR.log");
        } catch (MalformedURLException e1) {
            logger.error(
                    "URI " + this.targetFolder + this.getProcess().getTitle() + ".PDF-ERROR.log is malformed",
                    e1);
        } catch (IOException e1) {
            logger.error("Ressource " + uri + " could not be created", e);
        }
        try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(fileService.write(uri)))) {
            output.write(text);
        } catch (IOException e1) {
            logger.error("Error while reporting error to user in file " + uri, e);
        }
        return;
    } finally {
        if (method != null) {
            method.releaseConnection();
        }

    }
    setStatusMessage("done");
    setStatusProgress(100);
}

From source file:org.opendatakit.api.odktables.FileService.java

@POST
@Path("{odkClientVersion}/{filePath:.*}")
public Response putFile(@PathParam("odkClientVersion") String odkClientVersion,
        @PathParam("filePath") List<PathSegment> segments, byte[] content)
        throws IOException, ODKTaskLockException, PermissionDeniedException, ODKDatastoreException {

    TreeSet<GrantedAuthorityName> ui = SecurityServiceUtil.getCurrentUserSecurityInfo(callingContext);
    if (!ui.contains(GrantedAuthorityName.ROLE_ADMINISTER_TABLES)) {
        throw new PermissionDeniedException("User does not belong to the 'Administer Tables' group");
    }/*from   w w w . jav  a  2 s  .c o  m*/

    if (segments.size() < 1) {
        return Response.status(Status.BAD_REQUEST).entity(FileService.ERROR_MSG_INSUFFICIENT_PATH)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    }
    String appRelativePath = constructPathFromSegments(segments);
    String tableId = FileManager.getTableIdForFilePath(appRelativePath);
    String contentType = req.getContentType();

    // DbTableFileInfo.NO_TABLE_ID -- means that we are working with app-level
    // permissions
    if (!DbTableFileInfo.NO_TABLE_ID.equals(tableId)) {
        userPermissions.checkPermission(appId, tableId, TablePermission.WRITE_PROPERTIES);
    }

    FileManager fm = new FileManager(appId, callingContext);

    FileContentInfo fi = new FileContentInfo(appRelativePath, contentType, Long.valueOf(content.length), null,
            content);

    ConfigFileChangeDetail outcome = fm.putFile(odkClientVersion, tableId, fi, userPermissions);

    UriBuilder ub = info.getBaseUriBuilder();
    ub.path(OdkTables.class, "getFilesService");
    URI self = ub.path(FileService.class, "getFile")
            .build(ArrayUtils.toArray(appId, odkClientVersion, appRelativePath), false);

    String locationUrl = self.toURL().toExternalForm();

    return Response.status((outcome == ConfigFileChangeDetail.FILE_UPDATED) ? Status.ACCEPTED : Status.CREATED)
            .header("Location", locationUrl)
            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
            .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
            .build();
}

From source file:org.apache.accumulo.start.classloader.AccumuloClassLoader.java

/**
 * Populate the list of URLs with the items in the classpath string
 *///w ww.  ja  va2s  .c o m
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "class path configuration is controlled by admin, not unchecked user input")
private static void addUrl(String classpath, ArrayList<URL> urls) throws MalformedURLException {
    classpath = classpath.trim();
    if (classpath.length() == 0)
        return;

    classpath = replaceEnvVars(classpath, System.getenv());

    // Try to make a URI out of the classpath
    URI uri = null;
    try {
        uri = new URI(classpath);
    } catch (URISyntaxException e) {
        // Not a valid URI
    }

    if (uri == null || !uri.isAbsolute() || (uri.getScheme() != null && uri.getScheme().equals("file://"))) {
        // Then treat this URI as a File.
        // This checks to see if the url string is a dir if it expand and get all jars in that
        // directory
        final File extDir = new File(classpath);
        if (extDir.isDirectory())
            urls.add(extDir.toURI().toURL());
        else {
            if (extDir.getParentFile() != null) {
                File[] extJars = extDir.getParentFile()
                        .listFiles((dir, name) -> name.matches("^" + extDir.getName()));
                if (extJars != null && extJars.length > 0) {
                    for (File jar : extJars)
                        urls.add(jar.toURI().toURL());
                } else {
                    log.debug("ignoring classpath entry {}", classpath);
                }
            } else {
                log.debug("ignoring classpath entry {}", classpath);
            }
        }
    } else {
        urls.add(uri.toURL());
    }

}

From source file:com.aurel.track.lucene.LuceneUtil.java

/**
 * Gets the context path of the application
 * @return//from www. j a  v  a2 s. c  o m
 */
public static String getContexPath() {
    URL url = null;
    File file;
    //get the application context path
    url = LuceneUtil.class.getResource("/../..");
    if (url == null) {
        return null;
    }
    if (url.getPath() != null) {
        file = new File(url.getPath());
        if (file.exists()) {
            return stripTrailingPathSeparator(url.getPath());
        }
    }
    //see Bug ID:  4466485 (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4466485) 
    URI uri = null;
    try {
        uri = new URI(url.toString());
    } catch (URISyntaxException e) {
        LOGGER.error("Getting the lucene index root URI from URL failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    if (uri == null) {
        return null;
    }
    //sometimes it is enough
    if (uri.getPath() != null) {
        file = new File(uri.getPath());
        if (file.exists()) {
            return stripTrailingPathSeparator(uri.getPath());
        }
    }

    try {
        url = uri.toURL();
    } catch (MalformedURLException e) {
    }
    if (url != null && url.getPath() != null) {
        file = new File(url.getPath());
        if (file.exists()) {
            return stripTrailingPathSeparator(url.getPath());
        }
    }
    return "";
}

From source file:com.favalike.http.GAEClientConnection.java

@Override
public void sendRequestHeader(HttpRequest request) throws HttpException, IOException {
    try {//  w w  w  .j  a v  a2 s  .c o m
        HttpHost host = route.getTargetHost();

        URI uri = new URI(host.getSchemeName() + "://" + host.getHostName()
                + ((host.getPort() == -1) ? "" : (":" + host.getPort())) + request.getRequestLine().getUri());

        this.request = new HTTPRequest(uri.toURL(), HTTPMethod.valueOf(request.getRequestLine().getMethod()),
                FetchOptions.Builder.disallowTruncate().doNotFollowRedirects());
    } catch (URISyntaxException ex) {
        throw new IOException("Malformed request URI: " + ex.getMessage(), ex);
    } catch (IllegalArgumentException ex) {
        throw new IOException("Unsupported HTTP method: " + ex.getMessage(), ex);
    }

    for (Header h : request.getAllHeaders()) {
        this.request.addHeader(new HTTPHeader(h.getName(), h.getValue()));
    }
}

From source file:com.couchbase.client.vbucket.ConfigurationProviderHTTP.java

/**
 * Create a URL which has the appropriate headers to interact with the
 * service. Most exception handling is up to the caller.
 *
 * @param resource the URI either absolute or relative to the base for this
 * ClientManager//from  www  .ja  va  2s .  c  om
 * @return
 * @throws java.io.IOException
 */
private URLConnection urlConnBuilder(URI base, URI resource) throws IOException {
    if (!resource.isAbsolute() && base != null) {
        resource = base.resolve(resource);
    }
    URL specURL = resource.toURL();
    URLConnection connection = specURL.openConnection();
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("user-agent", "spymemcached vbucket client");
    connection.setRequestProperty("X-memcachekv-Store-Client-" + "Specification-Version", CLIENT_SPEC_VER);
    if (restUsr != null) {
        try {
            connection.setRequestProperty("Authorization", buildAuthHeader(restUsr, restPwd));
        } catch (UnsupportedEncodingException ex) {
            throw new IOException("Could not encode specified credentials for " + "HTTP request.", ex);
        }
    }
    return connection;
}

From source file:com.w20e.socrates.process.RunnerFactoryImpl.java

/**
 * Create a runner instance, or null if the runner cannot be created. The
 * runner holds a reference to the model, and will be initialized with a
 * workflow definition.//from  w ww .j a  v  a  2 s. c o  m
 * 
 * @param id
 *            questionnaire id
 * @param l
 *            a <code>Locale</code> value
 * @param medium
 *            a <code>String</code> value
 * @return a <code>Runner</code> value
 * @exception UnsupportedMediumException
 *                if an error occurs
 */
@Override
public Runner createRunner(final URI url) throws UnsupportedMediumException {

    if (!this.runners.containsKey(url)) {
        LOGGER.fine("Creating new runner for id " + url.toString());
        try {
            Configuration cfg = ConfigurationResource.getInstance().getConfiguration(url.toURL());

            if (cfg == null) {
                return null;
            }

            this.runners.put(url, new RunnerImpl(new URL((String) cfg.getProperty("runner.url"))));
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Couldn't create runner", e);
            throw new UnsupportedMediumException(e.getMessage());
        }
    }

    return this.runners.get(url);
}

From source file:org.mulgara.resolver.http.HttpContent.java

public HttpContent(URI uri) throws URISyntaxException, MalformedURLException {
    this(uri.toURL());
}

From source file:org.lexevs.dao.database.service.Author.EntityRevisionTest.java

@Before
public void loadSystemRelease() throws Exception {
    extensionLoadingListenerRegistry.setEnableListeners(true);

    URI sourceURI = new File("src/test/resources/csRevision/Automobiles2010_Test_Entity.xml").toURI();

    org.exolab.castor.xml.Unmarshaller um = new org.exolab.castor.xml.Unmarshaller(SystemRelease.class);
    SystemRelease systemRelease = (SystemRelease) um
            .unmarshal(new InputStreamReader(sourceURI.toURL().openConnection().getInputStream()));

    service.loadSystemRelease(systemRelease, true);
}