Example #1
1
  private String getResult(String URL, HashMap optionalParameters) {
    StringBuilder sb = new StringBuilder();
    sb.append(URL);
    try {

      Iterator iterator = optionalParameters.keySet().iterator();

      int index = 0;
      while (iterator.hasNext()) {
        if (index == 0) {
          sb.append("?");
        } else {
          sb.append("&");
        }
        String key = (String) iterator.next();
        sb.append(key);
        sb.append("=");
        sb.append(URLEncoder.encode(optionalParameters.get(key).toString(), "UTF-8"));
        index++;
      }

      URI uri = new URI(String.format(sb.toString()));
      URL url = uri.toURL();

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      if (conn.getResponseCode() != 200) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String output;
      sb = new StringBuilder();
      while ((output = br.readLine()) != null) {
        sb.append(output);
      }

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    } catch (URISyntaxException e) {
      e.printStackTrace();
      return null;
    }
    return sb.toString();
  }
  /**
   * Resolve COLLADA references relative to the COLLADA document. If the reference is relative then
   * it will resolved relative to the .dae file, not the kml file. If the COLLADA document may be
   * contained in a KMZ archive the resources will be resolved relative to the .dae file within the
   * archive. Normally references in a KMZ are resolved relative to the root of the archive, but
   * Model references are an exception. See
   * https://developers.google.com/kml/documentation/kmzarchives and
   * https://developers.google.com/kml/documentation/kmlreference#model
   *
   * <p>{@inheritDoc}.
   */
  public String resolveFilePath(String path) throws IOException {
    KMLLink link = this.model.getLink();

    // Check the resource map to see if an alias is defined for this resource.
    String alias = this.resourceMap.get(path);
    if (alias != null) path = alias;

    // If the path is relative then resolve it relative to the COLLADA file.
    File f = new File(path);
    if (!f.isAbsolute() && link != null && link.getHref() != null) {
      try {
        URI base = new URI(null, link.getHref(), null);
        URI ref = new URI(null, path, null);

        path = base.resolve(ref).getPath();
      } catch (URISyntaxException ignored) {
        // Ignored
      }
    }

    Object o = this.parent.getRoot().resolveReference(path);
    if (o instanceof URL || o instanceof String) return o.toString();

    return null;
  }
Example #3
0
  public static int loadURIResource(URI uri, CPU cpu, int addr) {
    int i;

    System.out.println("loadURL: " + uri.toString());

    try {
      DataInputStream s = new DataInputStream(new BufferedInputStream(uri.toURL().openStream()));

      i = 0;
      try {
        while (true) {
          cpu.write8_a32(addr + i, s.readByte());
          i++;
        }
      } catch (EOFException e) {
        // end
      }
    } catch (IOException e) {
      e.printStackTrace(System.err);
      throw new IllegalArgumentException(e);
    }

    System.out.printf("loadURL: '%s' done, %dbytes.\n", uri.toString(), i);

    return i;
  }
Example #4
0
 static {
   dict = null;
   String wnhome = System.getenv("WNHOME");
   String path =
       (new StringBuilder(String.valueOf(wnhome)))
           .append(File.separator)
           .append("dict")
           .toString();
   System.out.println(
       (new StringBuilder("Path to dictionary:")).append(getWNLocation()).toString());
   URL url = null;
   try {
     File f =
         new File(
             (new StringBuilder(String.valueOf(getWNLocation())))
                 .append(File.separator)
                 .append("dict")
                 .toString());
     URI uri = f.toURI();
     url = uri.toURL();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   }
   dict = new Dictionary(url);
   dict.open();
 }
Example #5
0
 /** Returns the Jetty server that the Namenode is listening on. */
 private String getInfoServer() throws IOException {
   URI fsName = FileSystem.getDefaultUri(conf);
   if (!"hdfs".equals(fsName.getScheme())) {
     throw new IOException("This is not a DFS");
   }
   return NetUtils.getServerAddress(
       conf, "dfs.info.bindAddress", "dfs.info.port", "dfs.http.address");
 }
 private ModuleSource loadFromPathList(String moduleId, Object validator, Iterable<URI> paths)
     throws IOException, URISyntaxException {
   if (paths == null) {
     return null;
   }
   for (URI path : paths) {
     final ModuleSource moduleSource = loadFromUri(path.resolve(moduleId), path, validator);
     if (moduleSource != null) {
       return moduleSource;
     }
   }
   return null;
 }
