예제 #1
0
  public void updateEntry(String name, EntryConfig entryConfig) throws Exception {

    log.debug(TextUtil.repeat("-", 70));

    Directory directory = getDirectory();
    List<Entry> children = null;

    if (directory != null) {
      try {
        Entry oldEntry = directory.removeEntry(entryConfig.getName());
        if (oldEntry != null) {
          children = oldEntry.getChildren();
          oldEntry.destroy();
        }
      } catch (Exception e) {
        log.error(e.getMessage(), e);
      }
    }

    removeEntryService(entryConfig.getName());

    DirectoryConfig directoryConfig = getDirectoryConfig();
    directoryConfig.updateEntryConfig(name, entryConfig);

    if (directory != null) {
      try {
        Entry newEntry = directory.createEntry(entryConfig);
        if (children != null) newEntry.addChildren(children);
      } catch (Exception e) {
        log.error(e.getMessage(), e);
      }
    }

    createEntryService(entryConfig.getName());
  }
예제 #2
0
  // TODO: Make ln fit the 30 line
  public void ln(String firstPath, String secondPath) throws Exception {
    // Initialize the variables.
    JShellItem targetItem;
    JShellItem aliasItem;
    String newName;
    Directory destinationDirectory;

    // Find and reference the target item. Throw Exception if the path
    // doesn't exist.
    targetItem = getItemAtPath(firstPath, 0);
    if (targetItem == null) {
      throw new Exception(firstPath + ": doesn't exist.");
    }

    // Find and reference the destination Directory.
    if (secondPath.endsWith("/")) {
      destinationDirectory = (Directory) getItemAtPath(secondPath, 0);
      newName = targetItem.getName();
    } else {
      destinationDirectory = (Directory) getItemAtPath(secondPath, 1);
      newName = secondPath.substring(secondPath.lastIndexOf("/") + 1);
    }

    // If the Directory destination is not found.
    if (destinationDirectory == null) {
      throw new Exception(secondPath + " is an invalid destination path.");
    }

    // Throw Exception when there is a JShellItem that already exist within
    // the destination Directory.
    if (destinationDirectory.contains(newName)) {
      throw new Exception(secondPath + ": already exists.");
    }

    // If the target item is a Directory object.
    if (targetItem instanceof Directory)
      // Create a new Directory object that will references it's contents
      // from the target item.
      aliasItem =
          new DirectoryAlias(
              newName,
              destinationDirectory.getPath() + newName + "/",
              destinationDirectory,
              (Directory) targetItem);

    // If the target item is a File object.
    else
      // Create a new FileAlias object that will reference it's contents
      // from the target item.
      aliasItem =
          new FileAlias(
              newName,
              destinationDirectory.getPath() + newName,
              destinationDirectory,
              (File) targetItem);

    // Add the alias object to the destination Directory.
    destinationDirectory.addItem(aliasItem);
  }
예제 #3
0
 public void assertDeleteContent(Store store, DirectoryService service) throws IOException {
   store.deleteContent();
   assertThat(
       Arrays.toString(store.directory().listAll()),
       store.directory().listAll().length,
       equalTo(0));
   assertThat(store.stats().sizeInBytes(), equalTo(0l));
   for (Directory dir : service.build()) {
     assertThat(dir.listAll().length, equalTo(0));
   }
 }
예제 #4
0
  /**
   * Return the names of the contained items, if path leads to a Directory. Or, return the path
   * provided, if it leads to a File.
   *
   * @param paths a list of Strings containing the desired paths.
   * @return a String containing the relevant contents.
   */
  public String ls(List<String> paths) throws Exception {
    // If ls is called without parameters.
    if (paths.isEmpty()) {
      if (!currentOptions_.equals("R")) {
        if (currentDirectory_.getSize() == 0) {
          return "";
        } else {
          return currentDirectory_.ls().substring(2);
        }
      }
      paths.add(currentDirectory_.getPath());
      return ls(paths);

      // If ls is called with paramters.
    } else {
      String lsOutput = "";
      for (int i = 0; i < paths.size(); i++) {
        JShellItem target = getItemAtPath(paths.get(i), 0);
        if (!lsOutput.isEmpty()) {
          lsOutput += "\n";
        }
        lsOutput += paths.get(i);
        if (target == null) {
          lsOutput += ": No such file or directory";
        } else {

          if (target instanceof Directory
              && currentOptions_.equals("R")
              && ((Directory) target).getNumDirectories() > 0
              && !(target instanceof DirectoryAlias)) {
            List<String> recursivePath = recurseOnPath(paths.get(i), false);
            Collections.reverse(recursivePath);
            lsOutput += target.ls();
            lsOutput += "\n";
            lsOutput += ls(recursivePath.subList(1, recursivePath.size()));
          } else {
            // list paths separately
            lsOutput += target.ls();

            // if there are more paths, print a blank line
            if (i < paths.size() - 1) {
              lsOutput += "\n";
            }
            // notify user if there is an error in the path
            // specified
          }
        }
      }
      return lsOutput;
    }
  }
