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

The following examples show how to use java.io.DataInputStream#readShort() . 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: GeneratorParametersRecorder.java    From HotswapAgent with GNU General Public License v2.0 6 votes vote down vote up
/**
 * http://stackoverflow.com/questions/1649674/resolve-class-name-from-bytecode
 *
 * @param bytes
 * @return
 * @throws Exception
 */
public static String getClassName(byte[] bytes) throws Exception {
    DataInputStream dis = new DataInputStream(
            new ByteArrayInputStream(bytes));
    dis.readLong(); // skip header and class version
    int cpcnt = (dis.readShort() & 0xffff) - 1;
    int[] classes = new int[cpcnt];
    String[] strings = new String[cpcnt];
    for (int i = 0; i < cpcnt; i++) {
        int t = dis.read();
        if (t == 7)
            classes[i] = dis.readShort() & 0xffff;
        else if (t == 1)
            strings[i] = dis.readUTF();
        else if (t == 5 || t == 6) {
            dis.readLong();
            i++;
        } else if (t == 8)
            dis.readShort();
        else
            dis.readInt();
    }
    dis.readShort(); // skip access flags
    return strings[classes[(dis.readShort() & 0xffff) - 1] - 1].replace('/',
            '.');
}
 
Example 2
Source File: BinaryPListParser.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
    * array	1010 nnnn	[int]	objref*	// nnnn is count, unless '1111', then int count follows
    */
private void parseShortArray(DataInputStream in, int count) throws IOException
{
	BPLArray arr = new BPLArray();
	arr.objectTable = objectTable;
	arr.objref = new int[count];

	for (int i = 0; i < count; i++)
	{
		arr.objref[i] = in.readShort() & 0xffff;
		if (arr.objref[i] == -1)
		{
			throw new IOException("parseShortArray: illegal EOF in objref*"); //$NON-NLS-1$
		}
	}

	objectTable.add(arr);
}
 
Example 3
Source File: ReplicaMetadataRequest.java    From ambry with Apache License 2.0 6 votes vote down vote up
public static ReplicaMetadataRequest readFrom(DataInputStream stream, ClusterMap clusterMap,
    FindTokenHelper findTokenHelper) throws IOException {
  Short versionId = stream.readShort();
  validateVersion(versionId);
  int correlationId = stream.readInt();
  String clientId = Utils.readIntString(stream);
  int replicaMetadataRequestInfoListCount = stream.readInt();
  ArrayList<ReplicaMetadataRequestInfo> replicaMetadataRequestInfoList =
      new ArrayList<ReplicaMetadataRequestInfo>(replicaMetadataRequestInfoListCount);
  for (int i = 0; i < replicaMetadataRequestInfoListCount; i++) {
    ReplicaMetadataRequestInfo replicaMetadataRequestInfo =
        ReplicaMetadataRequestInfo.readFrom(stream, clusterMap, findTokenHelper, versionId);
    replicaMetadataRequestInfoList.add(replicaMetadataRequestInfo);
  }
  long maxTotalSizeOfEntries = stream.readLong();
  // ignore version for now
  return new ReplicaMetadataRequest(correlationId, clientId, replicaMetadataRequestInfoList, maxTotalSizeOfEntries,
      versionId);
}
 
Example 4
Source File: DTD.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private AttributeList readAttributeList(DataInputStream in, String[] names)
                throws IOException  {
        AttributeList result = null;
        for (int num = in.readByte(); num > 0; --num) {
            short nameId = in.readShort();
            int type = in.readByte();
            int modifier = in.readByte();
            short valueId = in.readShort();
            String value = (valueId == -1) ? null : names[valueId];
            Vector<String> values = null;
            short numValues = in.readShort();
            if (numValues > 0) {
                values = new Vector<String>(numValues);
                for (int i = 0; i < numValues; i++) {
                    values.addElement(names[in.readShort()]);
                }
            }
result = new AttributeList(names[nameId], type, modifier, value,
                                       values, result);
            // We reverse the order of the linked list by doing this, but
            // that order isn't important.
        }
        return result;
    }
 
