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

The following examples show how to use java.io.DataInputStream#close() . 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: SingularValueDecompositionTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private void loadRealMatrix(RealMatrix m, String resourceName) {
    try {
        DataInputStream in = new DataInputStream(getClass().getResourceAsStream(resourceName));
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        int row = 0;
        while ((strLine = br.readLine()) != null) {
            int col = 0;
            for (String entry : strLine.split(",")) {
                m.setEntry(row, col++, Double.parseDouble(entry));
            }
            row++;
        }
        in.close();
    } catch (IOException e) {}
}
 
Example 2
Source File: HttpClientConnection.java    From ICERest with Apache License 2.0 6 votes vote down vote up
/**
 * 写入文件到  服务器
 *
 * @param boundary    分隔符
 * @param uploadFiles 文件集合
 * @param writer      写入对象
 * @throws IOException
 */
private void writeUploadFiles(String boundary, Map<String, HttpClientFile> uploadFiles, DataOutputStream writer) throws IOException {
    // file
    HttpClientFile httpClientFile;
    for (String key : uploadFiles.keySet()) {
        httpClientFile = uploadFiles.get(key);
        if (httpClientFile == null) continue;

        writer.write(("\r\n" + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + httpClientFile.getName() + "\"\r\n" + "Content-Type:" + httpClientFile.getContentType() + "\r\n\r\n").getBytes());

        DataInputStream in = new DataInputStream(httpClientFile.getInputStream());
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            writer.write(bufferOut, 0, bytes);
        }
        in.close();
    }
}
 
Example 3
Source File: TestTFileByteArrays.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureGetNonExistentMetaBlock() throws IOException {
  if (skip)
    return;
  writer.append("keyX".getBytes(), "valueX".getBytes());

  // create a new metablock
  DataOutputStream outMeta =
      writer.prepareMetaBlock("testX", Compression.Algorithm.GZ.getName());
  outMeta.write(123);
  outMeta.write("foo".getBytes());
  outMeta.close();
  closeOutput();

  Reader reader = new Reader(fs.open(path), fs.getFileStatus(path).getLen(), conf);
  DataInputStream mb = reader.getMetaBlock("testX");
  Assert.assertNotNull(mb);
  mb.close();
  try {
    DataInputStream mbBad = reader.getMetaBlock("testY");
    Assert.fail("Error on handling non-existent metablocks.");
  } catch (Exception e) {
    // noop, expecting exceptions
  }
  reader.close();
}
 
Example 4
Source File: VisitorTest.java    From Serpent with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testObjectifyDictToClass() throws IOException
{
	Parser p = new Parser();
	File testdatafile = new File("src/test/java/testserpent.utf8.bin");
	byte[] ser = new byte[(int) testdatafile.length()];
	FileInputStream fis=new FileInputStream(testdatafile);
	DataInputStream dis = new DataInputStream(fis);
	dis.readFully(ser);
	dis.close();
	fis.close();
	
	Ast ast = p.parse(ser);
	
	ObjectifyVisitor visitor = new ObjectifyVisitor(new ArithmeticExcFromDict());
	ast.accept(visitor);
	Object thing = visitor.getObject();
	
	Map<Object,Object> dict = (Map<Object,Object>) thing;
	assertEquals(11, dict.size());
	
	ArithmeticException exc = (ArithmeticException) dict.get("exc");
	assertEquals("fault", exc.getMessage());
}
 
Example 5
Source File: BinaryInstaller.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
public static boolean copyFile (InputStream is, File outputFile)
{

    try {
        if (outputFile.exists())
            outputFile.delete();

        boolean newFile = outputFile.createNewFile();
        DataOutputStream out = new DataOutputStream(new FileOutputStream(outputFile));
        DataInputStream in = new DataInputStream(is);

        int b = -1;
        byte[] data = new byte[1024];

        while ((b = in.read(data)) != -1) {
            out.write(data);
        }

        if (b == -1); //rejoice

        //
        out.flush();
        out.close();
        in.close();
        // chmod?

        return newFile;


    } catch (IOException ex) {
        Log.e("Binaryinstaller", "error copying binary", ex);
        return false;
    }

}
 
Example 6
Source File: HtmlWriter.java    From html5index with Apache License 2.0 5 votes vote down vote up
public static void copyFile(String from, String to) throws IOException {
  DataInputStream dis = new DataInputStream(new FileInputStream(from));
  byte[] buf = new byte[(int) new File(from).length()];
  dis.readFully(buf);
  dis.close();
  FileOutputStream fos = new FileOutputStream(to);
  fos.write(buf);
  fos.close();
}
 
