private boolean copyAssetsToFilesystem(String assetsSrc, String des) {
   if (SQLiteDebug.isDebug) {
     Log.i(TAG, "Copy " + assetsSrc + " to " + des);
   }
   InputStream istream = null;
   OutputStream ostream = null;
   try {
     AssetManager am = context.getAssets();
     istream = am.open(assetsSrc);
     ostream = new FileOutputStream(des);
     byte[] buffer = new byte[1024 * 64];
     int length;
     while ((length = istream.read(buffer)) > 0) {
       ostream.write(buffer, 0, length);
     }
     istream.close();
     ostream.close();
   } catch (Exception e) {
     e.printStackTrace();
     try {
       if (istream != null) istream.close();
       if (ostream != null) ostream.close();
     } catch (Exception ee) {
       ee.printStackTrace();
     }
     return false;
   }
   return true;
 }
Exemplo n.º 2
0
        public void run() {
            try {
                gatewaySocket = sslFactory.createServerSocket(gatewayPort);
            } catch (IOException e) {
                messages.release();
                throw new RuntimeException(e);
            }

            InputStream in = null;
            OutputStream out = null;
            try {
                // Listen for connections
                startUp.release();
                Socket socket = gatewaySocket.accept();

                // Create streams to securely send and receive data to the client
                in = socket.getInputStream();
                out = socket.getOutputStream();

                // Read from in and write to out...
                byte[] read = readFully(in);
                received.write(read);
                messages.release();


                // Close the socket
                in.close();
                out.close();
            } catch(Throwable e) {
                try { in.close(); } catch (Exception _) {}
                try { out.close(); } catch (Exception _) {}
                messages.release();
            }
        }
Exemplo n.º 3
0
  public synchronized void save() throws IOException {
    OutputStream os = null;
    try {
      File newSaved = new File(saved.getParentFile(), saved.getName() + ".new");
      File backupSaved = new File(saved.getParentFile(), saved.getName() + ".bak");
      os = new FileOutputStream(newSaved);
      marshaller.marshall(os, session);
      os.close();
      os = null;

      if (backupSaved.exists()) {
        if (!backupSaved.delete()) {
          throw new IOException("could not remove backup " + backupSaved.getAbsolutePath());
        }
      }
      if (saved.exists()) {
        if (!saved.renameTo(backupSaved)) {
          throw new IOException("could not backup " + saved.getAbsolutePath());
        }
      }
      if (!newSaved.renameTo(saved)) {
        backupSaved.renameTo(saved);
        throw new IOException("could not rename " + saved.getAbsolutePath());
      }

    } finally {
      if (os != null) os.close();
    }
  }
Exemplo n.º 4
0
    private String doCommand(String command) throws IOException {
      InputStream is = null;
      OutputStream os = null;

      command = "command=" + command;
      byte[] postData = command.getBytes("UTF-8");
      int postDataLength = postData.length;
      URL url = new URL(getString(R.string.command));

      try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setFixedLengthStreamingMode(postDataLength);

        os = new BufferedOutputStream(conn.getOutputStream());
        os.write(postData);
        os.close();

        is = new BufferedInputStream(conn.getInputStream());
        String message = decodeIt(readIt(is));

        conn.disconnect();
        return message;
      } finally {
        // Makes sure that the streams are closed.
        if (is != null) {
          is.close();
        }
        if (os != null) {
          os.close();
        }
      }
    }
 @Override
 public void onStart() {
   super.onStart();
   try {
     InputStream in = getAssets().open("hid-gadget-test");
     OutputStream out =
         new BufferedOutputStream(
             new FileOutputStream(getFilesDir().getAbsolutePath() + "/hid-gadget-test"));
     copyFile(in, out);
     in.close();
     out.close();
     Runtime.getRuntime()
         .exec("/system/bin/chmod 755 " + getFilesDir().getAbsolutePath() + "/hid-gadget-test")
         .waitFor();
     in = getAssets().open("hid-gadget-test-" + android.os.Build.CPU_ABI);
     out =
         new BufferedOutputStream(
             new FileOutputStream(getFilesDir().getAbsolutePath() + "/hid-gadget-test"));
     copyFile(in, out);
     in.close();
     out.close();
     Runtime.getRuntime()
         .exec("/system/bin/chmod 755 " + getFilesDir().getAbsolutePath() + "/hid-gadget-test")
         .waitFor();
   } catch (Exception e) {
   }
 }
