Example usage for java.net URI isAbsolute

List of usage examples for java.net URI isAbsolute

Introduction

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

Prototype

public boolean isAbsolute() 

Source Link

Document

Tells whether or not this URI is absolute.

Usage

From source file:org.lilyproject.indexer.admin.cli.BaseIndexerAdminCli.java

@Override
protected int processOptions(CommandLine cmd) throws Exception {
    int result = super.processOptions(cmd);
    if (result != 0)
        return result;

    if (cmd.hasOption(nameOption.getOpt())) {
        indexName = cmd.getOptionValue(nameOption.getOpt());
    }//ww w  .j a  va2  s  .c o m

    if (cmd.hasOption(solrShardsOption.getOpt())) {
        solrShards = new HashMap<String, String>();
        String[] solrShardEntries = cmd.getOptionValue(solrShardsOption.getOpt()).split(",");
        Set<String> addresses = new HashSet<String>();
        // Be helpful to the user and validate the URIs are syntactically correct
        for (String shardEntry : solrShardEntries) {
            int sep = shardEntry.indexOf(':');
            if (sep == -1) {
                System.out.println(
                        "SOLR shards should be specified as 'name:URL' pairs, which the following is not:");
                System.out.println(shardEntry);
                return 1;
            }

            String shardName = shardEntry.substring(0, sep).trim();
            if (shardName.length() == 0) {
                System.out.println("Zero-length shard name in the following shard entry:");
                System.out.println(shardEntry);
                return 1;
            }

            if (shardName.equals("http")) {
                System.out.println("You forgot to specify a shard name for the SOLR shard " + shardEntry);
                return 1;
            }

            String shardAddress = shardEntry.substring(sep + 1).trim();
            try {
                URI uri = new URI(shardAddress);
                if (!uri.isAbsolute()) {
                    System.out.println("Not an absolute URI: " + shardAddress);
                    return 1;
                }
            } catch (URISyntaxException e) {
                System.out.println("Invalid SOLR shard URI: " + shardAddress);
                System.out.println(e.getMessage());
                return 1;
            }

            if (solrShards.containsKey(shardName)) {
                System.out.println("Duplicate shard name: " + shardName);
                return 1;
            }

            if (addresses.contains(shardAddress)) {
                if (!cmd.hasOption(forceOption.getOpt())) {
                    System.out.println("You have two shards pointing to the same URI:");
                    System.out.println(shardAddress);
                    System.out.println();
                    System.out.println("If this is what you want, use the --" + forceOption.getLongOpt()
                            + " option to bypass this check.");
                    return 1;
                }
            }

            addresses.add(shardAddress);

            solrShards.put(shardName, shardAddress);
        }

        if (solrShards.isEmpty()) {
            // Probably cannot occur
            System.out.println("No SOLR shards specified though option is used.");
            return 1;
        }
    }

    if (cmd.hasOption(shardingConfigurationOption.getOpt())) {
        File configurationFile = new File(cmd.getOptionValue(shardingConfigurationOption.getOpt()));

        if (!configurationFile.exists()) {
            System.out.println("Specified sharding configuration file not found:");
            System.out.println(configurationFile.getAbsolutePath());
            return 1;
        }

        shardingConfiguration = FileUtils.readFileToByteArray(configurationFile);
    }

    if (cmd.hasOption(configurationOption.getOpt())) {
        File configurationFile = new File(cmd.getOptionValue(configurationOption.getOpt()));

        if (!configurationFile.exists()) {
            System.out.println("Specified indexer configuration file not found:");
            System.out.println(configurationFile.getAbsolutePath());
            return 1;
        }

        indexerConfiguration = FileUtils.readFileToByteArray(configurationFile);

        if (!cmd.hasOption(forceOption.getOpt())) {
            LilyClient lilyClient = null;
            try {
                lilyClient = new LilyClient(zkConnectionString, 10000);
                IndexerConfBuilder.build(new ByteArrayInputStream(indexerConfiguration),
                        lilyClient.getRepository());
            } catch (Exception e) {
                System.out.println(); // separator line because LilyClient might have produced some error logs
                System.out.println("Failed to parse & build the indexer configuration.");
                System.out.println();
                System.out.println("If this problem occurs because no Lily node is available");
                System.out.println("or because certain field types or record types do not exist,");
                System.out.println(
                        "then you can skip this validation using the option --" + forceOption.getLongOpt());
                System.out.println();
                if (e instanceof IndexerConfException) {
                    printExceptionMessages(e);
                } else {
                    e.printStackTrace();
                }
                return 1;
            } finally {
                Closer.close(lilyClient);
            }
        }
    }

    if (cmd.hasOption(generalStateOption.getOpt())) {
        String stateName = cmd.getOptionValue(generalStateOption.getOpt());
        try {
            generalState = IndexGeneralState.valueOf(stateName.toUpperCase());
        } catch (IllegalArgumentException e) {
            System.out.println("Invalid index state: " + stateName);
            return 1;
        }
    }

    if (cmd.hasOption(updateStateOption.getOpt())) {
        String stateName = cmd.getOptionValue(updateStateOption.getOpt());
        try {
            updateState = IndexUpdateState.valueOf(stateName.toUpperCase());
        } catch (IllegalArgumentException e) {
            System.out.println("Invalid index update state: " + stateName);
            return 1;
        }
    }

    if (cmd.hasOption(buildStateOption.getOpt())) {
        String stateName = cmd.getOptionValue(buildStateOption.getOpt());
        try {
            buildState = IndexBatchBuildState.valueOf(stateName.toUpperCase());
        } catch (IllegalArgumentException e) {
            System.out.println("Invalid index build state: " + stateName);
            return 1;
        }

        if (buildState != IndexBatchBuildState.BUILD_REQUESTED) {
            System.out.println("The build state can only be set to " + IndexBatchBuildState.BUILD_REQUESTED);
            return 1;
        }
    }

    if (cmd.hasOption(outputFileOption.getOpt())) {
        outputFileName = cmd.getOptionValue(outputFileOption.getOpt());
        File file = new File(outputFileName);

        if (!cmd.hasOption(forceOption.getOpt()) && file.exists()) {
            System.out.println("The specified output file already exists:");
            System.out.println(file.getAbsolutePath());
            System.out.println();
            System.out.println("Use --" + forceOption.getLongOpt() + " to overwrite it.");
        }
    }

    return 0;
}

