Example #1
0
  public static void main(String[] args) {
    // setup
    final Path in = getPath("in.txt");
    final Path out = getPath("out.txt");

    // action
    try {
      final byte[] bytes = Files.readAllBytes(in);
      System.out.println("-->");
      System.out.println(new String(bytes));

      final byte[] reversed = CollectionUtils.reverse(bytes);
      Files.write(out, reversed);
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }

    // check
    try {
      final byte[] result = Files.readAllBytes(out);
      System.out.println("<--");
      System.out.println(new String(result));
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }
Example #2
0
  @Test
  public void packingALargeFileShouldGenerateTheSameOutputWhenOverwritingAsWhenAppending()
      throws IOException {
    File reference = File.createTempFile("reference", ".zip");
    String packageName = getClass().getPackage().getName().replace(".", "/");
    URL sample = Resources.getResource(packageName + "/macbeth.properties");
    byte[] input = Resources.toByteArray(sample);

    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output, OVERWRITE_EXISTING);
        ZipOutputStream ref = new ZipOutputStream(new FileOutputStream(reference))) {
      CustomZipEntry entry = new CustomZipEntry("macbeth.properties");
      entry.setTime(System.currentTimeMillis());
      out.putNextEntry(entry);
      ref.putNextEntry(entry);
      out.write(input);
      ref.write(input);
    }

    byte[] seen = Files.readAllBytes(output);
    byte[] expected = Files.readAllBytes(reference.toPath());

    // Make sure the output is valid.
    try (ZipInputStream in = new ZipInputStream(Files.newInputStream(output))) {
      ZipEntry entry = in.getNextEntry();
      assertEquals("macbeth.properties", entry.getName());
      assertNull(in.getNextEntry());
    }

    assertArrayEquals(expected, seen);
  }
Example #3
0
  @VisibleForTesting
  static void writeAar(
      Path aar, final MergedAndroidData data, Path manifest, Path rtxt, Path classes)
      throws IOException {
    try (final ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(aar.toFile()))) {
      ZipEntry manifestEntry = new ZipEntry("AndroidManifest.xml");
      zipOut.putNextEntry(manifestEntry);
      zipOut.write(Files.readAllBytes(manifest));
      zipOut.closeEntry();

      ZipEntry classJar = new ZipEntry("classes.jar");
      zipOut.putNextEntry(classJar);
      zipOut.write(Files.readAllBytes(classes));
      zipOut.closeEntry();

      Files.walkFileTree(
          data.getResourceDirFile().toPath(),
          new ZipDirectoryWriter(zipOut, data.getResourceDirFile().toPath(), "res"));

      ZipEntry r = new ZipEntry("R.txt");
      zipOut.putNextEntry(r);
      zipOut.write(Files.readAllBytes(rtxt));
      zipOut.closeEntry();

      if (data.getAssetDirFile().exists() && data.getAssetDirFile().list().length > 0) {
        Files.walkFileTree(
            data.getAssetDirFile().toPath(),
            new ZipDirectoryWriter(zipOut, data.getAssetDirFile().toPath(), "assets"));
      }
    }
    aar.toFile().setLastModified(EPOCH);
  }
  private Toolbox loadToolbox() throws IOException, URISyntaxException {

    Path foundPath = findToolsDir();

    Toolbox box;
    if (Files.isDirectory(foundPath)) {
      box = new Toolbox(foundPath);

      Path tempDir = Files.createTempDirectory(TOOLS_DIR_NAME);
      Path tempZipFile = tempDir.resolve(TOOLS_ZIP_NAME);

      dirToZip(foundPath, tempZipFile);
      byte[] zipContents = Files.readAllBytes(tempZipFile);
      box.setZipContents(zipContents);
      Files.delete(tempZipFile);
      Files.delete(tempDir);
    }

    // found tools zip
    else {
      FileSystem fs = FileSystems.newFileSystem(foundPath, null);
      Path toolsPath = fs.getPath(TOOLS_DIR_NAME);
      box = new Toolbox(toolsPath);

      byte[] zipContents = Files.readAllBytes(foundPath);
      box.setZipContents(zipContents);
    }

    return box;
  }
  public static SSLSocketFactory getSocketFactory(
      String caCrtFile, String crtFile, String keyFile, String password) throws Exception {

    char[] passwordCharArray = password == null ? new char[0] : password.toCharArray();

    Security.addProvider(new BouncyCastleProvider());
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    X509Certificate caCert =
        (X509Certificate)
            cf.generateCertificate(
                new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile))));

    X509Certificate cert =
        (X509Certificate)
            cf.generateCertificate(
                new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile))));

    File privateKeyFile = new File(keyFile);
    PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passwordCharArray);
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");

    Object object = pemParser.readObject();
    KeyPair kp;

    if (object instanceof PEMEncryptedKeyPair) {
      kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    } else {
      kp = converter.getKeyPair((PEMKeyPair) object);
    }

    pemParser.close();

    KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    caKeyStore.load(null, null);
    caKeyStore.setCertificateEntry("ca-certificate", caCert);
    TrustManagerFactory trustManagerFactory =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(caKeyStore);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("certificate", cert);
    keyStore.setKeyEntry(
        "private-key",
        kp.getPrivate(),
        passwordCharArray,
        new java.security.cert.Certificate[] {cert});
    KeyManagerFactory keyManagerFactory =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, passwordCharArray);

    SSLContext context = SSLContext.getInstance("TLSv1");
    context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return context.getSocketFactory();
  }