예제 #5
0
 /**
  * Creates a file at the path passed in the parameter.
  *
  * @param path The path at which the file is to be created. The path has to contain the file name
  *     as well.
  */
 public void mkfile(String path) throws Exception {
   Directory target = currentDirectory_;
   if (path.startsWith("/")) {
     String targetPath = path.substring(0, path.lastIndexOf("/"));
     target = (Directory) getItemAtPath(targetPath, 0);
   }
   if (target != null) {
     String fileName = path.substring(path.lastIndexOf("/") + 1);
     if (path.indexOf("/") != -1) {
       target = (Directory) getItemAtPath(path.substring(0, path.lastIndexOf("/")), 0);
     }
     target.addItem(new File(fileName, target.getPath() + fileName, target));
   }
 }
예제 #6
0
  public boolean buildManifest(ExtFile appDir, Map<String, Object> usesFramework)
      throws BrutException {
    try {
      if (!new File(appDir, "AndroidManifest.xml").exists()) {
        return false;
      }
      if (!apkOptions.forceBuildAll) {
        LOGGER.info("Checking whether resources has changed...");
      }

      File apkDir = new File(appDir, APK_DIRNAME);

      if (apkOptions.debugMode) {
        mAndRes.remove_application_debug(new File(apkDir, "AndroidManifest.xml").getAbsolutePath());
      }

      if (apkOptions.forceBuildAll
          || isModified(
              newFiles(APK_MANIFEST_FILENAMES, appDir), newFiles(APK_MANIFEST_FILENAMES, apkDir))) {
        LOGGER.info("Building AndroidManifest.xml...");

        File apkFile = File.createTempFile("APKTOOL", null);
        apkFile.delete();

        File ninePatch = new File(appDir, "9patch");
        if (!ninePatch.exists()) {
          ninePatch = null;
        }

        mAndRes.aaptPackage(
            apkFile,
            new File(appDir, "AndroidManifest.xml"),
            null,
            ninePatch,
            null,
            parseUsesFramework(usesFramework));

        Directory tmpDir = new ExtFile(apkFile).getDirectory();
        tmpDir.copyToDir(apkDir, APK_MANIFEST_FILENAMES);
      }
      return true;
    } catch (IOException | DirectoryException ex) {
      throw new AndrolibException(ex);
    } catch (AndrolibException ex) {
      LOGGER.warning("Parse AndroidManifest.xml failed, treat it as raw file.");
      return buildManifestRaw(appDir);
    }
  }
예제 #7
0
 public static String getDateTaken(File file) {
   Directory exifDirectory = getMetaDirectory(file);
   try {
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd hh:mm:ss"); // original format
     if (exifDirectory != null) {
       String dateStr = exifDirectory.getString(ExifDirectory.TAG_DATETIME_ORIGINAL);
       Date date = formatter.parse(dateStr);
       formatter = new SimpleDateFormat("MM/dd/yyyy"); // desired format
       return formatter.format(date);
     }
     return "no date picture taken info";
   } catch (ParseException e) {
     e.printStackTrace();
   }
   return "error occurred while getting the date";
 }
