Java Code Examples for java.io.DataInputStream#readUTF()

The following examples show how to use java.io.DataInputStream#readUTF() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DateStrDictionaryTest.java    From kylin with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrite() throws IOException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dataout = new DataOutputStream(bout);
    dict.write(dataout);
    dataout.close();
    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
    DataInputStream datain = new DataInputStream(bin);

    String datePattern = datain.readUTF();
    int baseId = datain.readInt();
    datain.close();

    assertEquals(DateFormat.DEFAULT_DATE_PATTERN, datePattern);
    assertEquals(baseId, 0);
}
 
Example 2
Source File: BundleImpl.java    From ACDD with MIT License 6 votes vote down vote up
BundleImpl(File file) throws Exception {
    long currentTimeMillis = System.currentTimeMillis();
    DataInputStream dataInputStream = new DataInputStream(new FileInputStream(new File(file, "meta")));
    this.location = dataInputStream.readUTF();
    this.currentStartlevel = dataInputStream.readInt();
    this.persistently = dataInputStream.readBoolean();
    dataInputStream.close();

    this.bundleDir = file;
    this.state = BundleEvent.STARTED;
    try {
        this.archive = new BundleArchive(this.location, file);
        resolveBundle(false);
        Framework.bundles.put(this.location, this);
        Framework.notifyBundleListeners(1, this);
        if (Framework.DEBUG_BUNDLES && log.isInfoEnabled()) {
            log.info("Framework: Bundle " + toString() + " loaded. " + (System.currentTimeMillis() - currentTimeMillis) + " ms");
        }
    } catch (Exception e) {
        throw new BundleException("Could not load bundle " + this.location, e.getCause());
    }
}
 
Example 3
Source File: DownloadAction.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Deserializes one action that was serialized with {@link #serializeToStream(DownloadAction,
 * OutputStream)} from the {@code input}, using the {@link Deserializer}s that supports the
 * action's type.
 *
 * <p>The caller is responsible for closing the given {@link InputStream}.
 *
 * @param deserializers {@link Deserializer}s for supported actions.
 * @param input The stream from which to read the action.
 * @return The deserialized action.
 * @throws IOException If there is an IO error reading from {@code input}, or if the action type
 *     isn't supported by any of the {@code deserializers}.
 */
public static DownloadAction deserializeFromStream(
    Deserializer[] deserializers, InputStream input) throws IOException {
  // Don't close the stream as it closes the underlying stream too.
  DataInputStream dataInputStream = new DataInputStream(input);
  String type = dataInputStream.readUTF();
  int version = dataInputStream.readInt();
  for (Deserializer deserializer : deserializers) {
    if (type.equals(deserializer.type) && deserializer.version >= version) {
      return deserializer.readFromStream(version, dataInputStream);
    }
  }
  throw new DownloadException("No deserializer found for:" + type + ", " + version);
}
 
Example 4
Source File: Resources.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
private String[] readImageBorder(DataInputStream input) throws IOException {
    // Read number of images can be 2, 3, 8 or 9
    int size = input.readByte();
    String[] imageBorder = new String[size];
            
    for(int iter = 0 ; iter < size ; iter++) {
        imageBorder[iter] = input.readUTF();
    }
    return imageBorder;
}
 
Example 5
Source File: NTRUEncryptionParameters.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a parameter set from an input stream.
 *
 * @param is an input stream
 * @throws IOException
 */
public NTRUEncryptionParameters(InputStream is)
    throws IOException
{
    DataInputStream dis = new DataInputStream(is);
    N = dis.readInt();
    q = dis.readInt();
    df = dis.readInt();
    df1 = dis.readInt();
    df2 = dis.readInt();
    df3 = dis.readInt();
    db = dis.readInt();
    dm0 = dis.readInt();
    c = dis.readInt();
    minCallsR = dis.readInt();
    minCallsMask = dis.readInt();
    hashSeed = dis.readBoolean();
    oid = new byte[3];
    dis.read(oid);
    sparse = dis.readBoolean();
    fastFp = dis.readBoolean();
    polyType = dis.read();

    String alg = dis.readUTF();

    if ("SHA-512".equals(alg))
    {
        hashAlg = new SHA512Digest();
    }
    else if ("SHA-256".equals(alg))
    {
        hashAlg = new SHA256Digest();
    }

    init();
}
 
