예제 #1
0
 public static boolean download(
     URL url, String file, int prefix, int totalFilesize, IProgressUpdater updater) {
   File fFile = new File(new File(file).getParentFile().getPath());
   if (!fFile.exists()) fFile.mkdirs();
   boolean downloaded = true;
   BufferedInputStream in = null;
   FileOutputStream out = null;
   BufferedOutputStream bout = null;
   try {
     int count;
     int totalCount = 0;
     byte data[] = new byte[BUFFER];
     in = new BufferedInputStream(url.openStream());
     out = new FileOutputStream(file);
     bout = new BufferedOutputStream(out);
     while ((count = in.read(data, 0, BUFFER)) != -1) {
       bout.write(data, 0, count);
       totalCount += count;
       if (updater != null) updater.update(prefix + totalCount, totalFilesize);
     }
   } catch (Exception e) {
     e.printStackTrace();
     Utils.logger.log(Level.SEVERE, "Download error!");
     downloaded = false;
   } finally {
     try {
       close(in);
       close(bout);
       close(out);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return downloaded;
 }
예제 #2
0
  /**
   * Crea el fichero de indices con la informacion inicial necesaria para un archivo concreto.
   *
   * @param fichero es el fichero de indices que tendra toda la informacion.
   * @param archivo es el objeto que representa el archivo en concreto.
   * @param fragmentos es la lista de fragmentos que faltan de dicho archivo.
   */
  public void crearFicheroIndices(File fichero, Archivo archivo, Vector<Fragmento> fragmentos) {
    Vector<Fragmento> fragTengo = new Vector<Fragmento>(), fragFaltan = fragmentos;
    Indices indices = new Indices(archivo, fragTengo, fragFaltan);
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    try {
      ObjectOutputStream os = new ObjectOutputStream(bs);
      os.writeObject(indices);
      os.close();

    } catch (IOException e) {
      /*System.out.println("Error -> posibles causas: ");
      System.out.println( "\tProblemas al crear un flujo de bytes serializable" );
      System.out.println( "\tProblemas al serializar el objeto indice" );
      System.out.println( "\tProblemas al cerrar el flujo serializable" );*/
      ControlDeErrores.getInstancia()
          .registrarError(
              ErrorEGorilla.ERROR_DISCO,
              "Error -> posibles causas: "
                  + "\tProblemas al crear un flujo de bytes serializable"
                  + "\tProblemas al serializar el objeto indice"
                  + "\tProblemas al cerrar el flujo serializable");
      // e.printStackTrace();
    }

    byte[] bytes = bs.toByteArray(); // devuelve byte[]

    try {
      if (fichero.exists() == true) {
        String nombreNuevoFichero = fichero.getName();
        nombreNuevoFichero += "_" + archivo.getHash();
        fichero = new File(nombreNuevoFichero);
      }
      FileOutputStream ficheroIndices = new FileOutputStream(fichero);
      BufferedOutputStream bufferedOutput = new BufferedOutputStream(ficheroIndices);
      bufferedOutput.write(bytes, 0, bytes.length);
      bufferedOutput.close();
      // creo que tambien hace falta cerrar el otro
      ficheroIndices.close();
    } catch (FileNotFoundException e) {
      System.out.println("No existe el fichero <" + fichero.getName() + ">");
    } catch (IOException e) {
      /*System.out.println("Error -> posibles causas: ");
      System.out.println( "\tProblemas al escribir en el fichero <"+fichero.getName()+">" );
      System.out.println( "\tProblemas al cerrar el flujo o el fichero <"+fichero.getName()+">" );*/
      ControlDeErrores.getInstancia()
          .registrarError(
              ErrorEGorilla.ERROR_DISCO,
              "Error -> posibles causas: "
                  + "\tProblemas al escribir en el fichero <"
                  + fichero.getName()
                  + ">"
                  + "\tProblemas al cerrar el flujo o el fichero <"
                  + fichero.getName()
                  + ">");
      // e.printStackTrace();
    }
  }
예제 #3
0
 public void write(File file, Drawing drawing) throws IOException {
     BufferedOutputStream out = new BufferedOutputStream(
             new FileOutputStream(file));
     try {
         write(out, drawing);
     } finally {
         if (out != null) {
             out.close();
         }
     }
 }
예제 #4
0
 @Override
 public void write(@SuppressWarnings("NullableProblems") byte[] bytes) {
   try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true))) {
     bos.write(bytes);
     bos.close();
   } catch (IOException e) {
     RuntimeException ex =
         new RuntimeException("Unable to write to file " + file.getAbsolutePath());
     ex.initCause(e);
     throw ex;
   }
 }
예제 #5
0
  /** Download resource to the given file */
  private boolean download(URL target, File file) {

    _log.addDebug("JarDiffHandler:  Doing download");

    boolean ret = true;
    boolean delete = false;
    // use bufferedstream for better performance
    BufferedInputStream in = null;
    BufferedOutputStream out = null;
    try {
      in = new BufferedInputStream(target.openStream());
      out = new BufferedOutputStream(new FileOutputStream(file));
      int read = 0;
      int totalRead = 0;
      byte[] buf = new byte[BUF_SIZE];
      while ((read = in.read(buf)) != -1) {
        out.write(buf, 0, read);
        totalRead += read;
      }

      _log.addDebug("total read: " + totalRead);
      _log.addDebug("Wrote URL " + target.toString() + " to file " + file);

    } catch (IOException ioe) {

      _log.addDebug("Got exception while downloading resource: " + ioe);

      ret = false;

      if (file != null) delete = true;

    } finally {

      try {
        in.close();
        in = null;
      } catch (IOException ioe) {
        _log.addDebug("Got exception while downloading resource: " + ioe);
      }

      try {
        out.close();
        out = null;
      } catch (IOException ioe) {
        _log.addDebug("Got exception while downloading resource: " + ioe);
      }

      if (delete) {
        file.delete();
      }
    }
    return ret;
  }
예제 #6
0
  /**
   * Copies a file or directory
   *
   * @param src the file or directory to copy
   * @param dest where copy
   * @throws IOException
   */
  public static void copyFile(File src, File dest) throws IOException {
    if (!src.exists()) throw new IOException("File not found '" + src.getAbsolutePath() + "'");
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));

    byte[] read = new byte[4096];
    int len;
    while ((len = in.read(read)) > 0) out.write(read, 0, len);

    out.flush();
    out.close();
    in.close();
  }
예제 #7
0
 /**
  * Sends an input stream to the server.
  *
  * @param input xml input
  * @throws IOException I/O exception
  */
 private void send(final InputStream input) throws IOException {
   final BufferedInputStream bis = new BufferedInputStream(input);
   final BufferedOutputStream bos = new BufferedOutputStream(out);
   for (int b; (b = bis.read()) != -1; ) {
     // 0x00 and 0xFF will be prefixed by 0xFF
     if (b == 0x00 || b == 0xFF) bos.write(0xFF);
     bos.write(b);
   }
   bos.write(0);
   bos.flush();
   info = receive();
   if (!ok()) throw new IOException(info);
 }