예제 #8
0
  /**
   * Print the path of the files specified by the paths argument whose path contains regex.
   *
   * @param regex is a String regular expression
   * @param paths is a List of paths
   */
  public String find(String regex, List<String> paths) throws Exception {
    String results = "";
    regex = regex.replace("?", ".?").replace("*", ".*?");
    Pattern regexPattern = Pattern.compile(regex);
    Matcher regexMatcher;

    // If the user input was empty, call find on the current directory.
    if (paths.isEmpty()) {
      paths.add(currentDirectory_.getPath());
    }
    // Loop through the paths.
    for (String path : paths) {
      List<String> recursiveListing = recurseOnPath(path, true);
      // Loop through the list of JShellItems found recursively.
      for (String name : recursiveListing) {
        regexMatcher = regexPattern.matcher(name);
        // Append to results if match is found.
        if (regexMatcher.find()) {
          results = results + name + "\n";
        }
      }
    }
    if (results.endsWith("\n")) {
      results = results.substring(0, results.length() - 1);
    } else {
      results = "find: no such file or directory.";
    }
    // Return the completed output.
    return results;
  }
예제 #9
0
  private void generateValuesFile(ResValuesFile valuesFile, Directory out, ExtXmlSerializer serial)
      throws AndrolibException {
    try {
      OutputStream outStream = out.getFileOutput(valuesFile.getPath());
      serial.setOutput((outStream), null);
      serial.startDocument(null, null);
      serial.startTag(null, "resources");

      for (ResResource res : valuesFile.listResources()) {
        if (valuesFile.isSynthesized(res)) {
          continue;
        }
        ((ResValuesXmlSerializable) res.getValue()).serializeToResValuesXml(serial, res);
      }

      serial.endTag(null, "resources");
      serial.newLine();
      serial.endDocument();
      serial.flush();
      outStream.close();
    } catch (IOException ex) {
      throw new AndrolibException("Could not generate: " + valuesFile.getPath(), ex);
    } catch (DirectoryException ex) {
      throw new AndrolibException("Could not generate: " + valuesFile.getPath(), ex);
    }
  }
예제 #10
0
  private void generatePublicXml(ResPackage pkg, Directory out, XmlSerializer serial)
      throws AndrolibException {
    try {
      OutputStream outStream = out.getFileOutput("values/public.xml");
      serial.setOutput(outStream, null);
      serial.startDocument(null, null);
      serial.startTag(null, "resources");

      for (ResResSpec spec : pkg.listResSpecs()) {
        serial.startTag(null, "public");
        serial.attribute(null, "type", spec.getType().getName());
        serial.attribute(null, "name", spec.getName());
        serial.attribute(null, "id", String.format("0x%08x", spec.getId().id));
        serial.endTag(null, "public");
      }

      serial.endTag(null, "resources");
      serial.endDocument();
      serial.flush();
      outStream.close();
    } catch (IOException ex) {
      throw new AndrolibException("Could not generate public.xml file", ex);
    } catch (DirectoryException ex) {
      throw new AndrolibException("Could not generate public.xml file", ex);
    }
  }
예제 #11
0
  public boolean buildResourcesFull(File appDir, Map<String, Object> usesFramework)
      throws AndrolibException {
    try {
      if (!new File(appDir, "res").exists()) {
        return false;
      }
      if (!apkOptions.forceBuildAll) {
        LOGGER.info("Checking whether resources has changed...");
      }
      File apkDir = new File(appDir, APK_DIRNAME);
      if (apkOptions.forceBuildAll
          || isModified(
              newFiles(APP_RESOURCES_FILENAMES, appDir),
              newFiles(APK_RESOURCES_FILENAMES, apkDir))) {
        LOGGER.info("Building resources...");

        File apkFile = File.createTempFile("APKTOOL", null);
        apkFile.delete();

        File ninePatch = new File(appDir, "9patch");
        if (!ninePatch.exists()) {
          ninePatch = null;
        }
        mAndRes.aaptPackage(
            apkFile,
            new File(appDir, "AndroidManifest.xml"),
            new File(appDir, "res"),
            ninePatch,
            null,
            parseUsesFramework(usesFramework));

        Directory tmpDir = new ExtFile(apkFile).getDirectory();
        tmpDir.copyToDir(
            apkDir,
            tmpDir.containsDir("res")
                ? APK_RESOURCES_FILENAMES
                : APK_RESOURCES_WITHOUT_RES_FILENAMES);

        // delete tmpDir
        apkFile.delete();
      }
      return true;
    } catch (IOException | BrutException ex) {
      throw new AndrolibException(ex);
    }
  }
