@Override
 protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage)
     throws IOException, HttpMessageNotReadableException {
   MediaType contentType = inputMessage.getHeaders().getContentType();
   Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : DEFAULT_CHARSET;
   return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));
 }
示例#2
0
  public int doEndTag() throws JspException {
    try {
      List<ValidationMetaData> rules = new ArrayList<ValidationMetaData>();
      if (commandName != null) {
        rules.addAll(getValidationMetaDataForCommand());
      }
      String bodyString = null;
      if (bodyContent != null) {
        // body can be a JSON object, specifying date formats, or other extra configuration info
        bodyString = FileCopyUtils.copyToString(bodyContent.getReader());
        bodyString = bodyString.trim().replaceAll("\\s{2,}", " ");
      }

      JspWriter out = pageContext.getOut();
      out.write("<script type=\"text/javascript\" id=\"");
      out.write(commandName + "JSR303JSValidator");
      out.write("\">");
      generator.generateJavaScript(
          out,
          commandName,
          true,
          bodyString,
          rules,
          new MessageSourceAccessor(
              getRequestContext().getWebApplicationContext(), getRequestContext().getLocale()));
      out.write("</script>");
      return EVAL_PAGE;
    } catch (IOException e) {
      throw new JspException("Could not write validation rules", e);
    }
  }
  @Test
  public void testGetMergeWithNewLine() throws Exception {
    String fName1 = UUID.randomUUID() + ".txt";
    String name1 = "local/merge/" + fName1;
    TestUtils.writeToFS(cfg, name1);

    String fName2 = UUID.randomUUID() + ".txt";
    String name2 = "local/merge/" + fName2;
    TestUtils.writeToFS(cfg, name2);

    File dir = new File("local");
    dir.mkdir();

    String localName = "local/merge.txt";
    File fl1 = new File(localName);

    try {
      shell.getmerge("local/merge/", localName, true);
      assertTrue(fl1.exists());
      String content = FileCopyUtils.copyToString(new FileReader(fl1));
      assertTrue(content.contains(name1 + "\n"));
      assertTrue(content.contains(name2));
      assertEquals(content.length(), name1.length() + name2.length() + 2);
    } finally {
      FileSystemUtils.deleteRecursively(dir);
    }
  }
 @Test
 public void createPidFile() throws Exception {
   File file = this.temporaryFolder.newFile();
   ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file);
   listener.onApplicationEvent(EVENT);
   assertThat(FileCopyUtils.copyToString(new FileReader(file)), not(isEmptyString()));
 }
 public String getResourceString(String str) {
   try {
     return FileCopyUtils.copyToString(new InputStreamReader(getClass().getResourceAsStream(str)));
   } catch (IOException e) {
   }
   return null;
 }
  protected XmlModel assertRoutes(File file, int expected, String ns) throws Exception {
    if (ns == null || ns.trim().length() == 0) {
      ns = CamelNamespaces.springNS;
    }
    XmlModel x = assertLoadModel(file, expected);

    // now lets add a route and write it back again...
    DefaultCamelContext tmpContext = new DefaultCamelContext();
    tmpContext.addRoutes(
        new RouteBuilder() {
          @Override
          public void configure() throws Exception {
            from("seda:newFrom").to("seda:newTo");
          }
        });
    x.getContextElement().getRoutes().addAll(tmpContext.getRouteDefinitions());

    List<RouteDefinition> routes = x.getRouteDefinitionList();
    assertEquals("routes: " + routes, expected + 1, routes.size());

    // now lets write to XML      model
    outDir.mkdirs();
    File outFile = new File(outDir, file.getName());
    System.out.println("Generating file: " + outFile);
    tool.marshal(outFile, x);

    assertFileExists(outFile);

    // lets check the file has the correct namespace inside it
    String text = FileCopyUtils.copyToString(new FileReader(outFile));
    assertTrue("Namespace " + ns + " not present in output file\n" + text, text.contains(ns));

    return x;
  }