Exemplo n.º 6
0
  /**
   * Creates the binary and signature file.
   *
   * <p>It will create the output files based on the previous <code>prepareCompiledClasses()</code>.
   *
   * @param outputFile the output file to be created
   * @param signatureFile the signature file to be created
   * @throws ToolsetException will be raised in any error case
   */
  public void createBinaryFile(File outputFile, File signatureFile) throws ToolsetException {
    OutputStream os = null;
    try {
      // now create the output stream
      OutputStream osUnbuffered = new FileOutputStream(outputFile);
      os = new BufferedOutputStream(osUnbuffered, 4096);
      ByteWriter writer = null;
      if (this.byteOrder == IRuntimeToolset.BYTE_ORDER_BIG_ENDIAN) {
        writer = new BEByteWriter(os);
      } else {
        writer = new LEByteWriter(os);
      }

      // now dump the binaries into the stream
      this.binary.dump(writer);
      BinaryReport report = new BinaryReport(this.binary);
      Writer signatureWriter = new FileWriter(signatureFile);
      report.report(signatureWriter);
      signatureWriter.close();
      os.close();
    } catch (Exception ex) {
      throw new ToolsetException(
          "Some error occured during creating binary file: " + ex.getMessage());
    } finally {
      if (os != null) {
        try {
          os.close();
        } catch (IOException ex) {
          // ignore in finally
        }
      }
    }
  }