From source file:org.apache.http.impl.client.DefaultRedirectHandler.java

public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException {
    Args.notNull(response, "HTTP response");
    //get the location header to find out where to redirect to
    final Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }//  ww w  . ja  v  a  2s  .c  o m
    final String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri;
    try {
        uri = new URI(location);
    } catch (final URISyntaxException ex) {
        throw new ProtocolException("Invalid redirect URI: " + location, ex);
    }

    final HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        final HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        Asserts.notNull(target, "Target host");

        final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

        try {
            final URI requestURI = new URI(request.getRequestLine().getUri());
            final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (final URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        final URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                final HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (final URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:uk.co.flax.biosolr.elasticsearch.mapper.ontology.owl.OntologyHelper.java

/**
 * Construct a new ontology helper instance.
 * //from w  w w .  j av a2  s  .  c  o m
 * @param ontologyUri the URI giving the location of the ontology.
 * @param config the ontology configuration, containing the property URIs
 * for labels, synonyms, etc.
 * @throws OWLOntologyCreationException if the ontology cannot be read for
 * some reason - internal inconsistencies, etc.
 * @throws URISyntaxException if the URI cannot be parsed.
 */
public OntologyHelper(URI ontologyUri, OntologySettings config)
        throws OWLOntologyCreationException, URISyntaxException {
    this.config = config;

    if (!ontologyUri.isAbsolute()) {
        // Try to read as a file from the resource path
        LOGGER.debug("Ontology URI {} is not absolute - loading from classpath", ontologyUri);
        URL url = this.getClass().getClassLoader().getResource(ontologyUri.toString());
        if (url != null) {
            ontologyUri = url.toURI();
        }
    }
    this.ontologyUri = ontologyUri;
    LOGGER.info("Loading ontology from " + ontologyUri + "...");

    OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
    IRI iri = IRI.create(ontologyUri);
    this.ontology = manager.loadOntologyFromOntologyDocument(iri);
    // Use a buffering reasoner - not interested in ongoing changes
    this.reasoner = new StructuralReasonerFactory().createReasoner(ontology);
    // this.shortFormProvider = new SimpleShortFormProvider();
    this.owlNothingIRI = manager.getOWLDataFactory().getOWLNothing().getIRI();

    // Initialise the class map
    initialiseClassMap();
}

From source file:org.vietspider.net.client.impl.AbstractHttpClient.java

private HttpHost determineTarget(HttpUriRequest request) {
    // A null target may be acceptable if there is a default target.
    // Otherwise, the null target is detected in the director.
    HttpHost target = null;/*from   ww w .  ja  v  a 2s. co m*/

    URI requestURI = request.getURI();
    if (requestURI.isAbsolute()) {
        target = new HttpHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme());
    }
    return target;
}

From source file:org.mitre.mpf.mvc.controller.MediaController.java

@RequestMapping(value = "/saveURL", method = RequestMethod.POST)
@ResponseBody//w w  w  .j av  a 2s. c  o m
public Map<String, String> saveMedia(@RequestParam(value = "urls", required = true) String[] urls,
        @RequestParam(value = "desiredpath", required = true) String desiredpath, HttpServletResponse response)
        throws WfmProcessingException, MpfServiceException {
    log.debug("URL Upload to Directory:" + desiredpath + " urls:" + urls.length);

    String err = "Illegal or missing desiredpath";
    if (desiredpath == null) {
        log.error(err);
        throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, err);
    }
    ;
    String webTmpDirectory = propertiesUtil.getRemoteMediaCacheDirectory().getAbsolutePath();
    //verify the desired path
    File desiredPath = new File(desiredpath);
    if (!desiredPath.exists() || !desiredPath.getAbsolutePath().startsWith(webTmpDirectory)) {//make sure it is valid and within the remote-media directory
        log.error(err);
        throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, err);
    }

    //passing in urls as a list of Strings
    //download the media to the server
    //build a map of success or failure for each file with a custom response object
    Map<String, String> urlResultMap = new HashMap<String, String>();
    for (String enteredURL : urls) {
        enteredURL = enteredURL.trim();
        URI uri;
        try {
            uri = new URI(enteredURL);
            //the check for absolute URI determines if any scheme is present, regardless of validity
            //(which is checked in both this and the next try block)
            if (!uri.isAbsolute()) {
                uri = new URI("http://" + uri.toASCIIString());
            }
        } catch (URISyntaxException incorrectUriTranslation) {
            log.error("The string {} did not translate cleanly to a URI.", enteredURL, incorrectUriTranslation);
            urlResultMap.put(enteredURL, "String did not cleanly convert to URI");
            continue;
        }
        File newFile = null;
        String localName = null;
        try {
            URL url = uri.toURL(); //caught by MalformedURLException
            //will throw an IOException,which is already caught 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");
            connection.connect();
            connection.disconnect();

            String filename = url.getFile();
            if (filename.isEmpty()) {
                String err2 = "The filename does not exist when uploading from the url '" + url + "'";
                log.error(err2);
                urlResultMap.put(enteredURL, err2);
                continue;
            }

            if (!ioUtils.isApprovedFile(url)) {
                String contentType = ioUtils.getMimeType(url);
                String msg = "The media is not a supported type. Please add a whitelist." + contentType
                        + " entry to the mediaType.properties file.";
                log.error(msg + " URL:" + url);
                urlResultMap.put(enteredURL, msg);
                continue;
            }

            localName = uri.getPath();
            //we consider no path to be malformed for our purposes
            if (localName.isEmpty()) {
                throw new MalformedURLException(String.format("%s does not have valid path", uri));
            }

            //use the full path name for the filename to allow for more unique filenames
            localName = localName.substring(1);//remove the leading '/'
            localName = localName.replace("/", "-");//replace the rest of the path with -

            //get a new unique filename incase the name currently exists
            newFile = ioUtils.getNewFileName(desiredpath, localName);

            //save the file
            FileUtils.copyURLToFile(url, newFile);
            log.info("Completed write of {} to {}", uri.getPath(), newFile.getAbsolutePath());
            urlResultMap.put(enteredURL, "successful write to: " + newFile.getAbsolutePath());
        } catch (MalformedURLException badUrl) {
            log.error("URI {} could not be converted. ", uri, badUrl);
            urlResultMap.put(enteredURL, "Unable to locate media at the provided address.");
        } catch (IOException badWrite) {
            log.error("Error writing media to temp file from {}.", enteredURL, badWrite);
            urlResultMap.put(enteredURL,
                    "Unable to save media from this url. Please view the server logs for more information.");
            if (newFile != null && newFile.exists()) {
                newFile.delete();
            }
        } catch (Exception failure) { //catch the remaining exceptions
            //this is most likely a failed connection 
            log.error("Exception thrown while saving media from the url {}.", enteredURL, failure);
            urlResultMap.put(enteredURL,
                    "Error while saving media from this url. Please view the server logs for more information.");
        }
    }
    return urlResultMap;
}

