public void info(String msg) {
   SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
   try {
     IOUtils.write(
         String.format("[INFO][%s] %s", sdf.format(new Date()), msg), this.getOutputStream());
     IOUtils.write(IOUtils.LINE_SEPARATOR, this.getOutputStream());
   } catch (IOException e) {
     log.error(e.getMessage(), e);
   }
 }
  @Override
  public void doEncode(ILoggingEvent event) throws IOException {

    write(formatter.writeValueAsBytes(event, getContext()), outputStream);
    write(CoreConstants.LINE_SEPARATOR, outputStream);

    if (immediateFlush) {
      outputStream.flush();
    }
  }
  private void createLeiEtAlSolution(Solution solution) throws IOException {
    // open the output file
    Calendar c = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd-HH-mm-ss");

    String outputDirectory = getOutputDirectory();

    if (StringUtils.isNotEmpty(outputDirectory)) {
      File outputFile =
          new File(
              outputDirectory
                  + "LeiEtAl-"
                  + solution.getVrpProblem().getDescription()
                  + "-"
                  + sdf.format(c.getTime())
                  + ".csv");
      outputStream = FileUtils.openOutputStream(outputFile, true);
      LeiEtAlHeuristic metaHeuristic = getMetaheuristicOutputStream();

      IOUtils.write(
          "Iteration; #CustomersChanged; RemovalHeuristic; TimeForRemoval; InsertionHeuristic; "
              + "TimeForInsertion; BestSolution?; ImprovedSolution?; AcceptedSolution?; TotalDistance; RecourseCost;"
              + "PenaltyCost; Anzahl Touren; KFZ Soll; Solution; Weights \n\n",
          outputStream);

      long startTime = System.nanoTime();
      Solution improvedSolutionVehicleMinimizationStage = minimizationStage(solution);
      Solution improvedSolutionDistanceMinimizationStage =
          metaHeuristic.improve(improvedSolutionVehicleMinimizationStage, configuration);
      long endTime = System.nanoTime();
      String timeTaken = (endTime - startTime) / 1000 / 1000 + " ms\n";

      // create an intermediate --- line, just for easier cutting
      IOUtils.write("----------\n", outputStream);
      IOUtils.write(timeTaken, outputStream);
      IOUtils.write(improvedSolutionDistanceMinimizationStage.getIteration() + "\n", outputStream);
      IOUtils.write(improvedSolutionDistanceMinimizationStage.getSolutionAsString(), outputStream);

      //            IOUtils.closeQuietly(outputStream);
    } else {
      LeiEtAlHeuristic metaHeuristic = getMetaheuristicConsoleOutput();

      long startTime = System.nanoTime();
      Solution improvedSolutionVehicleMinimizationStage = minimizationStage(solution);
      Solution improvedSolutionDistanceMinimizationStage =
          metaHeuristic.improve(improvedSolutionVehicleMinimizationStage, configuration);
      long endTime = System.nanoTime();
      String timeTaken = (endTime - startTime) / 1000 / 1000 + " ms\n";

      System.out.println("----------");
      System.out.println(timeTaken);
      System.out.println(improvedSolutionDistanceMinimizationStage.getIteration());
      System.out.println(improvedSolutionDistanceMinimizationStage.getSolutionAsString());
    }
  }
 public void error(String errorMsg, Throwable t) {
   SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
   try {
     IOUtils.write(
         String.format("[ERROR][%s] %s", sdf.format(new Date()), errorMsg),
         this.getOutputStream());
     IOUtils.write(IOUtils.LINE_SEPARATOR, this.getOutputStream());
     t.printStackTrace(new PrintStream(this.getOutputStream()));
     IOUtils.write(IOUtils.LINE_SEPARATOR, this.getOutputStream());
   } catch (IOException e) {
     log.error(e.getMessage(), e);
   }
 }
 public static void persistentInFile(String fileDir, String fileName, String str) {
   File file = new File(fileDir, fileName);
   FileWriter fileWriter = null;
   try {
     fileWriter = new FileWriter(file, true);
     IOUtils.write(str, fileWriter);
     IOUtils.write(LINE_SEPARATOR.getBytes(), fileWriter);
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     IOUtils.closeQuietly(fileWriter);
   }
 }
    @Override
    public void createContent() throws Exception {
      try {
        IContentItem responseContentItem =
            outputHandler.getOutputContentItem(
                IOutputHandler.RESPONSE, IOutputHandler.CONTENT, null, null);
        // mime type setting will blow up since servlet api used by grizzly is too old
        try {
          responseContentItem.setMimeType("text/plain");
        } catch (Throwable t) {
        }
        OutputStream outputStream = responseContentItem.getOutputStream(null);
        IParameterProvider pathParams = parameterProviders.get("path");
        String command = pathParams.getStringParameter("cmd", "");

        Object testParamValue =
            parameterProviders.get(IParameterProvider.SCOPE_REQUEST).getParameter("testParam");
        assertEquals("testParam is missing from request", "testParamValue", testParamValue);

        IOUtils.write(
            "hello this is service content generator servicing command " + command, outputStream);
        outputStream.close();
      } catch (Throwable t) {
        t.printStackTrace();
      }
    }
  private void createLeiEtAlSolution(VrpProblem problem, String name) throws IOException {
    // first, create an initial solution
    StochasticPushForwardInsertionSolver initialSolver = new StochasticPushForwardInsertionSolver();
    Solution solution = initialSolver.solve(problem);

    LeiEtAlHeuristic leaHeuristic = new LeiEtAlHeuristic();

    long startTime = System.nanoTime();
    Solution improvedSolution = leaHeuristic.improve(solution, configuration);
    long endTime = System.nanoTime();
    String timeTaken = (endTime - startTime) / 1000 / 1000 + " ms\n";

    IOUtils.write(
        name
            + ";"
            + problem.getCustomers().size()
            + 1
            + ";"
            + problem.getVehicleCount()
            + ";"
            + problem.getVehicles().iterator().next().getCapacity()
            + ";"
            + String.format("%.3f", improvedSolution.getTotalDistance())
            + ";"
            + String.format("%.3f", improvedSolution.getExpectedRecourseCost())
            + ";"
            + String.format(
                "%.3f", improvedSolution.getSumOfDistanceAndExpectedRecourseCostAndPenaltyCost())
            + ";"
            + timeTaken
            + "\n",
        outputStream);
  }
 private void innerGet(String path, HttpServletResponse response) throws IOException {
   path = path.replace("/static/", "");
   if (FilenameUtils.isExtension(path, "js")) {
     path = "js/" + path;
     response.setContentType("text/javascript; charset=UTF-8");
   } else if (FilenameUtils.isExtension(path, "css") || FilenameUtils.isExtension(path, "less")) {
     path = "css/" + path;
     response.setContentType("text/css; charset=UTF-8");
   } else if (FilenameUtils.isExtension(path, IMG_EXTENSION)) {
     path = "img/" + path;
     response.setContentType("image/" + FilenameUtils.getExtension(path));
   }
   path = "view/" + path;
   if (path.endsWith(".handlebars.js")) {
     // handlebars
     response.setContentType("text/javascript; charset=UTF-8");
     path = path.substring(0, path.length() - 3);
     File file = new File(getWebInf(), path);
     String content = FileUtils.readFileToString(file, "UTF-8");
     try {
       content = HandlebarsObj.toJavaScript(content);
       IOUtils.write(content.getBytes("UTF-8"), response.getOutputStream());
     } catch (Exception e) {
       throw new ServerError(e);
     }
   } else {
     sendFile(response, path);
   }
 }