Exemplo n.º 7
0
 /**
  * Try to save the peak file
  *
  * @return true, if the operation succeeded and the file was saved, false otherwise
  */
 protected boolean savePeak() {
   // Save peak File
   File p = FileManager.getParallelFile(source, "gmpk");
   OutputStream out;
   try {
     out = new FileOutputStream(p);
   } catch (FileNotFoundException e1) {
     e1.printStackTrace();
     return false;
   }
   WaveForm peak = afWF.getPeakWaveForm();
   ProgressThread saver =
       new SavePeakWaveFormThread(peak, peak.getIntervallSize(), out, source.lastModified());
   ProgressMonitor progress =
       new ProgressMonitor(
           getShell(), saver, "Saving Peak File...", "Saving Peak File " + p.getAbsolutePath());
   try {
     progress.start();
   } catch (NotFinishedException ex) {
     try {
       out.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
     return false;
   }
   try {
     out.close();
   } catch (IOException e4) {
     e4.printStackTrace();
     return false;
   }
   return true;
 }
Exemplo n.º 8
0
  /**
   * 向配置文件中写一条配置信息
   *
   * @param key
   * @param value
   */
  public void writeProperty(String key, String value) {
    InputStream is = null;
    OutputStream os = null;
    Properties p = new Properties();
    try {
      //			is = new FileInputStream(properiesName);
      is = PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);
      p.load(is);
      String path = PropertiesUtil.class.getClassLoader().getResource(properiesName).getFile();
      path = path.replaceAll("%20", " ");
      os = new FileOutputStream(path);

      p.setProperty(key, value);
      p.store(os, key);
      os.flush();
      os.close();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (null != is) is.close();
        if (null != os) os.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 9
0
  /**
   * Copies a file. If the destination exists it is overwritten.
   *
   * @param srcFile
   * @param dstFile
   * @throws IOException
   */
  public static void copyFile(File srcFile, File dstFile) throws IOException {
    InputStream in = null;
    OutputStream out = null;
    try {
      in = new FileInputStream(srcFile);
      // Get the parent directory
      File parentDir = new File(dstFile.getParentFile().getAbsolutePath());
      parentDir.mkdirs();

      // Create file if it doesn't exist (if it exists it will be overwritten)
      if (!dstFile.exists()) dstFile.createNewFile();

      out = new FileOutputStream(dstFile);

      // Transfer bytes from in to out
      byte[] buf = new byte[1024];
      int len;
      while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
      in.close();
      out.close();
    } catch (Exception e) {
      try {
        if (in != null) in.close();
        if (out != null) out.close();
      } catch (Exception ignore) {
      }
      throw new IOException("Error on copying file", e);
    }
  }
Exemplo n.º 10
0
  private static void writeFile(
      ByteCodeClass cls, File outputDir, ConcatenatingFileOutputStream writeBufferInstead)
      throws Exception {
    OutputStream outMain =
        writeBufferInstead != null
                && ByteCodeTranslator.output == ByteCodeTranslator.OutputType.OUTPUT_TYPE_IOS
            ? writeBufferInstead
            : new FileOutputStream(
                new File(
                    outputDir, cls.getClsName() + "." + ByteCodeTranslator.output.extension()));

    if (outMain instanceof ConcatenatingFileOutputStream) {
      ((ConcatenatingFileOutputStream) outMain).beginNextFile(cls.getClsName());
    }
    if (ByteCodeTranslator.output == ByteCodeTranslator.OutputType.OUTPUT_TYPE_IOS) {
      outMain.write(cls.generateCCode(classes).getBytes());
      outMain.close();

      // we also need to write the header file for iOS
      String headerName = cls.getClsName() + ".h";
      FileOutputStream outHeader = new FileOutputStream(new File(outputDir, headerName));
      outHeader.write(cls.generateCHeader().getBytes());
      outHeader.close();
    } else {
      outMain.write(cls.generateCSharpCode().getBytes());
      outMain.close();
    }
  }
Exemplo n.º 11
0
 public static Typeface loadTypeface(Context context, int font) {
   Typeface typeface = FontLoader.FONT_CACHE.get(font);
   if (typeface == null) {
     try {
       File file = new File(context.getApplicationInfo().dataDir + "/fonts");
       if (!file.exists()) {
         file.mkdirs();
       }
       file = new File(file, Integer.toHexString(font));
       if (file.exists()) {
         file.delete();
       }
       Resources res = context.getResources();
       InputStream is = new BufferedInputStream(res.openRawResource(font));
       OutputStream os = new ByteArrayOutputStream(Math.max(is.available(), 1024));
       byte[] buffer = new byte[1024];
       int read;
       while ((read = is.read(buffer)) > 0) {
         os.write(buffer, 0, read);
       }
       is.close();
       os.flush();
       buffer = ((ByteArrayOutputStream) os).toByteArray();
       os.close();
       os = new FileOutputStream(file);
       os.write(buffer);
       os.flush();
       os.close();
       FontLoader.FONT_CACHE.put(font, typeface = Typeface.createFromFile(file));
     } catch (Exception e) {
       Log.e(FontLoader.TAG, "Error of loading font", e);
     }
   }
   return typeface;
 }
Exemplo n.º 12
0
 public int run() throws IOException {
   try {
     int b = in.read();
     if (b != -1) {
       dOut.write(b);
       size++;
       return 1;
     } else {
       dOut.close();
       tmpOut.close();
       LongObjectId loid = LongObjectId.fromRaw(dOut.getMessageDigest().digest());
       Path mediaFile = lfsUtil.getMediaFile(loid);
       if (Files.isRegularFile(mediaFile)) {
         long fsSize = Files.size(mediaFile);
         if (fsSize != size) {
           throw new CorruptMediaFile(mediaFile, size, fsSize);
         }
       } else {
         FileUtils.mkdirs(mediaFile.getParent().toFile(), true);
         FileUtils.rename(tmpFile.toFile(), mediaFile.toFile());
       }
       LfsPointer lfsPointer = new LfsPointer(loid, size);
       lfsPointer.encode(out);
       out.close();
       return -1;
     }
   } catch (IOException e) {
     out.close();
     dOut.close();
     tmpOut.close();
     throw e;
   }
 }
Exemplo n.º 13
0
  /**
   * @param ds
   * @param outFile
   * @return
   * @throws IOException
   */
  private RIDResponseObject handleSVG(Dataset ds, BaseDocument doc) throws IOException {
    OutputStream out = doc.getOutputStream();
    try {
      DcmElement elem = ds.get(Tags.WaveformSeq);
      WaveformGroup wfgrp =
          new WaveformGroup(
              ds.getString(Tags.SOPClassUID),
              elem,
              0,
              ridSupport.getWaveformCorrection()); // TODO all groups
      if (log.isDebugEnabled()) log.debug(wfgrp);
      WaveformInfo wfInfo = new WaveformInfo(ds);

      SVGCreator svgCreator = new SVGCreator(wfgrp, wfInfo, new Float(27.6f), new Float(20.3f));
      svgCreator.toXML(out);
      out.close();
      return new RIDStreamResponseObjectImpl(
          doc.getInputStream(), CONTENT_TYPE_SVGXML, HttpServletResponse.SC_OK, null);
    } catch (Throwable t) {
      if (out != null)
        try {
          out.close();
        } catch (IOException e) {
        }
      log.error("Cant create SVG for Waveform!", t);
      log.error("Waveform Dataset:");
      log.error(ds);
      return new RIDStreamResponseObjectImpl(
          null,
          RIDSupport.CONTENT_TYPE_HTML,
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
          "Error while creating waveform SVG! Reason:" + t.getMessage());
    }
  }
Exemplo n.º 14
0
 /**
  * Creates a process builder for the application, using the config, logging, and system
  * properties.
  */
 ProcessBuilder createProcessBuilder() throws Exception {
   /* Create the application configuration file */
   File configFile = File.createTempFile("SimpleApp", "config");
   OutputStream configOut = new FileOutputStream(configFile);
   config.store(configOut, null);
   configOut.close();
   /* Create the logging configuration file */
   File loggingFile = File.createTempFile("SimpleApp", "logging");
   OutputStream loggingOut = new FileOutputStream(loggingFile);
   logging.store(loggingOut, null);
   loggingOut.close();
   /* Create the command line for running the Kernel */
   List<String> command = new ArrayList<String>();
   command.add(System.getProperty("java.home") + "/bin/java");
   command.add("-cp");
   command.add(System.getProperty("java.class.path"));
   command.add("-Djava.util.logging.config.file=" + loggingFile);
   command.add("-Djava.library.path=" + System.getProperty("java.library.path"));
   Enumeration<?> names = system.propertyNames();
   while (names.hasMoreElements()) {
     Object name = names.nextElement();
     command.add("-D" + name + "=" + system.get(name));
   }
   command.add("com.sun.sgs.impl.kernel.Kernel");
   command.add(configFile.toURI().toURL().getPath());
   /* Return the process builder */
   return new ProcessBuilder(command);
 }
  public WorkspaceSnapshot snapshot(
      AbstractBuild<?, ?> build,
      FilePath ws,
      DirScanner scanner,
      TaskListener listener,
      String archiveMethod)
      throws IOException, InterruptedException {
    File wss = new File(build.getRootDir(), CloneWorkspaceUtil.getFileNameForMethod(archiveMethod));
    if (archiveMethod == "ZIP") {
      OutputStream os = new BufferedOutputStream(new FileOutputStream(wss));
      try {
        ws.zip(os, scanner);
      } finally {
        os.close();
      }

      return new WorkspaceSnapshotZip();
    } else {
      OutputStream os =
          new BufferedOutputStream(
              FilePath.TarCompression.GZIP.compress(new FileOutputStream(wss)));
      try {
        ws.tar(os, scanner);
      } finally {
        os.close();
      }

      return new WorkspaceSnapshotTar();
    }
  }
Exemplo n.º 16
0
 /**
  * Decode Base64 encoded data from one file to the other. Characters in the Base64 alphabet, white
  * space and equals sign are expected to be in urlencoded data. The presence of other characters
  * could be a sign that the data is corrupted.
  *
  * @param fIn File to be decoded.
  * @param fOut File to which the results should be written (may be the same as fIn).
  * @param throwExceptions Whether to throw exceptions when unexpected data is encountered.
  * @throws IOException if an IO error occurs.
  * @throws Base64DecodingException if unexpected data is encountered when throwExceptions is
  *     specified.
  * @since ostermillerutils 1.00.00
  */
 public static void decode(File fIn, File fOut, boolean throwExceptions) throws IOException {
   File temp = null;
   InputStream in = null;
   OutputStream out = null;
   try {
     in = new BufferedInputStream(new FileInputStream(fIn));
     temp = File.createTempFile("Base64", null, null);
     out = new BufferedOutputStream(new FileOutputStream(temp));
     decode(in, out, throwExceptions);
     in.close();
     in = null;
     out.flush();
     out.close();
     out = null;
     FileHelper.move(temp, fOut, true);
   } finally {
     if (in != null) {
       try {
         in.close();
       } catch (IOException ignore) {
         if (throwExceptions) throw ignore;
       }
       in = null;
     }
     if (out != null) {
       try {
         out.flush();
         out.close();
       } catch (IOException ignore) {
         if (throwExceptions) throw ignore;
       }
       out = null;
     }
   }
 }
Exemplo n.º 17
0
  /**
   * Test method does three tests on the supplied data: 1. encoded ---[DECODE]--> decoded 2. decoded
   * ---[ENCODE]--> encoded 3. decoded ---[WRAP-WRAP-WRAP-etc...] --> decoded
   *
   * <p>By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the Base64OutputStream wraps itself in
   * encode and decode mode over and over again.
   *
   * @param encoded base64 encoded data
   * @param decoded the data from above, but decoded
   * @param chunkSize chunk size (line-length) of the base64 encoded data.
   * @param seperator Line separator in the base64 encoded data.
   * @throws Exception Usually signifies a bug in the Base64 commons-codec implementation.
   */
  private void testByChunk(byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator)
      throws Exception {

    // Start with encode.
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    OutputStream out = new Base64OutputStream(byteOut, true, chunkSize, seperator);
    out.write(decoded);
    out.close();
    byte[] output = byteOut.toByteArray();
    assertTrue("Streaming chunked base64 encode", Arrays.equals(output, encoded));

    // Now let's try decode.
    byteOut = new ByteArrayOutputStream();
    out = new Base64OutputStream(byteOut, false);
    out.write(encoded);
    out.close();
    output = byteOut.toByteArray();
    assertTrue("Streaming chunked base64 decode", Arrays.equals(output, decoded));

    // I always wanted to do this! (wrap encoder with decoder etc etc).
    byteOut = new ByteArrayOutputStream();
    out = byteOut;
    for (int i = 0; i < 10; i++) {
      out = new Base64OutputStream(out, false);
      out = new Base64OutputStream(out, true, chunkSize, seperator);
    }
    out.write(decoded);
    out.close();
    output = byteOut.toByteArray();

    assertTrue("Streaming chunked base64 wrap-wrap-wrap!", Arrays.equals(output, decoded));
  }
  public static void copy(
      InputStream src, OutputStream dest, CopyProgressListener l, boolean autoClose)
      throws IOException {
    CopyProgressEvent evt = null;
    if (l != null) {
      evt = new CopyProgressEvent();
    }
    try {
      byte[] buffer = new byte[BUFFER_SIZE];
      int c;
      long total = 0;

      if (l != null) {
        l.start(evt);
      }
      while ((c = src.read(buffer)) != -1) {
        if (Thread.currentThread().isInterrupted()) {
          throw new IOException("transfer interrupted");
        }
        dest.write(buffer, 0, c);
        total += c;
        if (l != null) {
          l.progress(evt.update(buffer, c, total));
        }
      }

      if (l != null) {
        evt.update(EMPTY_BUFFER, 0, total);
      }

      try {
        dest.flush();
      } catch (IOException ex) {
        // ignore
      }

      // close the streams
      if (autoClose) {
        src.close();
        dest.close();
      }
    } finally {
      if (autoClose) {
        try {
          src.close();
        } catch (IOException ex) {
          // ignore
        }
        try {
          dest.close();
        } catch (IOException ex) {
          // ignore
        }
      }
    }

    if (l != null) {
      l.end(evt);
    }
  }
Exemplo n.º 19
0
 public static byte[] encode(byte[] b) throws Exception {
   ByteArrayOutputStream baos = null;
   OutputStream b64os = null;
   try {
     baos = new ByteArrayOutputStream();
     b64os = MimeUtility.encode(baos, "base64");
     b64os.write(b);
     b64os.close();
     return baos.toByteArray();
   } catch (Exception e) {
     throw new Exception(e);
   } finally {
     try {
       if (baos != null) {
         baos.close();
         baos = null;
       }
     } catch (Exception e) {
     }
     try {
       if (b64os != null) {
         b64os.close();
         b64os = null;
       }
     } catch (Exception e) {
     }
   }
 }
 private void a(CircuitBreaker circuitBreaker, byte[] bArr, String str) {
   if (!circuitBreaker.b()) {
     try {
       OutputStream bufferedOutputStream = new BufferedOutputStream(a(str));
       try {
         a(bufferedOutputStream, bArr);
         try {
           bufferedOutputStream.flush();
           bufferedOutputStream.close();
         } catch (IOException e) {
         }
       } catch (IOException e2) {
         try {
           Log.w(a, "Caught IOException while writing asset to disk: %s", new Object[] {str});
           circuitBreaker.a();
           try {
             bufferedOutputStream.flush();
             bufferedOutputStream.close();
           } catch (IOException e3) {
           }
         } catch (Throwable th) {
           try {
             bufferedOutputStream.flush();
             bufferedOutputStream.close();
           } catch (IOException e4) {
           }
         }
       }
     } catch (IOException e5) {
       Log.e(a, "Could not write an asset to disk: %s", new Object[] {str});
       circuitBreaker.a();
     }
   }
 }
 /**
  * Write map of sets to a file.
  *
  * <p>The serialization format is XML properties format where values are comma separated lists.
  *
  * @param m map to serialize
  * @param filename output filename
  */
 private void writeMapToXML(final Map<String, Set<String>> m, final String filename) {
   if (m == null) {
     return;
   }
   final Properties prop = new Properties();
   for (final Map.Entry<String, Set<String>> entry : m.entrySet()) {
     final String key = entry.getKey();
     final String value = StringUtils.assembleString(entry.getValue(), COMMA);
     prop.setProperty(key, value);
   }
   final File outputFile = new File(tempDir, filename);
   OutputStream os = null;
   try {
     os = new FileOutputStream(outputFile);
     prop.storeToXML(os, null);
     os.close();
   } catch (final IOException e) {
     this.logger.logException(e);
   } finally {
     if (os != null) {
       try {
         os.close();
       } catch (final Exception e) {
         logger.logException(e);
       }
     }
   }
 }
Exemplo n.º 22
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    logger.info("get: " + req.getQueryString());

    String sessionId = req.getParameter("sessionId");
    if (!Utils.isNullOrEmpty(sessionId)) {
      Session session = getSessionCache().getSessionForSessionId(sessionId);
      if (session.getUserProfile() != null) {
        String picture = req.getParameter("picture");
        if ("tmp".equals(picture)) {
          String fileName = req.getParameter("filename");
          if (fileName.contains("..")) return;
          System.out.println("fnis:" + fileName);
          File picFile = new File(Backend.getWorkDir() + "tmpfiles" + File.separator + fileName);

          OutputStream out = resp.getOutputStream();
          FileInputStream fi = new FileInputStream(picFile);
          resp.setContentType("image");
          IOUtils.copy(fi, out);
          fi.close();
          out.close();

        } else if ("user".equals(picture)) {
          try {
            byte[] rawPicture = null;
            String fromUniqueUserId = req.getParameter("uniqueUserId");

            if (session.getUserProfile().getUniqueUserID().equals(fromUniqueUserId)) {
              if (Boolean.parseBoolean(req.getParameter("bigPicture"))) {
                logger.info("sending big user picture");
                rawPicture = session.getUserProfile().getUserCredentials().getPicture();
              } else {
                logger.info("sending small user picture");
                rawPicture = session.getUserProfile().getUserCredentials().getSmallPicture();
              }
            }
            OutputStream out = resp.getOutputStream();
            if (rawPicture == null) {
              FileInputStream fi =
                  new FileInputStream(
                      Backend.getWebContentFolder().getAbsolutePath()
                          + File.separator
                          + "images"
                          + File.separator
                          + "replacement_user_image.png");
              resp.setContentType("image");
              IOUtils.copy(fi, out);
              fi.close();
            } else {
              out.write(rawPicture);
            }
            out.close();
          } catch (Exception e) {
            logger.error("error sending user picture", e);
          }
        }
      }
    } else super.doGet(req, resp);
  }
Exemplo n.º 23
0
  @BeforeTest(alwaysRun = true)
  public void setUp() throws Exception {
    SecureRandom.getInstance("SHA1PRNG").nextBytes(nonEncodableBytesToWrite);
    String phrase = "all work and no play make Jack a dull boy";
    byte[] bytes = phrase.getBytes();
    int cursor = 0;
    while (cursor <= bytesToWrite.length) {
      System.arraycopy(
          bytes,
          0,
          bytesToWrite,
          cursor,
          (bytes.length + cursor < bytesToWrite.length)
              ? bytes.length
              : bytesToWrite.length - cursor);
      cursor += bytes.length;
    }
    ByteArrayOutputStream nonCompressed = new ByteArrayOutputStream();
    OutputStream os = new LZFOutputStream(nonCompressed);
    os.write(nonEncodableBytesToWrite);
    os.close();
    nonCompressableBytes = nonCompressed.toByteArray();

    ByteArrayOutputStream compressed = new ByteArrayOutputStream();
    os = new LZFOutputStream(compressed);
    os.write(bytesToWrite);
    os.close();
    compressedBytes = compressed.toByteArray();
  }
Exemplo n.º 24
0
  /*
   * (non-Javadoc)
   *
   * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest,
   * javax.servlet.ServletResponse)
   */
  @Override
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {
      String messageId = request.getParameter("messageId");
      String attachmentIndex = request.getParameter("attachmentIndex");
      boolean isThumbnail = Boolean.valueOf(request.getParameter("thumbnail")).booleanValue();

      if (messageId != null) {
        IMailbox mailbox = SessionManager.get().getMailbox();
        Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

        if (isThumbnail) {
          List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
          int index = Integer.valueOf(attachmentIndex);

          MimePart retrievePart = attachmentList.get(index);

          ContentType contentType = new ContentType(retrievePart.getContentType());
          response.setContentType(contentType.getBaseType());

          BufferedInputStream bufInputStream =
              new BufferedInputStream(retrievePart.getInputStream());
          OutputStream outputStream = response.getOutputStream();

          writeScaledImage(bufInputStream, outputStream);

          bufInputStream.close();
          outputStream.flush();
          outputStream.close();
        } else {
          Part imagePart = findImagePart(msg);
          if (imagePart != null) {
            ContentType contentType = new ContentType(imagePart.getContentType());
            response.setContentType(contentType.getBaseType());

            BufferedInputStream bufInputStream =
                new BufferedInputStream(imagePart.getInputStream());
            OutputStream outputStream = response.getOutputStream();

            byte[] inBuf = new byte[1024];
            int len = 0;
            int total = 0;
            while ((len = bufInputStream.read(inBuf)) > 0) {
              outputStream.write(inBuf, 0, len);
              total += len;
            }

            bufInputStream.close();
            outputStream.flush();
            outputStream.close();
          }
        }
      }
    } catch (Exception ex) {
      log.error(ex.getMessage(), ex);
    }
  }
  /**
   * The main processing loop for this actor. All we do here is call
   * <em>ourSession.shellMainLoop</em>. This allows the shell session to begin processing commands
   * with the proper permissions for invoking the local "impl" commands.
   */
  @pausable
  public void execute() {
    try {
      //      Log.println("<ShellActorImpl.run>: Requesting session reference from service...");
      Object[] invokeArgs = new Object[1];
      invokeArgs[0] = create.constructorArgs[0];
      ourSession =
          (ShellSession) mgrActorInvokeService(manager, Shell.name, "shellProxyInit", invokeArgs);
    } catch (Exception e) {
      // If we get an error here then we have no reliable way of
      // reporting it because the creator of this actor is set to
      // null.  So, just log the error and kill ourselves by calling
      // actorFatalError.
      //      Log.println("Error in run loop of shell actor: " + e);

      // Have to do some handstands to log the stack trace.
      CharArrayWriter temp1 = new CharArrayWriter();
      PrintWriter temp2 = new PrintWriter(temp1, true);
      e.printStackTrace(temp2);
      temp2.close();
      temp1.close();
      //      Log.println(temp1.toString());

      // kill ourselves
      mgrActorFatalError(manager, e);
    }

    // Now initialize our session actor before running it
    //    Log.println("<ShellActorImpl.run>: Received references, initializing session...");
    ourSession.ourActor = self;
    ourSession.ourActorRef = this;
    active = true;

    //    Log.println("<ShellActorImpl.run>: Creating stream aliases...");
    stdinName = ((BasicActorManager) manager).actorCreateAlias(this);
    stdoutName = ((BasicActorManager) manager).actorCreateAlias(this);
    stderrName = ((BasicActorManager) manager).actorCreateAlias(this);

    // When the shell loop exits we are considered in active.  We also
    // close the standard streams at this point.
    ourSession.shellMainLoop();
    try {
      if (stdinStream != null) stdinStream.close();
      if (stdoutStream != null) stdoutStream.close();
      if (stderrStream != null) stderrStream.close();
    } catch (IOException e) {
      // We ignore these since it probably indicates that the
      // connection has already been closed.
    }
    active = false;

    // Even though our shell session has died at this point.  We still
    // need to keep this actor around as our address may have been
    // propagated over the network.  So we just suspend the actor here
    // and rely on garbage collection to eventually clean up old shell
    // actors.
    // suspend();

  }
 private void writeOldPropertiesFiles(Properties props) throws IOException {
   OutputStream os1 = new FileOutputStream(pageOneOldFilename);
   props.store(os1, "test");
   os1.close();
   OutputStream os2 = new FileOutputStream(pageTwoOldFilename);
   props.store(os2, "test");
   os2.close();
 }
  private ChannelManager.TARTT_ERROR downloadFile(ChannelFile file) {
    InputStream input = null;
    OutputStream output = null;
    HttpURLConnection connection = null;
    try {
      URL url = new URL(file.getUrl());
      connection = (HttpURLConnection) url.openConnection();
      connection.setConnectTimeout(10000);
      connection.setReadTimeout(10000);
      connection.connect();

      if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        Log.e(TAG, "Connection error " + connection.getResponseCode());
        return ChannelManager.TARTT_ERROR.DOWNLOAD_ABORTED;
      }

      input = connection.getInputStream();
      File outputFolder = new File(mTargetFolder, file.getDirname());
      outputFolder.mkdirs();
      File outputFile = new File(outputFolder, file.getFilename());
      output = new FileOutputStream(outputFile, false);

      byte data[] = new byte[4096];
      int count;
      while ((count = input.read(data)) != -1) {
        // allow canceling
        if (isCancelled()) {
          try {
            if (output != null) output.close();
            if (input != null) input.close();
          } catch (IOException ignored) {
          }
          return ChannelManager.TARTT_ERROR.DOWNLOAD_ABORTED;
        }
        mBytesLoaded += count;
        publishProgress(mBytesLoaded);
        output.write(data, 0, count);
      }

      if (!MD5.checkMD5(file.getMd5(), outputFile)) {
        Log.e(TAG, "File was corrupt, downloading again");
        mBytesLoaded = -file.getFilesize();
        return downloadFile(file);
      }
    } catch (Exception e) {
      Log.e(TAG, "Exception downloading " + e.fillInStackTrace());
      return ChannelManager.TARTT_ERROR.DOWNLOAD_ABORTED;
    } finally {
      try {
        if (output != null) output.close();
        if (input != null) input.close();
      } catch (IOException ignored) {
      }

      if (connection != null) connection.disconnect();
    }
    return null;
  }