Example #7
0
  @Override
  public void chatLinkClicked(URI url) {
    String action = url.getPath();
    if (action.equals("/SHOWPREVIEW")) {
      enableReplacement.setSelected(cfg.getBoolean(ReplacementProperty.REPLACEMENT_ENABLE, true));
      enableReplacementProposal.setSelected(
          cfg.getBoolean(ReplacementProperty.REPLACEMENT_PROPOSAL, true));

      currentMessageID = url.getQuery();
      currentLinkPosition = url.getFragment();

      this.setVisible(true);
      this.setLocationRelativeTo(chatPanel);
    }
  }
  public void setLibrary(URI url) throws Exception {
    if (url == null) url = new URI("http://repo.jpm4j.org/");

    this.host = new URLClient(url.toString());
    host.setReporter(reporter);
    library = JSONRPCProxy.createRPC(JpmRepo.class, host, "jpm");
  }
 void put(final URI uri, ArtifactData data) throws Exception {
   reporter.trace("put %s %s", uri, data);
   File tmp = createTempFile(repoDir, "mtp", ".whatever");
   tmp.deleteOnExit();
   try {
     copy(uri.toURL(), tmp);
     byte[] sha = SHA1.digest(tmp).digest();
     reporter.trace("SHA %s %s", uri, Hex.toHexString(sha));
     ArtifactData existing = get(sha);
     if (existing != null) {
       reporter.trace("existing");
       xcopy(existing, data);
       return;
     }
     File meta = new File(repoDir, Hex.toHexString(sha) + ".json");
     File file = new File(repoDir, Hex.toHexString(sha));
     rename(tmp, file);
     reporter.trace("file %s", file);
     data.file = file.getAbsolutePath();
     data.sha = sha;
     data.busy = false;
     CommandData cmddata = parseCommandData(data);
     if (cmddata.bsn != null) {
       data.name = cmddata.bsn + "-" + cmddata.version;
     } else data.name = Strings.display(cmddata.title, cmddata.bsn, cmddata.name, uri);
     codec.enc().to(meta).put(data);
     reporter.trace("TD = " + data);
   } finally {
     tmp.delete();
     reporter.trace("puted %s %s", uri, data);
   }
 }
Example #10
0
  private /*synchronized*/ void add_a_documentation_URL(String URLname)
      throws VisualizerLoadException {
    try {
      URI infoURI = new URI(URLname);
      if (infoURI.getScheme() == null) {
        // Now we recreate it with the appended rel scheme
        infoURI = new URI("Rel:" + URLname);
      }
      // If it does have a scheme definition then it's already set to go.

      GaigsAV.docCtlTable.put(new Integer(Snaps), infoURI); // add map snap -> URI
      // System.out.println("Adding documentation URL for snap " + Snaps + " " + my_url.toString());
    } catch (Exception e) {
      throw new VisualizerLoadException("Aieee... bad SHO file");
    }
  }
Example #11
0
 private void downloadInternal(URI address, File destination) throws Exception {
   OutputStream out = null;
   URLConnection conn;
   InputStream in = null;
   try {
     URL url = address.toURL();
     out = new BufferedOutputStream(new FileOutputStream(destination));
     conn = url.openConnection();
     final String userAgentValue = calculateUserAgent();
     conn.setRequestProperty("User-Agent", userAgentValue);
     in = conn.getInputStream();
     byte[] buffer = new byte[BUFFER_SIZE];
     int numRead;
     long progressCounter = 0;
     while ((numRead = in.read(buffer)) != -1) {
       progressCounter += numRead;
       if (progressCounter / PROGRESS_CHUNK > 0) {
         System.out.print(".");
         progressCounter = progressCounter - PROGRESS_CHUNK;
       }
       out.write(buffer, 0, numRead);
     }
   } finally {
     System.out.println("");
     if (in != null) {
       in.close();
     }
     if (out != null) {
       out.close();
     }
   }
 }