예제 #12
0
  public void decode(ResTable resTable, ExtFile apkFile, File outDir) throws AndrolibException {
    Duo<ResFileDecoder, AXmlResourceParser> duo = getResFileDecoder();
    ResFileDecoder fileDecoder = duo.m1;
    ResAttrDecoder attrDecoder = duo.m2.getAttrDecoder();

    attrDecoder.setCurrentPackage(resTable.listMainPackages().iterator().next());

    Directory inApk, in = null, out;
    try {
      inApk = apkFile.getDirectory();
      out = new FileDirectory(outDir);

      LOGGER.info("Decoding AndroidManifest.xml with resources...");

      fileDecoder.decodeManifest(inApk, "AndroidManifest.xml", out, "AndroidManifest.xml");

      if (inApk.containsDir("res")) {
        in = inApk.getDir("res");
      }
      out = out.createDir("res");
    } catch (DirectoryException ex) {
      throw new AndrolibException(ex);
    }

    ExtMXSerializer xmlSerializer = getResXmlSerializer();
    for (ResPackage pkg : resTable.listMainPackages()) {
      attrDecoder.setCurrentPackage(pkg);

      LOGGER.info("Decoding file-resources...");
      for (ResResource res : pkg.listFiles()) {
        fileDecoder.decode(res, in, out);
      }

      LOGGER.info("Decoding values */* XMLs...");
      for (ResValuesFile valuesFile : pkg.listValuesFiles()) {
        generateValuesFile(valuesFile, out, xmlSerializer);
      }
      generatePublicXml(pkg, out, xmlSerializer);
      LOGGER.info("Done.");
    }

    AndrolibException decodeError = duo.m2.getFirstError();
    if (decodeError != null) {
      throw decodeError;
    }
  }
예제 #13
0
  /**
   * Copy file or directory oldFile to newFile;
   *
   * @param oldFile a full path to a JShellItem or the name of a JShellItem in the current directory
   *     which needs to be copied.
   * @param newFile a full path to a directory or the name of a directory in the current directory
   *     to which oldFile needs to be copied.
   */
  public void cp(String oldPath, String newPath) throws Exception {
    Directory destinationParent;
    String newName;
    if (oldPath.equals(newPath)) {
      return;
    }
    JShellItem oldItem = getItemAtPath(oldPath, 0);
    if (oldItem == null) {
      throw new Exception(oldItem + " does not exist.");
    }
    if (newPath.endsWith("/")) {
      destinationParent = (Directory) getItemAtPath(newPath, 0);
      newName = oldItem.getName();
    } else {
      destinationParent = (Directory) getItemAtPath(newPath, 1);
      newName = newPath.substring(newPath.lastIndexOf("/") + 1);
    }

    if (destinationParent == null) {
      throw new Exception(newPath + " is an invalid destination path.");
    }
    if (destinationParent.contains(newName)) {
      throw new Exception(destinationParent.getPath() + newName + " already exists.");
    }
    if (oldItem instanceof File) {
      File newItem =
          new File(
              newName,
              destinationParent.getPath() + "/" + newName,
              destinationParent,
              ((File) oldItem).getContent());
      destinationParent.addItem(newItem);
    } else {
      if (destinationParent.isChildOf((Directory) oldItem)) {
        throw new Exception(
            String.format("cp: cannot copy '%s' into itself, '%s'", oldPath, newPath));
      }
      Directory newItem =
          new Directory(newName, destinationParent.getPath() + newName + "/", destinationParent);
      destinationParent.addItem(newItem);
      for (JShellItem item : ((Directory) oldItem).getContents().values()) {
        cp(item.getPath(), newItem.getPath());
      }
    }
  }
예제 #14
0
  public void removeEntry(String entryName) throws Exception {

    log.debug(TextUtil.repeat("-", 70));

    Directory directory = getDirectory();
    if (directory != null) {
      try {
        directory.destroy(entryName);
      } catch (Exception e) {
        log.error(e.getMessage(), e);
      }
    }

    DirectoryConfig directoryConfig = getDirectoryConfig();
    directoryConfig.removeEntryConfig(entryName);

    removeEntryService(entryName);
  }