Esempio n. 9
0
  public static void writeDataToRequest(
      HttpRequest newWebRequest, String postedData, boolean disableRequestCompression) {

    HttpEntityEnclosingRequestBase requestMethod = (HttpEntityEnclosingRequestBase) newWebRequest;

    try {
      if (disableRequestCompression) {
        StringEntity entity = new StringEntity(postedData, ContentType.APPLICATION_JSON);
        entity.setChunked(true);
        requestMethod.setEntity(entity);
      } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzipOS = new GZIPOutputStream(baos);
        IOUtils.write(postedData, gzipOS, Consts.UTF_8.name());
        IOUtils.closeQuietly(gzipOS);
        ByteArrayEntity entity =
            new ByteArrayEntity(baos.toByteArray(), ContentType.APPLICATION_JSON);
        entity.setChunked(true);
        requestMethod.setEntity(entity);
      }

    } catch (IOException e) {
      throw new RuntimeException("Unable to gzip data!", e);
    }
  }
  /**
   * This extracts the given class' resource to the specified file if it doesn't already exist.
   *
   * @param resourceClass the class associated with the resource
   * @param name the resource's name
   * @param file where to put the resource
   * @return true if successful, false if not.
   */
  public boolean extractResourceAsFile(Class resourceClass, String name, File file) {
    InputStream stream = resourceClass.getResourceAsStream(name);
    if (stream == null) {
      return false;
    }

    byte[] bytes = new byte[0];
    try {
      bytes = IOUtils.toByteArray(stream);
    } catch (IOException e) {
      logger.error("Extracting resource as file", e);
      return false;
    }

    FileOutputStream fileOutputStream = null;
    try {
      fileOutputStream = new FileOutputStream(file);
      IOUtils.write(bytes, fileOutputStream);
      return true;
    } catch (IOException e) {
      logger.error("Extracting resource as file (writing bytes)", e);
      return false;
    } finally {
      IOUtils.closeQuietly(fileOutputStream);
    }
  }
