コード例 #1
0
  /**
   * This method will read the standard input and save the content to a temporary. source file since
   * the source file will be parsed mutiple times. The HTML source file is parsed and checked for
   * Charset in HTML tags at first time, then source file is parsed again for the converting The
   * temporary file is read from standard input and saved in current directory and will be deleted
   * after the conversion has completed.
   *
   * @return the vector of the converted temporary source file name
   */
  public Vector getStandardInput() throws FileAccessException {
    byte[] buf = new byte[2048];
    int len = 0;
    FileInputStream fis = null;
    FileOutputStream fos = null;
    File tempSourceFile;
    String tmpSourceName = ".tmpSource_stdin";

    File outFile = new File(tmpSourceName);

    tempSourceFile = new File(System.getProperty("user.dir") + sep + tmpSourceName);
    if (!tempSourceFile.exists()) {
      try {
        fis = new FileInputStream(FileDescriptor.in);
        fos = new FileOutputStream(outFile);
        while ((len = fis.read(buf, 0, 2048)) != -1) fos.write(buf, 0, len);
      } catch (IOException e) {
        System.out.println(ResourceHandler.getMessage("plugin_converter.write_permission"));
        return null;
      }
    } else {
      throw new FileAccessException(ResourceHandler.getMessage("plugin_converter.overwrite"));
    }
    tempSourceFile = new File(System.getProperty("user.dir") + sep + tmpSourceName);
    if (tempSourceFile.exists()) {
      fileSpecs.add(tmpSourceName);
      return fileSpecs;
    } else {
      throw new FileAccessException(
          ResourceHandler.getMessage("plugin_converter.write_permission"));
    }
  }
コード例 #2
0
  /**
   * This method will take in a string which will be a directory. It will make sure that the
   * directory exists and return the absolute path
   *
   * @return the value of the absolute directory
   */
  private String doesExistAndAbsolute(String dir) {

    File tempDirFile = new File(dir);
    try {
      if (tempDirFile.exists()) {
        if (tempDirFile.isAbsolute()) {
          return dir;
        } else {
          tempDirFile = new File(System.getProperty("user.dir") + sep + dir);
          if (tempDirFile.exists()) {
            return tempDirFile.getAbsolutePath();
          } else {
            throw new NotDirectoryException(
                ResourceHandler.getMessage("caption.reldirnotfound")
                    + ":  "
                    + tempDirFile.getAbsolutePath());
          }
        }
      } else {
        throw new NotDirectoryException(
            ResourceHandler.getMessage("caption.absdirnotfound")
                + ":  "
                + tempDirFile.getAbsolutePath());
      }

    } catch (NotDirectoryException e) {
      System.out.println(
          ResourceHandler.getMessage("caption.absdirnotfound")
              + ":  "
              + tempDirFile.getAbsolutePath());
      return null; // this is just so it would compile
    }
  }
コード例 #3
0
ファイル: JettyServer.java プロジェクト: angelndevil2/LoadT
  public void run() {

    Properties jettyProperties = new Properties();
    String pFileName = PropertiesUtil.getJettyPropertiesFile();
    try {
      jettyProperties.load(new FileInputStream(pFileName));
    } catch (IOException e) {
      log.error("load properties from {} error.", pFileName);
      return;
    }

    // crate server
    server = new Server(Integer.parseInt(jettyProperties.getProperty(PropList.HTTP_PORT)));

    // Create the ResourceHandler. It is the object that will actually handle the request for a
    // given file. It is
    // a Jetty Handler object so it is suitable for chaining with other handlers as you will see in
    // other examples.
    ResourceHandler resource_handler = new ResourceHandler();
    // Configure the ResourceHandler. Setting the resource base indicates where the files should be
    // served out of.
    // In this example it is the current directory but it can be configured to anything that the jvm
    // has access to.
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[] {"index.html"});
    resource_handler.setResourceBase(PropertiesUtil.getWebBaseDir());

    log.debug(PropertiesUtil.getWebBaseDir());

    // Add a single handler on context "/hello"
    ContextHandler context = new ContextHandler();
    context.setContextPath("/LoadT");
    context.setHandler(new LoadTHandler());

    // Add the ResourceHandler to the server.
    GzipHandler gzip = new GzipHandler();
    server.setHandler(gzip);

    // make handler chain
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {resource_handler, context, new DefaultHandler()});
    gzip.setHandler(handlers);

    try {
      server.start();
    } catch (Exception e) {
      log.error("embedded jetty server start error.", e);
    }

    server.dumpStdErr();

    /*
    try {
        server.join();
    } catch (InterruptedException e) {
        log.info("jetty server interrupted", e);
    }*/
  }
コード例 #4
0
 @Override
 public void processFromDirectory(String metaDir) throws Exception {
   log.debug("Processing html files in '{}' for copyright update.", metaDir);
   ResourceHandler handler = injector.getInstance(ResourceHandler.class);
   log.trace("Got handler from injector. {}", handler);
   File contentDirectory = new File(metaDir).getAbsoluteFile().getParentFile();
   if (contentDirectory.exists()) {
     log.trace("The contentDirectory '{}' exists.", contentDirectory);
     Collection<File> htmlFiles =
         FileUtils.listFiles(contentDirectory, new String[] {"html", "htm"}, true);
     log.debug("Found {} html files.", htmlFiles.size());
     for (File htmlFile : htmlFiles) {
       log.trace("Processing {}", htmlFile);
       handler.handleFile(htmlFile);
     }
   }
 }