예제 #15
0
 private Bucket getBucket(@Nullable Resource reference) {
   if (reference == null) {
     return null;
   }
   if (StringUtils.isNotBlank(reference.getKey())) {
     return buckets.get(reference);
   }
   String relativePathFromSourceDir = null;
   boolean isTest = false;
   boolean isDir = false;
   if (reference instanceof File) {
     File referenceFile = (File) reference;
     isTest = Qualifiers.UNIT_TEST_FILE.equals(referenceFile.getQualifier());
     relativePathFromSourceDir = referenceFile.relativePathFromSourceDir();
   } else if (reference instanceof Directory) {
     isDir = true;
     Directory referenceDir = (Directory) reference;
     relativePathFromSourceDir = referenceDir.relativePathFromSourceDir();
     if (Directory.ROOT.equals(relativePathFromSourceDir)) {
       relativePathFromSourceDir = "";
     }
   }
   if (relativePathFromSourceDir != null) {
     // Resolve using deprecated key
     List<java.io.File> dirs;
     if (isTest) {
       dirs = getProject().getFileSystem().getTestDirs();
     } else {
       dirs = getProject().getFileSystem().getSourceDirs();
     }
     for (java.io.File src : dirs) {
       java.io.File abs = new java.io.File(src, relativePathFromSourceDir);
       Bucket b =
           getBucket(
               isDir
                   ? Directory.fromIOFile(abs, getProject())
                   : File.fromIOFile(abs, getProject()));
       if (b != null) {
         return b;
       }
     }
   }
   return null;
 }
예제 #16
0
 @Test
 public void testVerifyingIndexOutputWithBogusInput() throws IOException {
   Directory dir = newDirectory();
   int length = scaledRandomIntBetween(10, 1024);
   IndexOutput verifyingOutput =
       new Store.LuceneVerifyingIndexOutput(
           new StoreFileMetaData("foo1.bar", length, ""),
           dir.createOutput("foo1.bar", IOContext.DEFAULT));
   try {
     while (length > 0) {
       verifyingOutput.writeByte((byte) random().nextInt());
       length--;
     }
     fail("should be a corrupted index");
   } catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
     // ok
   }
   IOUtils.close(verifyingOutput, dir);
 }