Example 7
Source File: Vocabulary.java    From topic-detection with Apache License 2.0 5 votes vote down vote up
public static void main(String[] argv) throws IOException {
	
	File root = new File("/home/manosetro/Desktop/corpus");
	
	Vocabulary vocabulary = new Vocabulary();
	
	for(File doc : root.listFiles()) {
		Set<String> terms = new HashSet<String>();
		FileInputStream fstream = new FileInputStream(doc);
		 
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		
		String line = null;
		while ((line=br.readLine()) != null) {
			StringTokenizer tokenizer = new StringTokenizer(line);
			while(tokenizer.hasMoreTokens())
				terms.add(tokenizer.nextToken());
		}	
		br.close();
		in.close();
		fstream.close();
		System.out.println(doc.getName()+" terms: "+terms.size());
		vocabulary.update(terms.toArray(new String[terms.size()]));
	}

	System.out.println(vocabulary.documents);

}
 
Example 8
Source File: Writables.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Copy one Writable to another.  Copies bytes using data streams.
 * @param bytes Source Writable
 * @param tgt Target Writable
 * @return The target Writable.
 * @throws IOException e
 */
public static Writable copyWritable(final byte [] bytes, final Writable tgt)
throws IOException {
  DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
  try {
    tgt.readFields(dis);
  } finally {
    dis.close();
  }
  return tgt;
}
 
Example 9
Source File: TestDelegationToken.java    From big-c with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void checkTokenIdentifier(UserGroupInformation ugi, final Token<?> token)
    throws Exception {
  Assert.assertNotNull(token);
  // should be able to use token.decodeIdentifier() but webhdfs isn't
  // registered with the service loader for token decoding
  DelegationTokenIdentifier identifier = new DelegationTokenIdentifier();
  byte[] tokenId = token.getIdentifier();
  DataInputStream in = new DataInputStream(new ByteArrayInputStream(tokenId));
  try {
    identifier.readFields(in);
  } finally {
    in.close();
  }
  Assert.assertNotNull(identifier);
  LOG.info("A valid token should have non-null password, and should be renewed successfully");
  Assert.assertTrue(null != dtSecretManager.retrievePassword(identifier));
  dtSecretManager.renewToken((Token<DelegationTokenIdentifier>) token, "JobTracker");
  ugi.doAs(
      new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
          token.renew(config);
          token.cancel(config);
          return null;
        }
      });
}
 
Example 10
Source File: JStaticFile.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
protected void build(OutputStream os) throws IOException {
    DataInputStream dis = new DataInputStream(classLoader.getResourceAsStream(resourceName));

    byte[] buf = new byte[256];
    int sz;
    while( (sz=dis.read(buf))>0 )
        os.write(buf,0,sz);

    dis.close();
}
 
Example 11
Source File: FixedByteWidthRowColDataFileWriterTest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiCol()
    throws Exception {

  File file = new File("test_single_col_writer.dat");
  file.delete();
  int rows = 100;
  int cols = 2;
  int[] columnSizes = new int[]{4, 4};
  FixedByteSingleValueMultiColWriter writer = new FixedByteSingleValueMultiColWriter(file, rows, cols, columnSizes);
  int[][] data = new int[rows][cols];
  Random r = new Random();
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      data[i][j] = r.nextInt();
      writer.setInt(i, j, data[i][j]);
    }
  }
  writer.close();
  DataInputStream dis = new DataInputStream(new FileInputStream(file));
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      Assert.assertEquals(dis.readInt(), data[i][j]);
    }
  }
  dis.close();
  file.delete();
}
 
Example 12
Source File: PluginWrapperHelper.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
public List<PluginWrapper> generatePluginWrappers() {
	List<PluginWrapper> mapList = new ArrayList<PluginWrapper>();
	File pluginWorkspaceDir = new File(pluginWorkspace);
	for (File file : pluginWorkspaceDir.listFiles()) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			if (file.isDirectory() && !file.isHidden() && !file.getName().equals("tempCompressedPluginFileRepository")) {// avoid .svn dir and temp repository
				String configFilePath = file.getAbsolutePath() + "//config.conf";

				FileInputStream fileInpuStream = new FileInputStream(configFilePath);
				DataInputStream dataInputStream = new DataInputStream(fileInpuStream);
				BufferedReader bufferReader = new BufferedReader(new InputStreamReader(dataInputStream));
				String strLine;
				//Read File Line By Line
				while ((strLine = bufferReader.readLine()) != null) {
					addToMap(strLine, map);
				}
				//Close resource
				bufferReader.close();
				dataInputStream.close();
				fileInpuStream.close();
				PluginWrapper pluginWrapper = new PluginWrapper(file.getAbsolutePath(), map);
				mapList.add(pluginWrapper);
			}
		} catch (Exception e) {//Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}
	return mapList;
}
 
