List of usage examples for java.nio ByteOrder LITTLE_ENDIAN
ByteOrder LITTLE_ENDIAN
To view the source code for java.nio ByteOrder LITTLE_ENDIAN.
Click Source Link
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
private byte[] encodeActionResponse(UUID uuid, int iconId, String caption) { short length = (short) (29 + caption.getBytes().length); ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length); buf.order(ByteOrder.BIG_ENDIAN); buf.putShort(length);/*from w w w.j ava2s . c om*/ buf.putShort(ENDPOINT_NOTIFICATIONACTION); buf.put(NOTIFICATIONACTION_RESPONSE); buf.putLong(uuid.getMostSignificantBits()); buf.putLong(uuid.getLeastSignificantBits()); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put(NOTIFICATIONACTION_ACK); buf.put((byte) 2); //nr of attributes buf.put((byte) 6); // icon buf.putShort((short) 4); // length buf.putInt(0x80000000 | iconId); buf.put((byte) 2); // title buf.putShort((short) caption.getBytes().length); buf.put(caption.getBytes()); return buf.array(); }
From source file:services.object.ObjectService.java
public void insertOpcodes(Map<Integer, INetworkRemoteEvent> swgOpcodes, Map<Integer, INetworkRemoteEvent> objControllerOpcodes) { swgOpcodes.put(Opcodes.SelectCharacter, new INetworkRemoteEvent() { @Override/* w ww . j av a 2s .c om*/ public void handlePacket(IoSession session, IoBuffer data) throws Exception { data = data.order(ByteOrder.LITTLE_ENDIAN); data.position(0); SelectCharacter selectCharacter = new SelectCharacter(); selectCharacter.deserialize(data); long objectId = selectCharacter.getCharacterId(); Client client = core.getClient(session); if (client == null) { System.err.println("NULL Client"); return; } CreatureObject creature = null; if (objectId != 0L && getObject(objectId) == null) { creature = getCreatureFromDB(objectId); if (creature == null) { System.err.println("Cant get creature from db"); } else { if (creature.getCustomName() == null || creature.getCustomName().isEmpty()) { System.err.println("Name: " + creature.getCustomName()); System.err.println("Player with ObjID of " + creature.getObjectID() + " tried logging in but has a null/empty name!"); return; } else { //System.err.println("SelectCharacter: not in object list"); Because it wasnt added still at this point } } } else { if (!(getObject(objectId) instanceof CreatureObject)) { System.out.println("Character is not an instance of CreatureObject or is null!"); return; } creature = (CreatureObject) getObject(objectId); if (creature.getCustomName() == null || creature.getCustomName().isEmpty()) { System.err.println( "Creature's custom name was null/empty! Name: " + creature.getCustomName()); } if (creature.getAttachment("disconnectTask") != null) ((ScheduledFuture<?>) creature.getAttachment("disconnectTask")).cancel(true); if (creature.getClient() != null) { if (!creature.getClient().getSession().isClosing()) { System.err.println("Character is already disconnecting..."); return; } creature.setClient(null); } } creature.setIntendedTarget(0); creature.setLookAtTarget(0); PlayerObject ghost = (PlayerObject) creature.getSlottedObject("ghost"); if (ghost == null) { System.err.println("The Character's Ghost is null!"); return; } System.out.println("Character '" + creature.getCustomName() + "' now zoning..."); ghost.clearFlagBitmask(PlayerFlags.LD); final CreatureObject finalCreature = creature; creature.viewChildren(creature, true, false, new Traverser() { public void process(SWGObject object) { finalCreature.makeUnaware(object); } }); creature.getAwareObjects().removeAll(creature.getAwareObjects()); creature.setAttachment("disconnectTask", null); creature.setClient(client); Planet planet = core.terrainService.getPlanetByID(creature.getPlanetId()); creature.setPlanet(planet); client.setParent(creature); session.setAttribute("CmdSceneReady", false); objectList.put(creature.getObjectID(), creature); creature.viewChildren(creature, true, true, (object) -> { objectList.put(object.getObjectID(), object); }); creature.viewChildren(creature, true, true, (object) -> { if (object != null) { if (object.getMutex() == null) object.initializeBaselines(); object.initAfterDBLoad(); if (object.getParentId() != 0 && object.getContainer() == null) object.setParent(getObject(object.getParentId())); object.getContainerInfo(object.getTemplate()); // if(getObject(object.getObjectID()) != null) // objectList.put(object.getObjectID(), object); if (!checkIfObjectAlreadyInList(object.getObjectID())) objectList.put(object.getObjectID(), object); } else { Thread.currentThread().dumpStack(); } }); if (creature.getParentId() != 0) { SWGObject parent = getObject(creature.getParentId()); if (parent == null) System.out.println("parentId isn't 0 but getObject(parentId) is null in SelectCharacter"); else if (parent.getContainer() == null) System.out.println("parent.getContainer() is null in SelectCharacter"); else if (parent.getContainer().getTemplate() == null) System.out.println("parent.getContainer().getTemplate() is null in SelectCharacter"); if (parent != null && parent.getContainer() != null && parent.getContainer().getTemplate() != null) System.out.println("Building: " + parent.getContainer().getTemplate()); parent._add(creature); } Point3D position = creature.getPosition(); if (Float.isNaN(position.x) || Float.isNaN(position.y) || Float.isNaN(position.z)) { creature.setPosition(new Point3D(0, 0, 0)); position = creature.getPosition(); } HeartBeatMessage heartBeat = new HeartBeatMessage(); session.write(heartBeat.serialize()); UnkByteFlag unkByteFlag = new UnkByteFlag(); session.write(unkByteFlag.serialize()); core.buffService.clearBuffs(creature); CmdStartScene startScene = new CmdStartScene((byte) 0, objectId, creature.getPlanet().getPath(), creature.getTemplate(), position.x, position.y, position.z, core.getGalacticTime() / 1000, 0); session.write(startScene.serialize()); ChatServerStatus chatServerStatus = new ChatServerStatus(); client.getSession().write(chatServerStatus.serialize()); VoiceChatStatus voiceStatus = new VoiceChatStatus(); client.getSession().write(voiceStatus.serialize()); ParametersMessage parameters = new ParametersMessage(); session.write(parameters.serialize()); ChatOnConnectAvatar chatConnect = new ChatOnConnectAvatar(); creature.getClient().getSession().write(chatConnect.serialize()); creature.makeAware(core.guildService.getGuildObject()); core.chatService.loadMailHeaders(client); core.simulationService.handleZoneIn(client); creature.makeAware(creature); //ChatOnGetFriendsList friendsListMessage = new ChatOnGetFriendsList(ghost); //client.getSession().write(friendsListMessage.serialize()); if (ghost != null) { //ghost.clearFlagBitmask(PlayerFlags.LD); String objectShortName = creature.getCustomName().toLowerCase(); if (creature.getCustomName().contains(" ")) { String[] splitName = creature.getCustomName().toLowerCase().split(" "); objectShortName = splitName[0].toLowerCase(); } core.chatService.playerStatusChange(objectShortName, (byte) 1); if (!ghost.getFriendList().isEmpty()) { // Find out what friends are online/offline for (String friend : ghost.getFriendList()) { SWGObject friendObject = core.objectService.getObjectByFirstName(friend); if (friendObject != null && friendObject.isInQuadtree()) { ChatFriendsListUpdate onlineNotifyStatus = new ChatFriendsListUpdate(friend, (byte) 1); client.getSession().write(onlineNotifyStatus.serialize()); } else { ChatFriendsListUpdate onlineNotifyStatus = new ChatFriendsListUpdate(friend, (byte) 0); client.getSession().write(onlineNotifyStatus.serialize()); } } } List<Integer> joinedChannels = ghost.getJoinedChatChannels(); for (Integer roomId : joinedChannels) { ChatRoom room = core.chatService.getChatRoom(roomId); if (room != null) { core.chatService.joinChatRoom(objectShortName, roomId); } // work-around for any channels that may have been deleted, or only spawn on server startup, that were added to the joined channels else { ghost.removeChannel(roomId); } } } creature.sendSystemMessage(core.getMotd(), DisplayType.Chat); if (creature.getGuildId() != 0) { Guild guild = core.guildService.getGuildById(creature.getGuildId()); if (guild != null && guild.getMembers().containsKey(creature.getObjectID())) { core.guildService.sendGuildMotd(creature, guild); } } if (core.getBountiesODB().contains(creature.getObjectID())) core.missionService.getBountyMap().put(creature.getObjectID(), (BountyListItem) core.getBountiesODB().get(creature.getObjectID())); if (creature.getSlottedObject("datapad") != null) { creature.getSlottedObject("datapad").viewChildren(creature, true, false, new Traverser() { @Override public void process(SWGObject obj) { if (obj instanceof MissionObject) { MissionObject mission = (MissionObject) obj; if (mission.getMissionType().equals("bounty")) { ((BountyMissionObjective) mission.getObjective()).checkBountyActiveStatus(core); } } } }); } // New players that skip tutorial if (creature.getLevel() <= (short) 1) { core.playerService.grantLevel(creature, 5); TangibleObject inventory = (TangibleObject) creature.getSlottedObject("inventory"); if (inventory != null) inventory.add(core.objectService.createObject( "object/tangible/npe/shared_npe_uniform_box.iff", creature.getPlanet())); } core.playerService.postZoneIn(creature); } }); }
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
byte[] encodeInstallMetadata(UUID uuid, String appName, short appVersion, short sdkVersion, int flags, int iconId) { final short METADATA_LENGTH = 126; byte[] name_buf = new byte[96]; System.arraycopy(appName.getBytes(), 0, name_buf, 0, appName.getBytes().length); ByteBuffer buf = ByteBuffer.allocate(METADATA_LENGTH); buf.order(ByteOrder.BIG_ENDIAN); buf.putLong(uuid.getMostSignificantBits()); // watchapp uuid buf.putLong(uuid.getLeastSignificantBits()); buf.order(ByteOrder.LITTLE_ENDIAN); buf.putInt(flags);//from w w w.j ava 2s .com buf.putInt(iconId); buf.putShort(appVersion); buf.putShort(sdkVersion); buf.put((byte) 0); // app_face_bgcolor buf.put((byte) 0); // app_face_template_id buf.put(name_buf); // 96 bytes return encodeBlobdb(uuid, BLOBDB_INSERT, BLOBDB_APP, buf.array()); }
From source file:au.org.ala.layers.intersect.Grid.java
/** * @param points input array for longitude and latitude * double[number_of_points][2] * @return array of .gri file values corresponding to the * points provided// w ww.ja v a 2 s .c om */ public float[] getValues(double[][] points) { //confirm inputs since they come from somewhere else if (points == null || points.length == 0) { return null; } //use preloaded grid data if available Grid g = Grid.getLoadedGrid(filename); if (g != null) { return g.getValues2(points); } if (subgrids != null) { return getValues3(points, Math.min(1024 * 1024, 64 * points.length)); } float[] ret = new float[points.length]; int length = points.length; long size; int i, pos; byte[] b; RandomAccessFile afile = null; File f2 = new File(filename + ".GRI"); try { //read of random access file can throw an exception if (!f2.exists()) { afile = new RandomAccessFile(filename + ".gri", "r"); } else { afile = new RandomAccessFile(filename + ".GRI", "r"); } if (datatype.equalsIgnoreCase("BYTE")) { size = 1; b = new byte[(int) size]; for (i = 0; i < length; i++) { pos = (int) getcellnumber(points[i][0], points[i][1]); if (pos >= 0) { afile.seek(pos * size); ret[i] = afile.readByte(); } else { ret[i] = Float.NaN; } } } else if (datatype.equalsIgnoreCase("UBYTE")) { size = 1; b = new byte[(int) size]; for (i = 0; i < length; i++) { pos = (int) getcellnumber(points[i][0], points[i][1]); if (pos >= 0) { afile.seek(pos * size); ret[i] = afile.readByte(); if (ret[i] < 0) { ret[i] += 256; } } else { ret[i] = Float.NaN; } } } else if (datatype.equalsIgnoreCase("SHORT")) { size = 2; b = new byte[(int) size]; for (i = 0; i < length; i++) { pos = (int) getcellnumber(points[i][0], points[i][1]); if (pos >= 0) { afile.seek(pos * size); afile.read(b); if (byteorderLSB) { ret[i] = (short) (((0xFF & b[1]) << 8) | (b[0] & 0xFF)); } else { ret[i] = (short) (((0xFF & b[0]) << 8) | (b[1] & 0xFF)); } //ret[i] = afile.readShort(); } else { ret[i] = Float.NaN; } } } else if (datatype.equalsIgnoreCase("INT")) { size = 4; b = new byte[(int) size]; for (i = 0; i < length; i++) { pos = (int) getcellnumber(points[i][0], points[i][1]); if (pos >= 0) { afile.seek(pos * size); afile.read(b); if (byteorderLSB) { ret[i] = ((0xFF & b[3]) << 24) | ((0xFF & b[2]) << 16) + ((0xFF & b[1]) << 8) + (b[0] & 0xFF); } else { ret[i] = ((0xFF & b[0]) << 24) | ((0xFF & b[1]) << 16) + ((0xFF & b[2]) << 8) + ((0xFF & b[3]) & 0xFF); } //ret[i] = afile.readInt(); } else { ret[i] = Float.NaN; } } } else if (datatype.equalsIgnoreCase("LONG")) { size = 8; b = new byte[(int) size]; for (i = 0; i < length; i++) { pos = (int) getcellnumber(points[i][0], points[i][1]); if (pos >= 0) { afile.seek(pos * size); afile.read(b); if (byteorderLSB) { ret[i] = ((long) (0xFF & b[7]) << 56) + ((long) (0xFF & b[6]) << 48) + ((long) (0xFF & b[5]) << 40) + ((long) (0xFF & b[4]) << 32) + ((long) (0xFF & b[3]) << 24) + ((long) (0xFF & b[2]) << 16) + ((long) (0xFF & b[1]) << 8) + (0xFF & b[0]); } else { ret[i] = ((long) (0xFF & b[0]) << 56) + ((long) (0xFF & b[1]) << 48) + ((long) (0xFF & b[2]) << 40) + ((long) (0xFF & b[3]) << 32) + ((long) (0xFF & b[4]) << 24) + ((long) (0xFF & b[5]) << 16) + ((long) (0xFF & b[6]) << 8) + (0xFF & b[7]); } //ret[i] = afile.readLong(); } else { ret[i] = Float.NaN; } } } else if (datatype.equalsIgnoreCase("FLOAT")) { size = 4; b = new byte[(int) size]; for (i = 0; i < length; i++) { pos = (int) getcellnumber(points[i][0], points[i][1]); if (pos >= 0) { afile.seek(pos * size); afile.read(b); ByteBuffer bb = ByteBuffer.wrap(b); if (byteorderLSB) { bb.order(ByteOrder.LITTLE_ENDIAN); } ret[i] = bb.getFloat(); } else { ret[i] = Float.NaN; } } } else if (datatype.equalsIgnoreCase("DOUBLE")) { size = 8; b = new byte[8]; for (i = 0; i < length; i++) { pos = (int) getcellnumber(points[i][0], points[i][1]); if (pos >= 0) { afile.seek(pos * size); afile.read(b); ByteBuffer bb = ByteBuffer.wrap(b); if (byteorderLSB) { bb.order(ByteOrder.LITTLE_ENDIAN); } ret[i] = (float) bb.getDouble(); //ret[i] = afile.readFloat(); } else { ret[i] = Float.NaN; } } } else { logger.error("datatype not supported in Grid.getValues: " + datatype); // / should not happen; catch anyway... for (i = 0; i < length; i++) { ret[i] = Float.NaN; } } //replace not a number for (i = 0; i < length; i++) { if ((float) ret[i] == (float) nodatavalue) { ret[i] = Float.NaN; } else { ret[i] *= rescale; } } } catch (Exception e) { logger.error("error getting grid file values", e); } finally { if (afile != null) { try { afile.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } return ret; }
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
public byte[] encodeSetMusicState(byte state, int position, int playRate, byte shuffle, byte repeat) { if (mFwMajor < 3) { return null; }/* w w w.ja v a2 s. c om*/ byte playState; switch (state) { case MusicStateSpec.STATE_PLAYING: playState = MUSICCONTROL_STATE_PLAYING; break; case MusicStateSpec.STATE_PAUSED: playState = MUSICCONTROL_STATE_PAUSED; break; default: playState = MUSICCONTROL_STATE_UNKNOWN; break; } int length = LENGTH_PREFIX + 12; // Encode Prefix ByteBuffer buf = ByteBuffer.allocate(length); buf.order(ByteOrder.BIG_ENDIAN); buf.putShort((short) (length - LENGTH_PREFIX)); buf.putShort(ENDPOINT_MUSICCONTROL); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put(MUSICCONTROL_SETPLAYSTATE); buf.put(playState); buf.putInt(position * 1000); buf.putInt(playRate); buf.put(shuffle); buf.put(repeat); return buf.array(); }
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
@Override public byte[] encodeSetMusicInfo(String artist, String album, String track, int duration, int trackCount, int trackNr) { String[] parts = { artist, album, track }; if (duration == 0 || mFwMajor < 3) { return encodeMessage(ENDPOINT_MUSICCONTROL, MUSICCONTROL_SETMUSICINFO, 0, parts); } else {/*from w ww.ja v a 2 s. co m*/ // Calculate length first int length = LENGTH_PREFIX + 9; if (parts != null) { for (String s : parts) { if (s == null || s.equals("")) { length++; // encode null or empty strings as 0x00 later continue; } length += (1 + s.getBytes().length); } } // Encode Prefix ByteBuffer buf = ByteBuffer.allocate(length); buf.order(ByteOrder.BIG_ENDIAN); buf.putShort((short) (length - LENGTH_PREFIX)); buf.putShort(ENDPOINT_MUSICCONTROL); buf.put(MUSICCONTROL_SETMUSICINFO); // Encode Pascal-Style Strings for (String s : parts) { if (s == null || s.equals("")) { buf.put((byte) 0x00); continue; } int partlength = s.getBytes().length; if (partlength > 255) partlength = 255; buf.put((byte) partlength); buf.put(s.getBytes(), 0, partlength); } buf.order(ByteOrder.LITTLE_ENDIAN); buf.putInt(duration * 1000); buf.putShort((short) (trackCount & 0xffff)); buf.putShort((short) (trackNr & 0xffff)); return buf.array(); } }
From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.DTAFileReader.java
private void parseValueLabelsReleasel108(BufferedInputStream stream) throws IOException { dbgLog.fine("parseValueLabelsRelease108(): start"); if (stream == null) { throw new IllegalArgumentException("stream == null!"); }/*from ww w . j a va 2 s. co m*/ int nvar = dataTable.getVarQuantity().intValue(); int length_label_name = constantTable.get("NAME"); int length_value_label_header = value_label_table_length + length_label_name + VALUE_LABEL_HEADER_PADDING_LENGTH; if (dbgLog.isLoggable(Level.FINE)) { dbgLog.fine("value_label_table_length=" + value_label_table_length); } if (dbgLog.isLoggable(Level.FINE)) { dbgLog.fine("length_value_label_header=" + length_value_label_header); } /* Seg field byte type 1-1. len_vlt(Seg.2) 4 int 1-2. vlt_name 9/33 char+(\0) == name used in Sec2.part 5 1-3. padding 3 byte ----------------------------------- 16/40 2-1. n(# of vls) 4 int 2-2. m(len_labels) 4 int 2-3. label_offsets 4*n int[] 2-4. values 4*n int[] 2-5. labels m char */ // This map will hold a temporary lookup table for all the categorical // value-label groups: // These groups have unique names, and a group *may be shared* between // multiple variables. In the method decodeDescriptorValueLabel above // we have populated a lookup table where variables are linked to the // corresponding value-label groups by name. Thus we must fully populate // the full map of all the variable group, then go through the list // of variables and create the dataverse variable categories from // them. -- L.A. 4.0 Map<String, Map<String, String>> tempValueLabelTable = new LinkedHashMap<>(); for (int i = 0; i < nvar; i++) { if (dbgLog.isLoggable(Level.FINE)) { dbgLog.fine("\n\n" + i + "th value-label table header"); } byte[] valueLabelHeader = new byte[length_value_label_header]; // Part 1: reading the header of a value-label table if exists int nbytes = stream.read(valueLabelHeader, 0, length_value_label_header); if (nbytes == 0) { throw new IOException("reading value label header: no datum"); } // 1.1 length_value_label_table ByteBuffer bb_value_label_header = ByteBuffer.wrap(valueLabelHeader, 0, value_label_table_length); if (isLittleEndian) { bb_value_label_header.order(ByteOrder.LITTLE_ENDIAN); } int length_value_label_table = bb_value_label_header.getInt(); if (dbgLog.isLoggable(Level.FINE)) { dbgLog.fine("length of this value-label table=" + length_value_label_table); } // 1.2 labelName String rawLabelName = new String(Arrays.copyOfRange(valueLabelHeader, value_label_table_length, (value_label_table_length + length_label_name)), "ISO-8859-1"); String labelName = getNullStrippedString(rawLabelName); if (dbgLog.isLoggable(Level.FINE)) { dbgLog.fine("label name = " + labelName + "\n"); } if (dbgLog.isLoggable(Level.FINE)) { dbgLog.fine(i + "-th value-label table"); } // Part 2: reading the value-label table byte[] valueLabelTable_i = new byte[length_value_label_table]; int noBytes = stream.read(valueLabelTable_i, 0, length_value_label_table); if (noBytes == 0) { throw new IOException("reading value label table: no datum"); } // 2-1. 4-byte-integer: number of units in this table (n) int valueLabelTable_offset = 0; ByteBuffer bb_value_label_pairs = ByteBuffer.wrap(valueLabelTable_i, valueLabelTable_offset, value_label_table_length); if (isLittleEndian) { bb_value_label_pairs.order(ByteOrder.LITTLE_ENDIAN); } int no_value_label_pairs = bb_value_label_pairs.getInt(); valueLabelTable_offset += value_label_table_length; if (dbgLog.isLoggable(Level.FINE)) { dbgLog.fine("no_value_label_pairs=" + no_value_label_pairs); } // 2-2. 4-byte-integer: length of the label section (m bytes) ByteBuffer bb_length_label_segment = ByteBuffer.wrap(valueLabelTable_i, valueLabelTable_offset, value_label_table_length); if (isLittleEndian) { bb_length_label_segment.order(ByteOrder.LITTLE_ENDIAN); } int length_label_segment = bb_length_label_segment.getInt(); valueLabelTable_offset += value_label_table_length; // 2-3. 4-byte-integer array (4xm): offset values for the label sec. // these "label offsets" actually appear to represent the byte // offsets of the label strings, as stored in the next section. // as of now, these are not used for anything, and the code // below assumes that the labels are already in the same // order as the numeric values! -- L.A. int[] label_offsets = new int[no_value_label_pairs]; int byte_offset = valueLabelTable_offset; for (int j = 0; j < no_value_label_pairs; j++) { // note: 4-byte singed, not java's long ByteBuffer bb_label_offset = ByteBuffer.wrap(valueLabelTable_i, byte_offset, value_label_table_length); if (isLittleEndian) { bb_label_offset.order(ByteOrder.LITTLE_ENDIAN); dbgLog.fine("label offset: byte reversed"); } label_offsets[j] = bb_label_offset.getInt(); dbgLog.fine("label offset [" + j + "]: " + label_offsets[j]); byte_offset += value_label_table_length; } // 2-4. 4-byte-integer array (4xm): value array (sorted) dbgLog.fine("value array"); int[] valueList = new int[no_value_label_pairs]; int offset_value = byte_offset; for (int k = 0; k < no_value_label_pairs; k++) { ByteBuffer bb_value_list = ByteBuffer.wrap(valueLabelTable_i, offset_value, value_label_table_length); if (isLittleEndian) { bb_value_list.order(ByteOrder.LITTLE_ENDIAN); } valueList[k] = bb_value_list.getInt(); offset_value += value_label_table_length; } // 2-5. m-byte chars that store label data (m units of labels) String label_segment = new String( Arrays.copyOfRange(valueLabelTable_i, offset_value, (length_label_segment + offset_value)), "ISO-8859-1"); // L.A. -- 2011.2.25: // This assumes that the labels are already stored in the right // order: (see my comment for the section 2.3 above) //String[] labelList = label_segment.split("\0"); // Instead, we should be using the offset values obtained in // the section 2.3 above, and select the corresponding // substrings: String[] labelList = new String[no_value_label_pairs]; for (int l = 0; l < no_value_label_pairs; l++) { String lblString = null; int lblOffset = label_offsets[l]; lblString = label_segment.substring(lblOffset); int nullIndx = lblString.indexOf('\000'); if (nullIndx > -1) { lblString = lblString.substring(0, nullIndx); } labelList[l] = lblString; } // this should work! -- L.A. // (TODO: check the v105 value label parsing method, to see if // something similar applies there) // Finally, we've reached the actual value-label pairs. We'll go // through them and put them on the temporary lookup map: tempValueLabelTable.put(labelName, new LinkedHashMap<>()); for (int l = 0; l < no_value_label_pairs; l++) { if (dbgLog.isLoggable(Level.FINE)) { dbgLog.fine(l + "-th pair:" + valueList[l] + "[" + labelList[l] + "]"); } // TODO: do we need any null/empty string checks here? -- L.A. 4.0 tempValueLabelTable.get(labelName).put(Integer.toString(valueList[l]), labelList[l]); } if (stream.available() == 0) { // reached the end of the file dbgLog.fine("reached the end of the file at " + i + "th value-label Table"); break; } } // for nvar loop // And now we can go through the list of variables, see if any have // value-label groups linked, then build dataverse VariableCategory // objects for them, using the values stored in the temporary map // we've just built: // TODO: this code is duplicated between this, and the "105 version" of // this method, above. Maybe it should be isolated in its own method. // -- L.A. 4.0 for (int i = 0; i < nvar; i++) { if (valueLabelsLookupTable[i] != null) { if (tempValueLabelTable.get(valueLabelsLookupTable[i]) != null) { // What if it is null? -- is it a legit condition, that // a variable was advertised as having categorical values, // but no such cat value group exists under this name? // -- L.A. for (String value : tempValueLabelTable.get(valueLabelsLookupTable[i]).keySet()) { VariableCategory cat = new VariableCategory(); cat.setValue(value); cat.setLabel(tempValueLabelTable.get(valueLabelsLookupTable[i]).get(value)); /* cross-link the variable and category to each other: */ cat.setDataVariable(dataTable.getDataVariables().get(i)); dataTable.getDataVariables().get(i).getCategories().add(cat); } } } } dbgLog.fine("parseValueLabelsRelease108(): end"); }
From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.sav.SAVFileReader.java
void decodeRecordType3and4(BufferedInputStream stream) throws IOException { dbgLog.fine("***** decodeRecordType3and4(): start *****"); Map<String, Map<String, String>> valueLabelTable = new LinkedHashMap<String, Map<String, String>>(); int safteyCounter = 0; while (true) { try {/*from www . j ava2 s . com*/ if (stream == null) { throw new IllegalArgumentException("stream == null!"); } // this secton may not exit so first check the 4-byte header value //if (stream.markSupported()){ stream.mark(1000); //} // 3.0 check the first 4 bytes byte[] headerCode = new byte[LENGTH_RECORD_TYPE3_CODE]; int nbytes_rt3 = stream.read(headerCode, 0, LENGTH_RECORD_TYPE3_CODE); // to-do check against nbytes //printHexDump(headerCode, "RT3 header test"); ByteBuffer bb_header_code = ByteBuffer.wrap(headerCode, 0, LENGTH_RECORD_TYPE3_CODE); if (isLittleEndian) { bb_header_code.order(ByteOrder.LITTLE_ENDIAN); } int intRT3test = bb_header_code.getInt(); dbgLog.fine("header test value: RT3=" + intRT3test); if (intRT3test != 3) { //if (stream.markSupported()){ dbgLog.fine("iteration=" + safteyCounter); // We have encountered a record that's not type 3. This means we've // processed all the type 3/4 record pairs. So we want to rewind // the stream and return -- so that the appropriate record type // reader can be called on it. // But before we return, we need to save all the value labels // we have found: smd.setValueLabelTable(valueLabelTable); stream.reset(); return; //} } // 3.1 how many value-label pairs follow byte[] number_of_labels = new byte[LENGTH_RT3_HOW_MANY_LABELS]; int nbytes_3_1 = stream.read(number_of_labels); if (nbytes_3_1 == 0) { throw new IOException("RT 3: reading recordType3.1: no byte was read"); } ByteBuffer bb_number_of_labels = ByteBuffer.wrap(number_of_labels, 0, LENGTH_RT3_HOW_MANY_LABELS); if (isLittleEndian) { bb_number_of_labels.order(ByteOrder.LITTLE_ENDIAN); } int numberOfValueLabels = bb_number_of_labels.getInt(); dbgLog.fine("number of value-label pairs=" + numberOfValueLabels); ByteBuffer[] tempBB = new ByteBuffer[numberOfValueLabels]; String valueLabel[] = new String[numberOfValueLabels]; for (int i = 0; i < numberOfValueLabels; i++) { // read 8-byte as value byte[] value = new byte[LENGTH_RT3_VALUE]; int nbytes_3_value = stream.read(value); if (nbytes_3_value == 0) { throw new IOException("RT 3: reading recordType3 value: no byte was read"); } // note these 8 bytes are interpreted later // currently no information about which variable's (=> type unknown) ByteBuffer bb_value = ByteBuffer.wrap(value, 0, LENGTH_RT3_VALUE); if (isLittleEndian) { bb_value.order(ByteOrder.LITTLE_ENDIAN); } tempBB[i] = bb_value; dbgLog.fine("bb_value=" + Hex.encodeHex(bb_value.array())); /* double valueD = bb_value.getDouble(); dbgLog.fine("value="+valueD); */ // read 1st byte as unsigned integer = label_length // read label_length byte as label byte[] labelLengthByte = new byte[LENGTH_RT3_LABEL_LENGTH]; int nbytes_3_label_length = stream.read(labelLengthByte); // add check-routine here dbgLog.fine("labelLengthByte" + Hex.encodeHex(labelLengthByte)); dbgLog.fine("label length = " + labelLengthByte[0]); // the net-length of a value label is saved as // unsigned byte; however, the length is less than 127 // byte should be ok int rawLabelLength = labelLengthByte[0] & 0xFF; dbgLog.fine("rawLabelLength=" + rawLabelLength); // -1 =>1-byte already read int labelLength = getSAVobsAdjustedBlockLength(rawLabelLength + 1) - 1; byte[] valueLabelBytes = new byte[labelLength]; int nbytes_3_value_label = stream.read(valueLabelBytes); // ByteBuffer bb_label = ByteBuffer.wrap(valueLabel,0,labelLength); valueLabel[i] = StringUtils.stripEnd( new String(Arrays.copyOfRange(valueLabelBytes, 0, rawLabelLength), defaultCharSet), " "); dbgLog.fine(i + "-th valueLabel=" + valueLabel[i] + "<-"); } // iter rt3 dbgLog.fine("end of RT3 block"); dbgLog.fine("start of RT4 block"); // 4.0 check the first 4 bytes byte[] headerCode4 = new byte[LENGTH_RECORD_TYPE4_CODE]; int nbytes_rt4 = stream.read(headerCode4, 0, LENGTH_RECORD_TYPE4_CODE); if (nbytes_rt4 == 0) { throw new IOException("RT4: reading recordType4 value: no byte was read"); } //printHexDump(headerCode4, "RT4 header test"); ByteBuffer bb_header_code_4 = ByteBuffer.wrap(headerCode4, 0, LENGTH_RECORD_TYPE4_CODE); if (isLittleEndian) { bb_header_code_4.order(ByteOrder.LITTLE_ENDIAN); } int intRT4test = bb_header_code_4.getInt(); dbgLog.fine("header test value: RT4=" + intRT4test); if (intRT4test != 4) { throw new IOException("RT 4: reading recordType4 header: no byte was read"); } // 4.1 read the how-many-variables bytes byte[] howManyVariablesfollow = new byte[LENGTH_RT4_HOW_MANY_VARIABLES]; int nbytes_rt4_1 = stream.read(howManyVariablesfollow, 0, LENGTH_RT4_HOW_MANY_VARIABLES); ByteBuffer bb_howManyVariablesfollow = ByteBuffer.wrap(howManyVariablesfollow, 0, LENGTH_RT4_HOW_MANY_VARIABLES); if (isLittleEndian) { bb_howManyVariablesfollow.order(ByteOrder.LITTLE_ENDIAN); } int howManyVariablesRT4 = bb_howManyVariablesfollow.getInt(); dbgLog.fine("how many variables follow: RT4=" + howManyVariablesRT4); int length_indicies = LENGTH_RT4_VARIABLE_INDEX * howManyVariablesRT4; byte[] variableIdicesBytes = new byte[length_indicies]; int nbytes_rt4_2 = stream.read(variableIdicesBytes, 0, length_indicies); // !!!!! Caution: variableIndex in RT4 starts from 1 NOT ** 0 ** int[] variableIndex = new int[howManyVariablesRT4]; int offset = 0; for (int i = 0; i < howManyVariablesRT4; i++) { ByteBuffer bb_variable_index = ByteBuffer.wrap(variableIdicesBytes, offset, LENGTH_RT4_VARIABLE_INDEX); offset += LENGTH_RT4_VARIABLE_INDEX; if (isLittleEndian) { bb_variable_index.order(ByteOrder.LITTLE_ENDIAN); } variableIndex[i] = bb_variable_index.getInt(); dbgLog.fine(i + "-th variable index number=" + variableIndex[i]); } dbgLog.fine("variable index set=" + ArrayUtils.toString(variableIndex)); dbgLog.fine("subtract 1 from variableIndex for getting a variable info"); boolean isNumeric = OBSwiseTypelList.get(variableIndex[0] - 1) == 0 ? true : false; Map<String, String> valueLabelPair = new LinkedHashMap<String, String>(); if (isNumeric) { // numeric variable dbgLog.fine("processing of a numeric value-label table"); for (int j = 0; j < numberOfValueLabels; j++) { valueLabelPair.put(doubleNumberFormatter.format(tempBB[j].getDouble()), valueLabel[j]); } } else { // String variable dbgLog.fine("processing of a string value-label table"); for (int j = 0; j < numberOfValueLabels; j++) { valueLabelPair.put( StringUtils.stripEnd(new String((tempBB[j].array()), defaultCharSet), " "), valueLabel[j]); } } dbgLog.fine("valueLabePair=" + valueLabelPair); dbgLog.fine("key variable's (raw) index =" + variableIndex[0]); valueLabelTable.put(OBSIndexToVariableName.get(variableIndex[0] - 1), valueLabelPair); dbgLog.fine("valueLabelTable=" + valueLabelTable); // create a mapping table that finds the key variable for this mapping table String keyVariableName = OBSIndexToVariableName.get(variableIndex[0] - 1); for (int vn : variableIndex) { valueVariableMappingTable.put(OBSIndexToVariableName.get(vn - 1), keyVariableName); } dbgLog.fine("valueVariableMappingTable:\n" + valueVariableMappingTable); } catch (IOException ex) { //ex.printStackTrace(); throw ex; } safteyCounter++; if (safteyCounter >= 1000000) { break; } } //while smd.setValueLabelTable(valueLabelTable); dbgLog.fine("***** decodeRecordType3and4(): end *****"); }
From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.dta.DTAFileReader.java
void parseValueLabelsRelease105(BufferedInputStream stream) throws IOException { dbgLog.fine("***** parseValueLabelsRelease105(): start *****"); if (stream == null) { throw new IllegalArgumentException("stream == null!"); }/*from w w w. j a v a2 s. co m*/ int nvar = (Integer) smd.getFileInformation().get("varQnty"); int length_label_name = constantTable.get("NAME") + 1; // note: caution +1 as the null character, not 9 byte int length_value_label_header = value_label_table_length + length_label_name; if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("value_label_table_length=" + value_label_table_length); if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("length_value_label_header=" + length_value_label_header); int length_lable_name_field = 8; /* Seg field byte type 1-1. no of pairs 2 int (= m) 1-2. vlt_name 10 includes char+(\0) == name used in Sec2.part 5 ----------------------------------- 11 2-1. values 2*n int[] 2-2. labels 8*n char */ for (int i = 0; i < nvar; i++) { if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("\n\n" + i + "th value-label table header"); byte[] valueLabelHeader = new byte[length_value_label_header]; // Part 1: reading the header of a value-label table if exists int nbytes = stream.read(valueLabelHeader, 0, length_value_label_header); if (nbytes == 0) { throw new IOException("reading value label header: no datum"); } // 1.1 number of value-label pairs in this table (= m) ByteBuffer bb_value_label_pairs = ByteBuffer.wrap(valueLabelHeader, 0, value_label_table_length); if (isLittleEndian) { bb_value_label_pairs.order(ByteOrder.LITTLE_ENDIAN); //if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("value lable table lenth: byte reversed"); } int no_value_label_pairs = bb_value_label_pairs.getShort(); if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("no_value_label_pairs=" + no_value_label_pairs); // 1.2 labelName String rawLabelName = new String(Arrays.copyOfRange(valueLabelHeader, value_label_table_length, (value_label_table_length + length_label_name)), "ISO-8859-1"); if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("rawLabelName(length)=" + rawLabelName.length()); String labelName = rawLabelName.substring(0, rawLabelName.indexOf(0)); if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("label name = " + labelName + "\n"); if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine(i + "-th value-label table"); // Part 2: reading the value-label table // the length of the value-label table is: 2*m + 8*m = 10*m int length_value_label_table = (value_label_table_length + length_lable_name_field) * no_value_label_pairs; if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("length_value_label_table=" + length_value_label_table); byte[] valueLabelTable_i = new byte[length_value_label_table]; int noBytes = stream.read(valueLabelTable_i, 0, length_value_label_table); if (noBytes == 0) { throw new IOException("reading value label table: no datum"); } // 2-1. 2-byte-integer array (2*m): value array (sorted) short[] valueList = new short[no_value_label_pairs]; int offset_value = 0; for (int k = 0; k < no_value_label_pairs; k++) { ByteBuffer bb_value_list = ByteBuffer.wrap(valueLabelTable_i, offset_value, value_label_table_length); if (isLittleEndian) { bb_value_list.order(ByteOrder.LITTLE_ENDIAN); } valueList[k] = bb_value_list.getShort(); offset_value += value_label_table_length; } if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("value_list=" + Arrays.toString(valueList) + "\n"); // 2-2. 8-byte chars that store label data (m units of labels) if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("current offset_value=" + offset_value); int offset_start = offset_value; int offset_end = offset_value + length_lable_name_field; String[] labelList = new String[no_value_label_pairs]; for (int l = 0; l < no_value_label_pairs; l++) { String string_l = new String(Arrays.copyOfRange(valueLabelTable_i, offset_start, offset_end), "ISO-8859-1"); int null_position = string_l.indexOf(0); if (null_position != -1) { labelList[l] = string_l.substring(0, null_position); } else { labelList[l] = string_l; } offset_start = offset_end; offset_end += length_lable_name_field; } Map<String, String> tmpValueLabelTable = new LinkedHashMap<String, String>(); for (int j = 0; j < no_value_label_pairs; j++) { if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine(j + "-th pair:" + valueList[j] + "[" + labelList[j] + "]"); tmpValueLabelTable.put(Integer.toString(valueList[j]), labelList[j]); } valueLabelTable.put(labelName, tmpValueLabelTable); if (stream.available() == 0) { // reached the end of this file // do exit-processing if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("***** reached the end of the file at " + i + "th value-label Table *****"); break; } } // for-loop if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("valueLabelTable:\n" + valueLabelTable); smd.setValueLabelTable(valueLabelTable); dbgLog.fine("***** parseValueLabelsRelease105(): end *****"); }
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
private byte[] encodePhoneVersion3x(byte os) { final short LENGTH_PHONEVERSION3X = 25; ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_PHONEVERSION3X); buf.order(ByteOrder.BIG_ENDIAN); buf.putShort(LENGTH_PHONEVERSION3X); buf.putShort(ENDPOINT_PHONEVERSION); buf.put((byte) 0x01); buf.putInt(-1); //0xffffffff buf.putInt(0);//from w ww . j a v a 2 s . c o m buf.putInt(os); buf.put(PHONEVERSION_APPVERSION_MAGIC); buf.put((byte) 4); // major buf.put((byte) 1); // minor buf.put((byte) 1); // patch buf.order(ByteOrder.LITTLE_ENDIAN); buf.putLong(0x00000000000029af); //flags return buf.array(); }