예제 #17
0
 public void testTermDocsEnum() throws Exception {
   Directory dir = newDirectory();
   IndexWriter w =
       new IndexWriter(
           dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
   Document d = new Document();
   d.add(newStringField("f", "j", Field.Store.NO));
   w.addDocument(d);
   w.commit();
   w.addDocument(d);
   IndexReader r = w.getReader();
   w.close();
   DocsEnum de = MultiFields.getTermDocsEnum(r, null, "f", new BytesRef("j"));
   assertEquals(0, de.nextDoc());
   assertEquals(1, de.nextDoc());
   assertEquals(DocIdSetIterator.NO_MORE_DOCS, de.nextDoc());
   r.close();
   dir.close();
 }
예제 #18
0
  public void writeOriginalFiles(ExtFile apkFile, File outDir) throws AndrolibException {
    LOGGER.info("Copying original files...");
    File originalDir = new File(outDir, "original");
    if (!originalDir.exists()) {
      originalDir.mkdirs();
    }

    try {
      Directory in = apkFile.getDirectory();
      if (in.containsFile("AndroidManifest.xml")) {
        in.copyToDir(originalDir, "AndroidManifest.xml");
      }
      if (in.containsDir("META-INF")) {
        in.copyToDir(originalDir, "META-INF");
      }
    } catch (DirectoryException ex) {
      throw new AndrolibException(ex);
    }
  }
예제 #19
0
 public void testSeparateEnums() throws Exception {
   Directory dir = newDirectory();
   IndexWriter w =
       new IndexWriter(
           dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
   Document d = new Document();
   d.add(newStringField("f", "j", Field.Store.NO));
   w.addDocument(d);
   w.commit();
   w.addDocument(d);
   IndexReader r = w.getReader();
   w.close();
   DocsEnum d1 = _TestUtil.docs(random(), r, "f", new BytesRef("j"), null, null, 0);
   DocsEnum d2 = _TestUtil.docs(random(), r, "f", new BytesRef("j"), null, null, 0);
   assertEquals(0, d1.nextDoc());
   assertEquals(0, d2.nextDoc());
   r.close();
   dir.close();
 }
예제 #20
0
 private void corruptFile(Directory dir, String fileIn, String fileOut) throws IOException {
   IndexInput input = dir.openInput(fileIn, IOContext.READONCE);
   IndexOutput output = dir.createOutput(fileOut, IOContext.DEFAULT);
   long len = input.length();
   byte[] b = new byte[1024];
   long broken = randomInt((int) len);
   long pos = 0;
   while (pos < len) {
     int min = (int) Math.min(input.length() - pos, b.length);
     input.readBytes(b, 0, min);
     if (broken >= pos && broken < pos + min) {
       // Flip one byte
       int flipPos = (int) (broken - pos);
       b[flipPos] = (byte) (b[flipPos] ^ 42);
     }
     output.writeBytes(b, min);
     pos += min;
   }
   IOUtils.close(input, output);
 }
예제 #21
0
  public String createEntry(EntryConfig entryConfig) throws Exception {

    log.debug(TextUtil.repeat("-", 70));

    DirectoryConfig directoryConfig = getDirectoryConfig();
    directoryConfig.addEntryConfig(entryConfig);

    Directory directory = getDirectory();
    if (directory != null) {
      try {
        directory.createEntry(entryConfig);
      } catch (Exception e) {
        log.error(e.getMessage(), e);
      }
    }

    createEntryService(entryConfig.getName());

    return entryConfig.getName();
  }
예제 #22
0
 @Test
 public void testVerifyingIndexOutput() throws IOException {
   Directory dir = newDirectory();
   IndexOutput output = dir.createOutput("foo.bar", IOContext.DEFAULT);
   int iters = scaledRandomIntBetween(10, 100);
   for (int i = 0; i < iters; i++) {
     BytesRef bytesRef = new BytesRef(TestUtil.randomRealisticUnicodeString(random(), 10, 1024));
     output.writeBytes(bytesRef.bytes, bytesRef.offset, bytesRef.length);
   }
   CodecUtil.writeFooter(output);
   output.close();
   IndexInput indexInput = dir.openInput("foo.bar", IOContext.DEFAULT);
   String checksum = Store.digestToString(CodecUtil.retrieveChecksum(indexInput));
   indexInput.seek(0);
   BytesRef ref = new BytesRef(scaledRandomIntBetween(1, 1024));
   long length = indexInput.length();
   IndexOutput verifyingOutput =
       new Store.LuceneVerifyingIndexOutput(
           new StoreFileMetaData("foo1.bar", length, checksum),
           dir.createOutput("foo1.bar", IOContext.DEFAULT));
   while (length > 0) {
     if (random().nextInt(10) == 0) {
       verifyingOutput.writeByte(indexInput.readByte());
       length--;
     } else {
       int min = (int) Math.min(length, ref.bytes.length);
       indexInput.readBytes(ref.bytes, ref.offset, min);
       verifyingOutput.writeBytes(ref.bytes, ref.offset, min);
       length -= min;
     }
   }
   Store.verify(verifyingOutput);
   verifyingOutput.writeByte((byte) 0x0);
   try {
     Store.verify(verifyingOutput);
     fail("should be a corrupted index");
   } catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
     // ok
   }
   IOUtils.close(indexInput, verifyingOutput, dir);
 }
 public static void checkIndex(ESLogger logger, Store store, ShardId shardId) {
   if (store.tryIncRef()) {
     logger.info("start check index");
     try {
       Directory dir = store.directory();
       if (!Lucene.indexExists(dir)) {
         return;
       }
       if (IndexWriter.isLocked(dir)) {
         ESTestCase.checkIndexFailed = true;
         throw new IllegalStateException("IndexWriter is still open on shard " + shardId);
       }
       try (CheckIndex checkIndex = new CheckIndex(dir)) {
         BytesStreamOutput os = new BytesStreamOutput();
         PrintStream out = new PrintStream(os, false, StandardCharsets.UTF_8.name());
         checkIndex.setInfoStream(out);
         out.flush();
         CheckIndex.Status status = checkIndex.checkIndex();
         if (!status.clean) {
           ESTestCase.checkIndexFailed = true;
           logger.warn(
               "check index [failure] index files={}\n{}",
               Arrays.toString(dir.listAll()),
               new String(os.bytes().toBytes(), StandardCharsets.UTF_8));
           throw new IOException("index check failure");
         } else {
           if (logger.isDebugEnabled()) {
             logger.debug(
                 "check index [success]\n{}",
                 new String(os.bytes().toBytes(), StandardCharsets.UTF_8));
           }
         }
       }
     } catch (Exception e) {
       logger.warn("failed to check index", e);
     } finally {
       logger.info("end check index");
       store.decRef();
     }
   }
 }
예제 #24
0
 public void buildCopyOriginalFiles(File appDir) throws AndrolibException {
   if (apkOptions.copyOriginalFiles) {
     File originalDir = new File(appDir, "original");
     if (originalDir.exists()) {
       try {
         LOGGER.info("Copy original files...");
         Directory in = (new ExtFile(originalDir)).getDirectory();
         if (in.containsFile("AndroidManifest.xml")) {
           LOGGER.info("Copy AndroidManifest.xml...");
           in.copyToDir(new File(appDir, APK_DIRNAME), "AndroidManifest.xml");
         }
         if (in.containsDir("META-INF")) {
           LOGGER.info("Copy META-INF...");
           in.copyToDir(new File(appDir, APK_DIRNAME), "META-INF");
         }
       } catch (DirectoryException ex) {
         throw new AndrolibException(ex);
       }
     }
   }
 }
예제 #25
0
  /**
   * Creates Directories in the paths provided. The path is considered to be invalid if (1) There is
   * already an item with the same path. (2) The immediate parent of the specified path does not
   * exist.
   *
   * @throws Exception if a provided path is invalid.
   * @param paths is the list of paths. Paths can be relative to the current directory or the full
   *     path.
   */
  public void mkdir(List<String> paths) throws Exception {
    for (String dir : paths) {
      if (!dir.startsWith("/")) {
        dir = currentDirectory_.getPath().concat(dir);
      }
      while (dir.endsWith("/")) {
        dir = dir.substring(0, dir.length() - 1);
      }
      String[] dirs = dir.split("/");
      String dirName = dirs[dirs.length - 1];
      dir = dir.substring(0, dir.length() - dirName.length());
      Directory parent = (Directory) getItemAtPath(dir, 0);

      if (parent == null) {
        throw new NullPointerException("The path specified is " + "incorrect.");
      }
      if (parent.getContents().keySet().contains(dirName)) {
        throw new Exception("A directory already exists at that " + "path.");
      }
      parent.addItem(new Directory(dirName, parent.getPath() + dirName + "/", parent));
    }
  }
예제 #26
0
  @Test
  public void testVerifyingIndexInput() throws IOException {
    Directory dir = newDirectory();
    IndexOutput output = dir.createOutput("foo.bar", IOContext.DEFAULT);
    int iters = scaledRandomIntBetween(10, 100);
    for (int i = 0; i < iters; i++) {
      BytesRef bytesRef = new BytesRef(TestUtil.randomRealisticUnicodeString(random(), 10, 1024));
      output.writeBytes(bytesRef.bytes, bytesRef.offset, bytesRef.length);
    }
    CodecUtil.writeFooter(output);
    output.close();

    // Check file
    IndexInput indexInput = dir.openInput("foo.bar", IOContext.DEFAULT);
    long checksum = CodecUtil.retrieveChecksum(indexInput);
    indexInput.seek(0);
    IndexInput verifyingIndexInput =
        new Store.VerifyingIndexInput(dir.openInput("foo.bar", IOContext.DEFAULT));
    readIndexInputFullyWithRandomSeeks(verifyingIndexInput);
    Store.verify(verifyingIndexInput);
    assertThat(checksum, equalTo(((ChecksumIndexInput) verifyingIndexInput).getChecksum()));
    IOUtils.close(indexInput, verifyingIndexInput);

    // Corrupt file and check again
    corruptFile(dir, "foo.bar", "foo1.bar");
    verifyingIndexInput =
        new Store.VerifyingIndexInput(dir.openInput("foo1.bar", IOContext.DEFAULT));
    readIndexInputFullyWithRandomSeeks(verifyingIndexInput);
    try {
      Store.verify(verifyingIndexInput);
      fail("should be a corrupted index");
    } catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
      // ok
    }
    IOUtils.close(verifyingIndexInput);
    IOUtils.close(dir);
  }