コード例 #5
0
  /**
   * This will make sure the destination path isn't the same as the backup directory, the
   * application will terminate if they are the same
   */
  private void checkForProblems() throws CommandLineException {

    if ((backupStr != null) && (destStr != null)) {
      File fBackupTemp = new File(backupStr);
      File fDestTemp = new File(destStr);

      if ((fDestTemp.getAbsolutePath()).equals(fBackupTemp.getAbsolutePath())) {
        System.out.println(ResourceHandler.getMessage("illegal_source_and_backup.info"));
        throw new CommandLineException();
      }
    }
  }
コード例 #6
0
  private void addResourceHandler(String contextPath, String filePath) throws Exception {
    if (handlerCollection != null) {
      logger.log(Level.INFO, "Adding resource : " + contextPath + "=>" + filePath);

      ResourceHandler resourceHandler = new ResourceHandler();
      resourceHandler.setResourceBase(filePath);

      logger.log(Level.INFO, "serving: " + resourceHandler.getBaseResource());

      ContextHandler contextHandler = new ContextHandler(contextPath);
      contextHandler.setHandler(resourceHandler);

      handlerCollection.addHandler(contextHandler);

      try {
        resourceHandler.start();
        contextHandler.start();
      } catch (Exception e) {
        logger.log(Level.INFO, "Could not start resource context", e);
      }
    }
  }
コード例 #7
0
  /**
   * This will take in the string given at the command line by the user find if it is null and calls
   * readline().
   *
   * @param s[] holds the given command line string
   */
  public CommandLine(String s[]) throws CommandLineException, IndexOutOfBoundsException {
    if (s == null || s.length == 0) { // there are no params
      params = false;
    } else {
      params = true;
      commandLine = s;
      readLine();
      //
      // If no files are specified, default.
      //

      if ((isStdIn() == false) && fileSpecs.isEmpty()) {

        String specs = ResourceHandler.getMessage("converter_gui.lablel2");
        StringTokenizer st = new StringTokenizer(specs, " ,");
        while (st.hasMoreTokens()) {
          fileSpecs.add(st.nextToken());
        }
      }
      checkForProblems();
    }
  }
コード例 #8
0
  @Override
  protected void doPost(
      @NotNull final HttpServletRequest request,
      @NotNull final HttpServletResponse response,
      @NotNull final Element xmlResponse) {
    final ActionErrors errors = new ActionErrors();
    final BasePropertiesBean propsBean = new BasePropertiesBean(null);
    PluginPropertiesUtil.bindPropertiesFromRequest(request, propsBean, true);

    final Map<String, String> props = propsBean.getProperties();
    final String subscriptionId = props.get(AzureWebConstants.SUBSCRIPTION_ID);
    final String certificate = props.get("secure:" + AzureWebConstants.MANAGEMENT_CERTIFICATE);

    final AzureApiConnector apiConnector;
    try {
      apiConnector = new AzureApiConnector(subscriptionId, certificate);
      apiConnector.test();
    } catch (InvalidCertificateException ex) {
      errors.addError(
          "certificateError",
          "Invalid Management certificate. Please enter the Management Certificate exactly as it is presented in the subscription file.");
      errors.serialize(xmlResponse);
      LOG.warnAndDebugDetails("An error during initializing connection: " + ex.getMessage(), ex);
      return;
    } catch (CheckedCloudException ex) {
      errors.addError(
          "pingError",
          "Error connecting to Microsoft Azure. Please check that your Management Certificate and Subscription ID are valid.");
      errors.serialize(xmlResponse);
      LOG.warnAndDebugDetails("An error during initializing connection: " + ex.getMessage(), ex);
      return;
    }

    final List<Promise<Content, Throwable, Void>> promises = new ArrayList<>(myHandlers.size());
    for (final ResourceHandler handler : myHandlers) {
      try {
        final Promise<Content, Throwable, Void> promise =
            handler
                .handle(apiConnector)
                .fail(
                    new FailCallback<Throwable>() {
                      @Override
                      public void onFail(Throwable result) {
                        LOG.warn(
                            String.format(
                                "Failed to execute handler %s: %s", handler.getName(), result),
                            result);
                        errors.addError(handler.getName(), result.getMessage());
                      }
                    });
        promises.add(promise);
      } catch (Throwable t) {
        LOG.warn(
            String.format("Failed to add handler %s: %s", handler.getName(), t.getMessage()), t);
        errors.addError(handler.getName(), t.getMessage());
      }
    }

    if (promises.size() == 0) {
      if (errors.hasErrors()) {
        writeErrors(xmlResponse, errors);
      }

      return;
    }

    try {
      myManager
          .when(promises.toArray(new Promise[] {}))
          .always(
              new AlwaysCallback<MultipleResults, OneReject>() {
                @Override
                public void onAlways(
                    Promise.State state, MultipleResults resolved, OneReject rejected) {
                  if (errors.hasErrors()) {
                    writeErrors(xmlResponse, errors);
                  } else {
                    for (OneResult oneResult : resolved) {
                      xmlResponse.addContent((Content) oneResult.getResult());
                    }
                  }
                }
              })
          .waitSafely();
    } catch (InterruptedException e) {
      LOG.warn("Request executing has been interrupted: " + e.getMessage());
      errors.addError("handler", e.getMessage());
      writeErrors(xmlResponse, errors);
    }
  }