Example 6
Source File: DataVectorStore.java    From lesk-wsd-dsm with GNU General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param inputFile
 * @throws IOException
 */
public void init(File inputFile) throws IOException {
    vectors = new HashMap<>();
    DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
    String header = input.readUTF();
    Properties props = readHeader(header);
    if (props == null) {
        vectorType = input.readUTF();
        dimension = input.readInt();
    } else {
        dimension = Integer.parseInt(props.getProperty("-dim"));
        vectorType = props.getProperty("-type");
    }
    ObjectVector.vecLength = dimension;
    int c = 0;
    while (input.available() > 0) {
        String key = input.readUTF();
        float[] v = new float[dimension];
        for (int i = 0; i < dimension; i++) {
            v[i] = input.readFloat();
        }
        vectors.put(key, v);
        c++;
        if (c % 10000 == 0) {
            System.out.print(c + " ");
        }
    }
    input.close();
    logger.log(Level.INFO, "Loaded {0} vectors.", vectors.size());
}
 
Example 7
Source File: CachedContentIndex.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Deserializes a {@link DefaultContentMetadata} from the given input stream.
 *
 * @param input Input stream to read from.
 * @return a {@link DefaultContentMetadata} instance.
 * @throws IOException If an error occurs during reading from the input.
 */
private static DefaultContentMetadata readContentMetadata(DataInputStream input)
    throws IOException {
  int size = input.readInt();
  HashMap<String, byte[]> metadata = new HashMap<>();
  for (int i = 0; i < size; i++) {
    String name = input.readUTF();
    int valueSize = input.readInt();
    if (valueSize < 0) {
      throw new IOException("Invalid value size: " + valueSize);
    }
    // Grow the array incrementally to avoid OutOfMemoryError in the case that a corrupt (and very
    // large) valueSize was read. In such cases the implementation below is expected to throw
    // IOException from one of the readFully calls, due to the end of the input being reached.
    int bytesRead = 0;
    int nextBytesToRead = Math.min(valueSize, INCREMENTAL_METADATA_READ_LENGTH);
    byte[] value = Util.EMPTY_BYTE_ARRAY;
    while (bytesRead != valueSize) {
      value = Arrays.copyOf(value, bytesRead + nextBytesToRead);
      input.readFully(value, bytesRead, nextBytesToRead);
      bytesRead += nextBytesToRead;
      nextBytesToRead = Math.min(valueSize - bytesRead, INCREMENTAL_METADATA_READ_LENGTH);
    }
    metadata.put(name, value);
  }
  return new DefaultContentMetadata(metadata);
}
 
Example 8
Source File: BinaryFS.java    From netbeans with Apache License 2.0 5 votes vote down vote up
final String getString(final ByteBuffer buffer) throws IOException {
    synchronized (strings) {
        int offset = buffer.getInt();
        String t = texts.get(offset);
        if (t != null) {
            return t;
        }
        strings.position(offset);
        String s = DataInputStream.readUTF(this);
        texts.put(offset, s);
        return s;
    }
}
 
Example 9
Source File: RequestSerialUtil.java    From CrossBow with Apache License 2.0 5 votes vote down vote up
public static WearDataRequest deSerializeRequest(byte[] request) throws IOException {
    //decompress the gzipped data
    byte[] deCompressed = Gzipper.unzip(request);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(deCompressed);
    DataInputStream dataStream = new DataInputStream(inputStream);

    //metadata
    String uuid = dataStream.readUTF();

    //byte arrays
    byte[] postBody = SerialUtil.readBytes(dataStream);

    //Strings
    String tag = dataStream.readUTF();
    String url = dataStream.readUTF();
    String bodyType = dataStream.readUTF();
    String cacheKey = dataStream.readUTF();

    //Enum
    Request.Priority priority = Request.Priority.valueOf(dataStream.readUTF());

    //ints
    int timeout = dataStream.readInt();
    int method = dataStream.readInt();
    int retryies = dataStream.readInt();

    //headers
    Map<String, String> headers = SerialUtil.readMap(dataStream);

    //transformer key, bundle
    String transformerKey = dataStream.readUTF();
    ParamsBundle transformerArgs = ParamsBundle.readFromStream(dataStream);
    dataStream.close();

    return new WearDataRequest(method, url, uuid, transformerKey,
            retryies, timeout, cacheKey, tag, bodyType,
            headers, postBody, priority, transformerArgs);
}
 
