Exemplo n.º 1
0
  public void write(SecureItemTable tbl, char[] password) throws IOException {
    OutputStream os = new FileOutputStream(file);
    OutputStream xmlout;

    if (password.length == 0) {
      xmlout = os;
      os = null;
    } else {
      PBEKeySpec keyspec = new PBEKeySpec(password);
      Cipher c;
      try {
        SecretKeyFactory fac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = fac.generateSecret(keyspec);

        c = Cipher.getInstance("PBEWithMD5AndDES");
        c.init(Cipher.ENCRYPT_MODE, key, pbeSpec);
      } catch (java.security.GeneralSecurityException exc) {
        os.close();
        IOException ioe = new IOException("Security exception during write");
        ioe.initCause(exc);
        throw ioe;
      }

      CipherOutputStream out = new CipherOutputStream(os, c);
      xmlout = out;
    }

    try {
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer t = tf.newTransformer();

      DOMSource src = new DOMSource(tbl.getDocument());
      StringWriter writer = new StringWriter();
      StreamResult sr = new StreamResult(writer);
      t.transform(src, sr);

      OutputStreamWriter osw = new OutputStreamWriter(xmlout, StandardCharsets.UTF_8);
      osw.write(writer.toString());
      osw.close();
    } catch (Exception exc) {
      IOException ioe = new IOException("Unable to serialize XML");
      ioe.initCause(exc);
      throw ioe;
    } finally {
      xmlout.close();
      if (os != null) os.close();
    }

    tbl.setDirty(false);
    return;
  }
  @Override
  public Object resolveObject(Object obj) throws IOException {

    // Until we've identified a remote object, we can't assume the orb is
    // available in the container.  If the orb is not present, this will be null.
    ProtocolManager protocolMgr = getProtocolManager();

    try {
      if ((protocolMgr != null) && protocolMgr.isStub(obj)) {
        protocolMgr.connectObject((Remote) obj);
        return obj;
      } else if (obj instanceof SerializableObjectFactory) {
        return ((SerializableObjectFactory) obj).createObject();
      } else {
        return obj;
      }
    } catch (IOException ioEx) {
      _ejbLogger.log(Level.SEVERE, "ejb.resolve_object_exception", ioEx);
      throw ioEx;
    } catch (Exception ex) {
      _ejbLogger.log(Level.SEVERE, "ejb.resolve_object_exception", ex);
      IOException ioe = new IOException();
      ioe.initCause(ex);
      throw ioe;
    }
  }
  private static void writeOnPrimitive(
      final ObjectOutput out, final Object obj, final ClassMetadataField metaField)
      throws IOException {

    try {
      final Field field = metaField.getField();
      final Class clazz = field.getType();
      if (clazz == Integer.TYPE) {
        out.writeInt(FieldsManager.getFieldsManager().getInt(obj, metaField));
      } else if (clazz == Byte.TYPE) {
        out.writeByte(FieldsManager.getFieldsManager().getByte(obj, metaField));
      } else if (clazz == Long.TYPE) {
        out.writeLong(FieldsManager.getFieldsManager().getLong(obj, metaField));
      } else if (clazz == Float.TYPE) {
        out.writeFloat(FieldsManager.getFieldsManager().getFloat(obj, metaField));
      } else if (clazz == Double.TYPE) {
        out.writeDouble(FieldsManager.getFieldsManager().getDouble(obj, metaField));
      } else if (clazz == Short.TYPE) {
        out.writeShort(FieldsManager.getFieldsManager().getShort(obj, metaField));
      } else if (clazz == Character.TYPE) {
        out.writeChar(field.getChar(obj));
      } else if (clazz == Boolean.TYPE) {
        out.writeBoolean(field.getBoolean(obj));
      } else {
        throw new RuntimeException("Unexpected datatype " + clazz.getName());
      }
    } catch (IllegalAccessException access) {
      IOException io = new IOException(access.getMessage());
      io.initCause(access);
      throw io;
    }
  }