Exemplo n.º 28
0
  private void copyDemoProject2() {
    AssetManager assetManager = getResources().getAssets();

    // now we copy soundscape.rss file
    String[] files2 = null;
    try {
      files2 = assetManager.list("rssDemoProject");
    } catch (Exception e) {
      Log.e("creation of RSS of Demo Project - ERROR", e.toString());
      e.printStackTrace();
    }
    for (int i = 0; i < files2.length; i++) {
      InputStream in = null;
      OutputStream out = null;
      try {
        in = assetManager.open("rssDemoProject/" + files2[i]);
        out = new FileOutputStream("/storage/emulated/0/notours/noToursDemo/" + files2[i]);
        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
      } catch (Exception e) {
        Log.e("copy RSS of Demo - ERROR", e.toString());
        e.printStackTrace();
      }
    }

    // copy sounds
    String[] files = null;
    try {
      files = assetManager.list("soundsDemoProject");
    } catch (Exception e) {
      Log.e("creation of Sounds of Demo Project - ERROR", e.toString());
      e.printStackTrace();
    }
    for (int i = 0; i < files.length; i++) {
      InputStream in = null;
      OutputStream out = null;
      try {
        in = assetManager.open("soundsDemoProject/" + files[i]);
        out = new FileOutputStream("/storage/emulated/0/notours/noToursDemo/sound/" + files[i]);
        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
      } catch (Exception e) {
        Log.e("copy sounds of Demo - ERROR", e.toString());
        e.printStackTrace();
      }
    }

    // end of for
  }