예제 #8
0
파일: Installer.java 프로젝트: suever/CTP
 // Take a tree of files starting in a directory in a zip file
 // and copy them to a disk directory, recreating the tree.
 private int unpackZipFile(
     File inZipFile, String directory, String parent, boolean suppressFirstPathElement) {
   int count = 0;
   if (!inZipFile.exists()) return count;
   parent = parent.trim();
   if (!parent.endsWith(File.separator)) parent += File.separator;
   if (!directory.endsWith(File.separator)) directory += File.separator;
   File outFile = null;
   try {
     ZipFile zipFile = new ZipFile(inZipFile);
     Enumeration zipEntries = zipFile.entries();
     while (zipEntries.hasMoreElements()) {
       ZipEntry entry = (ZipEntry) zipEntries.nextElement();
       String name = entry.getName().replace('/', File.separatorChar);
       if (name.startsWith(directory)) {
         if (suppressFirstPathElement) name = name.substring(directory.length());
         outFile = new File(parent + name);
         // Create the directory, just in case
         if (name.indexOf(File.separatorChar) >= 0) {
           String p = name.substring(0, name.lastIndexOf(File.separatorChar) + 1);
           File dirFile = new File(parent + p);
           dirFile.mkdirs();
         }
         if (!entry.isDirectory()) {
           System.out.println("Installing " + outFile);
           // Copy the file
           BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
           BufferedInputStream in = new BufferedInputStream(zipFile.getInputStream(entry));
           int size = 1024;
           int n = 0;
           byte[] b = new byte[size];
           while ((n = in.read(b, 0, size)) != -1) out.write(b, 0, n);
           in.close();
           out.flush();
           out.close();
           // Count the file
           count++;
         }
       }
     }
     zipFile.close();
   } catch (Exception e) {
     System.err.println("...an error occured while installing " + outFile);
     e.printStackTrace();
     System.err.println("Error copying " + outFile.getName() + "\n" + e.getMessage());
     return -count;
   }
   System.out.println(count + " files were installed.");
   return count;
 }
 /*.................................................................................................................*/
 public void cipresDownload(HttpClient httpclient, String URL, String filePath) {
   HttpGet httpget = new HttpGet(URL);
   httpget.addHeader("cipres-appkey", CIPRESkey);
   try {
     HttpResponse response = httpclient.execute(httpget);
     HttpEntity responseEntity = response.getEntity();
     BufferedInputStream bis = new BufferedInputStream(responseEntity.getContent());
     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
     int inByte;
     while ((inByte = bis.read()) != -1) bos.write(inByte);
     bis.close();
     bos.close();
     EntityUtils.consume(response.getEntity());
   } catch (IOException e) {
     Debugg.printStackTrace(e);
   }
 }
예제 #10
0
파일: MoquiStart.java 프로젝트: emer3/moqui
  protected File createTempFile(JarEntry je) throws IOException {
    byte[] jeBytes = getJarEntryBytes(outerFile, je);

    String tempName = je.getName().replace('/', '_') + ".";
    File tempDir = new File("execwartmp");
    if (tempDir.mkdir()) tempDir.deleteOnExit();
    File file = File.createTempFile("moqui_temp", tempName, tempDir);
    file.deleteOnExit();
    BufferedOutputStream os = null;
    try {
      os = new BufferedOutputStream(new FileOutputStream(file));
      os.write(jeBytes);
    } finally {
      if (os != null) os.close();
    }
    return file;
  }
예제 #11
0
  public static void copy(String srcFileName, String dstFileName) {
    try {
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(srcFileName));
      BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dstFileName));
      byte[] bytes = new byte[1024];

      int nb = in.read(bytes, 0, bytes.length);
      while (nb > 0) {
        out.write(bytes, 0, nb);
        nb = in.read(bytes, 0, bytes.length);
      }
      in.close();
      out.close();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      System.exit(1);
    }
  }
예제 #12
0
  public static int copyPlugin(JFrame frame, File source, String destFileName) {
    if (destFileName == null) destFileName = source.getName();
    if (!PluginCore.userPluginDir.exists()) {
      boolean created = PluginCore.userPluginDir.mkdirs();
      if (!created) {
        return UNABLE_TO_CREATE_DIR;
      }
    }
    File destFile = new File(PluginCore.userPluginDir, destFileName);
    BufferedInputStream in = null;
    BufferedOutputStream out = null;
    try {
      in = new BufferedInputStream(new FileInputStream(source));
      out = new BufferedOutputStream(new FileOutputStream(destFile));
      byte[] buf = new byte[1024];
      int count;
      while ((count = in.read(buf, 0, buf.length)) > 0) {
        out.write(buf, 0, count);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
      return UNABLE_TO_COPY_FILE;
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException ignore) {
          // UNABLE_TO_COPY_FILE;
        }
      }

      if (out != null) {
        try {
          out.close();
        } catch (IOException ignore) {
          // UNABLE_TO_COPY_FILE;
        }
      }
    }
    return SUCCESS;
  }
예제 #13
0
  public static void extract(String zipFile, String newPath, boolean overwrite)
      throws ZipException, IOException {
    File file = new File(zipFile);

    ZipFile zip = new ZipFile(file);

    new File(newPath).mkdir();
    Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
      // grab a zip file entry
      ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
      String currentEntry = entry.getName();
      File destFile = new File(newPath, currentEntry);
      // destFile = new File(newPath, destFile.getName());
      File destinationParent = destFile.getParentFile();

      // create the parent directory structure if needed
      destinationParent.mkdirs();

      if (!entry.isDirectory()) {
        if (!overwrite && destFile.exists()) continue;
        BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
        int currentByte;
        // establish buffer for writing file
        byte data[] = new byte[BUFFER];

        // write the current file to disk
        FileOutputStream fos = new FileOutputStream(destFile);
        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

        // read and write until last byte is encountered
        while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
          dest.write(data, 0, currentByte);
        }
        close(dest);
        close(is);
      }
    }
  }
예제 #14
0
  /**
   * Guarda la nueva informacion sobre los indices de un archivo concreto en su fichero
   * correspondiente.
   *
   * @param fichero es el fichero donde se almacenara el indice.
   * @param indices es el objeto que contiene la informacion sobre lo que tenemos del archivo.
   */
  public void guardarFicheroIndices(File fichero, Indices indices) {
    try {
      ByteArrayOutputStream bs = new ByteArrayOutputStream();
      ObjectOutputStream os = new ObjectOutputStream(bs);
      os.writeObject(indices);
      os.close();
      byte[] bytes = bs.toByteArray(); // devuelve byte[]

      FileOutputStream ficheroIndices = new FileOutputStream(fichero);
      BufferedOutputStream bufferedOutput = new BufferedOutputStream(ficheroIndices);
      // Pese a existir ya el fichero, como voy anadiendo fragmentos, el file aumenta
      // por lo q sobreescribo el fichero con mas bytes y no menos, ya que si fueran menos
      // quedarian bytes malos en el file
      bufferedOutput.write(bytes, 0, bytes.length);
      bufferedOutput.close();
      // creo que tambien hace falta cerrar el otro
      ficheroIndices.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #15
0
 private boolean unzipModuleData(
     final File directory, final ModuleZipInfo zipinfo, boolean deleteZip) {
   try (InputStream is = new BufferedInputStream(new FileInputStream(zipinfo.filename));
       ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is))) {
     ZipEntry entry;
     while ((entry = zis.getNextEntry()) != null) {
       String entryName = zipinfo.oldStyle ? removeTopDir(entry.getName()) : entry.getName();
       if (!entryName.isEmpty()) {
         if (entry.isDirectory()) {
           new File(directory, entryName).mkdir();
         } else {
           int count;
           byte[] buff = new byte[BUFFER_SIZE];
           BufferedOutputStream dest = null;
           try {
             OutputStream fos = new FileOutputStream(new File(directory, entryName));
             dest = new BufferedOutputStream(fos, BUFFER_SIZE);
             while ((count = zis.read(buff, 0, BUFFER_SIZE)) != -1) {
               dest.write(buff, 0, count);
             }
             dest.flush();
           } finally {
             if (dest != null) {
               dest.close();
             }
           }
         }
       }
     }
   } catch (Exception e) {
     log.error("Failed to unzip module", e);
     return false;
   } finally {
     directory.delete();
     if (deleteZip) {
       new File(zipinfo.filename).delete();
     }
   }
   return true;
 }
  protected void syncAppVersion() {
    final Metadata metadata =
        Metadata.getInstance(new File(getBasedir(), "application.properties"));
    if (syncVersion(metadata)) metadata.persist();

    String artifactId = project.getArtifactId();

    if (artifactId.startsWith("grails-")) artifactId = artifactId.substring("grails-".length());

    final String fName = getFullGrailsPluginName();
    if (fName != null) {
      File gpFile = new File(fName);

      String text = null;
      String mod = null;
      try {
        text = readFileAsString(gpFile);
        mod = text.replaceFirst(GRAILS_PLUGIN_VERSION_PATTERN, "$1" + project.getVersion() + "$5");
      } catch (IOException e) {
        // ignore
      }
      if (text != null && !mod.equalsIgnoreCase(text)) {
        BufferedOutputStream out = null;
        try {
          out = new BufferedOutputStream(new FileOutputStream(gpFile));
          out.write(mod.getBytes());
        } catch (IOException e) {
          // do nuffink
        } finally {
          if (out != null) {
            try {
              out.close();
            } catch (Exception ignored) {
              // ignored
            }
          }
        }
      }
    }
  }