From source file:org.dhatim.resource.URIResourceLocator.java

/**
 * Resolve the supplied uri against the baseURI.
 * <p/>/* w ww  .  j  a v  a 2 s  .co  m*/
 * Only resolved against the base URI if 'uri' is not absolute.
 *
 * @param uri URI to be resolved.
 * @return The resolved URI.
 */
public URI resolveURI(String uri) {
    URI uriObj;

    if (uri == null || uri.trim().equals("")) {
        throw new IllegalArgumentException("null or empty 'uri' paramater in method call.");
    }

    if (uri.charAt(0) == '\\' || uri.charAt(0) == '/') {
        uri = uri.substring(1);
        return URI.create(uri);
    } else {
        uriObj = URI.create(uri);
        if (!uriObj.isAbsolute()) {
            // Resolve the supplied URI against the baseURI...
            uriObj = baseURI.resolve(uriObj);
        }
    }

    return uriObj;
}

From source file:org.apache.taverna.robundle.manifest.Manifest.java

public PathMetadata getAggregation(URI uri) {
    uri = relativeToBundleRoot(uri);// ww  w  .jav a 2  s .  co m
    PathMetadata metadata = aggregates.get(uri);
    if (metadata == null) {
        metadata = new PathMetadata();
        if (!uri.isAbsolute() && uri.getFragment() == null) {
            Path path = uriToBundlePath(bundle, uri);
            metadata.setFile(path);
            metadata.setMediatype(guessMediaType(path));
        } else {
            metadata.setUri(uri);
        }
        aggregates.put(uri, metadata);
    }
    return metadata;
}