Example 10
Source File: DictionarySerializer.java    From kylin with Apache License 2.0 5 votes vote down vote up
public static Dictionary<?> deserialize(InputStream inputStream) {
    try {
        final DataInputStream dataInputStream = new DataInputStream(inputStream);
        final String type = dataInputStream.readUTF();
        final Dictionary<?> dictionary = ClassUtil.forName(type, Dictionary.class).getDeclaredConstructor().newInstance();
        dictionary.readFields(dataInputStream);
        return dictionary;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
Source File: CachedContentIndex.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
/**
 * Deserializes a {@link DefaultContentMetadata} from the given input stream.
 *
 * @param input Input stream to read from.
 * @return a {@link DefaultContentMetadata} instance.
 * @throws IOException If an error occurs during reading from the input.
 */
private static DefaultContentMetadata readContentMetadata(DataInputStream input)
    throws IOException {
  int size = input.readInt();
  HashMap<String, byte[]> metadata = new HashMap<>();
  for (int i = 0; i < size; i++) {
    String name = input.readUTF();
    int valueSize = input.readInt();
    if (valueSize < 0) {
      throw new IOException("Invalid value size: " + valueSize);
    }
    // Grow the array incrementally to avoid OutOfMemoryError in the case that a corrupt (and very
    // large) valueSize was read. In such cases the implementation below is expected to throw
    // IOException from one of the readFully calls, due to the end of the input being reached.
    int bytesRead = 0;
    int nextBytesToRead = Math.min(valueSize, INCREMENTAL_METADATA_READ_LENGTH);
    byte[] value = Util.EMPTY_BYTE_ARRAY;
    while (bytesRead != valueSize) {
      value = Arrays.copyOf(value, bytesRead + nextBytesToRead);
      input.readFully(value, bytesRead, nextBytesToRead);
      bytesRead += nextBytesToRead;
      nextBytesToRead = Math.min(valueSize - bytesRead, INCREMENTAL_METADATA_READ_LENGTH);
    }
    metadata.put(name, value);
  }
  return new DefaultContentMetadata(metadata);
}
 
Example 12
Source File: JJJVMConstantPoolImpl.java    From j-j-jvm with Apache License 2.0 4 votes vote down vote up
public JJJVMConstantPoolImpl(final JJJVMClass klazz, final DataInputStream inStream) throws IOException {
  int index = 0;

  this.klazz = klazz;

  int itemsNumber = inStream.readUnsignedShort();
  this.records = new JJJVMConstantPoolItem[itemsNumber];
  this.records[index++] = null;
  itemsNumber--;

  final StringBuilder strBuffer = new StringBuilder(128);

  while (itemsNumber > 0) {
    boolean doubleRecordItem = false;
    final int recordType = inStream.readUnsignedByte();
    final Object recordValue;
    switch (recordType) {
      case JJJVMConstantPoolItem.CONSTANT_UTF8: {
        recordValue = inStream.readUTF();
      }
      break;
      case JJJVMConstantPoolItem.CONSTANT_UNICODE: {
        final int len = inStream.readUnsignedShort();
        for (int i = 0; i < len; i++) {
          char ch_char = (char) inStream.readUnsignedShort();
          strBuffer.append(ch_char);
        }
        recordValue = strBuffer.toString();
        strBuffer.setLength(0);
      }
      break;
      case JJJVMConstantPoolItem.CONSTANT_INTEGER: {
        recordValue = inStream.readInt();
      }
      break;
      case JJJVMConstantPoolItem.CONSTANT_FLOAT: {
        recordValue = inStream.readFloat();
      }
      break;
      case JJJVMConstantPoolItem.CONSTANT_LONG: {
        recordValue = inStream.readLong();
        doubleRecordItem = true;
      }
      break;
      case JJJVMConstantPoolItem.CONSTANT_DOUBLE: {
        recordValue = inStream.readDouble();
        doubleRecordItem = true;
      }
      break;
      case JJJVMConstantPoolItem.CONSTANT_CLASSREF:
      case JJJVMConstantPoolItem.CONSTANT_STRING: {
        recordValue = inStream.readUnsignedShort();
      }
      break;
      case JJJVMConstantPoolItem.CONSTANT_FIELDREF:
      case JJJVMConstantPoolItem.CONSTANT_METHODREF:
      case JJJVMConstantPoolItem.CONSTANT_INTERFACEMETHOD:
      case JJJVMConstantPoolItem.CONSTANT_NAMETYPEREF:
      case JJJVMConstantPoolItem.CONSTANT_METHODHANDLE:
      case JJJVMConstantPoolItem.CONSTANT_INVOKEDYNAMIC: {
        final int high = inStream.readUnsignedShort();
        final int low = inStream.readUnsignedShort();
        recordValue = (high << 16) | low;
      }
      break;
      case JJJVMConstantPoolItem.CONSTANT_METHODTYPE: {
        final int descIndex = inStream.readUnsignedShort();
        recordValue = descIndex;
      }
      break;
      default: {
        throw new IOException("Unsupported constant pool item [" + recordType + ']');
      }
    }

    this.records[index++] = new JJJVMConstantPoolItem(this, recordType, recordValue);
    if (doubleRecordItem) {
      itemsNumber--;
      index++;
    }
    itemsNumber--;
  }
}
 
Example 13
Source File: TzdbZoneRulesProvider.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Loads the rules from a DateInputStream, often in a jar file.
 *
 * @param dis  the DateInputStream to load, not null
 * @throws Exception if an error occurs
 */
private void load(DataInputStream dis) throws Exception {
    if (dis.readByte() != 1) {
        throw new StreamCorruptedException("File format not recognised");
    }
    // group
    String groupId = dis.readUTF();
    if ("TZDB".equals(groupId) == false) {
        throw new StreamCorruptedException("File format not recognised");
    }
    // versions
    int versionCount = dis.readShort();
    for (int i = 0; i < versionCount; i++) {
        versionId = dis.readUTF();
    }
    // regions
    int regionCount = dis.readShort();
    String[] regionArray = new String[regionCount];
    for (int i = 0; i < regionCount; i++) {
        regionArray[i] = dis.readUTF();
    }
    regionIds = Arrays.asList(regionArray);
    // rules
    int ruleCount = dis.readShort();
    Object[] ruleArray = new Object[ruleCount];
    for (int i = 0; i < ruleCount; i++) {
        byte[] bytes = new byte[dis.readShort()];
        dis.readFully(bytes);
        ruleArray[i] = bytes;
    }
    // link version-region-rules
    for (int i = 0; i < versionCount; i++) {
        int versionRegionCount = dis.readShort();
        regionToRules.clear();
        for (int j = 0; j < versionRegionCount; j++) {
            String region = regionArray[dis.readShort()];
            Object rule = ruleArray[dis.readShort() & 0xffff];
            regionToRules.put(region, rule);
        }
    }
}
 
Example 14
Source File: Codec.java    From RichTextFX with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public String decode(DataInputStream is) throws IOException {
    return is.readUTF();
}
 
Example 15
Source File: UploadThread.java    From qingyang with Apache License 2.0 4 votes vote down vote up
private String request(String sourceid) throws IOException {

		DataInputStream in = new DataInputStream(socket.getInputStream());

		DataOutputStream out = new DataOutputStream(socket.getOutputStream());

		String params = "length=" + file.length() + ";filename="
				+ file.getName() + ";sourceid=" + sourceid + ";filePath="
				+ savePath;
		;

		// 发出上传请求
		out.writeUTF(params);

		out.flush();

		// 返回文件字符
		return in.readUTF();

	}
 
Example 16
Source File: QueryService.java    From kylin with Apache License 2.0 4 votes vote down vote up
@Override
public QueryRecord deserialize(DataInputStream in) throws IOException {
    String jsonStr = in.readUTF();
    return JsonUtil.readValue(jsonStr, QueryRecord.class);
}
 
Example 17
Source File: ClassTailor.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Customizes a class file by replacing constant pools.
 *
 * @param image
 *      The image of the template class.
 * @param replacements
 *      A list of pair of strings that specify the substitution
 *      {@code String[]{search_0, replace_0, search_1, replace_1, ..., search_n, replace_n }}
 *
 *      The search strings found in the constant pool will be replaced by the corresponding
 *      replacement string.
 */
public static byte[] tailor( InputStream image, String templateClassName, String newClassName, String... replacements ) {
    DataInputStream in = new DataInputStream(image);

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        DataOutputStream out = new DataOutputStream(baos);

        // skip until the constant pool count
        long l = in.readLong();
        out.writeLong(l);

        // read the constant pool size
        short count = in.readShort();
        out.writeShort(count);

        // replace constant pools
        for( int i=0; i<count; i++ ) {
            byte tag = in.readByte();
            out.writeByte(tag);
            switch(tag) {
            case 0:
                // this isn't described in the spec,
                // but class files often seem to have this '0' tag.
                // we can apparently just ignore it, but not sure
                // what this really means.
                break;

            case 1: // CONSTANT_UTF8
                {
                    String value = in.readUTF();
                    if(value.equals(templateClassName))
                        value = newClassName;
                    else {
                        for( int j=0; j<replacements.length; j+=2 )
                            if(value.equals(replacements[j])) {
                                value = replacements[j+1];
                                break;
                            }
                    }
                    out.writeUTF(value);
                }
            break;

            case 3: // CONSTANT_Integer
            case 4: // CONSTANT_Float
                out.writeInt(in.readInt());
                break;

            case 5: // CONSTANT_Long
            case 6: // CONSTANT_Double
                i++; // doubles and longs take two entries
                out.writeLong(in.readLong());
                break;

            case 7: // CONSTANT_Class
            case 8: // CONSTANT_String
                out.writeShort(in.readShort());
                break;

            case 9: // CONSTANT_Fieldref
            case 10: // CONSTANT_Methodref
            case 11: // CONSTANT_InterfaceMethodref
            case 12: // CONSTANT_NameAndType
                out.writeInt(in.readInt());
                break;

            default:
                throw new IllegalArgumentException("Unknown constant type "+tag);
            }
        }

        // then copy the rest
        byte[] buf = new byte[512];
        int len;
        while((len=in.read(buf))>0)
            out.write(buf,0,len);

        in.close();
        out.close();

        // by now we got the properly tailored class file image
        return baos.toByteArray();

    } catch( IOException e ) {
        // never happen
        logger.log(Level.WARNING,"failed to tailor",e);
        return null;
    }
}
 
Example 18
Source File: UIBuilder.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
private void readCommands(DataInputStream in, Component cmp, Resources res, boolean legacy) throws IOException {
    int commandCount = in.readInt();
    final String[] commandActions = new String[commandCount];
    final Command[] commands = new Command[commandCount];
    final String[] commandArguments = new String[commandCount];
    boolean hasAction = false;
    for(int iter = 0 ; iter < commandCount ; iter++) {
        String commandName = in.readUTF();
        String commandImageName = in.readUTF();
        String rollover = null;
        String pressed = null;
        String disabled = null;
        if(!legacy) {
            rollover = in.readUTF();
            pressed = in.readUTF();
            disabled = in.readUTF();
        }
        int commandId = in.readInt();
        commandActions[iter] = in.readUTF();
        if(commandActions[iter].length() > 0) {
            hasAction = true;
        }
        boolean isBack = in.readBoolean();
        commandArguments[iter] = "";
        if(commandActions[iter].equals("$Execute")) {
            commandArguments[iter] = in.readUTF();
        }
        commands[iter] = createCommandImpl(commandName, res.getImage(commandImageName), commandId, commandActions[iter], isBack, commandArguments[iter]);
        if(rollover != null && rollover.length() > 0) {
            commands[iter].setRolloverIcon(res.getImage(rollover));
        }
        if(pressed != null && pressed.length() > 0) {
            commands[iter].setPressedIcon(res.getImage(pressed));
        }
        if(disabled != null && disabled.length() > 0) {
            commands[iter].setPressedIcon(res.getImage(pressed));
        }
        if(isBack) {
            setBackCommand(((Form)cmp), commands[iter]);
        }
        // trigger listener creation if this is the only command in the form
        getFormListenerInstance(((Form)cmp), null);

        ((Form)cmp).addCommand(commands[iter]);
    }
    if(hasAction) {
        for(int iter = 0 ; iter < commands.length ; iter++) {
            commands[iter].putClientProperty(COMMAND_ARGUMENTS, commandArguments[iter]);
            commands[iter].putClientProperty(COMMAND_ACTION, commandActions[iter]);
        }
        if(resourceFilePath == null || isKeepResourcesInRam()) {
            resourceFile = res;
        }
    }
}
 
Example 19
Source File: CacheDataInput.java    From systemds with Apache License 2.0 4 votes vote down vote up
@Override
public String readUTF() throws IOException {
	return DataInputStream.readUTF(this);
}
 
Example 20
Source File: BackupUtils.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public static String readString(DataInputStream in) throws IOException {
    return (in.readByte() == NOT_NULL) ? in.readUTF() : null;
}