示例#7
0
  @Test
  public void testGetInputStreamOfFileInSubDirectory() throws Exception {
    // Invoke
    final InputStream inputStream = FileUtils.getInputStream(Loader.class, TEST_FILE);

    // Check
    final String contents = FileCopyUtils.copyToString(new InputStreamReader(inputStream));
    assertEquals("This file is required for FileUtilsTest.", contents);
  }
 @Test
 public void overridePidFile() throws Exception {
   File file = this.temporaryFolder.newFile();
   System.setProperty("PIDFILE", this.temporaryFolder.newFile().getAbsolutePath());
   ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file);
   listener.onApplicationEvent(EVENT);
   assertThat(
       FileCopyUtils.copyToString(new FileReader(System.getProperty("PIDFILE"))),
       not(isEmptyString()));
 }
 @Test
 public void exceptionsIncludeClassPackaging() throws Exception {
   this.loggingSystem.beforeInitialize();
   this.loggingSystem.initialize(null, null, getLogFile(null, tmpDir()));
   Matcher<String> expectedOutput = containsString("[junit-");
   this.output.expect(expectedOutput);
   this.logger.warn("Expected exception", new RuntimeException("Expected"));
   String fileContents =
       FileCopyUtils.copyToString(new FileReader(new File(tmpDir() + "/spring.log")));
   assertThat(fileContents, is(expectedOutput));
 }
  @Override
  @RunAsSystem
  public void initialize() {
    Resource resource = new ClassPathResource("roc-curve.R");
    if (resource.exists()) {
      long count =
          dataService.count(
              Script.ENTITY_NAME, new QueryImpl().eq(Script.NAME, ROC_CURVE_SCRIPT_NAME));
      if (count == 0) {
        Entity scriptType =
            dataService.findOne(ScriptType.ENTITY_NAME, new QueryImpl().eq(ScriptType.NAME, "R"));

        if (scriptType == null) throw new UnknownEntityException("ScriptType R does not exist!");

        String scriptContent;
        try {
          scriptContent =
              FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream(), "UTF-8"));

        } catch (IOException e) {
          throw new UncheckedIOException(e);
        }

        if (dataService.count(
                ScriptParameter.ENTITY_NAME,
                new QueryImpl().eq(ScriptParameter.NAME, ROC_CURVE_SCRIPT_PARAMETER))
            == 0) {
          dataService.add(
              ScriptParameter.ENTITY_NAME,
              new MapEntity(ImmutableMap.of(ScriptParameter.NAME, ROC_CURVE_SCRIPT_PARAMETER)));
        }

        Entity scriptParameterEntity =
            dataService.findOne(
                ScriptParameter.ENTITY_NAME,
                new QueryImpl().eq(ScriptParameter.NAME, ROC_CURVE_SCRIPT_PARAMETER));

        MapEntity scriptEntity = new MapEntity();
        scriptEntity.set(Script.NAME, ROC_CURVE_SCRIPT_NAME);
        scriptEntity.set(Script.GENERATE_TOKEN, true);
        scriptEntity.set(Script.TYPE, scriptType);
        scriptEntity.set(Script.RESULT_FILE_EXTENSION, "png");
        scriptEntity.set(Script.CONTENT, scriptContent);
        scriptEntity.set(Script.PARAMETERS, Arrays.asList(scriptParameterEntity));
        dataService.add(Script.ENTITY_NAME, scriptEntity);

        LOG.info("Script entity \"roc\" has been added to the database!");
      } else {
        LOG.info("Script entity \"roc\" already exists in the database!");
      }
    } else {
      LOG.info("R script \"roc-curve.R\" does not exist on classpath!");
    }
  }
 public void setPayload(InputStreamSource inputStreamSource) throws IOException {
   checkContent();
   InputStream is = null;
   try {
     is = inputStreamSource.getInputStream();
     Reader reader = new InputStreamReader(is, "UTF-8");
     content.replace(0, content.length(), FileCopyUtils.copyToString(reader));
   } finally {
     if (is != null) {
       is.close();
     }
   }
 }
示例#12
0
 public static String readText(Resource resource) {
   Reader reader = null;
   try {
     reader = getReaderForResource(resource);
     return FileCopyUtils.copyToString(reader);
   } catch (Exception e) {
     throw new ExecutionException("Unable to read resource " + resource.getDescription(), e);
   } finally {
     if (reader != null) {
       try {
         reader.close();
       } catch (IOException e) {
       }
     }
   }
 }
 @Test
 public void customExceptionConversionWord() throws Exception {
   System.setProperty("LOG_EXCEPTION_CONVERSION_WORD", "%ex");
   try {
     this.loggingSystem.beforeInitialize();
     this.logger.info("Hidden");
     this.loggingSystem.initialize(null, null, getLogFile(null, tmpDir()));
     Matcher<String> expectedOutput =
         Matchers.allOf(
             containsString("java.lang.RuntimeException: Expected"),
             not(containsString("Wrapped by:")));
     this.output.expect(expectedOutput);
     this.logger.warn(
         "Expected exception", new RuntimeException("Expected", new RuntimeException("Cause")));
     String fileContents =
         FileCopyUtils.copyToString(new FileReader(new File(tmpDir() + "/spring.log")));
     assertThat(fileContents, is(expectedOutput));
   } finally {
     System.clearProperty("LOG_EXCEPTION_CONVERSION_WORD");
   }
 }