Example #12
0
  private String internal_call(String ws, String[] values) {
    logger.info("#" + index + "请求调用web service: " + ws);
    OWLValue output;
    try {
      mKB = OWLFactory.createKB();
      mKB.createOntology(null);
      Service service = mKB.readService(URI.create(ws));

      ValueMap<Input, OWLValue> inputs = new ValueMap<Input, OWLValue>();

      for (int i = 0; i < values.length; i++) {
        Input input = service.getProcess().getInputs().get(i);
        inputs.setValue(input, mKB.createDataValue(values[i]));
        logger.info("\t" + input.getLocalName() + "  :  " + values[i]);
      }

      ProcessExecutionEngine exec = OWLSFactory.createExecutionEngine();
      ValueMap<Output, OWLValue> outputs;
      outputs = exec.execute(service.getProcess(), inputs, mKB);

      output = outputs.getDataValue(service.getProcess().getOutput().getName());
      logger.info("Result : " + output);
      return output.toString();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    }
    return "";
  }
  @Nullable
  static IdeaPluginDescriptorImpl loadDescriptorFromJar(File file, @NonNls String fileName) {
    try {
      URI fileURL = file.toURI();
      URL jarURL =
          new URL(
              "jar:"
                  + StringUtil.replace(fileURL.toASCIIString(), "!", "%21")
                  + "!/META-INF/"
                  + fileName);

      IdeaPluginDescriptorImpl descriptor = new IdeaPluginDescriptorImpl(file);
      FileInputStream in = new FileInputStream(file);
      ZipInputStream zipStream = new ZipInputStream(in);
      try {
        ZipEntry entry = zipStream.getNextEntry();
        if (entry.getName().equals(JarMemoryLoader.SIZE_ENTRY)) {
          entry = zipStream.getNextEntry();
          if (entry.getName().equals("META-INF/" + fileName)) {
            byte[] content = FileUtil.loadBytes(zipStream, (int) entry.getSize());
            Document document = JDOMUtil.loadDocument(new ByteArrayInputStream(content));
            descriptor.readExternal(document, jarURL);
            return descriptor;
          }
        }
      } finally {
        zipStream.close();
        in.close();
      }

      descriptor.readExternal(jarURL);
      return descriptor;
    } catch (XmlSerializationException e) {
      getLogger().info("Cannot load " + file, e);
      prepareLoadingPluginsErrorMessage(
          "Plugin file " + file.getName() + " contains invalid plugin descriptor file.");
    } catch (FileNotFoundException e) {
      return null;
    } catch (Exception e) {
      getLogger().info("Cannot load " + file, e);
    } catch (Throwable e) {
      getLogger().info("Cannot load " + file, e);
    }

    return null;
  }
  private void setPath(String path) throws URISyntaxException, IOException {
    // path starts with a /

    // get first component:
    int index = path.indexOf('/', 1);
    String first = path.substring(1, index);
    String rest = path.substring(index + 1);

    // the first part of the path is very similar to a url, due to the fact
    // it
    // may contain guest credentials. So I use the URI class to help me
    // parse it.
    // first as a url of its own. http = dymm
    URI url2 = new URI("dummy://" + first);
    String uinfo;
    credentials = new NamePasswordAuthentication();
    vmIdentifier = url2.getHost();

    String guestCred = fileURL.getProperty(GUEST_CREDENTIALS);
    if ((guestCred != null) && (!guestCred.isEmpty())) {
      uinfo = guestCred;
    } else {
      uinfo = url2.getUserInfo();
    }

    if (uinfo == null) {
      throw new IOException(
          "No guest credentials provided. please start the connection from the UI");
    }

    int indexOf = uinfo.indexOf(":");
    if (indexOf == -1) {
      throw new IOException(
          "No guest credentials provided. please start the connection from the UI");
    }

    guestUser = uinfo.substring(0, indexOf);
    guestPass = uinfo.substring(indexOf + 1);
    credentials.setInteractiveSession(false);
    credentials.setUsername(guestUser);
    credentials.setPassword(guestPass);

    pathInsideVm = rest;
  }
Example #15
0
 /**
  * Resolve a URI against a base URI. (Be sure to pay attention to the order or parameters.)
  *
  * @param href URI to resolve (accept human-readable URI)
  * @param base URI base (accept human-readable URI)
  * @return resolved URI
  */
 public static String resolveURI(String href, String base) {
   final String resolvedURIString;
   if (base != null) {
     final URI baseURI;
     try {
       baseURI = new URI(encodeHRRI(base, true));
     } catch (URISyntaxException e) {
       throw new OXFException(e);
     }
     resolvedURIString =
         baseURI
             .resolve(encodeHRRI(href, true))
             .normalize()
             .toString(); // normalize to remove "..", etc.
   } else {
     resolvedURIString = encodeHRRI(href, true);
   }
   return resolvedURIString;
 }