Exemplo n.º 29
0
  /**
   * Navigate based on a form. Complete and post the form.
   *
   * @param form The form to be posted.
   * @param submit The submit button on the form to simulate clicking.
   */
  public final void navigate(final Form form, final Input submit) {

    try {
      EncogLogging.log(EncogLogging.LEVEL_INFO, "Posting a form");

      InputStream is;
      URLConnection connection = null;
      OutputStream os;
      URL targetURL;

      if (form.getMethod() == Form.Method.GET) {
        os = new ByteArrayOutputStream();
      } else {

        connection = form.getAction().getUrl().openConnection();
        os = connection.getOutputStream();
      }

      // add the parameters if present
      final FormUtility formData = new FormUtility(os, null);
      for (final DocumentRange dr : form.getElements()) {
        if (dr instanceof FormElement) {
          final FormElement element = (FormElement) dr;
          if ((element == submit) || element.isAutoSend()) {
            final String name = element.getName();
            String value = element.getValue();
            if (name != null) {
              if (value == null) {
                value = "";
              }
              formData.add(name, value);
            }
          }
        }
      }

      // now execute the command
      if (form.getMethod() == Form.Method.GET) {
        String action = form.getAction().getUrl().toString();
        os.close();
        action += "?";
        action += os.toString();
        targetURL = new URL(action);
        connection = targetURL.openConnection();
        is = connection.getInputStream();
      } else {
        targetURL = form.getAction().getUrl();
        os.close();
        is = connection.getInputStream();
      }

      navigate(targetURL, is);
      is.close();
    } catch (final IOException e) {
      throw new BrowseError(e);
    }
  }
  /**
   * generate PDF file containing all site participant
   *
   * @param data
   */
  public void print_participant(String siteId) {

    HttpServletResponse res =
        (HttpServletResponse) ThreadLocalManager.get(RequestFilter.CURRENT_HTTP_RESPONSE);

    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();

    res.addHeader("Content-Disposition", "inline; filename=\"participants.pdf\"");
    res.setContentType("application/pdf");

    Document document = docBuilder.newDocument();

    // get the participant xml document
    generateParticipantXMLDocument(document, siteId);

    generatePDF(document, outByteStream);
    res.setContentLength(outByteStream.size());
    if (outByteStream.size() > 0) {
      // Increase the buffer size for more speed.
      res.setBufferSize(outByteStream.size());
    }

    /*
    // output xml for debugging purpose
    try
    {
    	TransformerFactory transformerFactory = TransformerFactory.newInstance();
           Transformer transformer = transformerFactory.newTransformer();
           DOMSource source = new DOMSource(document);
           StreamResult result =  new StreamResult(System.out);
           transformer.transform(source, result);
    }
    catch (Exception e)
    {

    }*/

    OutputStream out = null;
    try {
      out = res.getOutputStream();
      if (outByteStream.size() > 0) {
        outByteStream.writeTo(out);
      }
      res.setHeader("Refresh", "0");

      out.flush();
      out.close();
    } catch (Throwable ignore) {
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (Throwable ignore) {
        }
      }
    }
  }