Example #6
0
  public static void main(String[] args) throws IOException {

    String file1 = args[0];
    String file2 = args[1];

    String r1 = new String(Files.readAllBytes(Paths.get(file1)));
    String r2 = new String(Files.readAllBytes(Paths.get(file2)));

    new Solution().longestCommonSubString(r1, r2);
  }
Example #7
0
  /**
   * Constructor, decodes encrypted passwords and makes them available to the program.
   *
   * @throws Throwable If something went very wrong.
   */
  private WikiGen() throws Throwable {
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Files.readAllBytes(findConfig(pf)), "AES"));
    JSONObject jo =
        new JSONObject(new String(c.doFinal(Files.readAllBytes(findConfig(px))), "UTF-8"));

    for (String s : JSONObject.getNames(jo)) {
      JSONObject entry = jo.getJSONObject(s);
      master.put(s, entry.getString("pass"));
    }
  }
 @Test
 public void testEncode() throws IOException, JSONException {
   String path = getClass().getResource("/").getPath();
   byte[] msgBytes = Files.readAllBytes(Paths.get(path.substring(1) + "maze_data_1k.json"));
   String msgJsonStr = Charset.forName("UTF-8").decode(ByteBuffer.wrap(msgBytes)).toString();
   JSONObject msgs = new JSONObject(msgJsonStr);
   byte[] protoBytes = Files.readAllBytes(Paths.get(path.substring(1) + "maze_proto.json"));
   String protoJsonStr = Charset.forName("UTF-8").decode(ByteBuffer.wrap(protoBytes)).toString();
   JSONObject _proto = new JSONObject(protoJsonStr);
   JSONObject proto = ProtoBufParser.parse(_proto);
   Encoder encoder = new Encoder(proto);
   Decoder decoder = new Decoder(proto);
   ProtoBuf protoBuf = new ProtoBuf(encoder, decoder);
   Iterator<String> routes = msgs.keys();
   long encode_cost = 0L;
   long decode_cost = 0L;
   long all_cost = 0L;
   for (int i = 0; i < rTimes; i++) {
     while (routes.hasNext()) {
       String route = routes.next();
       long start = new Date().getTime();
       JSONObject msg = msgs.getJSONObject(route);
       try {
         String msgStr = msg.toString();
         System.out.println("encode route " + route + ":" + msgStr);
         byte[] encode = protoBuf.encode(route, msgStr);
         long encode_end = new Date().getTime();
         encode_cost += (encode_end - start);
         System.out.println(Arrays.toString(encode));
         String decode = protoBuf.decode(route, encode);
         long decode_end = new Date().getTime();
         decode_cost += (decode_end - encode_end);
         all_cost += (decode_end - start);
         org.junit.Assert.assertEquals("assert result", msgStr, decode);
         System.out.println("decode:" + decode);
       } catch (PomeloException e) {
         e.printStackTrace(); // To change body of catch statement use File | Settings | File
         // Templates.
       }
     }
   }
   System.out.println(
       "protobuf time cost sum:"
           + all_cost
           + ",encode cost sum:"
           + encode_cost
           + ",decode cost sum:"
           + decode_cost);
 }