예제 #27
0
  public void decodeUnknownFiles(ExtFile apkFile, File outDir, ResTable resTable)
      throws AndrolibException {
    LOGGER.info("Copying unknown files...");
    File unknownOut = new File(outDir, UNK_DIRNAME);
    ZipEntry invZipFile;

    // have to use container of ZipFile to help identify compression type
    // with regular looping of apkFile for easy copy
    try {
      Directory unk = apkFile.getDirectory();
      ZipFile apkZipFile = new ZipFile(apkFile.getAbsolutePath());

      // loop all items in container recursively, ignoring any that are pre-defined by aapt
      Set<String> files = unk.getFiles(true);
      for (String file : files) {
        if (!isAPKFileNames(file) && !file.endsWith(".dex")) {

          // copy file out of archive into special "unknown" folder
          unk.copyToDir(unknownOut, file);
          try {
            invZipFile = apkZipFile.getEntry(file);

            // lets record the name of the file, and its compression type
            // so that we may re-include it the same way
            if (invZipFile != null) {
              mResUnknownFiles.addUnknownFileInfo(
                  invZipFile.getName(), String.valueOf(invZipFile.getMethod()));
            }
          } catch (NullPointerException ignored) {
          }
        }
      }
      apkZipFile.close();
    } catch (DirectoryException | IOException ex) {
      throw new AndrolibException(ex);
    }
  }