示例#14
0
  private byte[] createGraphAsByteArray(String command, File workDir)
      throws IOException, RrdException {
    String[] commandArray = StringUtils.createCommandArray(command, '@');
    Process process;
    try {
      process = Runtime.getRuntime().exec(commandArray, null, workDir);
    } catch (IOException e) {
      IOException newE =
          new IOException(
              "IOException thrown while executing command '"
                  + command
                  + "' in "
                  + workDir.getAbsolutePath()
                  + ": "
                  + e);
      newE.initCause(e);
      throw newE;
    }

    // this closes the stream when its finished
    byte[] byteArray = FileCopyUtils.copyToByteArray(process.getInputStream());

    // this close the stream when its finished
    String errors = FileCopyUtils.copyToString(new InputStreamReader(process.getErrorStream()));

    // one particular warning message that originates in libart should be ignored
    if (errors.length() > 0 && errors.contains(IGNORABLE_LIBART_WARNING_STRING)) {
      LOG.debug(
          "Ignoring libart warning message in rrdtool stderr stream: {}",
          IGNORABLE_LIBART_WARNING_STRING);
      errors = errors.replaceAll(IGNORABLE_LIBART_WARNING_REGEX, "");
    }
    if (errors.length() > 0) {
      throw new RrdException(errors);
    }
    return byteArray;
  }
示例#15
0
 // This MUST remain private. Use XDMatchers.hasContentsThat() to assert
 private String getContents(int timeout) throws IOException {
   waitFor(file, timeout);
   Reader fileReader = new InputStreamReader(new FileInputStream(file), charset);
   return FileCopyUtils.copyToString(fileReader);
 }
示例#16
0
 private String read(File snippetFile) throws IOException {
   return FileCopyUtils.copyToString(new FileReader(snippetFile));
 }
  @Override
  public void afterPropertiesSet() throws Exception {
    if (!configuration.containsKey(Constants.FRAMEWORK_STORAGE)) {
      File storageDir =
          Bootstrap.getHmpHomeDirectory(this.applicationContext)
              .createRelative("osgi-storage")
              .getFile();
      if (!storageDir.exists()) {
        storageDir.mkdir();
      }
      configuration.put(Constants.FRAMEWORK_STORAGE, storageDir.getCanonicalPath());
    }
    if (!configuration.containsKey(Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT)) {
      configuration.put(
          Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    }
    if (!configuration.containsKey(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA)) {
      InputStreamReader isr =
          new InputStreamReader(getClass().getResourceAsStream(SYSTEM_PACKAGES_RESOURCE));
      String rawSystemPackages = FileCopyUtils.copyToString(isr);
      String[] lines = rawSystemPackages.split("\\r?\\n");
      String systemPackages = StringUtils.collectionToCommaDelimitedString(Arrays.asList(lines));
      configuration.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, systemPackages);
      LOGGER.debug(systemPackages);
      isr.close();
    }
    if (!configuration.containsKey("felix.fileinstall.dir")) {
      File pluginsDir = getPluginsDir(this.applicationContext).getFile();
      if (!pluginsDir.exists()) {
        pluginsDir.mkdir();
      }
      configuration.put("felix.fileinstall.dir", pluginsDir.getCanonicalPath());
    }

    ServiceLoader<FrameworkFactory> factoryLoader = ServiceLoader.load(FrameworkFactory.class);
    FrameworkFactory frameworkFactory = factoryLoader.iterator().next();

    framework = frameworkFactory.newFramework(configuration);
    framework.start();

    // install some bundles
    List<Bundle> installedBundles = new ArrayList<Bundle>();
    File bundlesDir =
        Bootstrap.getHmpHomeDirectory(this.applicationContext).createRelative("bundles").getFile();
    if (!bundlesDir.exists())
      throw new ServiceConfigurationError(
          "HMP OSGi system bundles missing or configured incorrectly (cannot find 'bundles' folder inside '"
              + Bootstrap.getHmpHomeDirectory(this.applicationContext).getFile().getAbsolutePath());
    for (File f : bundlesDir.listFiles()) {
      if (f.getName().endsWith("jar")) {
        try {
          Bundle bundle =
              framework.getBundleContext().installBundle("file:" + f.getCanonicalPath());
          installedBundles.add(bundle);
        } catch (BundleException e) {
          LOGGER.error("Unable to install bundle: " + f.getName(), e);
        }
      }
    }

    // start the installed bundles
    for (Bundle bundle : installedBundles) {
      if (bundle.getHeaders().get(Constants.FRAGMENT_HOST) == null) {
        try {
          bundle.start();
          LOGGER.info(
              "Started bundle: {}({})", bundle.getSymbolicName(), bundle.getVersion().toString());
        } catch (BundleException e) {
          LOGGER.error("Unable to start bundle: " + bundle.getSymbolicName(), e);
        }
      }
    }
  }