Example #9
0
 private String getFileContentsWithAbsolutePath(Path path) throws IOException {
   String platformExt = null;
   switch (Platform.detect()) {
     case LINUX:
       platformExt = "linux";
       break;
     case MACOS:
       platformExt = "macos";
       break;
     case WINDOWS:
       platformExt = "win";
       break;
     case FREEBSD:
       platformExt = "freebsd";
       break;
     case UNKNOWN:
       // Leave platformExt as null.
       break;
   }
   if (platformExt != null) {
     String extension = com.google.common.io.Files.getFileExtension(path.toString());
     String basename = com.google.common.io.Files.getNameWithoutExtension(path.toString());
     Path platformPath =
         extension.length() > 0
             ? path.getParent()
                 .resolve(String.format("%s.%s.%s", basename, platformExt, extension))
             : path.getParent().resolve(String.format("%s.%s", basename, platformExt));
     if (platformPath.toFile().exists()) {
       path = platformPath;
     }
   }
   return new String(Files.readAllBytes(path), UTF_8);
 }
Example #10
0
  public static void completeTest(NeoTwDatabase neoTwDatabase) throws Exception {
    // https://api.twitter.com/1.1/search/tweets.json?q=562b47a2e2704e07768b464c

    System.out.println("Parsing...");

    JSONObject completeJsonObject =
        new JSONObject(
            new String(Files.readAllBytes(Paths.get(SAMPLE_TWITTER_DIR + "complete.json"))));

    System.out.println("Inserting...");

    try (Transaction tx = neoTwDatabase.beginTx()) {
      JSONArray statusesJsonArray = completeJsonObject.optJSONArray("statuses");
      for (int i = 0; i < statusesJsonArray.length(); ++i) {
        JSONObject jsonObject = statusesJsonArray.getJSONObject(i);
        TwStatus twStatus = new TwStatus(jsonObject);
        Node node = neoTwDatabase.getOrCreateTwStatusNode(twStatus);
      }
      tx.success();
    }

    System.out.println("Checking...");

    try (Transaction tx = neoTwDatabase.beginTx()) {
      JSONArray statusesJsonArray = completeJsonObject.optJSONArray("statuses");
      for (int i = 0; i < statusesJsonArray.length(); ++i) {
        JSONObject jsonObject = statusesJsonArray.getJSONObject(i);
        TwStatus twStatus = new TwStatus(jsonObject);
        Node node = neoTwDatabase.getTwStatusNodeById(twStatus.getId());
        System.out.println(node.getProperty("jsonObject"));
      }
    }
  }
  /** Generate evolutions. */
  @Override
  public void create() {
    if (!environment.isProd()) {
      config
          .serverConfigs()
          .forEach(
              (key, serverConfig) -> {
                String evolutionScript = generateEvolutionScript(servers.get(key));
                if (evolutionScript != null) {
                  File evolutions = environment.getFile("conf/evolutions/" + key + "/1.sql");
                  try {
                    String content = "";
                    if (evolutions.exists()) {
                      content = new String(Files.readAllBytes(evolutions.toPath()), "utf-8");
                    }

                    if (content.isEmpty() || content.startsWith("# --- Created by Ebean DDL")) {
                      environment.getFile("conf/evolutions/" + key).mkdirs();
                      if (!content.equals(evolutionScript)) {
                        Files.write(evolutions.toPath(), evolutionScript.getBytes("utf-8"));
                      }
                    }
                  } catch (IOException e) {
                    throw new RuntimeException(e);
                  }
                }
              });
    }
  }