Example 5
Source File: AnnotationIndexTable.java    From java-master with Apache License 2.0 5 votes vote down vote up
public void initAttribute(DataInputStream infoStream, ConstantPool constantPool) throws Exception {
    this.constantPool = constantPool;
    annotationInfoIndex = infoStream.readShort();
    numberOfAnnotationAttributes = infoStream.readShort();
    if (numberOfAnnotationAttributes == 0) {
        return;
    }
    annotationAttributes = new AnnotationAttribute[numberOfAnnotationAttributes];
    for (int i = 0; i < annotationAttributes.length; i++) {
        AnnotationAttribute annotationAttribute = new AnnotationAttribute();
        annotationAttribute.initAttribute(infoStream, constantPool);
        annotationAttributes[i] = annotationAttribute;
    }
}
 
Example 6
Source File: DTD.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private String[] readNameArray(DataInputStream in, String[] names)
            throws IOException {
    int num = in.readShort();
    if (num == 0) {
        return null;
    }
    String[] result = new String[num];
    for (int i = 0; i < num; i++) {
        result[i] = names[in.readShort()];
    }
    return result;
}
 
Example 7
Source File: UndeleteRequest.java    From ambry with Apache License 2.0 5 votes vote down vote up
public static UndeleteRequest readFrom(DataInputStream stream, ClusterMap map) throws IOException {
  Short version = stream.readShort();
  if (version != UNDELETE_REQUEST_VERSION_1) {
    throw new IllegalStateException("Unknown undelete request version " + version);
  }
  int correlationId = stream.readInt();
  String clientId = Utils.readIntString(stream);
  BlobId id = new BlobId(stream, map);
  long operationTimeMs = stream.readLong();
  return new UndeleteRequest(correlationId, clientId, id, operationTimeMs);
}
 
Example 8
Source File: DocumentCacheFile.java    From document-viewer with GNU General Public License v3.0 5 votes vote down vote up
void loadAutoCropping(final DataInputStream in, final boolean docPage, final boolean leftPage)
        throws IOException {
    final int index = in.readShort();
    final SparseArrayEx<PageInfo> target = getPages(docPage, leftPage);
    PageInfo pageInfo = target.get(index, null);
    if (pageInfo == null) {
        pageInfo = new PageInfo(index);
        target.append(index, pageInfo);
    }
    pageInfo.autoCropping = new RectF(in.readFloat(), in.readFloat(), in.readFloat(), in.readFloat());
}
 
Example 9
Source File: PathChange.java    From Spade with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void read(DataInputStream in) throws IOException
{
	change = HistoryIO.create(in.readByte());
	change.read(in);
	colour = in.readInt();
	points = new short[in.readInt()];
	for(int i = 0; i < points.length; i++)
		points[i] = in.readShort();
}
 
Example 10
Source File: AttributeInfo.java    From java-master with Apache License 2.0 5 votes vote down vote up
public static AttributeInfo read(DataInputStream dataInputStream, ConstantPool constantPool) throws Exception {
    short attrNameIndex = dataInputStream.readShort();
    String name = ((ConstantUtf8Info) constantPool.getConstantInfos()[attrNameIndex]).getBytesValue();
    Class<? extends AttributeInfo> attributeTypeClz = AttributeTypeEnum.getAttributeType(name);
    AttributeInfo attributeInfo = attributeTypeClz.getDeclaredConstructor(short.class).newInstance(attrNameIndex);
    attributeInfo.constantPool = constantPool;
    attributeInfo.initAttributeInfo(dataInputStream, constantPool);
    return attributeInfo;
}
 
Example 11
Source File: ABITrace.java    From biojava with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Shuffle the pointers to point to the proper spots in the trace, then load the
 * traces into their arrays.
 */