Exemplo n.º 4
0
  /*
   * Generate PBE key
   */
  private SecretKey getPBEKey(char[] password) throws IOException {
    SecretKey skey = null;

    try {
      PBEKeySpec keySpec = new PBEKeySpec(password);
      SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
      skey = skFac.generateSecret(keySpec);
    } catch (Exception e) {
      IOException ioe = new IOException("getSecretKey failed: " + e.getMessage());
      ioe.initCause(e);
      throw ioe;
    }
    return skey;
  }
Exemplo n.º 5
0
  /**
   * Create a new font data element
   *
   * @param ttf The TTF file to read
   * @param size The size of the new font
   * @throws java.io.IOException Indicates a failure to
   */
  private FontData(InputStream ttf, float size) throws IOException {
    if (ttf.available() > MAX_FILE_SIZE) {
      throw new IOException("Can't load font - too big");
    }
    byte[] data = IOUtils.toByteArray(ttf);
    if (data.length > MAX_FILE_SIZE) {
      throw new IOException("Can't load font - too big");
    }

    this.size = size;
    try {
      javaFont = Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(data));
      TTFFile rawFont = new TTFFile();
      if (!rawFont.readFont(new FontFileReader(data))) {
        throw new IOException("Invalid font file");
      }
      upem = rawFont.getUPEM();
      ansiKerning = rawFont.getAnsiKerning();
      charWidth = rawFont.getAnsiWidth();
      fontName = rawFont.getPostScriptName();
      familyName = rawFont.getFamilyName();

      String name = getName();
      System.err.println("Loaded: " + name + " (" + data.length + ")");
      boolean bo = false;
      boolean it = false;
      if (name.indexOf(',') >= 0) {
        name = name.substring(name.indexOf(','));

        if (name.indexOf("Bold") >= 0) {
          bo = true;
        }
        if (name.indexOf("Italic") >= 0) {
          it = true;
        }
      }

      if ((bo & it)) {
        javaFont = javaFont.deriveFont(Font.BOLD | Font.ITALIC);
      } else if (bo) {
        javaFont = javaFont.deriveFont(Font.BOLD);
      } else if (it) {
        javaFont = javaFont.deriveFont(Font.ITALIC);
      }
    } catch (FontFormatException e) {
      IOException x = new IOException("Failed to read font");
      x.initCause(e);
      throw x;
    }
  }
Exemplo n.º 6
0
  /*
   * Generate PBE Algorithm Parameters
   */
  private AlgorithmParameters getAlgorithmParameters(String algorithm) throws IOException {
    AlgorithmParameters algParams = null;

    // create PBE parameters from salt and iteration count
    PBEParameterSpec paramSpec = new PBEParameterSpec(getSalt(), iterationCount);
    try {
      algParams = AlgorithmParameters.getInstance(algorithm);
      algParams.init(paramSpec);
    } catch (Exception e) {
      IOException ioe = new IOException("getAlgorithmParameters failed: " + e.getMessage());
      ioe.initCause(e);
      throw ioe;
    }
    return algParams;
  }
Exemplo n.º 7
0
 /**
  * Visitor method: print expression tree.
  *
  * @param prec The current precedence level.
  */
 public void printExpr(JCTree tree, int prec) throws IOException {
   int prevPrec = this.prec;
   try {
     this.prec = prec;
     if (tree == null) print("/*missing*/");
     else {
       tree.accept(this);
     }
   } catch (UncheckedIOException ex) {
     IOException e = new IOException(ex.getMessage());
     e.initCause(ex);
     throw e;
   } finally {
     this.prec = prevPrec;
   }
 }
 private static void writeSlotWithMethod(
     ClassMetaDataSlot slot,
     ObjectOutput out,
     Object obj,
     ObjectSubstitutionInterface substitution)
     throws IOException {
   try {
     slot.getPrivateMethodWrite()
         .invoke(obj, new Object[] {new ObjectOutputStreamProxy(out, obj, slot, substitution)});
   } catch (IOException e) {
     throw e;
   } catch (Exception e) {
     e.printStackTrace();
     IOException io = new IOException(e.getMessage());
     io.initCause(e);
     throw io;
   }
 }
 private static void readSlotWithMethod(
     ClassMetaDataSlot slot,
     short[] fieldsKey,
     ObjectInput input,
     Object obj,
     ObjectSubstitutionInterface substitution)
     throws IOException {
   try {
     slot.getPrivateMethodRead()
         .invoke(
             obj,
             new Object[] {new ObjectInputStreamProxy(input, fieldsKey, obj, slot, substitution)});
   } catch (IOException e) {
     throw e;
   } catch (Exception e) {
     IOException io = new IOException(e.getMessage());
     io.initCause(e);
     throw io;
   }
 }