Esempio n. 11
0
  @Override
  public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources)
      throws FrameworkException {

    if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) {

      try {
        final String sandboxFilename = getSandboxFileName(sources[0].toString());
        if (sandboxFilename != null) {

          final File file = new File(sandboxFilename);

          try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file, true))) {

            for (int i = 1; i < sources.length; i++) {
              IOUtils.write(sources[i].toString(), writer);
            }

            writer.flush();
          }
        }

      } catch (IOException ioex) {
        ioex.printStackTrace();
      }
    }

    return "";
  }
  @Test
  public void testReceivingFiles() throws Throwable {
    final Set<String> files = new ConcurrentSkipListSet<String>();
    integrationTestUtils.createConsumer(
        this.messageChannel,
        new MessageHandler() {
          @Override
          public void handleMessage(Message<?> message) throws MessagingException {
            File file = (File) message.getPayload();
            String filePath = file.getPath();
            files.add(filePath);
          }
        });

    int cnt = 10;
    for (int i = 0; i < cnt; i++) {
      File out = new File(directoryToMonitor, i + ".txt");
      Writer w = new BufferedWriter(new FileWriter(out));
      IOUtils.write("test" + i, w);
      IOUtils.closeQuietly(w);
    }

    Thread.sleep(TimeUnit.SECONDS.toMillis(20));
    Assert.assertEquals(cnt, files.size());
  }
  /**
   * Generates the metadata source file
   *
   * @param config the metadata configuration
   * @param directory the output directory
   * @param pkgName the output package name
   */
  protected void generateMetadataSource(MetadataConfig config, File directory, String pkgName)
      throws IOException {
    // Load template for M.java
    String template =
        IOUtils.toString(
            getClass().getClassLoader().getResourceAsStream(GEN_SOURCE_NAME + ".template"));
    template = template.replace("{PACKAGE}", pkgName);

    StringBuilder sb = new StringBuilder();
    renderReferencesAsClasses(sb, config);
    template = template.replace("{REFERENCES}", sb.toString());

    String outputPath =
        directory.getPath()
            + File.separator
            + pkgName.replace(".", File.separator)
            + File.separator
            + GEN_SOURCE_NAME;
    File outputFile = new File(outputPath);

    // Make sub-folders if necessary
    if (!outputFile.getParentFile().exists()) {
      outputFile.getParentFile().mkdirs();
    }

    FileWriter writer = new FileWriter(outputFile);
    IOUtils.write(template, writer);
    writer.close();

    getLog().info("Generated " + outputFile.getPath());
  }
    @Override
    public void execute() throws Exception {
      IParameterProvider pathParams = parameterProviders.get("path");
      String command = pathParams.getStringParameter("cmd", "");

      IOUtils.write("hello this is service content generator servicing command " + command, out);
      out.close();
    }
 /**
  * Creates a temporary JSON file with the specified layout.
  *
  * @param desc Layout descriptor.
  * @return Temporary JSON file containing the specified layout.
  * @throws IOException on I/O error.
  */
 public static File getTempFile(TableLayoutDesc desc) throws IOException {
   final File layoutFile = File.createTempFile("layout-" + desc.getName(), "json");
   layoutFile.deleteOnExit();
   final OutputStream fos = new FileOutputStream(layoutFile);
   IOUtils.write(ToJson.toJsonString(desc), fos);
   ResourceUtils.closeOrLog(fos);
   return layoutFile;
 }