From source file:org.dita.dost.module.BranchFilterModule.java

/**
 * Process map for branch replication.//www .j a va 2s.  com
 */
protected void processMap(final URI map) {
    assert !map.isAbsolute();
    this.map = map;
    currentFile = job.tempDirURI.resolve(map);
    // parse
    logger.info("Processing " + currentFile);
    final Document doc;
    try {
        logger.debug("Reading " + currentFile);
        doc = builder.parse(new InputSource(currentFile.toString()));
    } catch (final SAXException | IOException e) {
        logger.error("Failed to parse " + currentFile, e);
        return;
    }

    logger.debug("Split branches and generate copy-to");
    splitBranches(doc.getDocumentElement(), Branch.EMPTY);
    logger.debug("Filter map");
    filterBranches(doc.getDocumentElement());
    logger.debug("Rewrite duplicate topic references");
    rewriteDuplicates(doc.getDocumentElement());
    logger.debug("Filter topics and generate copies");
    generateCopies(doc.getDocumentElement(), Collections.emptyList());
    logger.debug("Filter existing topics");
    filterTopics(doc.getDocumentElement(), Collections.emptyList());

    logger.debug("Writing " + currentFile);
    Result result = null;
    try {
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        result = new StreamResult(currentFile.toString());
        serializer.transform(new DOMSource(doc), result);
    } catch (final TransformerConfigurationException | TransformerFactoryConfigurationError e) {
        throw new RuntimeException(e);
    } catch (final TransformerException e) {
        logger.error("Failed to serialize " + map.toString() + ": " + e.getMessage(), e);
    } finally {
        try {
            close(result);
        } catch (final IOException e) {
            logger.error("Failed to close result stream for " + map.toString() + ": " + e.getMessage(), e);
        }
    }
}

From source file:org.apache.taverna.scufl2.validation.correctness.CorrectnessVisitor.java

@Override
public void visitTyped(Typed bean) {
    URI configurableType = bean.getType();
    if (configurableType != null) {
        if (!configurableType.isAbsolute())
            listener.nonAbsoluteURI(bean, "configurableType", configurableType);
        else if (configurableType.getScheme().equals("file"))
            listener.nonAbsoluteURI(bean, "configurableType", configurableType);
    }//from   w w  w  .j  a v  a2 s  . com
    if (checkComplete && configurableType == null)
        listener.nullField(bean, "configurableType");
}

From source file:org.apache.taverna.scufl2.validation.correctness.CorrectnessVisitor.java

@Override
public void visitRoot(Root bean) {
    URI globalBaseURI = bean.getGlobalBaseURI();
    if (globalBaseURI != null) {
        if (!globalBaseURI.isAbsolute())
            listener.nonAbsoluteURI(bean, "globalBaseURI", globalBaseURI);
        else if (globalBaseURI.getScheme().equals("file"))
            listener.nonAbsoluteURI(bean, "globalBaseURI", globalBaseURI);
    }/*ww w  .  j a v a  2  s  . c o m*/
    if (checkComplete && globalBaseURI == null)
        listener.nullField(bean, "globalBaseURI");
}