Example #12
0
  public String toHTML(String template) {
    String templateText = "";
    File templateFile = new File(Consts.TEMPLATESPATH + "/" + template + ".tpl");
    try {
      templateText = new String(Files.readAllBytes(templateFile.toPath()), StandardCharsets.UTF_8);

      Class<?> c = this.getClass();
      Field[] fields = c.getDeclaredFields();

      // TODO:setSpec
      for (Field field : fields) {
        String replaceStr = StringEscapeUtils.escapeHtml(field.get(this).toString());
        templateText =
            templateText.replaceAll(
                "\\{\\$" + field.getName() + "\\}", Matcher.quoteReplacement(replaceStr));
      }
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return templateText;
  }
Example #13
0
 public static void odczytPlikuTekstowegoD() throws IOException {
   // dekrypt
   BufferedWriter writer = new BufferedWriter(new FileWriter("odszyfrowanie.txt"));
   FileInputStream fileInput = new FileInputStream("zaszyfrowany.txt");
   FileInputStream filen = new FileInputStream("n.txt");
   FileInputStream filed = new FileInputStream("d.txt");
   String nfile = "";
   String dfile = "";
   int r;
   while ((r = filen.read()) != -1) {
     nfile += (char) r;
   }
   while ((r = filed.read()) != -1) {
     dfile += (char) r;
   }
   filen.close();
   filed.close();
   // System.out.println(dfile);
   // System.out.println(nfile);
   BigInteger n = new BigInteger(nfile);
   BigInteger d = new BigInteger(dfile);
   String content = new String(Files.readAllBytes(Paths.get("zaszyfrowany.txt")));
   String[] odczytane = content.split(" ");
   for (String o : odczytane) {
     BigInteger wynik = new BigInteger(o).modPow(d, n);
     writer.write(new String(wynik.toByteArray()));
   }
   writer.close();
   fileInput.close();
 }
 @Test
 public void testGzip() throws IOException {
   String path = getClass().getResource("/").getPath();
   byte[] msgBytes = Files.readAllBytes(Paths.get(path.substring(1) + "maze_data_1k.json"));
   String msgJsonStr = Charset.forName("UTF-8").decode(ByteBuffer.wrap(msgBytes)).toString();
   long encode_cost = 0L;
   long decode_cost = 0L;
   long all_cost = 0L;
   for (int i = 0; i < rTimes; i++) {
     long start = new Date().getTime();
     String compress = GzipUtils.compress(msgJsonStr);
     long encode_end = new Date().getTime();
     encode_cost += (encode_end - start);
     String decompress = GzipUtils.decompress(compress);
     long decode_end = new Date().getTime();
     decode_cost += (decode_end - encode_end);
     all_cost += (decode_end - start);
   }
   System.out.println(
       "gzip time cost sum:"
           + all_cost
           + ",encode cost sum:"
           + encode_cost
           + ",decode cost sum:"
           + decode_cost);
 }
  @Activate
  public void activate(BundleContext context) throws Exception {
    String f = context.getProperty("be.iminds.iot.dianne.dataset.chars.location");
    if (f != null) {
      this.file = f;
    }

    try {
      byte[] encoded = Files.readAllBytes(Paths.get(file));
      data = new String(encoded, Charset.defaultCharset());

      data.chars()
          .forEach(
              c -> {
                if (!chars.contains("" + (char) c)) {
                  chars += "" + (char) c;
                }
              });

      labels = new String[chars.length()];
      for (int i = 0; i < labels.length; i++) {
        labels[i] = "" + chars.charAt(i);
      }

    } catch (Exception e) {
      System.err.println("Failed to load char sequence dataset ... ");
      throw e;
    }
  }
Example #16
0
 /**
  * Read string.
  *
  * @param targetFile the target file
  * @param encoding the encoding
  * @return the string
  */
 public static String readString(File targetFile, String encoding) {
   try {
     return new String(Files.readAllBytes(targetFile.toPath()), Charset.forName(encoding));
   } catch (IOException e) {
     return JMExceptionManager.handleExceptionAndReturnNull(log, e, "readString", targetFile);
   }
 }
  private String _read(String fileName) throws Exception {
    Path path = Paths.get(fileName);

    String s = new String(Files.readAllBytes(path), StringPool.UTF8);

    return StringUtil.replace(s, StringPool.RETURN_NEW_LINE, StringPool.NEW_LINE);
  }
Example #18
0
  private void start() {
    long start = System.currentTimeMillis();
    Path pDir =
        Paths.get(
            System.getProperty("user.home"),
            ".saas",
            "app",
            "db",
            "org.ubo.accountbook.SyntheticAccount"); // SyntheticAccount AccountPost
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    for (File f : pDir.toFile().listFiles()) {
      if (f.isDirectory()) {
        continue;
      }

      try {
        cacheList.add(
            CacheData.createCacheData(
                "org.ubo.accountbook.SyntheticAccount",
                Long.parseLong(f.getName()),
                Files.readAllBytes(f.toPath())));
      } catch (NumberFormatException | IOException e) {
        Logger.getGlobal().log(Level.SEVERE, null, e);
      }
    }

    System.out.println(">>>>>>>>>> " + cacheList.toArray()[0]);
    System.out.println("Time: " + (System.currentTimeMillis() - start));
  }
  @Test
  public void testFillEtcdWithYaml() throws IOException {
    String source =
        new String(
            Files.readAllBytes(
                Paths.get(
                    System.getProperty("user.dir")
                        + "\\src\\test\\resources\\apimanagement\\api.yaml")),
            Charset.defaultCharset());

    try {
      EtcdResponse respPutYaml =
          EtcdUtil.createBasicRequest("http://localhost:4001", "/amc", "")
              .setValue("file", source)
              .sendRequest();
      if (!EtcdUtil.checkOK(respPutYaml)) {
        throw new RuntimeException();
      }
      EtcdResponse respPutHash =
          EtcdUtil.createBasicRequest("http://localhost:4001", "/amc", "")
              .setValue("hash", "12345")
              .sendRequest();
    } catch (Exception ignored) {
    }
  }
Example #20
0
  @Test
  public void testContentsOfFileRetrieved() throws IOException {
    String key = "folder/1.txt";
    putTestFile(key, getFileFromResourceName(SAMPLE_FILE_RESOURCE_NAME));

    final TestRunner runner = TestRunners.newTestRunner(new FetchS3Object());

    runner.setProperty(FetchS3Object.CREDENTIALS_FILE, CREDENTIALS_FILE);
    runner.setProperty(FetchS3Object.REGION, REGION);
    runner.setProperty(FetchS3Object.BUCKET, BUCKET_NAME);

    final Map<String, String> attrs = new HashMap<>();
    attrs.put("filename", key);
    runner.enqueue(new byte[0], attrs);

    runner.run(1);

    runner.assertAllFlowFilesTransferred(FetchS3Object.REL_SUCCESS, 1);

    final List<MockFlowFile> ffs = runner.getFlowFilesForRelationship(FetchS3Object.REL_SUCCESS);
    final MockFlowFile out = ffs.iterator().next();

    final byte[] expectedBytes = Files.readAllBytes(getResourcePath(SAMPLE_FILE_RESOURCE_NAME));
    out.assertContentEquals(new String(expectedBytes));

    for (final Map.Entry<String, String> entry : out.getAttributes().entrySet()) {
      System.out.println(entry.getKey() + " : " + entry.getValue());
    }
  }
  @Test
  public void shouldRecordClassesAsDeserialized()
      throws TransformerConfigurationException, IOException, ClassNotFoundException,
          AttachNotSupportedException, AgentLoadException, AgentInitializationException {

    System.setProperty("notsoserial.whitelist", "src/test/resources/whitelist.txt");
    System.setProperty("notsoserial.dryrun", "target/is-deserialized.txt");
    System.setProperty("notsoserial.trace", "target/deserialized-trace.txt");

    attachAgent();

    byte[] ser = Files.readAllBytes(Paths.get("target").resolve("bytes.ser"));

    try {
      System.setProperty("pwned", "false");
      // Deserializing should not flip pwned to true
      deserialize(ser);
    } catch (ClassCastException e) {
      // Ignore, happens after exploit effect

    }
    assertThat(System.getProperty("pwned"), is("true"));

    Set<String> deserialized =
        new TreeSet<String>(Files.readAllLines(Paths.get("target/is-deserialized.txt")));
    assertThat(
        deserialized, hasItem("org.apache.commons.collections4.functors.InvokerTransformer"));
    assertThat(deserialized, hasItem("java.util.PriorityQueue"));
  }
 public void execute() throws MojoExecutionException {
   Log log = getLog();
   String root = project.getBasedir().getPath();
   String[] matchingFiles = scan(new File(root));
   for (String matchingFile : matchingFiles) {
     log.info("compiling '" + matchingFile + "'...");
     Path sourceFile = Paths.get(matchingFile);
     try {
       // Reading template file
       byte[] fileBytes = Files.readAllBytes(sourceFile);
       String template =
           Charset.forName(sourceEncoding).decode(ByteBuffer.wrap(fileBytes)).toString();
       // Creating template name
       int templateNameExtensionIndex = sourceFile.getFileName().toString().lastIndexOf('.');
       String templateName =
           templateNameExtensionIndex > 0
               ? sourceFile.getFileName().toString().substring(0, templateNameExtensionIndex)
               : sourceFile.getFileName().toString();
       // Compiling template
       String result = HoganTemplateCompileHelper.compileHoganTemplate(template, templateName);
       // Writing output file
       ByteBuffer bb = Charset.forName(outputEncoding).encode(result);
       fileBytes = new byte[bb.remaining()];
       bb.get(fileBytes);
       Path outputFilePath = sourceFile.getParent().resolve(templateName + ".js");
       log.info("writing '" + outputFilePath.toString() + "'");
       Files.write(outputFilePath, fileBytes, StandardOpenOption.CREATE);
     } catch (IOException e) {
       throw new MojoExecutionException("Error while compiling Hogan Template", e);
     }
   }
 }
Example #23
0
  public static void main(String[] args) throws IOException {
    Path path = Paths.get("../alice.txt");
    String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);

    Stream<String> words = Stream.of(contents.split("[\\P{L}]+"));
    show("words", words);
    Stream<String> song = Stream.of("gently", "down", "the", "stream");
    show("song", song);
    Stream<String> silence = Stream.empty();
    silence = Stream.<String>empty(); // Explicit type specification
    show("silence", silence);

    Stream<String> echos = Stream.generate(() -> "Echo");
    show("echos", echos);

    Stream<Double> randoms = Stream.generate(Math::random);
    show("randoms", randoms);

    Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE));
    show("integers", integers);

    Stream<String> wordsAnotherWay = Pattern.compile("[\\P{L}]+").splitAsStream(contents);
    show("wordsAnotherWay", wordsAnotherWay);

    try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
      show("lines", lines);
    }
  }
  @Test
  public void testScanOSGiLog() throws IOException {
    StringBundler sb = new StringBundler();

    try (DirectoryStream<Path> directoryStream =
        Files.newDirectoryStream(Paths.get(System.getProperty("osgi.state.dir")), "*.log")) {

      for (Path path : directoryStream) {
        if (!Files.isRegularFile(path)) {
          continue;
        }

        sb.append("\nPortal log assert failure, OSGi log found: ");
        sb.append(path);
        sb.append(StringPool.COLON);
        sb.append(StringPool.NEW_LINE);
        sb.append(new String(Files.readAllBytes(path), Charset.defaultCharset()));
        sb.append(StringPool.NEW_LINE);
      }
    }

    if (sb.index() != 0) {
      Assert.fail(sb.toString());
    }
  }
  private static String getCustomProperties() throws ReporterException {
    if (System.getProperty("reporter.config") == null) {
      return null;
    }
    File propFile = new File(System.getProperty("reporter.config"));
    if (!propFile.exists() || propFile.isDirectory()) {
      return null;
    }

    try {
      File file = Files.createTempFile("reporter", ".properties").toFile();
      file.deleteOnExit();
      FileWriter fw = new FileWriter(file);
      String fileText = new String(Files.readAllBytes(propFile.toPath()));

      // replace variables
      fileText =
          fileText.replace(
              "${file.separator}", Matcher.quoteReplacement(System.getProperty("file.separator")));
      fileText =
          fileText.replace("${user.dir}", Matcher.quoteReplacement(System.getProperty("user.dir")));

      fw.write(fileText);
      fw.close();
      return file.getAbsolutePath();
    } catch (IOException e) {
      throw new ReporterException(
          "Failed to read custom config file at: " + propFile.getAbsolutePath());
    }
  }