Esempio n. 16
0
  public void writeString(String outputFile, List<String> rs) throws Exception {
    OutputStream out = new FileOutputStream(new File(outputFile), false);
    for (String s : rs) {
      IOUtils.write(s + "\n", out, "GB2312");
    }

    out.close();
  }
Esempio n. 17
0
 @Test
 public void uploadFromFile() throws IOException {
   OutputStream outputStream = new FileOutputStream(downloadedFile);
   IOUtils.write(this.bytes, outputStream);
   outputStream.close();
   expectStatusCode(201);
   object.uploadObject(downloadedFile);
   verifyUploadContent(this.bytes);
 }
Esempio n. 18
0
 /**
  * Writes bytes from a <code>byte[]</code> to chars on a <code>Writer</code> using the specified
  * character encoding.
  *
  * <p>Character encoding names can be found at <a
  * href="http://www.iana.org/assignments/character-sets">IANA</a>.
  *
  * <p>This method uses {@link String#String(byte[], String)}.
  *
  * @param data the byte array to write, do not modify during output, null ignored
  * @param output the <code>Writer</code> to write to
  * @param encoding the encoding to use, null means platform default
  * @throws NullPointerException if output is null
  * @throws IOException if an I/O error occurs
  * @since Commons IO 1.1
  */
 public static void write(byte[] data, Writer output, String encoding) throws IOException {
   if (data != null) {
     if (encoding == null) {
       write(data, output);
     } else {
       output.write(new String(data, encoding));
     }
   }
 }
Esempio n. 19
0
 /**
  * Writes chars from a <code>String</code> to bytes on an <code>OutputStream</code> using the
  * specified character encoding.
  *
  * <p>Character encoding names can be found at <a
  * href="http://www.iana.org/assignments/character-sets">IANA</a>.
  *
  * <p>This method uses {@link String#getBytes(String)}.
  *
  * @param data the <code>String</code> to write, null ignored
  * @param output the <code>OutputStream</code> to write to
  * @param encoding the encoding to use, null means platform default
  * @throws NullPointerException if output is null
  * @throws IOException if an I/O error occurs
  * @since Commons IO 1.1
  */
 public static void write(String data, OutputStream output, String encoding) throws IOException {
   if (data != null) {
     if (encoding == null) {
       write(data, output);
     } else {
       output.write(data.getBytes(encoding));
     }
   }
 }
Esempio n. 20
0
 public TubainaDir writeIndex(StringBuffer bookContent) {
   File file = new File(currentFolder, "index.html");
   try {
     IOUtils.write(bookContent, new PrintStream(file, "UTF-8"));
     return this;
   } catch (IOException e) {
     throw new TubainaException("Couldn't create index.html in " + currentFolder);
   }
 }
Esempio n. 21
0
 public static void write(StringBuffer var0, OutputStream var1, String var2) throws IOException {
   if (var0 != null) {
     if (var2 == null) {
       write(var0, var1);
     } else {
       byte[] var3 = var0.toString().getBytes(var2);
       var1.write(var3);
     }
   }
 }
Esempio n. 22
0
 public static void write(byte[] var0, Writer var1, String var2) throws IOException {
   if (var0 != null) {
     if (var2 == null) {
       write(var0, var1);
     } else {
       String var3 = new String(var0, var2);
       var1.write(var3);
     }
   }
 }
Esempio n. 23
0
 public static void write(char[] var0, OutputStream var1, String var2) throws IOException {
   if (var0 != null) {
     if (var2 == null) {
       write(var0, var1);
     } else {
       byte[] var3 = (new String(var0)).getBytes(var2);
       var1.write(var3);
     }
   }
 }
Esempio n. 24
0
 /**
  * Writes a table layout as a JSON descriptor in a temporary file.
  *
  * @param layoutDesc Table layout descriptor to write.
  * @return the temporary File where the layout has been written.
  * @throws Exception on error.
  */
 private File getTempLayoutFile(TableLayoutDesc layoutDesc) throws Exception {
   final File layoutFile = File.createTempFile(layoutDesc.getName(), ".json", getLocalTempDir());
   final OutputStream fos = new FileOutputStream(layoutFile);
   try {
     IOUtils.write(ToJson.toJsonString(layoutDesc), fos);
   } finally {
     fos.close();
   }
   return layoutFile;
 }