Example #16
0
  @Override
  protected void setUp() throws IOException {
    Configuration conf = new Configuration();

    kfsEmul = new KFSEmulationImpl(conf);
    kosmosFileSystem = new KosmosFileSystem(kfsEmul);
    // a dummy URI; we are not connecting to any setup here
    kosmosFileSystem.initialize(URI.create("kfs:///"), conf);
    baseDir = new Path(System.getProperty("test.build.data", "/tmp") + "/kfs-test");
  }
  public void initialize(URI uri, Configuration conf) throws IOException {

    try {
      if (kfsImpl == null) {
        kfsImpl =
            new KFSImpl(
                conf.get("fs.kfs.metaServerHost", ""),
                conf.getInt("fs.kfs.metaServerPort", -1),
                statistics);
      }
      this.localFs = FileSystem.getLocal(conf);
      this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());

    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Unable to initialize KFS");
      System.exit(-1);
    }
  }
Example #18
0
  private String deleteResult(String URL) {
    StringBuilder sb = new StringBuilder();
    sb.append(URL);
    try {

      URI uri = new URI(String.format(sb.toString()));
      URL url = uri.toURL();

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("DELETE");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      if (conn.getResponseCode() != 204) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String output;
      sb = new StringBuilder();
      while ((output = br.readLine()) != null) {
        sb.append(output);
      }

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    } catch (URISyntaxException e) {
      e.printStackTrace();
      return null;
    }
    return sb.toString();
  }