private void setTraces() {
	int pointers[] = new int[4]; //alphabetical, 0=A, 1=C, 2=G, 3=T
	int datas[] = new int[4];
	char order[] = new char[4];

	datas[0] = DATA9;
	datas[1] = DATA10;
	datas[2] = DATA11;
	datas[3] = DATA12;

	for (int i = 0; i <= 3; i++) {
		order[i] = (char) traceData[FWO + i];
	}

	for (int i = 0; i <= 3; i++) {
		switch (order[i]) {
			case 'A':
			case 'a':
				pointers[0] = datas[i];
				break;
			case 'C':
			case 'c':
				pointers[1] = datas[i];
				break;
			case 'G':
			case 'g':
				pointers[2] = datas[i];
				break;
			case 'T':
			case 't':
				pointers[3] = datas[i];
				break;
			default:
				throw new IllegalArgumentException("Trace contains illegal values.");
		}
	}

	A = new int[traceLength];
	C = new int[traceLength];
	G = new int[traceLength];
	T = new int[traceLength];

	for (int i = 0; i <= 3; i++) {
		byte[] qq = new byte[traceLength * 2];
		getSubArray(qq, pointers[i]);
		DataInputStream dis = new DataInputStream(new ByteArrayInputStream(qq));
		for (int x = 0; x <= traceLength - 1; x++) {
			try {
				if (i == 0) A[x] = (int) dis.readShort();
				if (i == 1) C[x] = (int) dis.readShort();
				if (i == 2) G[x] = (int) dis.readShort();
				if (i == 3) T[x] = (int) dis.readShort();
			} catch (IOException e)//This shouldn't happen. If it does something must be seriously wrong.
			{
				throw new IllegalStateException("Unexpected IOException encountered while manipulating internal streams.");
			}
		}
	}
	return;
}
 