예제 #17
0
  public static void copyFile(File sourceFile, File destFile) throws IOException {
    Debugger.Write(
        "Copying File:" + sourceFile.toString() + " To " + destFile.toString(),
        Debugger.DebugLevel.Verbose);
    BufferedInputStream bsin = new BufferedInputStream(new FileInputStream(sourceFile));
    BufferedOutputStream bsout = new BufferedOutputStream(new FileOutputStream(destFile));
    int chunksize = 16 * 1024;
    int readamount = 0;
    byte[] buffer = new byte[chunksize];
    try {
      // write in chunks of chunksize.
      while ((readamount = bsin.read(buffer, 0, chunksize)) == chunksize) {
        bsout.write(buffer, 0, chunksize);
      }
      // write out the remainder.
      bsout.write(buffer, 0, readamount);

    } catch (Exception exx) {
      exx.printStackTrace();
    } finally {
      bsin.close();
      bsout.close();
    }
  }
예제 #18
0
  /**
   * Write uninstall data.
   *
   * @return true if the infos were successfuly written, false otherwise.
   */
  public boolean write() {
    try {
      if (!isUninstallShouldBeWriten()) {
        return false;
      }
      BufferedWriter extLogWriter = getExternLogFile(installdata);
      createOutputJar();
      // We get the data
      List<String> files = udata.getUninstalableFilesList();

      if (outJar == null) {
        return true; // it is allowed not to have an installer
      }

      System.out.println("[ Writing the uninstaller data ... ]");

      writeJarSkeleton(installdata, pathResolver, outJar);

      writeFilesLog(installdata, extLogWriter, files, outJar);

      writeUninstallerJarFileLog(udata, outJar);

      writeExecutables(udata, outJar);

      writeAdditionalUninstallData(udata, outJar);

      writeScriptFiles(udata, outJar);

      // Cleanup
      outJar.flush();
      outJar.close();
      bos.close();
      out.close();
      return true;
    } catch (Exception err) {
      err.printStackTrace();
      return false;
    }
  }
예제 #19
0
  public static void main(String[] argv) throws Exception {
    DSIndexer.setBatchProcessingMode(true);
    Date startTime = new Date();
    int status = 0;

    try {
      // create an options object and populate it
      CommandLineParser parser = new PosixParser();

      Options options = new Options();

      options.addOption("a", "add", false, "add items to DSpace");
      options.addOption("r", "replace", false, "replace items in mapfile");
      options.addOption("d", "delete", false, "delete items listed in mapfile");
      options.addOption("s", "source", true, "source of items (directory)");
      options.addOption("z", "zip", true, "name of zip file");
      options.addOption("c", "collection", true, "destination collection(s) Handle or database ID");
      options.addOption("m", "mapfile", true, "mapfile items in mapfile");
      options.addOption("e", "eperson", true, "email of eperson doing importing");
      options.addOption("w", "workflow", false, "send submission through collection's workflow");
      options.addOption(
          "n",
          "notify",
          false,
          "if sending submissions through the workflow, send notification emails");
      options.addOption("t", "test", false, "test run - do not actually import items");
      options.addOption("p", "template", false, "apply template");
      options.addOption("R", "resume", false, "resume a failed import (add only)");
      options.addOption("q", "quiet", false, "don't display metadata");

      options.addOption("h", "help", false, "help");

      CommandLine line = parser.parse(options, argv);

      String command = null; // add replace remove, etc
      String sourcedir = null;
      String mapfile = null;
      String eperson = null; // db ID or email
      String[] collections = null; // db ID or handles

      if (line.hasOption('h')) {
        HelpFormatter myhelp = new HelpFormatter();
        myhelp.printHelp("ItemImport\n", options);
        System.out.println(
            "\nadding items:    ItemImport -a -e eperson -c collection -s sourcedir -m mapfile");
        System.out.println(
            "\nadding items from zip file:    ItemImport -a -e eperson -c collection -s sourcedir -z filename.zip -m mapfile");
        System.out.println(
            "replacing items: ItemImport -r -e eperson -c collection -s sourcedir -m mapfile");
        System.out.println("deleting items:  ItemImport -d -e eperson -m mapfile");
        System.out.println(
            "If multiple collections are specified, the first collection will be the one that owns the item.");

        System.exit(0);
      }

      if (line.hasOption('a')) {
        command = "add";
      }

      if (line.hasOption('r')) {
        command = "replace";
      }

      if (line.hasOption('d')) {
        command = "delete";
      }

      if (line.hasOption('w')) {
        useWorkflow = true;
        if (line.hasOption('n')) {
          useWorkflowSendEmail = true;
        }
      }

      if (line.hasOption('t')) {
        isTest = true;
        System.out.println("**Test Run** - not actually importing items.");
      }

      if (line.hasOption('p')) {
        template = true;
      }

      if (line.hasOption('s')) // source
      {
        sourcedir = line.getOptionValue('s');
      }

      if (line.hasOption('m')) // mapfile
      {
        mapfile = line.getOptionValue('m');
      }

      if (line.hasOption('e')) // eperson
      {
        eperson = line.getOptionValue('e');
      }

      if (line.hasOption('c')) // collections
      {
        collections = line.getOptionValues('c');
      }

      if (line.hasOption('R')) {
        isResume = true;
        System.out.println("**Resume import** - attempting to import items not already imported");
      }

      if (line.hasOption('q')) {
        isQuiet = true;
      }

      boolean zip = false;
      String zipfilename = "";
      String ziptempdir = ConfigurationManager.getProperty("org.dspace.app.itemexport.work.dir");
      if (line.hasOption('z')) {
        zip = true;
        zipfilename = sourcedir + System.getProperty("file.separator") + line.getOptionValue('z');
      }

      // now validate
      // must have a command set
      if (command == null) {
        System.out.println(
            "Error - must run with either add, replace, or remove (run with -h flag for details)");
        System.exit(1);
      } else if ("add".equals(command) || "replace".equals(command)) {
        if (sourcedir == null) {
          System.out.println("Error - a source directory containing items must be set");
          System.out.println(" (run with -h flag for details)");
          System.exit(1);
        }

        if (mapfile == null) {
          System.out.println("Error - a map file to hold importing results must be specified");
          System.out.println(" (run with -h flag for details)");
          System.exit(1);
        }

        if (eperson == null) {
          System.out.println("Error - an eperson to do the importing must be specified");
          System.out.println(" (run with -h flag for details)");
          System.exit(1);
        }

        if (collections == null) {
          System.out.println("Error - at least one destination collection must be specified");
          System.out.println(" (run with -h flag for details)");
          System.exit(1);
        }
      } else if ("delete".equals(command)) {
        if (eperson == null) {
          System.out.println("Error - an eperson to do the importing must be specified");
          System.exit(1);
        }

        if (mapfile == null) {
          System.out.println("Error - a map file must be specified");
          System.exit(1);
        }
      }

      // can only resume for adds
      if (isResume && !"add".equals(command)) {
        System.out.println("Error - resume option only works with --add command");
        System.exit(1);
      }

      // do checks around mapfile - if mapfile exists and 'add' is selected,
      // resume must be chosen
      File myFile = new File(mapfile);

      if (!isResume && "add".equals(command) && myFile.exists()) {
        System.out.println("Error - the mapfile " + mapfile + " already exists.");
        System.out.println(
            "Either delete it or use --resume if attempting to resume an aborted import.");
        System.exit(1);
      }

      // does the zip file exist and can we write to the temp directory
      if (zip) {
        File zipfile = new File(sourcedir);
        if (!zipfile.canRead()) {
          System.out.println("Zip file '" + sourcedir + "' does not exist, or is not readable.");
          System.exit(1);
        }

        if (ziptempdir == null) {
          System.out.println(
              "Unable to unzip import file as the key 'org.dspace.app.itemexport.work.dir' is not set in dspace.cfg");
          System.exit(1);
        }
        zipfile = new File(ziptempdir);
        if (!zipfile.isDirectory()) {
          System.out.println(
              "'"
                  + ConfigurationManager.getProperty("org.dspace.app.itemexport.work.dir")
                  + "' as defined by the key 'org.dspace.app.itemexport.work.dir' in dspace.cfg "
                  + "is not a valid directory");
          System.exit(1);
        }
        File tempdir = new File(ziptempdir);
        if (!tempdir.exists() && !tempdir.mkdirs()) {
          log.error("Unable to create temporary directory");
        }
        sourcedir = ziptempdir + System.getProperty("file.separator") + line.getOptionValue("z");
        ziptempdir =
            ziptempdir
                + System.getProperty("file.separator")
                + line.getOptionValue("z")
                + System.getProperty("file.separator");
      }

      ItemImport myloader = new ItemImport();

      // create a context
      Context c = new Context();

      // find the EPerson, assign to context
      EPerson myEPerson = null;

      if (eperson.indexOf('@') != -1) {
        // @ sign, must be an email
        myEPerson = EPerson.findByEmail(c, eperson);
      } else {
        myEPerson = EPerson.find(c, Integer.parseInt(eperson));
      }

      if (myEPerson == null) {
        System.out.println("Error, eperson cannot be found: " + eperson);
        System.exit(1);
      }

      c.setCurrentUser(myEPerson);

      // find collections
      Collection[] mycollections = null;

      // don't need to validate collections set if command is "delete"
      if (!"delete".equals(command)) {
        System.out.println("Destination collections:");

        mycollections = new Collection[collections.length];

        // validate each collection arg to see if it's a real collection
        for (int i = 0; i < collections.length; i++) {
          // is the ID a handle?
          if (collections[i].indexOf('/') != -1) {
            // string has a / so it must be a handle - try and resolve
            // it
            mycollections[i] = (Collection) HandleManager.resolveToObject(c, collections[i]);

            // resolved, now make sure it's a collection
            if ((mycollections[i] == null)
                || (mycollections[i].getType() != Constants.COLLECTION)) {
              mycollections[i] = null;
            }
          }
          // not a handle, try and treat it as an integer collection
          // database ID
          else if (collections[i] != null) {
            mycollections[i] = Collection.find(c, Integer.parseInt(collections[i]));
          }

          // was the collection valid?
          if (mycollections[i] == null) {
            throw new IllegalArgumentException(
                "Cannot resolve " + collections[i] + " to collection");
          }

          // print progress info
          String owningPrefix = "";

          if (i == 0) {
            owningPrefix = "Owning ";
          }

          System.out.println(owningPrefix + " Collection: " + mycollections[i].getMetadata("name"));
        }
      } // end of validating collections

      try {
        // If this is a zip archive, unzip it first
        if (zip) {
          ZipFile zf = new ZipFile(zipfilename);
          ZipEntry entry;
          Enumeration<? extends ZipEntry> entries = zf.entries();
          while (entries.hasMoreElements()) {
            entry = entries.nextElement();
            if (entry.isDirectory()) {
              if (!new File(ziptempdir + entry.getName()).mkdir()) {
                log.error("Unable to create contents directory");
              }
            } else {
              System.out.println("Extracting file: " + entry.getName());
              int index = entry.getName().lastIndexOf('/');
              if (index == -1) {
                // Was it created on Windows instead?
                index = entry.getName().lastIndexOf('\\');
              }
              if (index > 0) {
                File dir = new File(ziptempdir + entry.getName().substring(0, index));
                if (!dir.mkdirs()) {
                  log.error("Unable to create directory");
                }
              }
              byte[] buffer = new byte[1024];
              int len;
              InputStream in = zf.getInputStream(entry);
              BufferedOutputStream out =
                  new BufferedOutputStream(new FileOutputStream(ziptempdir + entry.getName()));
              while ((len = in.read(buffer)) >= 0) {
                out.write(buffer, 0, len);
              }
              in.close();
              out.close();
            }
          }
        }

        c.turnOffAuthorisationSystem();

        if ("add".equals(command)) {
          myloader.addItems(c, mycollections, sourcedir, mapfile, template);
        } else if ("replace".equals(command)) {
          myloader.replaceItems(c, mycollections, sourcedir, mapfile, template);
        } else if ("delete".equals(command)) {
          myloader.deleteItems(c, mapfile);
        }

        // complete all transactions
        c.complete();
      } catch (Exception e) {
        // abort all operations
        if (mapOut != null) {
          mapOut.close();
        }

        mapOut = null;

        c.abort();
        e.printStackTrace();
        System.out.println(e);
        status = 1;
      }

      // Delete the unzipped file
      try {
        if (zip) {
          System.gc();
          System.out.println("Deleting temporary zip directory: " + ziptempdir);
          ItemImport.deleteDirectory(new File(ziptempdir));
        }
      } catch (Exception ex) {
        System.out.println("Unable to delete temporary zip archive location: " + ziptempdir);
      }

      if (mapOut != null) {
        mapOut.close();
      }

      if (isTest) {
        System.out.println("***End of Test Run***");
      }
    } finally {
      DSIndexer.setBatchProcessingMode(false);
      Date endTime = new Date();
      System.out.println("Started: " + startTime.getTime());
      System.out.println("Ended: " + endTime.getTime());
      System.out.println(
          "Elapsed time: "
              + ((endTime.getTime() - startTime.getTime()) / 1000)
              + " secs ("
              + (endTime.getTime() - startTime.getTime())
              + " msecs)");
    }

    System.exit(status);
  }