Example 13
Source File: CCQuantifierDataManager.java    From jatecs with GNU General Public License v3.0 5 votes vote down vote up
public IQuantifier read(IStorageManager storageManager, String modelName) {
    IClassifier classifier = classifierDataManager.read(storageManager,
            modelName + classifierSuffix);
    IClassifierRuntimeCustomizer customizer = classifierDataManager
            .readClassifierRuntimeConfiguration(storageManager, modelName
                    + classifierSuffix);
    DataInputStream reader = new DataInputStream(
            storageManager.getInputStreamForResource(modelName
                    + thresholdSuffix));
    try {
        boolean perDocument = reader.readBoolean();
        ClassificationMode classificationMode = ClassificationMode.PER_DOCUMENT;
        if (perDocument) {
            classificationMode = ClassificationMode.PER_DOCUMENT;
        } else {
            classificationMode = ClassificationMode.PER_DOCUMENT;
        }
        boolean hasThresholds = reader.readBoolean();
        if (hasThresholds) {
            TShortDoubleHashMap thresholds = new TShortDoubleHashMap();
            int count = reader.readInt();
            for (int i = 0; i < count; ++i) {
                short cat = reader.readShort();
                double value = reader.readDouble();
                thresholds.put(cat, value);
            }
            reader.close();
            return new CCQuantifier(classifier, customizer,
                    classificationMode, thresholds);
        } else {
            reader.close();
            return new CCQuantifier(classifier, customizer,
                    classificationMode);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 14
Source File: RecordFromBinaryFileCreator.java    From kieker with Apache License 2.0 5 votes vote down vote up
/**
 * Create records from binary files.
 *
 * @param binaryFile
 *            binary file input, only used for logging info
 * @param inputStream
 *            data stream
 * @param outputPort
 *            filter output port
 * @throws IOException
 *             on io errors during reading
 * @throws MonitoringRecordException
 *             on deserialization issues
 */
public void createRecordsFromBinaryFile(final File binaryFile, final DataInputStream inputStream,
		final OutputPort<IMonitoringRecord> outputPort) throws IOException, MonitoringRecordException {
	RecordFromBinaryFileCreator.LOGGER.info("reading file {}", binaryFile.getAbsolutePath());

	final ReaderRegistry<String> registry = this.classNameRegistryRepository.get(binaryFile.getParentFile());

	final BinaryValueDeserializer deserializer = BinaryValueDeserializer.create(this.buffer, registry);

	boolean endOfStreamReached = false;
	while (!endOfStreamReached) {
		byte[] bytes = this.buffer.array();
		int bytesRead = inputStream.read(bytes, this.buffer.position(), this.buffer.remaining());
		this.buffer.position(this.buffer.position() + bytesRead);
		while (bytesRead > 0) {
			bytes = this.buffer.array();
			bytesRead = inputStream.read(bytes, this.buffer.position(), this.buffer.remaining());
			if (bytesRead >= 0) {
				this.buffer.position(this.buffer.position() + bytesRead);
			}
		}
		if (bytesRead == -1) {
			endOfStreamReached = true;
		}

		this.processBuffer(registry, deserializer, outputPort);

		if (endOfStreamReached) {
			inputStream.close();
		}
	}

}
 
Example 15
Source File: GeometryRTree.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void load(File path) {
    clear();

    if (!path.exists()) {
        return;
    }

    mPath = path;

    try {
        FileInputStream fileInputStream = new FileInputStream(path);
        DataInputStream dataInputStream = new DataInputStream(fileInputStream);

        maxEntries = dataInputStream.readInt();
        minEntries = dataInputStream.readInt();
        size = dataInputStream.readInt();

        dataInputStream.readBoolean();
        root = new Node();
        root.read(dataInputStream);

        dataInputStream.close();
        fileInputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 16
Source File: ContainerLocalizer.java    From big-c with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public int runLocalization(final InetSocketAddress nmAddr)
    throws IOException, InterruptedException {
  // load credentials
  initDirs(conf, user, appId, lfs, localDirs);
  final Credentials creds = new Credentials();
  DataInputStream credFile = null;
  try {
    // assume credentials in cwd
    // TODO: Fix
    Path tokenPath =
        new Path(String.format(TOKEN_FILE_NAME_FMT, localizerId));
    credFile = lfs.open(tokenPath);
    creds.readTokenStorageStream(credFile);
    // Explicitly deleting token file.
    lfs.delete(tokenPath, false);      
  } finally  {
    if (credFile != null) {
      credFile.close();
    }
  }
  // create localizer context
  UserGroupInformation remoteUser =
    UserGroupInformation.createRemoteUser(user);
  remoteUser.addToken(creds.getToken(LocalizerTokenIdentifier.KIND));
  final LocalizationProtocol nodeManager =
      remoteUser.doAs(new PrivilegedAction<LocalizationProtocol>() {
        @Override
        public LocalizationProtocol run() {
          return getProxy(nmAddr);
        }
      });

  // create user context
  UserGroupInformation ugi =
    UserGroupInformation.createRemoteUser(user);
  for (Token<? extends TokenIdentifier> token : creds.getAllTokens()) {
    ugi.addToken(token);
  }

  ExecutorService exec = null;
  try {
    exec = createDownloadThreadPool();
    CompletionService<Path> ecs = createCompletionService(exec);
    localizeFiles(nodeManager, ecs, ugi);
    return 0;
  } catch (Throwable e) {
    // Print traces to stdout so that they can be logged by the NM address
    // space.
    e.printStackTrace(System.out);
    return -1;
  } finally {
    try {
      if (exec != null) {
        exec.shutdownNow();
      }
      LocalDirAllocator.removeContext(appCacheDirContextName);
    } finally {
      closeFileSystems(ugi);
    }
  }
}
 
Example 17
Source File: ScanAndClearUnusedResource.java    From ScanUnusedResouce with Apache License 2.0 4 votes vote down vote up
private static void readContantsInClass(InputStream is, StringBuilder sb) throws IOException {
       DataInputStream dis = new DataInputStream(is);
       int magic = 0xCAFEBABE;
       if (!(magic == dis.readInt())) {
           dis.close();
           return;
       }

       dis.readShort(); //minor_version
       dis.readShort();//major_version
       int constant_pool_count = dis.readShort();

/*		常量池中数据项类型		类型标志 	类型描述
           CONSTANT_Utf8				1		UTF-8编码的Unicode字符串
		CONSTANT_Integer			3		int类型字面值
		CONSTANT_Float				4		float类型字面值
		CONSTANT_Long				5		long类型字面值
		CONSTANT_Double				6		double类型字面值
		CONSTANT_Class				7		对一个类或接口的符号引用
		CONSTANT_String	            8		String类型字面值
		CONSTANT_Fieldref			9		对一个字段的符号引用
		CONSTANT_Methodref			10		对一个类中声明的方法的符号引用
		CONSTANT_InterfaceMethodref	11		对一个接口中声明的方法的符号引用
		CONSTANT_NameAndType		12		对一个字段或方法的部分符号引用
 */
       for (int i = 1; i < constant_pool_count; i++) { // 常量池
           int tag = dis.readByte();
           switch (tag) {
               case 1: //CONSTANT_Utf8
                   short len = dis.readShort();
                   if (len < 0) {
                       System.out.println("len " + len);
                       continue;
                   }
                   byte[] bs = new byte[len];
                   dis.read(bs);
                   pln(new String(bs), sb);
                   continue;
               case 3: //CONSTANT_Integer
                   int v_int = dis.readInt();
                   pln(v_int, sb);
                   continue;
               case 4: //CONSTANT_Float
                   float v_float = dis.readFloat();
                   pln(v_float, sb);
                   continue;
               case 5: //CONSTANT_Long
                   long v_long = dis.readLong();
                   pln(v_long, sb);
                   continue;
               case 6: //CONSTANT_Double
                   double v_double = dis.readDouble();
                   pln(v_double, sb);
                   continue;
               case 7: //CONSTANT_String
                   dis.readShort();
                   continue;
               case 8: //CONSTANT_String
                   dis.readShort();
                   continue;
               case 9: //CONSTANT_Fieldref_info
                   dis.readShort(); //指向一个CONSTANT_Class_info数据项
                   dis.readShort(); //指向一个CONSTANT_NameAndType_info
                   continue;
               case 10: //CONSTANT_Methodref_info
                   dis.readShort(); //指向一个CONSTANT_Class_info数据项
                   dis.readShort(); //指向一个CONSTANT_NameAndType_info
                   continue;
               case 11: //CONSTANT_InterfaceMethodref_info
                   dis.readShort(); //指向一个CONSTANT_Class_info数据项
                   dis.readShort(); //指向一个CONSTANT_NameAndType_info
                   continue;
               case 12:
                   dis.readShort();
                   dis.readShort();
                   continue;
               default:
                   return;
           }
       }
   }
 
Example 18
Source File: EventInputFormatTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private void doTestRowSerDe(boolean concurrencyChecks) throws Exception {
  getConnection();
  Connection conn = startNetserverAndGetLocalNetConnection();
  final long statTS = System.currentTimeMillis();
  Statement st = conn.createStatement();
  st.execute("create hdfsstore myhdfs namenode 'localhost' homedir '" + HDFS_DIR + "' batchtimeinterval 5000 milliseconds");
  String concurrency = "persistent ENABLE CONCURRENCY CHECKS";
  st.execute("create table app.mytab1 (col1 int primary key, col2 varchar(100)) partition by primary key buckets 1 hdfsstore (myhdfs) "
      +(concurrencyChecks ? concurrency : ""));

  PreparedStatement ps = conn.prepareStatement("insert into mytab1 values (?, ?)");
  ps.setInt(1, 1);
  ps.setString(2, "Value-1");
  ps.execute();
  
  //Wait for data to get to HDFS...
  String qname = HDFSStoreFactoryImpl.getEventQueueName("/APP/MYTAB1");
  st.execute("CALL SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('" + qname + "', 1, 0)");
  
  Configuration conf = new Configuration();
  FileSystem fs = FileSystem.get(conf);
  FileStatus[] list = fs.listStatus(new Path(HDFS_DIR + "/APP_MYTAB1/0/"));
  assertEquals(1, list.length);
  
  conf.set(RowInputFormat.INPUT_TABLE, "MYTAB1");
  conf.set(RowInputFormat.HOME_DIR, HDFS_DIR);
  
  JobConf job = new JobConf(conf);
  job.setBoolean(RowInputFormat.CHECKPOINT_MODE, false);
  RowInputFormat ipformat = new RowInputFormat();
  InputSplit[] splits = ipformat.getSplits(job, 2);
  assertEquals(1, splits.length);
  RecordReader<Key, Row> rr = ipformat.getRecordReader(splits[0], job, null);
  Key key = rr.createKey();
  Row value = rr.createValue();
  assertTrue(rr.next(key, value));
  assertEquals(1, value.getRowAsResultSet().getInt(1));
  assertEquals("Value-1", value.getRowAsResultSet().getString(2));
  assertTrue(value.getTimestamp() > statTS);
  assertFalse(value.getRowAsResultSet().next());
  
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  DataOutputStream dos = new DataOutputStream(baos);
  value.write(dos);
  dos.close();
  
  byte[] buf = baos.toByteArray();
  DataInputStream dis = new DataInputStream(new ByteArrayInputStream(buf));
  Row row = new Row();
  row.readFields(dis);
  dis.close();
  
  assertEquals(1, row.getRowAsResultSet().getInt(1));
  assertEquals("Value-1", row.getRowAsResultSet().getString(2));
  assertFalse(value.getRowAsResultSet().next());
  
  TestUtil.shutDown();
}
 
Example 19
Source File: DerInputStream.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
protected DerValue[] readVector(int startLen) throws IOException {
    DerInputStream  newstr;

    byte lenByte = (byte)buffer.read();
    int len = getLength((lenByte & 0xff), buffer);

    if (len == -1) {
       // indefinite length encoding found
       int readLen = buffer.available();
       int offset = 2;     // for tag and length bytes
       byte[] indefData = new byte[readLen + offset];
       indefData[0] = tag;
       indefData[1] = lenByte;
       DataInputStream dis = new DataInputStream(buffer);
       dis.readFully(indefData, offset, readLen);
       dis.close();
       DerIndefLenConverter derIn = new DerIndefLenConverter();
       buffer = new DerInputBuffer(derIn.convert(indefData));
       if (tag != buffer.read())
            throw new IOException("Indefinite length encoding" +
                    " not supported");
       len = DerInputStream.getLength(buffer);
    }

    if (len == 0)
        // return empty array instead of null, which should be
        // used only for missing optionals
        return new DerValue[0];

    /*
     * Create a temporary stream from which to read the data,
     * unless it's not really needed.
     */
    if (buffer.available() == len)
        newstr = this;
    else
        newstr = subStream(len, true);

    /*
     * Pull values out of the stream.
     */
    Vector<DerValue> vec = new Vector<DerValue>(startLen);
    DerValue value;

    do {
        value = new DerValue(newstr.buffer);
        vec.addElement(value);
    } while (newstr.available() > 0);

    if (newstr.available() != 0)
        throw new IOException("extra data at end of vector");

    /*
     * Now stick them into the array we're returning.
     */
    int             i, max = vec.size();
    DerValue[]      retval = new DerValue[max];

    for (i = 0; i < max; i++)
        retval[i] = vec.elementAt(i);

    return retval;
}
 
Example 20
Source File: MsgDeliver.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * .
 * 
 * @param data
 *            byte[]
 */
public MsgDeliver(byte[] data) {
	if (data.length > 8 + 8 + 21 + 10 + 1 + 1 + 1 + 32 + 1 + 1 + 1 + 20) {// +Msg_length+
		String fmtStr = "gb2312";
		ByteArrayInputStream bins = new ByteArrayInputStream(data);
		DataInputStream dins = new DataInputStream(bins);
		try {
			this.setTotalLength(data.length + 4);
			this.setCommandId(dins.readInt());
			this.setSequenceId(dins.readInt());
			this.msgId = dins.readLong();// Msg_Id
			byte[] destIdByte = new byte[21];
			dins.read(destIdByte);
			this.destId = new String(destIdByte);// 21 目的号码 String
			byte[] service_IdByte = new byte[10];
			dins.read(service_IdByte);
			this.serviceId = new String(service_IdByte);// 10 业务标识 String
			this.tPPid = dins.readByte();
			this.tPUdhi = dins.readByte();
			this.msgFmt = dins.readByte();
			fmtStr = this.msgFmt == 8 ? "utf-8" : "gb2312";
			byte[] src_terminal_IdByte = new byte[32];
			dins.read(src_terminal_IdByte);
			this.srcTerminalId = new String(src_terminal_IdByte);// 源终端MSISDN号码
			this.srcTerminalType = dins.readByte();// 源终端号码类型,0:真实号码;1:伪码
			this.registeredDelivery = dins.readByte();// 是否为状态报告
														// 0:非状态报告1:状态报告
			this.msgLength = dins.readByte();// 消息长度
			byte[] msg_ContentByte = new byte[msgLength];
			dins.read(msg_ContentByte);
			if (registeredDelivery == 1) {
				this.msgContent = new String(msg_ContentByte, fmtStr);// 消息长度
				if (msgLength == 8 + 7 + 10 + 10 + 21 + 4) {
					ByteArrayInputStream binsC = new ByteArrayInputStream(
							data);
					DataInputStream dinsC = new DataInputStream(binsC);
					this.msgIdReport = dinsC.readLong();
					byte[] startByte = new byte[7];
					dinsC.read(startByte);
					this.stat = new String(startByte, fmtStr);
					byte[] submit_timeByte = new byte[10];
					dinsC.read(submit_timeByte);
					this.submitTime = new String(submit_timeByte, fmtStr);
					byte[] done_timeByte = new byte[7];
					dinsC.read(done_timeByte);
					this.doneTime = new String(done_timeByte, fmtStr);
					byte[] dest_terminal_IdByte = new byte[21];
					dinsC.read(dest_terminal_IdByte);
					this.destTerminalId = new String(dest_terminal_IdByte,
							fmtStr);
					this.sMSCSequence = dinsC.readInt();
					dinsC.close();
					binsC.close();
					this.result = 0;// 正确
				} else {
					this.result = 1;// 消息结构错
				}
			} else {
				this.msgContent = new String(msg_ContentByte, fmtStr);// 消息长度
			}
			byte[] linkIDByte = new byte[20];
			this.linkID = new String(linkIDByte);
			this.result = 0;// 正确
			dins.close();
			bins.close();
		} catch (IOException e) {
			this.result = 8;// 消息结构错
		}
	} else {
		this.result = 1;// 消息结构错
		logger.info("短信网关CMPP_DELIVER,解析数据包出错,包长度不一致。长度为:" + data.length);
	}
}