Esempio n. 25
0
 private String createUploadHandle(ModelId id, byte[] content, String fileName) {
   try {
     File file = File.createTempFile("vorto", fileName);
     IOUtils.write(content, new FileOutputStream(file));
     logger.debug("Created temporary file for upload : " + file.getName());
     return file.getName();
   } catch (IOException e) {
     throw new RuntimeException("Could not create temporary file for uploaded model", e);
   }
 }
 public void generar(final Programa programa) throws IOException, InterruptedException {
   OutputStream stream = ryspeGeneradorPdf.generar(programa.getIdPrograma());
   assertNotNull(stream);
   dest = "pdfs/reportePruebaIntegral" + System.currentTimeMillis() + ".pdf";
   FileOutputStream fileOutputStream = new FileOutputStream(dest);
   IOUtils.write(((ByteArrayOutputStream) stream).toByteArray(), fileOutputStream);
   stream.close();
   fileOutputStream.close();
   RypseIntegrationTest.abrirArchivoEscritorioUi(dest);
 }
Esempio n. 27
0
  /**
   * 请求远程地址,将内容输出到指定的OutputStream输出流,试用于文件下载
   *
   * @param out
   */
  public void post(OutputStream out) {

    String paramStr = "";

    if (StringUtils.isNotBlank(this.body)) {
      paramStr = this.body;
    } else if (this.getParam() != null) {
      paramStr = Http.param2String(this.getParam());
    }

    InputStream in = null;
    OutputStream out2 = null;
    HttpURLConnection conn = null;

    try {
      URL url = new URL(this.getAddress());
      // 打开和URL之间的连接
      conn = getHttpURLConnection(url);

      conn.setAllowUserInteraction(false);
      conn.setUseCaches(false);
      conn.setRequestMethod("POST");
      conn.setConnectTimeout(this.getConnectTimeout());
      conn.setReadTimeout(this.getReadTimeout());
      conn.setDoOutput(true);
      conn.setDoInput(true);

      // 设置的请求属性
      for (String name : this.getHeader()) {
        conn.setRequestProperty(name, this.getHeader().getHeader(name));
      }

      out2 = conn.getOutputStream();

      IOUtils.write(paramStr, out2, this.getEncoding());

      in = conn.getInputStream();

      IOUtils.copy(in, out);

    } catch (Exception e) {
      throw new HttpException("post方式请求远程地址失败", e);
    } finally {
      IOUtils.closeQuietly(out);
      IOUtils.closeQuietly(out2);
      IOUtils.closeQuietly(in);
      if (conn != null) {
        try {
          conn.disconnect();
        } catch (Exception e) {
          log.warn("关闭HttpURLConnection失败.", e);
        }
      }
    }
  }
 /**
  * Writes file to the local FS. Uses by.grsu.dz.dao.AbstractDao.getTableClass() to resolve
  * filename.
  *
  * @param xml data to be written in file
  */
 private void writeToFile(final String xml) {
   try {
     final File file = new File(getFileName());
     if (!file.exists()) {
       file.createNewFile();
     }
     IOUtils.write(xml, new FileOutputStream(file));
   } catch (final Exception e) {
     throw new RuntimeException(e);
   }
 }
Esempio n. 29
0
 @SneakyThrows
 public static boolean FilePutContents(String filePath, String contents) {
   boolean result = true;
   try {
     IOUtils.write(contents, new FileOutputStream(filePath));
   } catch (Exception e) {
     result = false;
     throw e;
   }
   return result;
 }
Esempio n. 30
0
  /**
   * Update the result file for this test. Result serialization is done with JSON and this should
   * adequate for most users. If you need an alternative format, you may override this method.
   *
   * @param actual the new result to be saved
   * @throws ParserException
   * @throws LexException
   * @throws IOException
   */
  protected void testUpdate(R actual) throws ParserException, LexException, IOException {
    Gson gson = new Gson();
    String json = gson.toJson(actual);

    // Make sure file can be created
    File f = new File(resultPath);
    if (!f.exists()) {
      f.getParentFile().mkdirs();
    }

    IOUtils.write(json, new FileOutputStream(resultPath), ParseTcFacade.UTF8);
  }