예제 #20
0
  public void run() {

    do {
      try {
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        File file = new File("time.txt");
        FileWriter fw = new FileWriter(file);
        Long start = 0l;
        Long end = 0l;
        BufferedWriter bw = new BufferedWriter(fw);
        System.out.println("Enter the preferred choice");
        System.out.println("1. REGISTER");
        System.out.println("2. LEAVE");
        System.out.println("3. SEARCH FOR RFC");
        System.out.println("4. KEEPALIVE");
        System.out.println("5. Do you want to EXIT");
        System.out.println("*********************************************");

        choice = Integer.parseInt(inFromUser.readLine());
        // System.out.println(" Client requesting for connection");
        clientSocket = new Socket("192.168.15.103", 6500);
        BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter outToServer =
            new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true);

        // outToServer.println("Peer Requesting Connection");

        switch (choice) {
          case 4:
            outToServer.println(
                "KEEP ALIVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;
          case 1:
            try {
              // System.out.println("Case 1 entered"); // testing
              // statement
              System.out.println("Please enter your IP addres");
              ip = inFromUser.readLine();
              outToServer.println(
                  "REG P2P-DI/1.1 -1 Portno 6789 Hostname "
                      + ip
                      + " OS: "
                      + System.getProperty("os.name")
                      + " "
                      + "v"
                      + System.getProperty("os.version")
                      + " USER: "******"user.name"));
              cookie = Integer.parseInt(inFromServer.readLine());
              TTL = 7200;

              System.out.println(inFromServer.readLine());
              System.out.print("You are registered at time : ");
              ct.currenttime();
              System.out.println("Peer " + cookie); // peer cookie value
              System.out.println("TTL Value :" + TTL);
              System.out.println("*********************************************");

              break;
            } catch (Exception e) {
            }
          case 2:

            // System.out.println("Case 2 entered"); testing statement
            outToServer.println(
                "LEAVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            // System.out.println("I am in peer"); testing statement
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;

          case 3:
            outToServer.println(
                "PQUERY P2P-DI Cookieno "
                    + cookie
                    + " Portno 6789"
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println("Which RFC number do you wish to have ?");
            reqrfc = Integer.parseInt(inFromUser.readLine());

            // System.out.println("Entered peer again");
            // outToServer.println("KEEP ALIVE cookieno "+cookie);

            String details = inFromServer.readLine();

            String[] parray = details.split(" ");
            int inactive = Integer.parseInt(parray[(parray.length - 1)]);
            // System.out.println(darray.length);
            if ((parray.length == 3) && (ip.equals(parray[1]))) {
              System.out.println("P2P-DI No Active Peers available");
              System.out.println("*********************************************");
            } else {
              System.out.println("****<POPULATING THE ACTIVE PEER LIST>****");
              System.out.println();
              System.out.println("The active peer list is as follows:");
              System.out.println();

              String[] darray = details.split(" ");

              // System.out.println("Array length"+darray.length);
              for (int i = 0; i < (darray.length - 2); i = i + 2) {

                acthostname[j] = darray[i + 1];
                System.out.println("Hostname :" + acthostname[j]);

                actportno[j] = Integer.parseInt(darray[i + 2]);
                System.out.println("Portno :" + actportno[j]);

                System.out.println("*****************************");
                j = j + 1;
              }

              System.out.println("Connecting to the active peers for its RFC Index");
              for (int x = 0; x < j; x++) {
                // System.out.println(ip);
                if (!(acthostname[x].equals(ip))) {
                  System.out.println("Connecting to " + acthostname[x]);

                  Socket peersocket = new Socket(acthostname[x], 6791); // implement
                  // a for
                  // loop

                  BufferedReader inFromPeer =
                      new BufferedReader(new InputStreamReader(peersocket.getInputStream()));
                  PrintWriter outToPeer =
                      new PrintWriter(new OutputStreamWriter(peersocket.getOutputStream()), true);

                  outToPeer.println("RFCIndex");
                  // System.out.println(inFromServer.readLine());
                  // int searchrfc=Integer.parseInt(inFromUser.readLine());
                  // outToServer.println(searchrfc);

                  String rfcindex = inFromPeer.readLine(); // tell server to
                  // send rfc in
                  // string
                  String rfcarray[] = rfcindex.split(" ");
                  //  System.out.println(rfcindex);
                  for (int i = 1; i < rfcarray.length; i = i + 4) {
                    trfcno[z] = Integer.parseInt(rfcarray[i]);
                    //	System.out.println("RFC number " + trfcno[z]);
                    trfctitle[z] = rfcarray[i + 1];
                    //	System.out.println("RFC Title " + trfctitle[z]);
                    tpeername[z] = rfcarray[i + 2];
                    //	System.out.println("Peer Ip Address " + tpeername[z]);
                    tpTTL[z] = Integer.parseInt(rfcarray[i + 3]);
                    //	System.out.println("TTL value :" + tpTTL[z]);

                    counter1 = counter1 + 1;

                    z = z + 1;
                  }
                  z = 0;
                  //         if(arraybound==0)
                  //         {
                  System.arraycopy(trfcno, 0, rfcno, counter2, trfcno.length);
                  System.arraycopy(trfctitle, 0, rfctitle, counter2, trfctitle.length);
                  System.arraycopy(tpeername, 0, peername, counter2, tpeername.length);
                  System.arraycopy(tpTTL, 0, pTTL, counter2, tpTTL.length);
                  z = 0;
                  counter2 = counter1;
                  counter1 = 0;
                  //         arraybound=arraybound+1;
                  //        }

                  System.out.println();
                  System.out.println();
                  System.out.println("*************************************************");
                  System.out.println("RFC Index received from the Peer");
                  //		System.out.println();
                  System.out.println("\n-----------------------------------------");
                  System.out.println("RFC Index System - Display RFC Idex");
                  System.out.println("-------------------------------------------");
                  System.out.format(
                      "%10s%15s%15s%10s", "RFC No", "RFC Title", "Peer Name", "TTL Value");
                  System.out.println();
                  // StudentNode current = top;
                  // while (current != null){
                  // Student read = current.getStudentNode();
                  for (int i = 0; i < 60; i++) {
                    System.out.format(
                        "%10s%15s%15s%10s",
                        " " + rfcno[i], rfctitle[i], peername[i], " " + pTTL[i]);
                    System.out.println();
                  }
                  // This will output with a set number of character spaces
                  // per field, giving the list a table-like quality
                  // }

                  peersocket.close();
                } // end of if

                for (int i = 0; i < rfcno.length; i++) {

                  if (rfcno[i] == reqrfc) {
                    String taddress = InetAddress.getByName(peername[i]).toString();
                    String[] taddr = taddress.split("/");
                    InetAddress tproperaddress = InetAddress.getByName(taddr[1]);
                    //	System.out.println("Inetaddress" + tproperaddress);

                    Socket peersocket1 = new Socket(tproperaddress, 6791); // implement
                    // a
                    // for
                    // loop
                    System.out.println("The connection to the Active Peer is establshed");
                    BufferedReader inFromP2P =
                        new BufferedReader(new InputStreamReader(peersocket1.getInputStream()));
                    PrintWriter outToP2P =
                        new PrintWriter(
                            new OutputStreamWriter(peersocket1.getOutputStream()), true);

                    System.out.println("Requested the RFC to the Active Peer Server");

                    start = System.currentTimeMillis();

                    outToP2P.println("GETRFC " + reqrfc);

                    // Socket socket = ;

                    try {

                      // Socket socket = null;
                      InputStream is = null;
                      FileOutputStream fos = null;
                      BufferedOutputStream bos = null;
                      int bufferSize = 0;

                      try {
                        is = peersocket1.getInputStream();

                        bufferSize = 64;
                        // System.out.println("Buffer size: " + bufferSize);
                      } catch (IOException ex) {
                        System.out.println("Can't get socket input stream. ");
                      }

                      try {
                        fos = new FileOutputStream("E:\\rfc" + reqrfc + "copy.txt");
                        bos = new BufferedOutputStream(fos);

                      } catch (FileNotFoundException ex) {
                        System.out.println("File not found. ");
                      }

                      byte[] bytes = new byte[bufferSize];

                      int count;

                      while ((count = is.read(bytes)) > 0) {
                        //	System.out.println(count);
                        bos.write(bytes, 0, count);
                      }
                      System.out.println("P2P-DI 200 OK The RFC is copied");
                      end = System.currentTimeMillis();
                      System.out.println(
                          "Total Time to download file   " + (end - start) + " milliseconds");

                      bos.flush();

                      bos.close();
                      is.close();
                      peersocket1.close();
                      break;

                    } catch (SocketException e) {
                      System.out.println("Socket exception");
                    }

                  } // end of if
                  else {
                    //  	System.out.println("No Peer with the required RFC could be found");

                  }
                  clientSocket.close();
                  //	System.out.println("Connection closed");
                  bw.close();
                  fw.close();
                } // end of inner for
              } // end of outer for
              System.out.println("Connection closed");
            } // end of switch
        } // end of else which checks the inactive conditions
      } // end of try
      catch (IOException ioe) {
        System.out.println("IOException on socket listen: " + ioe);
        ioe.printStackTrace();
      }

    } // end of do
    while (choice != 5);
  } // end of run
예제 #21
0
    public void run() {
      try {
        boolean keepalive = false;

        do {
          // reset user authentication
          user = password = null;
          String line = readLine();
          // Netscape sends an extra \n\r after bodypart, swallow it
          if ("".equals(line)) line = readLine();
          if (XmlRpc.debug) System.err.println(line);
          // get time of last request
          lastRequest = System.currentTimeMillis();
          int contentLength = -1;

          // tokenize first line of HTTP request
          StringTokenizer tokens = new StringTokenizer(line);
          String method = tokens.nextToken();
          String uri = tokens.nextToken();
          String httpversion = tokens.nextToken();
          keepalive = XmlRpc.getKeepAlive() && "HTTP/1.1".equals(httpversion);
          do {
            line = readLine();
            if (line != null) {
              if (XmlRpc.debug) System.err.println(line);
              String lineLower = line.toLowerCase();
              if (lineLower.startsWith("content-length:"))
                contentLength = Integer.parseInt(line.substring(15).trim());
              if (lineLower.startsWith("connection:"))
                keepalive = XmlRpc.getKeepAlive() && lineLower.indexOf("keep-alive") > -1;
              if (lineLower.startsWith("authorization: basic ")) parseAuth(line);
            }
          } while (line != null && !line.equals(""));

          if ("POST".equalsIgnoreCase(method)) {
            ServerInputStream sin = new ServerInputStream(input, contentLength);
            byte result[] = xmlrpc.execute(sin, user, password);
            output.write(httpversion.getBytes());
            output.write(ok);
            output.write(server);
            if (keepalive) output.write(conkeep);
            else output.write(conclose);
            output.write(ctype);
            output.write(clength);
            output.write(Integer.toString(result.length).getBytes());
            output.write(doubleNewline);
            output.write(result);
            output.flush();
          } else {
            output.write(httpversion.getBytes());
            output.write(" 400 Bad Request\r\n".getBytes());
            output.write("Server: helma.XML-RPC\r\n\r\n".getBytes());
            output.write(("Method " + method + " not implemented (try POST)").getBytes());
            output.flush();
            keepalive = false;
          }
        } while (keepalive);
      } catch (Exception exception) {
        if (XmlRpc.debug) {
          System.err.println(exception);
          exception.printStackTrace();
        }
      } finally {
        try {
          socket.close();
        } catch (IOException ignore) {
        }
      }
    }
예제 #22
0
  public void build_bricks() {

    ImagePlus imp;
    ImagePlus orgimp;
    ImageStack stack;
    FileInfo finfo;

    if (lvImgTitle.isEmpty()) return;
    orgimp = WindowManager.getImage(lvImgTitle.get(0));
    imp = orgimp;

    finfo = imp.getFileInfo();
    if (finfo == null) return;

    int[] dims = imp.getDimensions();
    int imageW = dims[0];
    int imageH = dims[1];
    int nCh = dims[2];
    int imageD = dims[3];
    int nFrame = dims[4];
    int bdepth = imp.getBitDepth();
    double xspc = finfo.pixelWidth;
    double yspc = finfo.pixelHeight;
    double zspc = finfo.pixelDepth;
    double z_aspect = Math.max(xspc, yspc) / zspc;

    int orgW = imageW;
    int orgH = imageH;
    int orgD = imageD;
    double orgxspc = xspc;
    double orgyspc = yspc;
    double orgzspc = zspc;

    lv = lvImgTitle.size();
    if (filetype == "JPEG") {
      for (int l = 0; l < lv; l++) {
        if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) {
          IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE");
          return;
        }
      }
    }

    // calculate levels
    /*		int baseXY = 256;
    		int baseZ = 256;

    		if (z_aspect < 0.5) baseZ = 128;
    		if (z_aspect > 2.0) baseXY = 128;
    		if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect);
    		if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect);

    		IJ.log("Z_aspect: " + z_aspect);
    		IJ.log("BaseXY: " + baseXY);
    		IJ.log("BaseZ: " + baseZ);
    */

    int baseXY = 256;
    int baseZ = 128;
    int dbXY = Math.max(orgW, orgH) / baseXY;
    if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2;
    int dbZ = orgD / baseZ;
    if (orgD % baseZ > 0) dbZ *= 2;
    lv = Math.max(log2(dbXY), log2(dbZ)) + 1;

    int ww = orgW;
    int hh = orgH;
    int dd = orgD;
    for (int l = 0; l < lv; l++) {
      int bwnum = ww / baseXY;
      if (ww % baseXY > 0) bwnum++;
      int bhnum = hh / baseXY;
      if (hh % baseXY > 0) bhnum++;
      int bdnum = dd / baseZ;
      if (dd % baseZ > 0) bdnum++;

      if (bwnum % 2 == 0) bwnum++;
      if (bhnum % 2 == 0) bhnum++;
      if (bdnum % 2 == 0) bdnum++;

      int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0);
      int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0);
      int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0);

      bwlist.add(bw);
      bhlist.add(bh);
      bdlist.add(bd);

      IJ.log("LEVEL: " + l);
      IJ.log("  width: " + ww);
      IJ.log("  hight: " + hh);
      IJ.log("  depth: " + dd);
      IJ.log("  bw: " + bw);
      IJ.log("  bh: " + bh);
      IJ.log("  bd: " + bd);

      int xyl2 = Math.max(ww, hh) / baseXY;
      if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2;
      if (lv - 1 - log2(xyl2) <= l) {
        ww /= 2;
        hh /= 2;
      }
      IJ.log("  xyl2: " + (lv - 1 - log2(xyl2)));

      int zl2 = dd / baseZ;
      if (dd % baseZ > 0) zl2 *= 2;
      if (lv - 1 - log2(zl2) <= l) dd /= 2;
      IJ.log("  zl2: " + (lv - 1 - log2(zl2)));

      if (l < lv - 1) {
        lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1));
        IJ.selectWindow(lvImgTitle.get(0));
        IJ.run(
            "Scale...",
            "x=- y=- z=- width="
                + ww
                + " height="
                + hh
                + " depth="
                + dd
                + " interpolation=Bicubic average process create title="
                + lvImgTitle.get(l + 1));
      }
    }

    for (int l = 0; l < lv; l++) {
      IJ.log(lvImgTitle.get(l));
    }

    Document doc = newXMLDocument();
    Element root = doc.createElement("BRK");
    root.setAttribute("version", "1.0");
    root.setAttribute("nLevel", String.valueOf(lv));
    root.setAttribute("nChannel", String.valueOf(nCh));
    root.setAttribute("nFrame", String.valueOf(nFrame));
    doc.appendChild(root);

    for (int l = 0; l < lv; l++) {
      IJ.showProgress(0.0);

      int[] dims2 = imp.getDimensions();
      IJ.log(
          "W: "
              + String.valueOf(dims2[0])
              + " H: "
              + String.valueOf(dims2[1])
              + " C: "
              + String.valueOf(dims2[2])
              + " D: "
              + String.valueOf(dims2[3])
              + " T: "
              + String.valueOf(dims2[4])
              + " b: "
              + String.valueOf(bdepth));

      bw = bwlist.get(l).intValue();
      bh = bhlist.get(l).intValue();
      bd = bdlist.get(l).intValue();

      boolean force_pow2 = false;
      /*			if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true;

      			if(force_pow2){
      				//force pow2
      				if(Pow2(bw) > bw) bw = Pow2(bw)/2;
      				if(Pow2(bh) > bh) bh = Pow2(bh)/2;
      				if(Pow2(bd) > bd) bd = Pow2(bd)/2;
      			}

      			if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2;
      			if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2;
      			if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2;

      */
      if (bw > imageW) bw = imageW;
      if (bh > imageH) bh = imageH;
      if (bd > imageD) bd = imageD;

      if (bw <= 1 || bh <= 1 || bd <= 1) break;

      if (filetype == "JPEG" && (bw < 8 || bh < 8)) break;

      Element lvnode = doc.createElement("Level");
      lvnode.setAttribute("lv", String.valueOf(l));
      lvnode.setAttribute("imageW", String.valueOf(imageW));
      lvnode.setAttribute("imageH", String.valueOf(imageH));
      lvnode.setAttribute("imageD", String.valueOf(imageD));
      lvnode.setAttribute("xspc", String.valueOf(xspc));
      lvnode.setAttribute("yspc", String.valueOf(yspc));
      lvnode.setAttribute("zspc", String.valueOf(zspc));
      lvnode.setAttribute("bitDepth", String.valueOf(bdepth));
      root.appendChild(lvnode);

      Element brksnode = doc.createElement("Bricks");
      brksnode.setAttribute("brick_baseW", String.valueOf(bw));
      brksnode.setAttribute("brick_baseH", String.valueOf(bh));
      brksnode.setAttribute("brick_baseD", String.valueOf(bd));
      lvnode.appendChild(brksnode);

      ArrayList<Brick> bricks = new ArrayList<Brick>();
      int mw, mh, md, mw2, mh2, md2;
      double tx0, ty0, tz0, tx1, ty1, tz1;
      double bx0, by0, bz0, bx1, by1, bz1;
      for (int k = 0; k < imageD; k += bd) {
        if (k > 0) k--;
        for (int j = 0; j < imageH; j += bh) {
          if (j > 0) j--;
          for (int i = 0; i < imageW; i += bw) {
            if (i > 0) i--;
            mw = Math.min(bw, imageW - i);
            mh = Math.min(bh, imageH - j);
            md = Math.min(bd, imageD - k);

            if (force_pow2) {
              mw2 = Pow2(mw);
              mh2 = Pow2(mh);
              md2 = Pow2(md);
            } else {
              mw2 = mw;
              mh2 = mh;
              md2 = md;
            }

            if (filetype == "JPEG") {
              if (mw2 < 8) mw2 = 8;
              if (mh2 < 8) mh2 = 8;
            }

            tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2);
            ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2);
            tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2);

            tx1 = 1.0d - 0.5d / mw2;
            if (mw < bw) tx1 = 1.0d;
            if (imageW - i == bw) tx1 = 1.0d;

            ty1 = 1.0d - 0.5d / mh2;
            if (mh < bh) ty1 = 1.0d;
            if (imageH - j == bh) ty1 = 1.0d;

            tz1 = 1.0d - 0.5d / md2;
            if (md < bd) tz1 = 1.0d;
            if (imageD - k == bd) tz1 = 1.0d;

            bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW;
            by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH;
            bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD;

            bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d);
            if (imageW - i == bw) bx1 = 1.0d;

            by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d);
            if (imageH - j == bh) by1 = 1.0d;

            bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d);
            if (imageD - k == bd) bz1 = 1.0d;

            int x, y, z;
            x = i - (mw2 - mw);
            y = j - (mh2 - mh);
            z = k - (md2 - md);
            bricks.add(
                new Brick(
                    x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1,
                    by1, bz1));
          }
        }
      }

      Element fsnode = doc.createElement("Files");
      lvnode.appendChild(fsnode);

      stack = imp.getStack();

      int totalbricknum = nFrame * nCh * bricks.size();
      int curbricknum = 0;
      for (int f = 0; f < nFrame; f++) {
        for (int ch = 0; ch < nCh; ch++) {
          int sizelimit = bdsizelimit * 1024 * 1024;
          int bytecount = 0;
          int filecount = 0;
          int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8);
          byte[] packed_data = new byte[pd_bufsize];
          String base_dataname =
              basename
                  + "_Lv"
                  + String.valueOf(l)
                  + "_Ch"
                  + String.valueOf(ch)
                  + "_Fr"
                  + String.valueOf(f);
          String current_dataname = base_dataname + "_data" + filecount;

          Brick b_first = bricks.get(0);
          if (b_first.z_ != 0) IJ.log("warning");
          int st_z = b_first.z_;
          int ed_z = b_first.z_ + b_first.d_;
          LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>();
          for (int s = st_z; s < ed_z; s++)
            iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));

          //					ImagePlus test;
          //					ImageStack tsst;
          //					test = NewImage.createByteImage("test", imageW, imageH, imageD,
          // NewImage.FILL_BLACK);
          //					tsst = test.getStack();
          for (int i = 0; i < bricks.size(); i++) {
            Brick b = bricks.get(i);

            if (ed_z > b.z_ || st_z < b.z_ + b.d_) {
              if (b.z_ > st_z) {
                for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst();
                st_z = b.z_;
              } else if (b.z_ < st_z) {
                IJ.log("warning");
                for (int s = st_z - 1; s > b.z_; s--)
                  iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                st_z = b.z_;
              }

              if (b.z_ + b.d_ > ed_z) {
                for (int s = ed_z; s < b.z_ + b.d_; s++)
                  iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                ed_z = b.z_ + b.d_;
              } else if (b.z_ + b.d_ < ed_z) {
                IJ.log("warning");
                for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast();
                ed_z = b.z_ + b.d_;
              }
            } else {
              IJ.log("warning");
              iplist.clear();
              st_z = b.z_;
              ed_z = b.z_ + b.d_;
              for (int s = st_z; s < ed_z; s++)
                iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
            }

            if (iplist.size() != b.d_) {
              IJ.log("Stack Error");
              return;
            }

            //						int zz = st_z;

            int bsize = 0;
            byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
            Iterator<ImageProcessor> ipite = iplist.iterator();
            while (ipite.hasNext()) {

              //							ImageProcessor tsip = tsst.getProcessor(zz+1);

              ImageProcessor ip = ipite.next();
              ip.setRoi(b.x_, b.y_, b.w_, b.h_);
              if (bdepth == 8) {
                byte[] data = (byte[]) ip.crop().getPixels();
                System.arraycopy(data, 0, bdata, bsize, data.length);
                bsize += data.length;
              } else if (bdepth == 16) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                short[] data = (short[]) ip.crop().getPixels();
                for (short e : data) buffer.putShort(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              } else if (bdepth == 32) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                float[] data = (float[]) ip.crop().getPixels();
                for (float e : data) buffer.putFloat(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              }
            }

            String filename =
                basename
                    + "_Lv"
                    + String.valueOf(l)
                    + "_Ch"
                    + String.valueOf(ch)
                    + "_Fr"
                    + String.valueOf(f)
                    + "_ID"
                    + String.valueOf(i);

            int offset = bytecount;
            int datasize = bdata.length;

            if (filetype == "RAW") {
              int dummy = -1;
              // do nothing
            }
            if (filetype == "JPEG" && bdepth == 8) {
              try {
                DataBufferByte db = new DataBufferByte(bdata, datasize);
                Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null);
                BufferedImage img =
                    new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY);
                img.setData(raster);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
                String format = "jpg";
                Iterator<javax.imageio.ImageWriter> iter =
                    ImageIO.getImageWritersByFormatName("jpeg");
                javax.imageio.ImageWriter writer = iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality((float) jpeg_quality * 0.01f);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(img, null, null), iwp);
                // ImageIO.write(img, format, baos);
                bdata = baos.toByteArray();
                datasize = bdata.length;
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
            if (filetype == "ZLIB") {
              byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
              Deflater compresser = new Deflater();
              compresser.setInput(bdata);
              compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
              compresser.setStrategy(Deflater.DEFAULT_STRATEGY);
              compresser.finish();
              datasize = compresser.deflate(tmpdata);
              bdata = tmpdata;
              compresser.end();
            }

            if (bytecount + datasize > sizelimit && bytecount > 0) {
              BufferedOutputStream fis = null;
              try {
                File file = new File(directory + current_dataname);
                fis = new BufferedOutputStream(new FileOutputStream(file));
                fis.write(packed_data, 0, bytecount);
              } catch (IOException e) {
                e.printStackTrace();
                return;
              } finally {
                try {
                  if (fis != null) fis.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  return;
                }
              }
              filecount++;
              current_dataname = base_dataname + "_data" + filecount;
              bytecount = 0;
              offset = 0;
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            } else {
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            }

            Element filenode = doc.createElement("File");
            filenode.setAttribute("filename", current_dataname);
            filenode.setAttribute("channel", String.valueOf(ch));
            filenode.setAttribute("frame", String.valueOf(f));
            filenode.setAttribute("brickID", String.valueOf(i));
            filenode.setAttribute("offset", String.valueOf(offset));
            filenode.setAttribute("datasize", String.valueOf(datasize));
            filenode.setAttribute("filetype", String.valueOf(filetype));

            fsnode.appendChild(filenode);

            curbricknum++;
            IJ.showProgress((double) (curbricknum) / (double) (totalbricknum));
          }
          if (bytecount > 0) {
            BufferedOutputStream fis = null;
            try {
              File file = new File(directory + current_dataname);
              fis = new BufferedOutputStream(new FileOutputStream(file));
              fis.write(packed_data, 0, bytecount);
            } catch (IOException e) {
              e.printStackTrace();
              return;
            } finally {
              try {
                if (fis != null) fis.close();
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
          }
        }
      }

      for (int i = 0; i < bricks.size(); i++) {
        Brick b = bricks.get(i);
        Element bricknode = doc.createElement("Brick");
        bricknode.setAttribute("id", String.valueOf(i));
        bricknode.setAttribute("st_x", String.valueOf(b.x_));
        bricknode.setAttribute("st_y", String.valueOf(b.y_));
        bricknode.setAttribute("st_z", String.valueOf(b.z_));
        bricknode.setAttribute("width", String.valueOf(b.w_));
        bricknode.setAttribute("height", String.valueOf(b.h_));
        bricknode.setAttribute("depth", String.valueOf(b.d_));
        brksnode.appendChild(bricknode);

        Element tboxnode = doc.createElement("tbox");
        tboxnode.setAttribute("x0", String.valueOf(b.tx0_));
        tboxnode.setAttribute("y0", String.valueOf(b.ty0_));
        tboxnode.setAttribute("z0", String.valueOf(b.tz0_));
        tboxnode.setAttribute("x1", String.valueOf(b.tx1_));
        tboxnode.setAttribute("y1", String.valueOf(b.ty1_));
        tboxnode.setAttribute("z1", String.valueOf(b.tz1_));
        bricknode.appendChild(tboxnode);

        Element bboxnode = doc.createElement("bbox");
        bboxnode.setAttribute("x0", String.valueOf(b.bx0_));
        bboxnode.setAttribute("y0", String.valueOf(b.by0_));
        bboxnode.setAttribute("z0", String.valueOf(b.bz0_));
        bboxnode.setAttribute("x1", String.valueOf(b.bx1_));
        bboxnode.setAttribute("y1", String.valueOf(b.by1_));
        bboxnode.setAttribute("z1", String.valueOf(b.bz1_));
        bricknode.appendChild(bboxnode);
      }

      if (l < lv - 1) {
        imp = WindowManager.getImage(lvImgTitle.get(l + 1));
        int[] newdims = imp.getDimensions();
        imageW = newdims[0];
        imageH = newdims[1];
        imageD = newdims[3];
        xspc = orgxspc * ((double) orgW / (double) imageW);
        yspc = orgyspc * ((double) orgH / (double) imageH);
        zspc = orgzspc * ((double) orgD / (double) imageD);
        bdepth = imp.getBitDepth();
      }
    }

    File newXMLfile = new File(directory + basename + ".vvd");
    writeXML(newXMLfile, doc);

    for (int l = 1; l < lv; l++) {
      imp = WindowManager.getImage(lvImgTitle.get(l));
      imp.changes = false;
      imp.close();
    }
  }
  public static void main(String[] aqf) {
    try {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      BufferedOutputStream bos = new BufferedOutputStream(System.out);
      String eol = System.getProperty("line.separator");
      byte[] eolb = eol.getBytes();
      byte[] spaceb = " ".getBytes();
      String str;
      String[] s;
      StringTokenizer st;
      int t, n, go, ct, x, y;

      Set set;
      Iterator it;

      m = new int[MAX];
      p = new int[MAX];
      hm = new HashMap<>();

      str = br.readLine();
      t = Integer.parseInt(str);
      while (t > 0) {
        Arrays.fill(m, 0);
        hm.clear();

        str = br.readLine();
        n = Integer.parseInt(str);
        str = br.readLine();
        st = new StringTokenizer(str, " ");
        int i = 1;
        while (st.hasMoreTokens()) p[i++] = Integer.parseInt(st.nextToken());

        for (i = 1; i <= n; i++) {
          if (m[i] == 0) {
            go = p[i];
            ct = 0;
            do {
              ct++;
              m[go] = 1;
              go = p[go];
            } while (go != p[i]);
            pf(ct);
          }
        }

        long ret = 1;
        set = hm.entrySet();
        it = set.iterator();
        while (it.hasNext()) {
          Map.Entry me = (Map.Entry) it.next();
          x = (int) me.getKey();
          y = (int) me.getValue();
          ret = (ret % MOD * expo(x, y)) % MOD;
        }

        bos.write(new Long(ret).toString().getBytes());
        bos.write(eolb);
        t -= 1;
      }
      bos.flush();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #24
0
  /**
   * Method called by the Form panel to update existing data.
   *
   * @param oldPersistentObject original value object, previous to the changes
   * @param persistentObject value object to save
   * @return an ErrorResponse value object in case of errors, VOResponse if the operation is
   *     successfully completed
   */
  public Response updateRecord(ValueObject oldPersistentObject, ValueObject persistentObject)
      throws Exception {
    PreparedStatement stmt = null;
    try {
      stmt =
          conn.prepareStatement(
              "update DEMO4 set TEXT=?,DECNUM=?,CURRNUM=?,THEDATE=?,COMBO=?,CHECK_BOX=?,RADIO=?,CODE=?,TA=?,FORMATTED_TEXT=?,URI=?,LINK_LABEL=?,YEAR=?,FILENAME=? where TEXT=?");
      DetailTestVO vo = (DetailTestVO) persistentObject;
      DetailTestVO oldVO = (DetailTestVO) oldPersistentObject;
      stmt.setObject(
          6, vo.getCheckValue() == null || !vo.getCheckValue().booleanValue() ? "N" : "Y");
      stmt.setString(5, vo.getCombo().getCode());
      stmt.setBigDecimal(3, vo.getCurrencyValue());
      stmt.setDate(4, vo.getDateValue());
      stmt.setBigDecimal(2, vo.getNumericValue());
      stmt.setObject(
          7,
          vo.getRadioButtonValue() == null || !vo.getRadioButtonValue().booleanValue() ? "N" : "Y");
      stmt.setString(1, vo.getStringValue());
      stmt.setString(8, vo.getLookupValue());
      stmt.setString(9, vo.getTaValue());
      stmt.setString(10, vo.getFormattedTextValue());
      stmt.setString(11, vo.getUri());
      stmt.setString(12, vo.getLinkLabel());
      stmt.setBigDecimal(13, vo.getYear());
      stmt.setString(14, vo.getFilename());
      stmt.setString(15, oldVO.getStringValue());
      stmt.execute();

      stmt.close();
      stmt = conn.prepareStatement("delete from DEMO4_LIST_VALUES where TEXT=?");
      stmt.setString(1, pk);
      stmt.execute();

      if (vo.getListValues() != null) {
        stmt.close();
        stmt = conn.prepareStatement("insert into DEMO4_LIST_VALUES(TEXT,CODE) values(?,?)");

        for (int i = 0; i < vo.getListValues().size(); i++) {
          stmt.setString(1, pk);
          stmt.setString(2, vo.getListValues().get(i).toString());
          stmt.execute();
        }
      }

      try {
        if (vo.getFilename() != null && vo.getFile() != null) {
          File f = new File(vo.getFilename());
          BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
          out.write(vo.getFile());
          out.close();
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      // this instruction is no more needed: the grid has been linked to the Form (see Form.linkGrid
      // method...)
      //      gridFrame.reloadData();
      return new VOResponse(vo);
    } catch (SQLException ex) {
      ex.printStackTrace();
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        stmt.close();
        conn.commit();
      } catch (SQLException ex1) {
      }
    }
  }
예제 #25
0
    @Override
    public void run() {
      try {
        StringBuilder filePath = new StringBuilder();
        filePath.append(Constants.IO.imageBaseDir).append(File.separator);
        filePath
            .append(card.hashCode())
            .append(".")
            .append(card.getName().replace(":", "").replace("//", "-"))
            .append(".jpg");
        File temporaryFile = new File(filePath.toString());
        String imagePath = CardImageUtils.generateImagePath(card);
        TFile outputFile = new TFile(imagePath);
        if (!outputFile.exists()) {
          outputFile.getParentFile().mkdirs();
        }
        File existingFile = new File(imagePath.replaceFirst("\\w{3}.zip", ""));
        if (existingFile.exists()) {
          new TFile(existingFile).cp_rp(outputFile);
          synchronized (sync) {
            update(cardIndex + 1, count);
          }
          existingFile.delete();
          File parent = existingFile.getParentFile();
          if (parent != null && parent.isDirectory() && parent.list().length == 0) {
            parent.delete();
          }
          return;
        }
        BufferedOutputStream out;

        // Logger.getLogger(this.getClass()).info(url.toString());
        URLConnection httpConn = url.openConnection(p);
        httpConn.connect();
        if (((HttpURLConnection) httpConn).getResponseCode() == 200) {
          try (BufferedInputStream in =
              new BufferedInputStream(((HttpURLConnection) httpConn).getInputStream())) {
            // try (BufferedInputStream in = new
            // BufferedInputStream(url.openConnection(p).getInputStream())) {
            out = new BufferedOutputStream(new TFileOutputStream(temporaryFile));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) != -1) {
              // user cancelled
              if (cancel) {
                in.close();
                out.flush();
                out.close();
                temporaryFile.delete();
                return;
              }
              out.write(buf, 0, len);
            }
          }
          out.flush();
          out.close();

          if (card.isTwoFacedCard()) {
            BufferedImage image = ImageIO.read(temporaryFile);
            if (image.getHeight() == 470) {
              BufferedImage renderedImage = new BufferedImage(265, 370, BufferedImage.TYPE_INT_RGB);
              renderedImage.getGraphics();
              Graphics2D graphics2D = renderedImage.createGraphics();
              if (card.isTwoFacedCard() && card.isSecondSide()) {
                graphics2D.drawImage(image, 0, 0, 265, 370, 313, 62, 578, 432, null);
              } else {
                graphics2D.drawImage(image, 0, 0, 265, 370, 41, 62, 306, 432, null);
              }
              graphics2D.dispose();
              writeImageToFile(renderedImage, outputFile);
            } else {
              new TFile(temporaryFile).cp_rp(outputFile);
            }
            temporaryFile.delete();
          } else {
            new TFile(temporaryFile).cp_rp(outputFile);
            temporaryFile.delete();
          }
        } else {
          Logger.getLogger(this.getClass())
              .error(convertStreamToString(((HttpURLConnection) httpConn).getErrorStream()));
        }

      } catch (Exception e) {
        log.error(e, e);
      }

      synchronized (sync) {
        update(cardIndex + 1, count);
      }
    }