Example #26
0
  @Test
  public void testCreateRelativeSymlinkToFilesInRoot() throws IOException {
    ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmp.getRoot());
    tmp.newFile("biz.txt");

    Path pathToDesiredLinkUnderProjectRoot = Paths.get("gamma.txt");
    Path pathToExistingFileUnderProjectRoot = Paths.get("biz.txt");
    Path relativePath =
        MorePaths.createRelativeSymlink(
            pathToDesiredLinkUnderProjectRoot,
            pathToExistingFileUnderProjectRoot,
            projectFilesystem);
    assertEquals("biz.txt", relativePath.toString());

    Path absolutePathToDesiredLinkUnderProjectRoot =
        projectFilesystem.resolve(pathToDesiredLinkUnderProjectRoot);
    assertTrue(Files.isSymbolicLink(absolutePathToDesiredLinkUnderProjectRoot));
    Path targetOfSymbolicLink = Files.readSymbolicLink(absolutePathToDesiredLinkUnderProjectRoot);
    assertEquals(relativePath, targetOfSymbolicLink);

    Path absolutePathToExistingFileUnderProjectRoot =
        projectFilesystem.resolve(pathToExistingFileUnderProjectRoot);
    Files.write(absolutePathToExistingFileUnderProjectRoot, "Hello, World!".getBytes());
    String dataReadFromSymlink =
        new String(Files.readAllBytes(absolutePathToDesiredLinkUnderProjectRoot));
    assertEquals("Hello, World!", dataReadFromSymlink);
  }
  @Test
  public void dataParsingTest() throws IOException {
    WhoIsParser parser = new WSWhoIsParser();

    String data =
        new String(
            Files.readAllBytes(Paths.get("src/test/resources/datec.com.ws.whois")),
            StandardCharsets.UTF_8);

    Assert.assertNotNull(data);

    Map<String, String> res = parser.parse(data);

    Assert.assertNotNull(res);

    Assert.assertEquals(res.get("created"), "2009-01-20");
    Assert.assertEquals(res.get("changed"), "2015-11-03");
    Assert.assertEquals(res.get("expires"), "2016-01-20");
    Assert.assertEquals(res.get("status"), "ok");
    Assert.assertEquals(res.get("dnssec"), "unsigned");

    Assert.assertEquals(res.get("registrar:name"), "Computer Services Limited");
    Assert.assertEquals(res.get("contacts:owner:name"), "Datec Samoa Limited");
    Assert.assertEquals(res.get("contacts:admin:name"), "Datec Samoa Limited");
    Assert.assertEquals(res.get("contacts:tech:name"), "Datec Samoa Limited");

    Assert.assertNotNull(res.get("nameservers"));
    Assert.assertTrue(res.get("nameservers") instanceof String);
    List<String> nss = Arrays.asList(res.get("nameservers").split(";"));
    Assert.assertEquals(nss.size(), 2);
    Assert.assertTrue(nss.contains("ns1.secure.net"));
    Assert.assertTrue(nss.contains("ns2.secure.net"));

    Assert.assertFalse(parser.isAvailable(data));
  }
