public static void main(String[] args) throws IOException {

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    String f1, f2, f3;

    f1 = reader.readLine();
    f2 = reader.readLine();
    f3 = reader.readLine();

    FileOutputStream file1 = new FileOutputStream(f1);
    FileInputStream file2 = new FileInputStream(f2);
    FileInputStream file3 = new FileInputStream(f3);

    byte buf[] = new byte[1000];
    while (file2.available() > 0) {
      int count = file2.read(buf);
      file1.write(buf, 0, count);
    }

    while (file3.available() > 0) {
      int count = file3.read(buf);
      file1.write(buf, 0, count);
    }

    file1.close();
    file2.close();
    file3.close();
  }
Пример #2
0
  public static void handle(
      BufferedReader inputBufferReader,
      PrintWriter outputPrintWriter,
      StringBuilder completeHeader) {
    outputPrintWriter.println("HTTP/1.1 200 OK\r\n");

    try {

      Properties properties = new Properties();
      FileInputStream fis = new FileInputStream("Webmail.properties");
      properties.load(fis);
      fis.close();
      String indexFilePath = properties.getProperty("index");

      byte[] indexFileBuffer = new byte[(int) new File(indexFilePath).length()];
      FileInputStream f;
      String indexFileString;
      f = new FileInputStream(indexFilePath);
      f.read(indexFileBuffer);
      indexFileString = new String(indexFileBuffer);
      f.close();
      outputPrintWriter.print(indexFileString);
      outputPrintWriter.flush();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 /**
  * Parses the given xml file and returns a list of the suppression rules contained.
  *
  * @param file an xml file containing suppression rules
  * @return a list of suppression rules
  * @throws SuppressionParseException thrown if the xml file cannot be parsed
  */
 public List<SuppressionRule> parseSuppressionRules(File file) throws SuppressionParseException {
   FileInputStream fis = null;
   try {
     fis = new FileInputStream(file);
     return parseSuppressionRules(fis);
   } catch (IOException ex) {
     LOGGER.debug("", ex);
     throw new SuppressionParseException(ex);
   } catch (SAXException ex) {
     try {
       if (fis != null) {
         try {
           fis.close();
         } catch (IOException ex1) {
           LOGGER.debug("Unable to close stream", ex1);
         }
       }
       fis = new FileInputStream(file);
     } catch (FileNotFoundException ex1) {
       throw new SuppressionParseException(ex);
     }
     return parseOldSuppressionRules(fis);
   } finally {
     if (fis != null) {
       try {
         fis.close();
       } catch (IOException ex) {
         LOGGER.debug("Unable to close stream", ex);
       }
     }
   }
 }
Пример #4
0
  public static Bitmap decodeFile(File f, Integer thumbnail_size) {
    Bitmap b = null;
    try {
      // Decode image size
      BitmapFactory.Options o = new BitmapFactory.Options();
      o.inJustDecodeBounds = true;

      FileInputStream fis = new FileInputStream(f);
      BitmapFactory.decodeStream(fis, null, o);
      fis.close();

      int scale = 1;
      if (o.outHeight > thumbnail_size || o.outWidth > thumbnail_size) {
        scale =
            (int)
                Math.pow(
                    2,
                    (int)
                        Math.round(
                            Math.log(thumbnail_size / (double) Math.max(o.outHeight, o.outWidth))
                                / Math.log(0.5)));
      }

      // Decode with inSampleSize
      BitmapFactory.Options o2 = new BitmapFactory.Options();
      o2.inSampleSize = scale;
      fis = new FileInputStream(f);
      b = BitmapFactory.decodeStream(fis, null, o2);
      fis.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return b;
  }
 /**
  * *****************************************************************************************************************
  * Change the fitnesse result page to a Maven site format.
  *
  * @param pServer FitNesse server configuration.
  * @throws MojoExecutionException If the result page can't be found.
  */
 void transformResultPage(Fitnesse pServer) throws MojoExecutionException {
   FileInputStream tIn = null;
   try {
     String tSrcFile = getTmpFileName(pServer);
     tIn = new FileInputStream(tSrcFile);
     File tDestFile = new File(getFinalFileName(pServer));
     if (tDestFile.exists()) {
       tDestFile.delete();
     }
     FileWriter tWriter = new FileWriter(tDestFile);
     FitnessePage tResult = new FitnessePage(new File(tSrcFile));
     transformHtml(tIn, tWriter, getOutputUrl(pServer), tResult.getStatus());
     tIn.close();
     tIn = null;
     if (!new File(tSrcFile).delete()) {
       getLog().error("Unable to delete tmp file [" + tSrcFile + "]");
     }
   } catch (FileNotFoundException e) {
     throw new MojoExecutionException("Unable to tranform html", e);
   } catch (IOException e) {
     throw new MojoExecutionException("Unable to tranform html", e);
   } finally {
     if (tIn != null) {
       try {
         tIn.close();
       } catch (IOException e) {
         throw new MojoExecutionException("Unable to close tmp file stream", e);
       }
     }
   }
 }
Пример #6
0
  public String hash() throws NoSuchAlgorithmException, IOException {
    FileInputStream fis;
    MessageDigest md;
    String hex;
    StringBuffer hexString;
    byte[] dataBytes;
    int nread;

    md = MessageDigest.getInstance("MD5");
    fis = new FileInputStream(this.path);
    dataBytes = new byte[65536];
    hexString = new StringBuffer();

    try {
      while ((nread = fis.read(dataBytes)) != -1) {
        md.update(dataBytes, 0, nread);
      }
    } finally {
      fis.close();
    }

    byte[] mdbytes = md.digest();

    for (int i = 0; i < mdbytes.length; i++) {
      hex = Integer.toHexString(0xff & mdbytes[i]);
      if (hex.length() == 1) {
        hexString.append('0');
      }
      hexString.append(hex);
    }
    fis.close();

    return hexString.toString();
  }
Пример #7
0
  public void loadFromFile() {
    Log.i(LOG_TAG, "Loading from file...");
    try {
      FileInputStream fis = openFileInput("cs_pinger_icmp");
      ObjectInputStream is = new ObjectInputStream(fis);
      PingSettings readPS = (PingSettings) is.readObject();
      is.close();
      fis.close();
      icmpPingSettings = readPS;

      fis = openFileInput("cs_pinger_http");
      is = new ObjectInputStream(fis);
      readPS = (PingSettings) is.readObject();
      is.close();
      fis.close();
      httpPingSettings = readPS;

      fis = openFileInput("cs_pinger_https");
      is = new ObjectInputStream(fis);
      readPS = (PingSettings) is.readObject();
      is.close();
      fis.close();
      httpsPingSettings = readPS;
    } catch (Exception e) {
      StringWriter errors = new StringWriter();
      e.printStackTrace(new PrintWriter(errors));
      Log.d(LOG_TAG, "File read error!\n" + errors.toString());
    }
  }
Пример #8
0
 private static Element getDocumentElement(final String filename, final boolean usingBackupFile)
     throws XmlException, IOException {
   DocumentBuilderFactory factory;
   DocumentBuilder builder;
   Document doc;
   FileInputStream is = null;
   try {
     is = new FileInputStream(new File(filename));
     factory = DocumentBuilderFactory.newInstance();
     builder = factory.newDocumentBuilder();
     doc = builder.parse(is);
     return doc.getDocumentElement();
   } catch (SAXException ex) {
     if (is != null) { // Close file - so we can delete it...
       is.close();
     }
     if (!usingBackupFile && restoreBackupFile(filename)) {
       return getDocumentElement(filename, true);
     }
     throw new XmlException(ex.getMessage(), ex);
   } catch (ParserConfigurationException ex) {
     throw new XmlException(ex.getMessage(), ex);
   } finally {
     if (is != null) {
       is.close();
     }
   }
 }
Пример #9
0
  // decodes image and scales it to reduce memory consumption
  private Bitmap decodeFile(File f) {
    try {
      // decode image size
      BitmapFactory.Options o = new BitmapFactory.Options();
      o.inJustDecodeBounds = true;
      FileInputStream stream1 = new FileInputStream(f);
      BitmapFactory.decodeStream(stream1, null, o);
      stream1.close();

      // Find the correct scale value. It should be the power of 2.
      final int REQUIRED_SIZE = 70;
      int width_tmp = o.outWidth, height_tmp = o.outHeight;
      int scale = 1;
      while (true) {
        if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
      }

      // decode with inSampleSize
      BitmapFactory.Options o2 = new BitmapFactory.Options();
      o2.inSampleSize = scale;
      FileInputStream stream2 = new FileInputStream(f);
      Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
      stream2.close();
      return bitmap;
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Пример #10
0
 /**
  * Read configuration from a file. <b>The existing configuration is not cleared nor reset.</b> If
  * you require a different behavior, then call {@link LogManager#resetConfiguration
  * resetConfiguration} method before calling <code>doConfigure</code>.
  *
  * <p>The configuration file consists of statements in the format <code>key=value</code>. The
  * syntax of different configuration elements are discussed below.
  *
  * <h3>Repository-wide threshold</h3>
  *
  * <p>The repository-wide threshold filters logging requests by level regardless of logger. The
  * syntax is:
  *
  * <pre>
  * log4j.threshold=[level]
  * </pre>
  *
  * <p>The level value can consist of the string values OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL
  * or a <em>custom level</em> value. A custom level value can be specified in the form
  * level#classname. By default the repository-wide threshold is set to the lowest possible value,
  * namely the level <code>ALL</code>.
  *
  * <h3>Appender configuration</h3>
  *
  * <p>Appender configuration syntax is:
  *
  * <pre>
  * # For appender named <i>appenderName</i>, set its class.
  * # Note: The appender name can contain dots.
  * log4j.appender.appenderName=fully.qualified.name.of.appender.class
  *
  * # Set appender specific options.
  * log4j.appender.appenderName.option1=value1
  * ...
  * log4j.appender.appenderName.optionN=valueN
  * </pre>
  *
  * For each named appender you can configure its {@link Layout}. The syntax for configuring an
  * appender's layout is:
  *
  * <pre>
  * log4j.appender.appenderName.layout=fully.qualified.name.of.layout.class
  * log4j.appender.appenderName.layout.option1=value1
  * ....
  * log4j.appender.appenderName.layout.optionN=valueN
  * </pre>
  *
  * The syntax for adding {@link Filter}s to an appender is:
  *
  * <pre>
  * log4j.appender.appenderName.filter.ID=fully.qualified.name.of.filter.class
  * log4j.appender.appenderName.filter.ID.option1=value1
  * ...
  * log4j.appender.appenderName.filter.ID.optionN=valueN
  * </pre>
  *
  * The first line defines the class name of the filter identified by ID; subsequent lines with the
  * same ID specify filter option - value paris. Multiple filters are added to the appender in the
  * lexicographic order of IDs.
  *
  * <p>The syntax for adding an {@link ErrorHandler} to an appender is:
  *
  * <pre>
  * log4j.appender.appenderName.errorhandler=fully.qualified.name.of.filter.class
  * log4j.appender.appenderName.errorhandler.root-ref={true|false}
  * log4j.appender.appenderName.errorhandler.logger-ref=loggerName
  * log4j.appender.appenderName.errorhandler.appender-ref=appenderName
  * log4j.appender.appenderName.errorhandler.option1=value1
  * ...
  * log4j.appender.appenderName.errorhandler.optionN=valueN
  * </pre>
  *
  * <h3>Configuring loggers</h3>
  *
  * <p>The syntax for configuring the root logger is:
  *
  * <pre>
  * log4j.rootLogger=[level], appenderName, appenderName, ...
  * </pre>
  *
  * <p>This syntax means that an optional <em>level</em> can be supplied followed by appender names
  * separated by commas.
  *
  * <p>The level value can consist of the string values OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL
  * or a <em>custom level</em> value. A custom level value can be specified in the form <code>
  * level#classname</code>.
  *
  * <p>If a level value is specified, then the root level is set to the corresponding level. If no
  * level value is specified, then the root level remains untouched.
  *
  * <p>The root logger can be assigned multiple appenders.
  *
  * <p>Each <i>appenderName</i> (separated by commas) will be added to the root logger. The named
  * appender is defined using the appender syntax defined above.
  *
  * <p>For non-root categories the syntax is almost the same:
  *
  * <pre>
  * log4j.logger.logger_name=[level|INHERITED|NULL], appenderName, appenderName, ...
  * </pre>
  *
  * <p>The meaning of the optional level value is discussed above in relation to the root logger.
  * In addition however, the value INHERITED can be specified meaning that the named logger should
  * inherit its level from the logger hierarchy.
  *
  * <p>If no level value is supplied, then the level of the named logger remains untouched.
  *
  * <p>By default categories inherit their level from the hierarchy. However, if you set the level
  * of a logger and later decide that that logger should inherit its level, then you should specify
  * INHERITED as the value for the level value. NULL is a synonym for INHERITED.
  *
  * <p>Similar to the root logger syntax, each <i>appenderName</i> (separated by commas) will be
  * attached to the named logger.
  *
  * <p>See the <a href="../../../../manual.html#additivity">appender additivity rule</a> in the
  * user manual for the meaning of the <code>additivity</code> flag.
  *
  * <h3>ObjectRenderers</h3>
  *
  * You can customize the way message objects of a given type are converted to String before being
  * logged. This is done by specifying an {@link org.apache.log4j.or.ObjectRenderer ObjectRenderer}
  * for the object type would like to customize.
  *
  * <p>The syntax is:
  *
  * <pre>
  * log4j.renderer.fully.qualified.name.of.rendered.class=fully.qualified.name.of.rendering.class
  * </pre>
  *
  * As in,
  *
  * <pre>
  * log4j.renderer.my.Fruit=my.FruitRenderer
  * </pre>
  *
  * <h3>ThrowableRenderer</h3>
  *
  * You can customize the way an instance of Throwable is converted to String before being logged.
  * This is done by specifying an {@link org.apache.log4j.spi.ThrowableRenderer ThrowableRenderer}.
  *
  * <p>The syntax is:
  *
  * <pre>
  * log4j.throwableRenderer=fully.qualified.name.of.rendering.class
  * log4j.throwableRenderer.paramName=paramValue
  * </pre>
  *
  * As in,
  *
  * <pre>
  * log4j.throwableRenderer=org.apache.log4j.EnhancedThrowableRenderer
  * </pre>
  *
  * <h3>Logger Factories</h3>
  *
  * The usage of custom logger factories is discouraged and no longer documented.
  *
  * <h3>Resetting Hierarchy</h3>
  *
  * The hierarchy will be reset before configuration when log4j.reset=true is present in the
  * properties file.
  *
  * <h3>Example</h3>
  *
  * <p>An example configuration is given below. Other configuration file examples are given in the
  * <code>examples</code> folder.
  *
  * <pre>
  *
  * # Set options for appender named "A1".
  * # Appender "A1" will be a SyslogAppender
  * log4j.appender.A1=org.apache.log4j.net.SyslogAppender
  *
  * # The syslog daemon resides on www.abc.net
  * log4j.appender.A1.SyslogHost=www.abc.net
  *
  * # A1's layout is a PatternLayout, using the conversion pattern
  * # <b>%r %-5p %c{2} %M.%L %x - %m\n</b>. Thus, the log output will
  * # include # the relative time since the start of the application in
  * # milliseconds, followed by the level of the log request,
  * # followed by the two rightmost components of the logger name,
  * # followed by the callers method name, followed by the line number,
  * # the nested disgnostic context and finally the message itself.
  * # Refer to the documentation of {@link PatternLayout} for further information
  * # on the syntax of the ConversionPattern key.
  * log4j.appender.A1.layout=org.apache.log4j.PatternLayout
  * log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c{2} %M.%L %x - %m\n
  *
  * # Set options for appender named "A2"
  * # A2 should be a RollingFileAppender, with maximum file size of 10 MB
  * # using at most one backup file. A2's layout is TTCC, using the
  * # ISO8061 date format with context printing enabled.
  * log4j.appender.A2=org.apache.log4j.RollingFileAppender
  * log4j.appender.A2.MaxFileSize=10MB
  * log4j.appender.A2.MaxBackupIndex=1
  * log4j.appender.A2.layout=org.apache.log4j.TTCCLayout
  * log4j.appender.A2.layout.ContextPrinting=enabled
  * log4j.appender.A2.layout.DateFormat=ISO8601
  *
  * # Root logger set to DEBUG using the A2 appender defined above.
  * log4j.rootLogger=DEBUG, A2
  *
  * # Logger definitions:
  * # The SECURITY logger inherits is level from root. However, it's output
  * # will go to A1 appender defined above. It's additivity is non-cumulative.
  * log4j.logger.SECURITY=INHERIT, A1
  * log4j.additivity.SECURITY=false
  *
  * # Only warnings or above will be logged for the logger "SECURITY.access".
  * # Output will go to A1.
  * log4j.logger.SECURITY.access=WARN
  *
  *
  * # The logger "class.of.the.day" inherits its level from the
  * # logger hierarchy.  Output will go to the appender's of the root
  * # logger, A2 in this case.
  * log4j.logger.class.of.the.day=INHERIT
  * </pre>
  *
  * <p>Refer to the <b>setOption</b> method in each Appender and Layout for class specific options.
  *
  * <p>Use the <code>#</code> or <code>!</code> characters at the beginning of a line for comments.
  *
  * <p>
  *
  * @param configFileName The name of the configuration file where the configuration information is
  *     stored.
  */
 public void doConfigure(String configFileName, LoggerRepository hierarchy) {
   Properties props = new Properties();
   FileInputStream istream = null;
   try {
     istream = new FileInputStream(configFileName);
     props.load(istream);
     istream.close();
   } catch (Exception e) {
     if (e instanceof InterruptedIOException || e instanceof InterruptedException) {
       Thread.currentThread().interrupt();
     }
     LogLog.error("Could not read configuration file [" + configFileName + "].", e);
     LogLog.error("Ignoring configuration file [" + configFileName + "].");
     return;
   } finally {
     if (istream != null) {
       try {
         istream.close();
       } catch (InterruptedIOException ignore) {
         Thread.currentThread().interrupt();
       } catch (Throwable ignore) {
       }
     }
   }
   // If we reach here, then the config file is alright.
   doConfigure(props, hierarchy);
 }
Пример #11
0
  /** Check if the file at 'path' starts with a cart header */
  private boolean isCartFormat(String path) throws Exception {
    FileInputStream fs = null;
    try {
      // check if the first 4 bytes spell CART
      fs = new FileInputStream(path);
      if (fs.read() != 67) return false; // C
      if (fs.read() != 65) return false; // A
      if (fs.read() != 82) return false; // R
      if (fs.read() != 84) return false; // T

      // extract the ehcksum from the header
      byte[] checksumBytes = new byte[4];
      fs.read(checksumBytes);
      fs.read(checksumBytes);
      fs.close();
      fs = null;
      // if the checksums match we have a CART
      if (decodeInt(checksumBytes, 0) == atariChecksum(path, 16)) {
        return true;
      }

      return false;
    } catch (Throwable e) {
      throw new Exception("Exception in isCartFormat", e);
    } finally {
      if (fs != null) {
        try {
          fs.close();
        } catch (Throwable e) {
          throw new Exception("Exception closing stream", e);
        }
      }
    }
  }
  private Bitmap loadBitmap(File f) {
    try {
      // decode image size
      BitmapFactory.Options o = new BitmapFactory.Options();
      o.inJustDecodeBounds = true;
      FileInputStream stream1 = new FileInputStream(f);
      BitmapFactory.decodeStream(stream1, null, o);
      stream1.close();

      // Find the correct scale value. It should be the power of 2.
      final int REQUIRED_SIZE = 1024;
      int width_tmp = o.outWidth, height_tmp = o.outHeight;
      int scale = 1;
      while (true) {
        if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
          break;
        }
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
      }

      // decode with inSampleSize
      BitmapFactory.Options o2 = new BitmapFactory.Options();
      o2.inSampleSize = scale;
      FileInputStream stream2 = new FileInputStream(f);
      Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
      stream2.close();
      return bitmap;
    } catch (IOException e) {
      showError(PlayActivity.this, new ABException(e));
    }
    return null;
  }
  @Test
  public void testUnshrinkEntry() throws Exception {
    ZipArchiveInputStream in =
        new ZipArchiveInputStream(new FileInputStream(getFile("SHRUNK.ZIP")));

    ZipArchiveEntry entry = in.getNextZipEntry();
    assertEquals("method", ZipMethod.UNSHRINKING.getCode(), entry.getMethod());
    assertTrue(in.canReadEntryData(entry));

    FileInputStream original = new FileInputStream(getFile("test1.xml"));
    try {
      assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(in));
    } finally {
      original.close();
    }

    entry = in.getNextZipEntry();
    assertEquals("method", ZipMethod.UNSHRINKING.getCode(), entry.getMethod());
    assertTrue(in.canReadEntryData(entry));

    original = new FileInputStream(getFile("test2.xml"));
    try {
      assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(in));
    } finally {
      original.close();
    }
  }
Пример #14
0
 public static void loadProp() {
   FileInputStream attestationPropertyFile = null;
   try {
     String configPath = "/etc/oat-appraiser/";
     attestationPropertyFile = new FileInputStream(configPath + PROPERTIES_NAME);
     attestationProperties.load(attestationPropertyFile);
     timeout = Long.parseLong(attestationProperties.getProperty("default_attest_timeout"));
     checkAttestInterval =
         Long.parseLong(attestationProperties.getProperty("check_attest_interval", "1000"));
     portalAddress = attestationProperties.getProperty("portal_address");
     defaultExpirationTime =
         Long.parseLong(attestationProperties.getProperty("default_expiration_time", "7"));
     if (portalAddress == null) {
       try {
         portalAddress = java.net.InetAddress.getLocalHost().getHostName();
       } catch (java.net.UnknownHostException e) {
         portalAddress = "localhost";
       }
     }
     attestationPropertyFile.close();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (attestationPropertyFile != null) attestationPropertyFile.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Пример #15
0
 private void copy(String source, String dest) {
   FileInputStream in = null;
   FileOutputStream out = null;
   try {
     in = new FileInputStream(source);
     out = new FileOutputStream(dest);
     int len = -1;
     byte[] buffer = new byte[8096];
     while ((len = in.read(buffer)) != -1) {
       out.write(buffer, 0, len);
     }
     in.close();
     out.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (in != null) in.close();
     } catch (IOException e) {
     }
     try {
       if (out != null) out.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Пример #16
0
 public List<FrozenParameters> extractParameters(String... parameterLabelsArray) {
   Set<String> parameterLabels = Utils.asSet(parameterLabelsArray);
   List<FrozenParameters> result = new ArrayList<FrozenParameters>();
   if (!canRead() || infos == null) return result;
   FileInputStream in = null;
   try {
     in = new FileInputStream(filepath);
     InputStreamReader inReader = new InputStreamReader(in);
     BufferedReader reader = new BufferedReader(inReader);
     String[] labels = readLabels(reader);
     if (labels == null) {
       in.close();
       return result;
     }
     while (reader.ready()) result.add(readParameter(parameterLabels, labels, reader));
     in.close();
   } catch (IOException e) {
     e.printStackTrace();
     if (in != null)
       try {
         in.close();
       } catch (IOException e1) {
       }
   }
   return result;
 }
Пример #17
0
 public static void odczytPlikuTekstowegoD() throws IOException {
   // dekrypt
   BufferedWriter writer = new BufferedWriter(new FileWriter("odszyfrowanie.txt"));
   FileInputStream fileInput = new FileInputStream("zaszyfrowany.txt");
   FileInputStream filen = new FileInputStream("n.txt");
   FileInputStream filed = new FileInputStream("d.txt");
   String nfile = "";
   String dfile = "";
   int r;
   while ((r = filen.read()) != -1) {
     nfile += (char) r;
   }
   while ((r = filed.read()) != -1) {
     dfile += (char) r;
   }
   filen.close();
   filed.close();
   // System.out.println(dfile);
   // System.out.println(nfile);
   BigInteger n = new BigInteger(nfile);
   BigInteger d = new BigInteger(dfile);
   String content = new String(Files.readAllBytes(Paths.get("zaszyfrowany.txt")));
   String[] odczytane = content.split(" ");
   for (String o : odczytane) {
     BigInteger wynik = new BigInteger(o).modPow(d, n);
     writer.write(new String(wynik.toByteArray()));
   }
   writer.close();
   fileInput.close();
 }
 @Override
 /** get the binary data from the file. */
 public byte[] getBinaryContent() {
   if (FILEOBJTYPE.equals(getObjType())) {
     FileInputStream fileReader = null;
     try {
       fileReader = new FileInputStream(file);
       byte[] buffer = null;
       if (file != null && file.length() > 0) {
         buffer = new byte[(int) file.length()];
         for (int i = 0; i < buffer.length; i++) {
           buffer[i] = (byte) fileReader.read();
         }
       }
       fileReader.close();
       return buffer;
     } catch (FileNotFoundException e) {
       logger.error("File not found: " + file, e);
       // TODO should we remove the file from the indexes?
     } catch (IOException e) {
       logger.error("Error reading file " + file + ".", e);
     } finally {
       if (fileReader != null) {
         try {
           fileReader.close();
         } catch (IOException e) {
           logger.error("Could not close file: " + file, e);
         }
       }
     }
   }
   return null;
 }
Пример #19
0
  public static byte[] readBytesFromFile(String loc) throws Exception {

    int size;
    byte[] data;
    File file;
    FileInputStream fis = null;

    try {

      size = getFileSize(loc);
      data = new byte[size];

      file = new File(loc);
      fis = new FileInputStream(file);

      fis.read(data);

      fis.close();
      fis = null;

      return data;

    } catch (Exception e) {
      try {
        if (fis != null) fis.close();
        throw e;
      } catch (Exception e1) {
        throw e;
      }
    }
  }
Пример #20
0
  public static void parsePKCS7(String pkcs7Path, String signPath) {
    try {
      File f = new File("test_cert.der");
      FileInputStream is = new FileInputStream(f);
      byte[] cert = new byte[(int) f.length()];
      is.read(cert);
      is.close();

      f = new File("test_signed.bin");
      is = new FileInputStream(f);
      byte[] signedData = new byte[(int) f.length()];
      is.read(signedData);
      is.close();

      f = new File("test.SF");
      is = new FileInputStream(f);
      byte[] signData = new byte[(int) f.length()];
      is.read(signData);
      is.close();

      boolean result = verifySignedData(signData, signedData, cert);
      System.out.println("verified:" + result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #21
0
  public static KeyPair LoadKeyPair(String path, String algorithm)
      throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read Public Key.
    File filePublicKey = new File(path + "/public.key");
    FileInputStream fis = new FileInputStream(path + "/public.key");
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);
    fis.close();

    // Read Private Key.
    File filePrivateKey = new File(path + "/private.key");
    fis = new FileInputStream(path + "/private.key");
    byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
    fis.read(encodedPrivateKey);
    fis.close();

    // Generate KeyPair.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return new KeyPair(publicKey, privateKey);
  }
Пример #22
0
  public static void updatePropertiesFile(
      File propsFile, Map<String, String> values, String comment) throws IOException {
    Properties props = new Properties();
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
      fis = new FileInputStream(propsFile);
      props.load(fis);
      fis.close();
      fis = null;
      props.putAll(values);

      fos = new FileOutputStream(propsFile);
      props.store(fos, comment);
      fos.close();
      fos = null;

    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (Exception ex) {

        }
      }
      if (fos != null) {
        try {
          fos.close();
        } catch (Exception ex) {
        }
      }
    }
  }
Пример #23
0
  private String buildCartFile(String newFileName, String path, byte cartHeader[]) {
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
      fis = new FileInputStream(path);
      File f = new File(newFileName);
      f.createNewFile();
      fos = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      fos.write(cartHeader);

      int bytesRead = 0;
      while ((bytesRead = fis.read(buffer)) > 0) {
        fos.write(buffer, 0, bytesRead);
      }
      fis.close();
      fos.close();
      return newFileName;
    } catch (Throwable e) {
      e.printStackTrace();
      try {
        if (null != fis) fis.close();
        if (null != fos) fos.close();
      } catch (Throwable ee) {
        ee.printStackTrace();
      }
      return null;
    }
  }
Пример #24
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);
  }
Пример #25
0
 public boolean accept(File value) {
   FileInputStream in = null;
   try {
     in = new FileInputStream(value);
   } catch (FileNotFoundException e) {
     return false;
   }
   try {
     long length = in.skip(128l);
     if (length != 128l) {
       in.close();
       return false;
     }
     byte[] read = new byte[4];
     length = in.read(read);
     if (length != 4l) {
       in.close();
       return false;
     }
     String test = new String(read);
     if (test.equalsIgnoreCase("DICM")) {
       in.close();
       return true;
     } else {
       in.close();
       return false;
     }
   } catch (IOException e) {
     log("Error reading file");
     return false;
   }
 }
Пример #26
0
  public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String file1 = reader.readLine();
    String file2 = reader.readLine();

    FileInputStream inputStream1 = new FileInputStream(file1);
    FileInputStream inputStream2 = new FileInputStream(file2);
    ArrayList<Integer> list = new ArrayList<>();
    while (inputStream2.available() > 0) {
      list.add(inputStream2.read());
    }
    while (inputStream1.available() > 0) {
      list.add(inputStream1.read());
    }
    FileOutputStream outputStream = new FileOutputStream(file1);

    for (Integer pair : list) {
      System.out.println(pair);

      outputStream.write(pair);
    }
    reader.close();
    inputStream1.close();
    inputStream2.close();
    outputStream.close();
  }
Пример #27
0
  public static void main(String args[]) throws Exception {
    // 参数
    String cacert = args[0];
    String lfcert = args[1];
    // CA "Xu Yingxiao"的证书
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in1 = new FileInputStream(cacert);
    java.security.cert.Certificate cac = cf.generateCertificate(in1);
    in1.close();
    // 用户"Liu Fang"的签名证书
    FileInputStream in2 = new FileInputStream(lfcert);
    java.security.cert.Certificate lfc = cf.generateCertificate(in2);
    in2.close();

    PublicKey pbk = cac.getPublicKey();
    boolean pass = false;
    try {
      lfc.verify(pbk);
      pass = true;
    } catch (Exception e) {
      pass = false;
      System.out.println(e);
    }
    if (pass) {
      System.out.println("The Certificate is signed by the CA Xu Yingxiao");
    } else {
      System.out.println("!!!The Certificate is not signed by the CA Xu Yingxiao");
    }
  }
Пример #28
0
 public static String readFile(String filename) {
   String s = "";
   FileInputStream in = null;
   // FileReader in = null;
   try {
     File file = new File(filename);
     byte[] buffer = new byte[(int) file.length()];
     // char[] buffer = new char[(int) file.length()];
     in = new FileInputStream(file);
     // in = new FileReader(file);
     in.read(buffer);
     s = new String(buffer);
     in.close();
   } catch (FileNotFoundException fnfx) {
     System.err.println("File not found: " + fnfx);
   } catch (IOException iox) {
     System.err.println("I/O problems: " + iox);
   } finally {
     if (in != null) {
       try {
         in.close();
       } catch (IOException ignore) {
         // ignore
       }
     }
   }
   return s;
 }
Пример #29
0
  /**
   * método que permite generar fichero de metadatos en carpeta separada comprueba si el fichero
   * manifest tiene un lomes integrado o un metadato externo. si el ODE no tiene metadatos.. no
   * genera nada
   */
  private void obtenerLOMES(String lomFileName) throws Exception {
    FileOutputStream fo = null;
    FileInputStream fin = null;
    Writer out = null;
    File lomes = null;
    Template template;
    try {
      if (pathLomesExterno != null) {
        lomes = new File(dirDestino + File.separator + lomFileName);
        if (!lomes.exists()) lomes.createNewFile();
      }

      if (pathLomesExterno != null && pathLomesExterno.equals("")) {
        // tiene lomes y no es un fichero externo adlcp:location
        template = cfg.getTemplate("lomes.ftl");
        cfg.setDefaultEncoding("UTF-8");
        fo = new FileOutputStream(lomes);
        out = new OutputStreamWriter(fo, "UTF-8");
        Environment env = template.createProcessingEnvironment(root, out);
        env.setOutputEncoding("UTF-8");
        env.process();

        out.flush();

      } else if (pathLomesExterno != null
          && !pathLomesExterno.equals(
              "")) { // fichero externo.. por lo que solamente lo copio al destino
        File origen = new File(pathOde + "/" + pathLomesExterno);
        fin = new FileInputStream(origen);
        fo = new FileOutputStream(lomes);
        int c;
        while ((c = fin.read()) >= 0) {
          fo.write(c);
        }
        fin.close();
        fo.close();
        origen = null;
      }
    } catch (Exception e) {
      if (logger.isDebugEnabled()) {
        logger.debug("Error en GeneradorHTML:obtenerLOMES .. " + e.getMessage());
      }
      throw e;
    } finally {
      lomes = null;
      if (fo != null) {
        try {
          fo.close();
        } catch (IOException e) {
        }
      }
      if (fin != null) {
        try {
          fin.close();
        } catch (IOException e) {
        }
      }
    }
  }
  static boolean restoreStoreFrom(File from) {
    String path = context.getDatabasePath(DATABASE_NAME + ".restore").getPath();

    File outDir = new File(path);
    if (!outDir.exists()) outDir.getParentFile().mkdirs();

    FileOutputStream ksOut;
    try {
      ksOut = new FileOutputStream(outDir);
    } catch (FileNotFoundException e) {
      Log.e(TAG, "Cannot open restore temp file for key manager", e);
      return false;
    }

    FileInputStream ksIn;
    try {
      ksIn = new FileInputStream(from);
    } catch (FileNotFoundException e) {
      Log.e(TAG, "Cannot open backup file for restore operation", e);
      return false;
    }

    byte[] buffer = new byte[8 * 1024];
    int read;
    try {
      while ((read = ksIn.read(buffer)) != -1) {
        ksOut.write(buffer, 0, read);
      }
    } catch (IOException e) {
      try {
        ksIn.close();
        ksOut.close();
      } catch (IOException e1) {
        outDir.delete(); // remove temp file in case of problems
        return false;
      }
      outDir.delete();
      return false;
    }
    try {
      ksIn.close();
    } catch (IOException ignore) {
    }

    try {
      ksOut.close();
      //  This may causes a IOEception "bad file number":  ksOut.getFD().sync();
    } catch (IOException e) {
      outDir.delete();
      return false;
    }
    // At this point the restore temp file is ready, rename it to real store file
    if (!outDir.renameTo(context.getDatabasePath(DATABASE_NAME))) {
      Log.e(TAG, "Restore from backup file: rename to key store name failed");
      return false;
    }
    return true;
  }