예제 #28
0
 public void decodeRawFiles(ExtFile apkFile, File outDir) throws AndrolibException {
   LOGGER.info("Copying assets and libs...");
   try {
     Directory in = apkFile.getDirectory();
     if (in.containsDir("assets")) {
       in.copyToDir(outDir, "assets");
     }
     if (in.containsDir("lib")) {
       in.copyToDir(outDir, "lib");
     }
     if (in.containsDir("libs")) {
       in.copyToDir(outDir, "libs");
     }
   } catch (DirectoryException ex) {
     throw new AndrolibException(ex);
   }
 }
예제 #29
0
 /** JShell constructor. Initialize instance variables and map each command to a number. */
 public JShell() {
   currentDirectory_ = new Directory("", "/", null);
   rootDirectory_ = currentDirectory_;
   rootDirectory_.setParentDirectory(rootDirectory_);
   commands_ = new HashMap<String, Integer>();
   commands_.put("exit", 0);
   commands_.put("mkdir", 1);
   commands_.put("cd", 2);
   commands_.put("ls", 3);
   commands_.put("pwd", 4);
   commands_.put("mv", 5);
   commands_.put("cp", 6);
   commands_.put("cat", 7);
   commands_.put("get", 8);
   commands_.put("echo", 9);
   commands_.put("rm", 10);
   commands_.put("ln", 11);
   commands_.put("man", 12);
   commands_.put("find", 13);
   commands_.put("grep", 14);
 }
예제 #30
0
  /**
   * Changes current working directory to dir.
   *
   * @param dir name of a directory in the current directory or may be a full path; '..' means a
   *     parent directory and '.' means the current directory; The directory separator must be '/',
   *     the forward slash.
   */
  public void cd(String dir) throws Exception {
    // Initialize the destination directory.
    JShellItem destination;
    String path = dir;

    // If user's input path doesn't begin with "/", use relative path
    // with the current directory.
    if (!dir.startsWith("/")) {
      dir = currentDirectory_.getPath().concat(dir);
    }

    // If user's input path doesn't end with "/", concatenate it to
    // complete a full path.
    if (!dir.endsWith("/")) {
      dir = dir.concat("/");
    }

    // Find the directory location.
    destination = getItemAtPath(dir, 0);

    // Check to see if user is trying to change directory into a File
    // object.
    if (destination instanceof File) {
      System.out.println(path + ": Not a directory.");

      // destination is a Directory Object.
    } else {
      // Use try to catch NullPointerException for directories that
      // doesn't exist.

      // If path exists, location of the directory is found.
      if (destination != null) {
        currentDirectory_ = (Directory) destination;
      } else {
        // The directory doesn't exist.
        throw new NullPointerException(path + ": no such directory.");
      }
    }
  }