Example #19
0
  /**
   * Evaluates a URI and adds it to the namespace map as a namespace.
   *
   * @param uri URI
   */
  protected void addNamespaceURI(URI uri) {

    if (uri == null) {
      throw new IllegalArgumentException("URI argument is null.");
    }

    // extract URI without fragment
    String uriString = uri.toString();
    String newURI = null;

    if (uriString != null) {

      // determine what comes last a '#' or '/'
      int hashindex = uriString.lastIndexOf('#');
      int slashindex = uriString.lastIndexOf('/');

      // validate (URI must contain a forward slash)
      if (slashindex == -1) {
        // namespace may have been evaluated already
        return;
      }

      // is there a '/' after the '#'?
      if (slashindex > hashindex) {

        // remove everything after the last '/'
        int index = uriString.lastIndexOf('/');
        newURI = uriString.substring(0, index) + "/";
      } else {

        // '#' comes after last '/' (remove entire fragment)
        newURI = uriString.replaceAll(uri.getFragment(), "");
      }

      // only add namespace if it is new
      if ((newURI != null) && (!namespaces.containsValue(newURI))) {
        // add to namespaces
        namespaces.put("ns" + namespaces.size(), newURI);
      }
    }
  }
 private boolean identifyNewCommitResource(
     HttpServletRequest request, HttpServletResponse response, Repository db, String newCommit)
     throws ServletException {
   try {
     URI u = getURI(request);
     IPath p = new Path(u.getPath());
     IPath np = new Path("/"); // $NON-NLS-1$
     for (int i = 0; i < p.segmentCount(); i++) {
       String s = p.segment(i);
       if (i == 2) {
         s += ".." + newCommit; // $NON-NLS-1$
       }
       np = np.append(s);
     }
     if (p.hasTrailingSeparator()) np = np.addTrailingSeparator();
     URI nu =
         new URI(
             u.getScheme(),
             u.getUserInfo(),
             u.getHost(),
             u.getPort(),
             np.toString(),
             u.getQuery(),
             u.getFragment());
     JSONObject result = new JSONObject();
     result.put(ProtocolConstants.KEY_LOCATION, nu);
     OrionServlet.writeJSONResponse(
         request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
     response.setHeader(
         ProtocolConstants.HEADER_LOCATION, resovleOrionURI(request, nu).toString());
     return true;
   } catch (Exception e) {
     return statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(
             IStatus.ERROR,
             HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
             "An error occured when identifying a new Commit resource.",
             e));
   }
 }
  protected void fetchHandlebars(String handlebarsName) throws MojoExecutionException {
    String downloadUrl = null;
    URLConnection conn = null;
    try {
      conn = handlebarsDownloadsUri.toURL().openConnection();
      List<GitHubDownloadDto> githubDownloadDtoList =
          JSON.decode(
              conn.getInputStream(),
              (new ArrayList<GitHubDownloadDto>() {}).getClass().getGenericSuperclass());
      for (GitHubDownloadDto githubDownloadDto : githubDownloadDtoList) {
        if (StringUtils.equals(githubDownloadDto.getName(), handlebarsName)) {
          downloadUrl = githubDownloadDto.getHtmlUrl();
        }
      }
    } catch (Exception e) {
      throw new MojoExecutionException("Failure fetch handlebars.", e);
    } finally {
      if (conn != null) {
        ((HttpURLConnection) conn).disconnect();
      }
    }

    conn = null;
    try {
      if (!cacheDir.exists()) {
        FileUtils.forceMkdir(cacheDir);
      }
      conn = new URL(downloadUrl).openConnection();
      if (((HttpURLConnection) conn).getResponseCode() == 302) {
        String location = conn.getHeaderField("Location");
        ((HttpURLConnection) conn).disconnect();
        conn = new URL(location).openConnection();
      }
      LOG.info("Fetch handlebars.js from GitHub (" + conn.getURL() + ")");
      IOUtils.copy(conn.getInputStream(), new FileOutputStream(new File(cacheDir, handlebarsName)));
    } catch (Exception e) {
      throw new MojoExecutionException("Failure fetch handlebars.", e);
    } finally {
      if (conn != null) {
        ((HttpURLConnection) conn).disconnect();
      }
    }
  }
  protected ModuleSource loadFromActualUri(URI uri, URI base, Object validator) throws IOException {
    final URL url = uri.toURL();
    final long request_time = System.currentTimeMillis();
    final URLConnection urlConnection = openUrlConnection(url);
    final URLValidator applicableValidator;
    if (validator instanceof URLValidator) {
      final URLValidator uriValidator = ((URLValidator) validator);
      applicableValidator = uriValidator.appliesTo(uri) ? uriValidator : null;
    } else {
      applicableValidator = null;
    }
    if (applicableValidator != null) {
      applicableValidator.applyConditionals(urlConnection);
    }
    try {
      urlConnection.connect();
      if (applicableValidator != null
          && applicableValidator.updateValidator(
              urlConnection, request_time, urlConnectionExpiryCalculator)) {
        close(urlConnection);
        return NOT_MODIFIED;
      }

      return new ModuleSource(
          getReader(urlConnection),
          getSecurityDomain(urlConnection),
          uri,
          base,
          new URLValidator(uri, urlConnection, request_time, urlConnectionExpiryCalculator));
    } catch (FileNotFoundException e) {
      return null;
    } catch (RuntimeException e) {
      close(urlConnection);
      throw e;
    } catch (IOException e) {
      close(urlConnection);
      throw e;
    }
  }
Example #23
0
    @Override
    public HTTPResponse call() throws Exception {
      final HttpURLConnection hc = (HttpURLConnection) uri.toURL().openConnection();
      hc.setReadTimeout(SOCKET_TIMEOUT);
      try {
        while (!stop) {
          try {
            final int code = hc.getResponseCode();

            final InputStream input = hc.getInputStream();
            final ByteList bl = new ByteList();
            for (int i; (i = input.read()) != -1; ) bl.add(i);

            return new HTTPResponse(code, bl.toString());
          } catch (final SocketTimeoutException e) {
          }
        }
        return null;
      } finally {
        hc.disconnect();
      }
    }
Example #24
0
    @Override
    public HTTPResponse call() throws Exception {
      final HttpURLConnection hc = (HttpURLConnection) uri.toURL().openConnection();
      try {
        hc.setDoOutput(true);
        hc.setRequestMethod(method.name());
        hc.setRequestProperty(MimeTypes.CONTENT_TYPE, MimeTypes.APP_XML);
        hc.getOutputStream().write(content);
        hc.getOutputStream().close();

        hc.setReadTimeout(SOCKET_TIMEOUT);
        while (!stop) {
          try {
            return new HTTPResponse(hc.getResponseCode());
          } catch (final SocketTimeoutException e) {
          }
        }
        return null;
      } finally {
        hc.disconnect();
      }
    }