Example #28
0
  public static void aclerkTest(NeoTwDatabase neoTwDatabase) throws Exception {
    final int aclerkId = 316751683;

    System.out.println("Parsing...");

    JSONObject aclerkJsonObject =
        new JSONObject(
            new String(Files.readAllBytes(Paths.get(SAMPLE_TWITTER_DIR + "aclerk.json"))));

    System.out.println("Inserting...");

    TwUser aclerkTwUser = new TwUser(aclerkJsonObject);
    try (Transaction tx = neoTwDatabase.beginTx()) {
      Node aclerkNode = neoTwDatabase.getOrCreateTwUserNode(aclerkTwUser);

      tx.success();
    }

    System.out.println("Checking...");
    try (Transaction tx = neoTwDatabase.beginTx()) {
      Node aclerkNode = neoTwDatabase.getTwUserNodeById(aclerkTwUser.getId());
      System.out.println(aclerkNode.getProperty("id"));
      System.out.println(aclerkNode.getProperty("screenName"));
      System.out.println(aclerkNode.getProperty("jsonObject"));
    }
  }
  @Test
  public void testRunWindupTiny() throws Exception {
    try (GraphContext context = createGraphContext()) {
      super.runTest(
          context, "../test-files/jee-example-app-1.0.0.ear", false, Arrays.asList("com.acme"));

      Path graphDirectory = context.getGraphDirectory();
      Path reportsDirectory = graphDirectory.resolve("reports");
      Path indexPath = graphDirectory.resolve(Paths.get("index.html"));

      Path appReportPath =
          resolveChildPath(
              reportsDirectory,
              "ApplicationDetails_JEE_Example_App__org_windup_example_jee_example_app_1_0_0_\\.html");
      Path appNonClassifiedReportPath =
          resolveChildPath(
              reportsDirectory,
              "compatiblefiles_JEE_Example_App__org_windup_example_jee_example_app_1_0_0_\\.html");
      Path productCatalogBeanPath =
          resolveChildPath(reportsDirectory, "ProductCatalogBean_java\\.html");

      Assert.assertTrue(indexPath.toFile().exists());
      Assert.assertTrue(appReportPath.toFile().exists());
      Assert.assertTrue(appNonClassifiedReportPath.toFile().exists());
      Assert.assertTrue(productCatalogBeanPath.toFile().exists());

      String appReportContent = new String(Files.readAllBytes(appReportPath));

      Assert.assertTrue(appReportContent.contains("Used only to support migration activities."));
      allDecompiledFilesAreLinked(context);
    }
  }
  public static void main(String[] args) {
    String filename = "pi/pi.txt";

    BenchmarkTimer timer = new BenchmarkTimer();
    timer.start("Histgram(CPU) Parallel");

    byte[] pi = null;
    try {
      pi = Files.readAllBytes(Paths.get(filename));
    } catch (IOException e) {
    }
    if (pi == null) return;

    timer.record("load");

    /* CPU */
    int nCores = Runtime.getRuntime().availableProcessors();
    System.out.println("Creating histgram with " + nCores + " threads.");

    int[] histgram = ParallelHigramMaker.make(pi, nCores);
    timer.record("make");

    HistgramCommon.outputHistgram("CPU", histgram);
    timer.output(System.out);
  }