Exemplo n.º 10
0
  /** Populates data in this DependencyGrammar from the character stream given by the Reader r. */
  @Override
  public void readData(BufferedReader in) throws IOException {
    final String LEFT = "left";
    int lineNum = 1;
    // all lines have one rule per line
    boolean doingStop = false;

    for (String line = in.readLine(); line != null && line.length() > 0; line = in.readLine()) {
      try {
        if (line.equals("BEGIN_STOP")) {
          doingStop = true;
          continue;
        }
        String[] fields =
            StringUtils.splitOnCharWithQuoting(
                line, ' ', '\"',
                '\\'); // split on spaces, quote with doublequote, and escape with backslash
        //        System.out.println("fields:\n" + fields[0] + "\n" + fields[1] + "\n" + fields[2] +
        // "\n" + fields[3] + "\n" + fields[4] + "\n" + fields[5]);

        short distance = (short) Integer.parseInt(fields[4]);
        IntTaggedWord tempHead = new IntTaggedWord(fields[0], '/', wordIndex, tagIndex);
        IntTaggedWord tempArg = new IntTaggedWord(fields[2], '/', wordIndex, tagIndex);
        IntDependency tempDependency =
            new IntDependency(tempHead, tempArg, fields[3].equals(LEFT), distance);

        double count = Double.parseDouble(fields[5]);
        if (doingStop) {
          expandStop(tempDependency, distance, count, false);
        } else {
          expandArg(tempDependency, distance, count);
        }
      } catch (Exception e) {
        IOException ioe = new IOException("Error on line " + lineNum + ": " + line);
        ioe.initCause(e);
        throw ioe;
      }
      //      System.out.println("read line " + lineNum + ": " + line);
      lineNum++;
    }
  }
Exemplo n.º 11
0
  /**
   * Copies this file to another file. This object is the source file. The destination file is given
   * as the argument. If the destination file, does not exist a new one will be created. Otherwise
   * the source file will be appended to the destination file. Directories will be copied
   * recursively.
   *
   * @param file The file to receive the data.
   * @throws NullPointerException If file is null.
   * @throws IOException If an IOException occurs.
   */
  public void copyTo(GeneralFile file, boolean forceOverwrite) throws IOException {
    if (file == null) {
      throw new NullPointerException();
    }

    if (isDirectory()) {
      // recursive copy
      GeneralFile[] fileList = listFiles();

      file.mkdir();
      if (fileList != null) {
        for (int i = 0; i < fileList.length; i++) {
          fileList[i].copyTo(
              FileFactory.newFile(
                  file.getFileSystem(), file.getAbsolutePath(), fileList[i].getName()),
              forceOverwrite);
        }
      }
    } else {
      if (file.isDirectory()) {
        // change the destination from a directory to a file
        file = FileFactory.newFile(file, getName());
      }
      try {
        if (file instanceof LocalFile) {
          ftpClient.get(getPath(), ((LocalFile) file).getFile());
        } else if (file instanceof FTPFile) {
          ftpClient.transfer(
              getPath(), ((FTPFile) file).getFTPClient(), file.getPath(), !forceOverwrite, null);
        } else {
          super.copyTo(file);
        }
      } catch (FTPException e) {
        IOException io = new IOException();
        io.initCause(e);
        throw io;
      }
    }
  }
Exemplo n.º 12
0
 /*
  * parse Algorithm Parameters
  */
 private AlgorithmParameters parseAlgParameters(DerInputStream in) throws IOException {
   AlgorithmParameters algParams = null;
   try {
     DerValue params;
     if (in.available() == 0) {
       params = null;
     } else {
       params = in.getDerValue();
       if (params.tag == DerValue.tag_Null) {
         params = null;
       }
     }
     if (params != null) {
       algParams = AlgorithmParameters.getInstance("PBE");
       algParams.init(params.toByteArray());
     }
   } catch (Exception e) {
     IOException ioe = new IOException("parseAlgParameters failed: " + e.getMessage());
     ioe.initCause(e);
     throw ioe;
   }
   return algParams;
 }