Example 12
Source File: ClassTailor.java    From openjdk-jdk8u 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 13
Source File: SvmDDagSingleLabelDataManager.java    From jatecs with GNU General Public License v3.0 4 votes vote down vote up
@Override
public IClassifier read(IStorageManager storageManager, String modelName) {
    if (storageManager == null)
        throw new NullPointerException("The storage manager is 'null'");
    if (!storageManager.isOpen())
        throw new IllegalStateException("The storage manager is not open");
    if (modelName == null || modelName.isEmpty())
        throw new IllegalArgumentException(
                "The model name is 'null' or empty");

    try {
        SvmDDagSingleLabelClassifier c = new SvmDDagSingleLabelClassifier();
        DataInputStream is = new DataInputStream(new BufferedInputStream(
                storageManager.getInputStreamForResource(modelName
                        + "_index_keys")));
        try {
            int numClassifiers = is.readInt();
            for (int i = 0; i < numClassifiers; i++) {
                short catPositive = is.readShort();
                short catNegative = is.readShort();
                String wtStr = is.readUTF();
                WeightingType wt = WeightingType.valueOf(wtStr);
                String key = LocalClassifier.buildKey(catPositive,
                        catNegative);
                SvmDataManager svmDataManager = new SvmDataManager();
                IClassifier localClassifier = svmDataManager.read(
                        storageManager, modelName + "_" + key + "_svm");

                IContentDB contentDB = TroveReadWriteHelper.readContent(
                        storageManager, modelName + "_" + key
                                + "_contentDB", TroveContentDBType.Full);

                LocalClassifier lc = new LocalClassifier();
                lc.catIDNegative = catNegative;
                lc.catIDPositive = catPositive;
                lc.localClassifier = localClassifier;
                lc.weightingType = wt;
                lc.localContentDB = contentDB;
                c.getLocalClassifiers().put(key, lc);
            }

            return c;
        } finally {
            is.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(
                "Reading SvmDDagSingleLabelClassifier model", e);
    }
}
 
Example 14
Source File: TzdbZoneRulesProvider.java    From openjdk-8-source 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 15
Source File: MockId.java    From ambry with Apache License 2.0 4 votes vote down vote up
public MockId(DataInputStream stream) throws IOException {
  id = Utils.readShortString(stream);
  accountId = stream.readShort();
  containerId = stream.readShort();
}
 
Example 16
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 17
Source File: Table.java    From QNotified with GNU General Public License v3.0 4 votes vote down vote up
public static Table readTable(DataInputStream in) throws IOException {
    Table table = new Table();
    int _f = in.readInt(), _r = in.readInt();
    table.fields = new String[_f];
    table.types = new byte[_f];
    //table.records=new HashMap(_r);
    int i, ii;
    Object fn;
    Object[] recval;
    table.keyType = in.readByte();
    table.keyName = readIStr(in);
    for (ii = 0; ii < _f; ii++) {
        table.types[ii] = in.readByte();
        table.fields[ii] = readIStr(in);
    }
    byte rtype;
    a:
    for (ii = 0; ii < _r; ii++) {
        fn = readTypeAndObj(in);
        recval = new Object[_f];
        for (i = 0; i < _f; i++) {
            rtype = (byte) in.read();
            switch (rtype) {
                case TYPE_VOID:
                    recval[i] = null;
                    break;
                case TYPE_BYTE:
                    recval[i] = (byte) in.read();
                    break;
                case TYPE_BOOL:
                    recval[i] = in.read() != 0;
                    break;
                case TYPE_WCHAR32:
                    recval[i] = in.readInt();
                    break;
                case TYPE_INT:
                    recval[i] = in.readInt();
                    break;
                case TYPE_SHORT:
                    recval[i] = in.readShort();
                    break;
                case TYPE_LONG:
                    recval[i] = in.readLong();
                    break;
                case TYPE_FLOAT:
                    recval[i] = in.readFloat();
                    break;
                case TYPE_DOUBLE:
                    recval[i] = in.readDouble();
                    break;
                case TYPE_IUTF8:
                    recval[i] = readIStr(in);
                    break;
                case TYPE_IRAW:
                    recval[i] = readIRaw(in);
                    break;
                case TYPE_TABLE:
                    recval[i] = readTable(in);
                    break;
                case TYPE_EOF:
                    break a;
                default:
                    throw new IOException("Unexpected type:" + table.types[i] + ",record_name:\"" + fn + "\"");
            }
        }
        table.records.put(fn, recval);
    }
    return table;
}
 
Example 18
Source File: UndoGraphEditState.java    From constellation with Apache License 2.0 4 votes vote down vote up
public UndoGraphEditState(final DataInputStream in) throws Exception {
    operationCount = in.readInt();
    operationStack = new short[operationCount];
    for (int i = 0; i < operationCount; i++) {
        operationStack[i] = in.readShort();
    }

    byteCount = in.readInt();
    byteStack = new byte[byteCount];
    for (int i = 0; i < byteCount; i++) {
        byteStack[i] = in.readByte();
    }

    shortCount = in.readInt();
    shortStack = new short[shortCount];
    for (int i = 0; i < shortCount; i++) {
        shortStack[i] = in.readShort();
    }

    intCount = in.readInt();
    intStack = new int[intCount];
    for (int i = 0; i < intCount; i++) {
        intStack[i] = in.readInt();
    }

    longCount = in.readInt();
    longStack = new long[longCount];
    for (int i = 0; i < longCount; i++) {
        longStack[i] = in.readLong();
    }

    final Map<Integer, Class<?>> classMap = new HashMap<>();
    classMap.put(0, null);

    objectCount = in.readInt();
    byte[] buffer = new byte[1024];
    for (int i = 0; i < objectCount; i++) {
        final int objectClassIndex = in.readInt();
        final Class<?> objectClass;
        if (classMap.containsKey(objectClassIndex)) {
            objectClass = classMap.get(objectClassIndex);
        } else {
            final int classLength = in.readInt();
            if (classLength > buffer.length) {
                buffer = Arrays.copyOf(buffer, classLength);
            }
            in.read(buffer, 0, classLength);
            final String objectName = new String(buffer, 0, classLength, UTF8);
            objectClass = Class.forName(objectName);
        }
        classMap.put(objectClassIndex, objectClass);
        objectMap.put(objectClass, objectClassIndex);
    }

    objectStack = new Object[objectCount];
    Arrays.setAll(objectStack, index -> classMap.get(index));
}
 
Example 19
Source File: SunFileReader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 3 votes vote down vote up
/**
 * rlshort
 * Protected helper method to read 16 bits value. Swap high with low byte.
 * @param DataInputStream
 * @return the swapped value.
 * @exception IOException
 */
final short rlshort(DataInputStream dis)  throws IOException {

    short s=0;
    short high, low;

    s = dis.readShort();

    high = (short)(( s & 0xFF ) << 8) ;
    low = (short)(( s & 0xFF00 ) >>> 8);

    s = (short)( high | low );

    return s;
}
 
Example 20
Source File: SunFileWriter.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * rlshort
 * Protected helper method to read 16 bits value. Swap high with low byte.
 * @return the swapped value.
 * @exception IOException
 */
final short rlshort(DataInputStream dis)  throws IOException {

    short s=0;
    short high, low;

    s = dis.readShort();

    high = (short)(( s & 0xFF ) << 8) ;
    low = (short)(( s & 0xFF00 ) >>> 8);

    s = (short)( high | low );

    return s;
}