Example usage for java.net URL getPath

List of usage examples for java.net URL getPath

Introduction

In this page you can find the example usage for java.net URL getPath.

Prototype

public String getPath() 

Source Link

Document

Gets the path part of this URL .

Usage

From source file:com.gargoylesoftware.htmlunit.CookieManager.java

/**
 * Helper that builds a CookieOrigin./*  w  ww. j  a v a2s  . c  o m*/
 * @param url the url to be used
 * @return the new CookieOrigin
 */
public CookieOrigin buildCookieOrigin(final URL url) {
    final URL normalizedUrl = replaceForCookieIfNecessary(url);

    return new CookieOrigin(normalizedUrl.getHost(), getPort(normalizedUrl), normalizedUrl.getPath(),
            "https".equals(normalizedUrl.getProtocol()));
}

From source file:com.eucalyptus.http.MappingHttpRequest.java

public MappingHttpRequest(HttpVersion httpVersion, HttpMethod method, String uri) {
    super(httpVersion);
    this.method = method;
    this.uri = uri;
    try {//w  w  w. j av a  2s. co m
        URL url = new URL("http://eucalyptus" + uri);
        this.servicePath = url.getPath();
        this.parameters = Maps.newHashMap();
        this.rawParameters = Maps.newHashMap();
        this.nonQueryParameterKeys = Sets.newHashSet();
        this.query = this.query == url.getQuery() ? this.query : url.getQuery();// new URLCodec().decode(url.toURI( ).getQuery( ) ).replaceAll( " ", "+" );
        this.formFields = Maps.newHashMap();
        this.populateParameters();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.francelabs.datafari.updateprocessor.DatafariUpdateProcessor.java

@Override
public void processAdd(final AddUpdateCommand cmd) throws IOException {
    final SolrInputDocument doc = cmd.getSolrInputDocument();

    // Sometimes Tika put several ids so we keep the first one which is
    // always the right one
    if (doc.getFieldValues("id").size() > 1) {
        final Object id = doc.getFieldValue("id");
        doc.remove("id");
        doc.addField("id", id);
    }/* w  w w.j  a  v a2 s.c  o m*/

    // Try to retrieve at the ignored_filelastmodified field to set it's
    // value in the last_modified field
    if (doc.getFieldValue("ignored_filelastmodified") != null) {
        final Object last_modified = doc.getFieldValue("ignored_filelastmodified");
        doc.remove("last_modified");
        doc.addField("last_modified", last_modified);
    }

    // Sometimes Tika put several last_modified dates, so we keep the first
    // one which is always the right one
    if ((doc.getFieldValues("last_modified") != null) && (doc.getFieldValues("last_modified").size() > 1)) {
        final Object last_modified = doc.getFieldValue("last_modified");
        doc.remove("last_modified");
        doc.addField("last_modified", last_modified);
    }

    final String url = (String) doc.getFieldValue("id");

    // Create path hierarchy for facet
    final List<String> urlHierarchy = new ArrayList<>();

    /*
     * // Create path hierarchy for facet
     *
     * final List<String> urlHierarchy = new ArrayList<String>();
     *
     * final String path = url.replace("file:", ""); int previousIndex = 1; int
     * depth = 0; // Tokenize the path and add the depth as first character for
     * each token // (like: 0/home, 1/home/project ...) for (int i = 0; i <
     * path.split("/").length - 2; i++) { int endIndex = path.indexOf('/',
     * previousIndex); if (endIndex == -1) { endIndex = path.length() - 1; }
     * urlHierarchy.add(depth + path.substring(0, endIndex)); depth++;
     * previousIndex = endIndex + 1; }
     *
     * // Add the tokens to the urlHierarchy field doc.addField("urlHierarchy",
     * urlHierarchy);
     */

    doc.addField("url", url);

    String filename = "";
    final SolrInputField streamNameField = doc.get("ignored_stream_name");
    if (streamNameField != null) {
        filename = (String) streamNameField.getFirstValue();
    } else {
        final Pattern pattern = Pattern.compile("[^/]*$");
        final Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            filename = matcher.group();
        }
    }

    if (url.startsWith("http")) {
        if (doc.get("title") == null) {
            doc.addField("title", filename);
        }
        doc.addField("source", "web");
    }

    if (url.startsWith("file")) {
        doc.removeField("title");
        doc.addField("title", filename);
        doc.addField("source", "file");
    }

    String extension = "";
    URL urlObject = new URL(url);
    String path = urlObject.getPath();
    final SolrInputField mimeTypeField = doc.get("ignored_content_type");

    String nameExtension = FilenameUtils.getExtension(path);
    String tikaExtension = mimeTypeField == null ? "" : extensionFromMimeTypeField(mimeTypeField);

    if (extensionFromName) {
        extension = nameExtension.length() > 1 && nameExtension.length() < 5 ? nameExtension : tikaExtension;
    } else {
        extension = tikaExtension.length() > 1 && tikaExtension.length() < 5 ? tikaExtension : nameExtension;
    }
    /*
    if (extensionFromName || mimeTypeField == null) {
       if (path.contains(".")){
         extension = FilenameUtils.getExtension(path);
          if (extension.length() > 4 || extension.length() < 1) {
    // If length is too long, try extracting from tika information if available
    String tryExtension = mimeTypeField==null ? null : extensionFromMimeTypeField(mimeTypeField);
    if (tryExtension != null) {
      extension = tryExtension;
    } else {
      // Else default to bin for anything else
      extension = "bin";
    }
          }
       }
       else if (urlObject.getProtocol().equals("http") || urlObject.getProtocol().equals("https")) {
         extension = null;
         if (mimeTypeField != null) {
           extension = extensionFromMimeTypeField(mimeTypeField);
         } 
         if (extension == null) {
           extension = "html";
         }
       }
    } else {
      extension = extensionFromMimeTypeField(mimeTypeField);
      if (extension == null) {
        extension = FilenameUtils.getExtension(path);
      }
    }
    */
    doc.addField("extension", extension.toLowerCase());

    super.processAdd(cmd);
}

From source file:com.viddu.handlebars.HandlebarsMojoTest.java

public void testExecute() throws MojoExecutionException {
    ClassLoader ccl = Thread.currentThread().getContextClassLoader();
    URL handleBarsUrl = ccl.getResource("handlebars-1.0.rc.1.js");
    URL templatesUrl = ccl.getResource("templates");
    String outputDir = "target/compiledTemplates";

    HandlebarsMojo hbMojo = new HandlebarsMojo();
    hbMojo.setHandlebarsLibrary(new File(handleBarsUrl.getPath()));
    hbMojo.setInputDirectory(new File(templatesUrl.getPath()));
    hbMojo.setOutputDirectory(new File(outputDir));
    hbMojo.execute();//  ww w . j  a  va  2  s .  co  m
}

From source file:com.scvngr.levelup.core.net.request.factory.ClaimRequestFactoryTest.java

@SmallTest
public void testBuildClaimRequest() throws BadRequestException {
    final LevelUpRequest request = (LevelUpRequest) new ClaimRequestFactory(getContext(),
            new MockAccessTokenRetriever()).buildClaimCampaignRequest(SAMPLE_CODE);

    assertEquals(HttpMethod.POST, request.getMethod());
    assertEquals(0, request.getBodyLength(getContext()));
    final URL url = request.getUrl(getContext());
    assertNotNull(url);//from w  w w  .  jav a 2  s.  com
    // Make sure we hit the proper API version and url.
    final String expectedUrl = String.format(Locale.US, "/v15/codes/%s/claims", SAMPLE_CODE);
    assertEquals(expectedUrl, url.getPath());
}

From source file:eu.medsea.mimeutil.detector.ExtensionMimeDetector.java

/**
 * Get the mime type of a URL using extension mappings. Only the extension is important here.
 * @param url is a valid URL/*from w  ww  .  ja v  a  2  s  .  c om*/
 * @return collection of the matched mime types.
 * @throws MimeException if errors occur.
 */
public Collection getMimeTypesURL(final URL url) throws MimeException {
    return getMimeTypesFileName(url.getPath());
}

From source file:com.santhoshknn.sudoku.GridExtractor.java

/**
 * <p>/*from  w ww  . j a va2  s.  co  m*/
 * Parses the supplied file to extract a 9x9 grid of integers substituting
 * the supplied x with a 0
 * </p>
 * <b>Note:</b>Used internally for testing with various data. REST API uses
 * the operation above
 *
 * @param input
 * @return extracted grid if valid input, null otherwise
 */
public GridResponse parseFromFile(final String fileName) {
    int[][] grid = new int[9][9]; // default 0 vals
    GridResponse response = new GridResponse();
    Scanner scanner = null;
    String error = null;
    try {
        URL url = getClass().getResource(fileName);
        log.info("Reading input file [{}]", url.getFile());
        scanner = new Scanner(new File(url.getPath()));
        int row = 0;
        while (scanner.hasNext()) {
            int col = 0;
            String line = scanner.nextLine();
            // delete whitespaces added for cosmetic purpose
            line = StringUtils.deleteWhitespace(line);
            if (line.isEmpty())
                continue; // Sanitize input. Remove line added for
                          // readability
                          // fail if line's length!=9
            if (line.length() != 9) {
                error = INVALID_CHARS_IN_FILE + ":" + (row + 1);
                break;
            }

            for (int i = 0; i < line.length(); i++) {
                //log.info("Row [{}] Char is [{}]",row,line.charAt(i));
                if (Character.isDigit(line.charAt(i))) {
                    int number = Character.getNumericValue(line.charAt(i));
                    grid[row][col] = number;
                } else {
                    grid[row][col] = 0;
                }
                col++;
            }
            if (row == 9)
                break;
            row++;
        }
    } catch (FileNotFoundException e) {
        log.error("Error reading file [{}]", fileName, e);
    } finally {
        if (scanner != null)
            scanner.close();
    }
    if (null == error) {
        response.setGrid(grid);
    } else {
        response.setError(error);
        log.error(error);
    }
    return response;
}

From source file:com.anrisoftware.sscontrol.filesystem.FileSystem.java

@SuppressWarnings("unchecked")
private MimeType mimeType(URL url) throws MimeException, FileSystemException {
    Collection<MimeType> type;
    if (isFileScheme(url)) {
        type = mime.getMimeTypes(new File(url.getPath()));
    } else {/*from   www  . j a  va  2  s  .  com*/
        type = mime.getMimeTypes(url);
    }
    Iterator<MimeType> it = type.iterator();
    if (it.hasNext()) {
        return it.next();
    }
    throw log.noMimeTypeReturned(url);
}

From source file:io.fabric8.fab.DependencyTestSupport.java

protected DependencyTreeResult collectDependencies(String pomName) throws Exception {
    URL resource = getClass().getClassLoader().getResource(pomName);
    assertNotNull("Could not find: " + pomName + " on the classpath", resource);
    File rootPom = new File(resource.getPath());

    DependencyTreeResult node = mavenResolver.collectDependencies(rootPom, false);
    if (LOG.isDebugEnabled()) {
        LOG.debug("File: " + pomName);
        LOG.debug(node.getTreeDescription());
    }// www .  java 2s.co  m

    List<DependencyTree.DuplicateDependency> duplicateDependencies = node.getTree()
            .checkForDuplicateDependencies();
    assertEquals("Should not have duplicates: " + duplicateDependencies, 0, duplicateDependencies.size());
    return node;
}

From source file:org.frontcache.hystrix.FC_BypassCache.java

/**
 * forward all kind of requests (GET, POST, PUT, ...)
 * /*from  ww  w  .j  a  v a 2 s.co  m*/
 * @param httpclient
 * @param verb
 * @param uri
 * @param request
 * @param headers
 * @param params
 * @param requestEntity
 * @return
 * @throws Exception
 */
private HttpResponse forward(HttpClient httpclient, String verb, String uri, HttpServletRequest request,
        Map<String, List<String>> headers, InputStream requestEntity) throws Exception {

    URL host = context.getOriginURL();
    HttpHost httpHost = FCUtils.getHttpHost(host);
    uri = (host.getPath() + uri).replaceAll("/{2,}", "/");

    HttpRequest httpRequest;
    switch (verb.toUpperCase()) {
    case "POST":
        HttpPost httpPost = new HttpPost(uri + context.getRequestQueryString());
        httpRequest = httpPost;
        httpPost.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
        break;
    case "PUT":
        HttpPut httpPut = new HttpPut(uri + context.getRequestQueryString());
        httpRequest = httpPut;
        httpPut.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
        break;
    case "PATCH":
        HttpPatch httpPatch = new HttpPatch(uri + context.getRequestQueryString());
        httpRequest = httpPatch;
        httpPatch.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
        break;
    default:
        httpRequest = new BasicHttpRequest(verb, uri + context.getRequestQueryString());
    }

    try {
        httpRequest.setHeaders(FCUtils.convertHeaders(headers));
        Header acceptEncoding = httpRequest.getFirstHeader("accept-encoding");
        if (acceptEncoding != null && acceptEncoding.getValue().contains("gzip")) {
            httpRequest.setHeader("accept-encoding", "gzip");
        }
        HttpResponse originResponse = httpclient.execute(httpHost, httpRequest);
        return originResponse;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        // httpclient.getConnectionManager().shutdown();
    }
}