Exemplo n.º 13
0
  /**
   * Copies this file to another file. This object is the source file. The destination file is given
   * as the argument. If the destination file, does not exist a new one will be created. Otherwise
   * the source file will be appended to the destination file. Directories will be copied
   * recursively.
   *
   * @param file The file to receive the data.
   * @throws NullPointerException If file is null.
   * @throws IOException If an IOException occurs.
   */
  public void copyFrom(GeneralFile file, boolean forceOverwrite) throws IOException {
    if (file == null) {
      throw new NullPointerException();
    }

    if (file.isDirectory()) {
      // recursive copy
      GeneralFile[] fileList = file.listFiles();

      mkdir();
      if (fileList != null) {
        for (int i = 0; i < fileList.length; i++) {
          FileFactory.newFile(this, fileList[i].getName()).copyFrom(fileList[i], forceOverwrite);
        }
      }
    } else {
      if (isDirectory()) {
        // change the destination from a directory to a file
        GeneralFile subFile = FileFactory.newFile(this, file.getName());
        subFile.copyFrom(file);
        return;
      }
      try {
        if (file instanceof LocalFile) {
          ftpClient.put(((LocalFile) file).getFile(), getPath(), !forceOverwrite);
        } else if (file instanceof FTPFile) {
          ftpClient.transfer(file.getPath(), ftpClient, getPath(), !forceOverwrite, null);
        } else {
          super.copyTo(file);
        }
      } catch (FTPException e) {
        IOException io = new IOException();
        io.initCause(e);
        throw io;
      }
    }
  }
Exemplo n.º 14
0
 public static IOException createIOException(Exception e) {
   IOException ioException = new IOException(e.getMessage());
   ioException.initCause(e);
   return ioException;
 }
    /**
     * Opens a connection to the media source of the associated <tt>DataSource</tt>.
     *
     * @throws IOException if anything goes wrong while opening a connection to the media source of
     *     the associated <tt>DataSource</tt>
     */
    public synchronized void connect() throws IOException {
      javax.media.format.AudioFormat af = (javax.media.format.AudioFormat) getFormat();
      int channels = af.getChannels();
      int channelConfig;

      switch (channels) {
        case Format.NOT_SPECIFIED:
        case 1:
          channelConfig = AudioFormat.CHANNEL_IN_MONO;
          break;
        case 2:
          channelConfig = AudioFormat.CHANNEL_IN_STEREO;
          break;
        default:
          throw new IOException("channels");
      }

      int sampleSizeInBits = af.getSampleSizeInBits();
      int audioFormat;

      switch (sampleSizeInBits) {
        case 8:
          audioFormat = AudioFormat.ENCODING_PCM_8BIT;
          break;
        case 16:
          audioFormat = AudioFormat.ENCODING_PCM_16BIT;
          break;
        default:
          throw new IOException("sampleSizeInBits");
      }

      double sampleRate = af.getSampleRate();

      length =
          (int)
              Math.round(
                  20 /* milliseconds */ * (sampleRate / 1000) * channels * (sampleSizeInBits / 8));

      /*
       * Apart from the thread in which #read(Buffer) is executed, use the
       * thread priority for the thread which will create the AudioRecord.
       */
      setThreadPriority();
      try {
        int minBufferSize =
            AudioRecord.getMinBufferSize((int) sampleRate, channelConfig, audioFormat);

        audioRecord =
            new AudioRecord(
                MediaRecorder.AudioSource.DEFAULT,
                (int) sampleRate,
                channelConfig,
                audioFormat,
                Math.max(length, minBufferSize));

        // tries to configure audio effects if available
        configureEffects();
      } catch (IllegalArgumentException iae) {
        IOException ioe = new IOException();

        ioe.initCause(iae);
        throw ioe;
      }

      setThreadPriority = true;
    }