Example #25
0
 private void setResponseLocationHeader(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException {
   URI requestURI = ServletResourceHandler.getURI(req);
   String responsePath =
       "/"
           + new Path(requestURI.getPath()).segment(0)
           + "/import/"
           + id; //$NON-NLS-1$ //$NON-NLS-2$
   URI responseURI;
   try {
     responseURI =
         new URI(requestURI.getScheme(), requestURI.getAuthority(), responsePath, null, null);
   } catch (URISyntaxException e) {
     // should not be possible
     throw new ServletException(e);
   }
   resp.setHeader(ProtocolConstants.HEADER_LOCATION, responseURI.toString());
 }
Example #26
0
 public static String convertUrlToBaseStringURI(URL url) {
   URI uri = null;
   try {
     uri = url.toURI();
   } catch (URISyntaxException e1) {
     e1.printStackTrace();
   }
   String scheme = uri.getScheme().toLowerCase();
   String host = uri.getHost().toLowerCase();
   int port = uri.getPort();
   if ((scheme.equals(HTTP_PROTOCOL) && port == HTTP_DEFAULT_PORT)
       || (scheme.equals(HTTPS_PROTOCOL) && port == HTTPS_DEFAULT_PORT)) {
     port = -1;
   }
   URI baseUri = null;
   try {
     baseUri = new URI(scheme, null, host, port, uri.getPath(), null, null);
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
   return baseUri.toString();
 }
Example #27
0
  /**
   * @param since last modified time to use
   * @param req
   * @param url if null, ignored
   * @param redirCount number of redirs we've done
   */
  public static HttpData getDataOnce(
      HttpServletRequest req,
      HttpServletResponse res,
      long since,
      String surl,
      int redirCount,
      int timeout)
      throws IOException, HttpException, DataSourceException, MalformedURLException {

    HttpMethodBase request = null;
    HostConfiguration hcfg = new HostConfiguration();

    /*
      [todo hqm 2006-02-01] Anyone know why this code was here? It is setting
      the mime type to something which just confuses the DHTML parser.

      if (res != null) {
        res.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
        }
    */

    try {

      // TODO: [2002-01-09 bloch] cope with cache-control
      // response headers (no-store, no-cache, must-revalidate,
      // proxy-revalidate).

      if (surl == null) {
        surl = getURL(req);
      }
      if (surl == null || surl.equals("")) {
        throw new MalformedURLException(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="url is empty or null"
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-312"));
      }

      String reqType = "";
      String headers = "";

      if (req != null) {
        reqType = req.getParameter("reqtype");
        headers = req.getParameter("headers");
      }

      boolean isPost = false;
      mLogger.debug("reqtype = " + reqType);

      if (reqType != null && reqType.equals("POST")) {
        request = new LZPostMethod();
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        isPost = true;
        mLogger.debug("setting POST req method");
      } else if (reqType != null && reqType.equals("PUT")) {
        request = new LZPutMethod();
        // todo [hqm 2007] treat PUT like POST?
        isPost = true;
        mLogger.debug("setting PUT req method");
      } else if (reqType != null && reqType.equals("DELETE")) {
        request = new LZDeleteMethod();
        mLogger.debug("setting DELETE req method");
      } else {
        mLogger.debug("setting GET (default) req method");
        request = new LZGetMethod();
      }

      request.setHttp11(mUseHttp11);

      // Proxy the request headers
      if (req != null) {
        LZHttpUtils.proxyRequestHeaders(req, request);
      }

      // Set headers from query string
      if (headers != null && headers.length() > 0) {
        StringTokenizer st = new StringTokenizer(headers, "\n");
        while (st.hasMoreTokens()) {
          String h = st.nextToken();
          int i = h.indexOf(":");
          if (i > -1) {
            String n = h.substring(0, i);
            String v = h.substring(i + 2, h.length());
            request.setRequestHeader(n, v);
            mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="setting header " + p[0] + "=" + p[1]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(
                    HTTPDataSource.class.getName(), "051018-359", new Object[] {n, v}));
          }
        }
      }

      mLogger.debug("Parsing url");
      URI uri = LZHttpUtils.newURI(surl);
      try {
        hcfg.setHost(uri);
      } catch (Exception e) {
        throw new MalformedURLException(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="can't form uri from " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-376", new Object[] {surl}));
      }

      // This gets us the url-encoded (escaped) path and query string
      String path = uri.getEscapedPath();
      String query = uri.getEscapedQuery();
      mLogger.debug(
          /* (non-Javadoc)
           * @i18n.test
           * @org-mes="encoded path:  " + p[0]
           */
          org.openlaszlo.i18n.LaszloMessages.getMessage(
              HTTPDataSource.class.getName(), "051018-389", new Object[] {path}));
      mLogger.debug(
          /* (non-Javadoc)
           * @i18n.test
           * @org-mes="encoded query: " + p[0]
           */
          org.openlaszlo.i18n.LaszloMessages.getMessage(
              HTTPDataSource.class.getName(), "051018-397", new Object[] {query}));

      // This call takes a decoded (unescaped) path
      request.setPath(path);

      boolean hasQuery = (query != null && query.length() > 0);

      String rawcontent = null;
      // Newer rawpost protocol puts lzpostbody as a separate
      // top level query arg in the request.
      rawcontent = req.getParameter("lzpostbody");

      if (isPost) {
        // Older rawpost protocol put the "lzpostbody" arg
        // embedded in the "url" args's query args
        if (rawcontent == null && hasQuery) {
          rawcontent = findQueryArg("lzpostbody", query);
        }
        if (rawcontent != null) {
          // Get the unescaped query string
          ((EntityEnclosingMethod) request).setRequestBody(rawcontent);
        } else if (hasQuery) {
          StringTokenizer st = new StringTokenizer(query, "&");
          while (st.hasMoreTokens()) {
            String it = st.nextToken();
            int i = it.indexOf("=");
            if (i > 0) {
              String n = it.substring(0, i);
              String v = it.substring(i + 1, it.length());
              // POST encodes values during request
              ((PostMethod) request).addParameter(n, URLDecoder.decode(v, "UTF-8"));
            } else {
              mLogger.warn(
                  /* (non-Javadoc)
                   * @i18n.test
                   * @org-mes="ignoring bad token (missing '=' char) in query string: " + p[0]
                   */
                  org.openlaszlo.i18n.LaszloMessages.getMessage(
                      HTTPDataSource.class.getName(), "051018-429", new Object[] {it}));
            }
          }
        }
      } else {
        // This call takes an encoded (escaped) query string
        request.setQueryString(query);
      }

      // Put in the If-Modified-Since headers
      if (since != -1) {
        String lms = LZHttpUtils.getDateString(since);
        request.setRequestHeader(LZHttpUtils.IF_MODIFIED_SINCE, lms);
        mLogger.debug(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="proxying lms: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-450", new Object[] {lms}));
      }

      mLogger.debug(
          /* (non-Javadoc)
           * @i18n.test
           * @org-mes="setting up http client"
           */
          org.openlaszlo.i18n.LaszloMessages.getMessage(
              HTTPDataSource.class.getName(), "051018-460"));
      HttpClient htc = null;
      if (mConnectionMgr != null) {
        htc = new HttpClient(mConnectionMgr);
      } else {
        htc = new HttpClient();
      }

      htc.setHostConfiguration(hcfg);

      // This is the data timeout
      mLogger.debug(
          /* (non-Javadoc)
           * @i18n.test
           * @org-mes="timeout set to " + p[0]
           */
          org.openlaszlo.i18n.LaszloMessages.getMessage(
              HTTPDataSource.class.getName(), "051018-478", new Object[] {new Integer(timeout)}));
      htc.setTimeout(timeout);

      // Set connection timeout the same
      htc.setConnectionTimeout(mConnectionTimeout);

      // Set timeout for getting a connection
      htc.setHttpConnectionFactoryTimeout(mConnectionPoolTimeout);

      // TODO: [2003-03-05 bloch] this should be more configurable (per app?)
      if (!isPost) {
        request.setFollowRedirects(mFollowRedirects > 0);
      }

      long t1 = System.currentTimeMillis();
      mLogger.debug("starting remote request");
      int rc = htc.executeMethod(hcfg, request);
      String status = HttpStatus.getStatusText(rc);
      if (status == null) {
        status = "" + rc;
      }
      mLogger.debug(
          /* (non-Javadoc)
           * @i18n.test
           * @org-mes="remote response status: " + p[0]
           */
          org.openlaszlo.i18n.LaszloMessages.getMessage(
              HTTPDataSource.class.getName(), "051018-504", new Object[] {status}));

      HttpData data = null;
      if (isRedirect(rc) && mFollowRedirects > redirCount) {
        String loc = request.getResponseHeader("Location").toString();
        String hostURI = loc.substring(loc.indexOf(": ") + 2, loc.length());
        mLogger.info(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="Following URL from redirect: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-517", new Object[] {hostURI}));
        long t2 = System.currentTimeMillis();
        if (timeout > 0) {
          timeout -= (t2 - t1);
          if (timeout < 0) {
            throw new InterruptedIOException(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes=p[0] + " timed out after redirecting to " + p[1]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(
                    HTTPDataSource.class.getName(), "051018-529", new Object[] {surl, loc}));
          }
        }

        data = getDataOnce(req, res, since, hostURI, redirCount++, timeout);
      } else {
        data = new HttpData(request, rc);
      }

      if (req != null && res != null) {
        // proxy response headers
        LZHttpUtils.proxyResponseHeaders(request, res, req.isSecure());
      }

      return data;

    } catch (ConnectTimeoutException ce) {
      // Transduce to an InterrupedIOException, since lps takes these to be timeouts.
      if (request != null) {
        request.releaseConnection();
      }
      throw new InterruptedIOException(
          /* (non-Javadoc)
           * @i18n.test
           * @org-mes="connecting to " + p[0] + ":" + p[1] + " timed out beyond " + p[2] + " msecs."
           */
          org.openlaszlo.i18n.LaszloMessages.getMessage(
              HTTPDataSource.class.getName(),
              "051018-557",
              new Object[] {
                hcfg.getHost(), new Integer(hcfg.getPort()), new Integer(mConnectionTimeout)
              }));
    } catch (HttpRecoverableException hre) {
      if (request != null) {
        request.releaseConnection();
      }
      throw hre;
    } catch (HttpException e) {
      if (request != null) {
        request.releaseConnection();
      }
      throw e;
    } catch (IOException ie) {
      if (request != null) {
        request.releaseConnection();
      }
      throw ie;
    } catch (RuntimeException e) {
      if (request != null) {
        request.releaseConnection();
      }
      throw e;
    }
  }
Example #28
0
  /**
   * Creates a new FTPFile instance by converting the given file: URI into an abstract pathname.
   *
   * <p>FTP URI protocol:<br>
   * ftp:// [ userName [ : password ] @ ] host [ : port ][ / path ]
   *
   * <p>example:<br>
   * ftp://[email protected]:21/pub/testfile.txt
   *
   * @param uri An absolute, hierarchical URI using a supported scheme.
   * @throws NullPointerException if <code>uri</code> is <code>null</code>.
   * @throws IllegalArgumentException If the preconditions on the parameter do not hold.
   */
  public FTPFile(URI uri) throws IOException, URISyntaxException {
    super(uri);

    if (uri.getScheme().equals("ftp")) {
      String userinfo = uri.getUserInfo();
      if (userinfo != null) {
        int index = userinfo.indexOf(":");
        if (index >= 0) {
          setFileSystem(
              new FTPFileSystem(
                  new FTPAccount(
                      uri.getHost(),
                      uri.getPort(),
                      userinfo.substring(0, index - 1),
                      userinfo.substring(index + 1),
                      uri.getPath())));
        } else {
          setFileSystem(
              new FTPFileSystem(
                  new FTPAccount(uri.getHost(), uri.getPort(), userinfo, "", uri.getPath())));
        }
      } else {
        fileSystem =
            new FTPFileSystem(
                new FTPAccount(uri.getHost(), uri.getPort(), null, "", uri.getPath()));
      }

      setFileName(uri.getPath());
      ftpClient = ((FTPFileSystem) fileSystem).getFTPClient();
    } else {
      throw new URISyntaxException(uri.toString(), "Wrong URI scheme");
    }
  }
Example #29
0
 /**
  * Construct a new GET request.
  *
  * @param request request string without the base URI
  */
 public Get(final String request) {
   uri = URI.create(BASE_URL + request);
 }
Example #30
0
 /**
  * Construct a new request.
  *
  * @param request request string without the base URI
  * @param data data to send to the server
  * @param m HTTP method
  */
 protected Put(final String request, final byte[] data, final HTTPMethod m) {
   uri = URI.create(BASE_URL + request);
   content = data;
   method = m;
 }