List of usage examples for java.nio ByteBuffer rewind
public final Buffer rewind()
From source file:com.yobidrive.diskmap.needles.NeedleManager.java
/** Read method for repair routines: reads sequentially the log from the given checkpoint until end of all files. * Last file is truncated after the last valid needle (MAGIC numbers and MD5 OK) * @param needlePointer/*from w w w.j a va 2 s . c om*/ * @param checkPoint No repair will occur for needles <= checkpoint, index should be repaired in this case and checkpoint reseted * @return * @throws NeedleManagerException */ public PointedNeedle readNextNeedleFromDiskInLogSequence(NeedlePointer checkPoint) throws NeedleManagerException { Boolean repairMode = (checkPoint != null); ByteBuffer needleBuffer = null; int retry = 2; // System.out.print("0") ; try { long position = -1L; int readBytes = -1; int totalHeaderReadBytes = 0; FileChannel fc = null; while (retry > 0) { retry--; // System.out.print("a") ; fc = getChannel(repairNeedle.getNeedleFileNumber()); if (fc == null) return null; // System.out.print("b") ; // logger.info("Repairing: reading file "+repairNeedle.toString() ) ; // Position and read needle for check position = repairNeedle.getNeedleOffset(); // System.out.print("c") ; // Acquires a ByteBuffer if (threadBufferQ == null) return null; // System.out.println("1") ; if (needleBuffer == null) needleBuffer = threadBufferQ.take(); // System.out.println("2") ; // Finally we have a buffer needleBuffer.rewind(); needleBuffer.limit(MAXKEYSIZE + MAXVERSIONSIZE + Needle.NEEDLEOVERHEAD); // First read header to know the data size totalHeaderReadBytes = 0; readBytes = 0; while (readBytes >= 0 && totalHeaderReadBytes < needleBuffer.limit()) { readBytes = fc.read(needleBuffer, position + totalHeaderReadBytes); totalHeaderReadBytes += readBytes; } if (totalHeaderReadBytes <= 0) { if (!repairMode) return null; // End of file, select next file if (position == 0 || repairNeedle.positionToNextFile() == null) { // Clean end if (repairNeedle.compareTo(checkPoint) <= 0) { // We should NEVER repair a checkpointed needle. Kill checkpoint and rebuild index! throw new BrokenCheckPointException( "Missing checkpointed record " + repairNeedle.toString()); } return null; } else { // Continue with next file retry = 1; // System.out.println("-") ; logger.info("Reading in sequence: switching to next file, " + repairNeedle.toString()); continue; } } else { // We have our needle (good or bad), do not retry retry = 0; } } Needle needle = new Needle(); if (!needle.getNeedleHeaderFromBuffer(needleBuffer)) { // Incorrect header: truncate file at this position and removes all subsequent files if (!repairMode) return null; if (repairNeedle.compareTo(checkPoint) <= 0) { // We should NEVER repair a checkpointed needle. Kill checkpoint and rebuild index! throw new BrokenCheckPointException("Broken checkpointed record " + repairNeedle.toString()); } truncate(repairNeedle); return null; } // System.out.println("3") ; // Needle Header is OK, read the rest until end of needle. Change limit to include data needleBuffer.position(totalHeaderReadBytes); needleBuffer.limit(needle.getTotalSizeFromData()); readBytes = 0; int totalContentReadBytes = 0; while (readBytes >= 0 && totalContentReadBytes < needleBuffer.limit() - totalHeaderReadBytes) { readBytes = fc.read(needleBuffer, position + totalHeaderReadBytes + totalContentReadBytes); totalContentReadBytes += readBytes; } needleBuffer.rewind(); needleBuffer.position(needle.getHeaderSize()); // Parse data and verifies checksum if (!needle.getNeedleDataFromBuffer(needleBuffer)) { // Incorrect data: truncate file at this position and removes all subsequent files if (!repairMode) return null; if (repairNeedle.compareTo(checkPoint) <= 0) { // We should NEVER repair a checkpointed needle. Kill checkpoint and rebuild index! throw new BrokenCheckPointException("Broken checkpointed record " + repairNeedle.toString()); } // System.out.print("truncate...") ; truncate(repairNeedle); // System.out.print("truncated.") ; return null; } // Now needle is parsed and OK PointedNeedle pn = new PointedNeedle(); pn.setNeedlePointer(repairNeedle.clone()); pn.setNeedle(needle); // System.out.println("4") ; // Put needle in cache needleReadCache.put(pn.getNeedlePointer(), needle); // Put needleHeader in cache needleHeaderReadCache.put(pn.getNeedlePointer(), needle.getNeedleHeader(pn.getNeedlePointer())); repairNeedle.positionToNextNeedle(position + needle.getRoundedTotalSize()); return pn; } catch (Throwable th) { logger.error("Error reading needle at " + repairNeedle.getFormattedNeedleFileNumber() + "/" + repairNeedle.getFormattedNeedleOffset(), th); throw new NeedleManagerException(); } finally { if (needleBuffer != null) { try { threadBufferQ.put(needleBuffer); } catch (InterruptedException ie) { throw new BucketTableManagerException("Error giving back needle read thread", ie); } } } }
From source file:org.openhab.binding.mart.handler.martHandler.java
/** * this function reads from a buffer and writes into a channel * A buffer is essentially a block of memory into which you can write data, which * you can then later read again/*from w w w . j a v a2s . c o m*/ * * @param buffer * @param theChannel */ protected void writer(ByteBuffer buffer, DatagramChannel theChannel) { lock.lock(); try { // represents the key representing the channel's registration with the Selector (selector). SelectionKey theSelectionKey = theChannel.keyFor(selector); // check if the key isn't null if (theSelectionKey != null) { synchronized (selector) { try { // selects a set of keys whose corresponding channels are ready // for I/O operations selector.selectNow(); } catch (IOException e) { logger.error("An exception occured while selecting {}", e.getMessage()); } } // returns this selector's selected-key set Iterator<SelectionKey> iterate = selector.selectedKeys().iterator(); while (iterate.hasNext()) { SelectionKey selectKey = iterate.next(); iterate.remove(); // checks if the key is valid // tests whether this channels is ready for writing // checks whether the current select key is equal to the channel's registered key // with the selector if (selectKey.isValid() && selectKey.isWritable() && selectKey == theSelectionKey) { boolean error = false; // sets the position back to 0, so you can reread all the data in the buffer buffer.rewind(); try { logger.debug("Sending '{}' in the channel '{}'->'{}'", new Object[] { new String(buffer.array()), theChannel.getLocalAddress(), theChannel.getRemoteAddress() }); // www.businessdictionary.com/definition/datagram.html // writes a datagram to this channel theChannel.write(buffer); } catch (NotYetConnectedException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "The remote host is not yet connected"); error = true; } catch (ClosedChannelException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "The connection to the remote host is closed"); error = true; } catch (IOException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "An Io exception occurred"); error = true; } if (error) { try { // closes the channel if it hasn't being closed already theChannel.close(); } catch (Exception e) { logger.warn("An exception occured while closing the channel '{}': {}", datagramChannel, e.getMessage()); } } // re-establish connection onConnectionLost(); } } } } finally { lock.unlock(); } }
From source file:org.apache.hadoop.yarn.client.api.impl.TestYarnClient.java
@Test public void testAutomaticTimelineDelegationTokenLoading() throws Exception { Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true); SecurityUtil.setAuthenticationMethod(AuthenticationMethod.KERBEROS, conf); TimelineDelegationTokenIdentifier timelineDT = new TimelineDelegationTokenIdentifier(); final Token<TimelineDelegationTokenIdentifier> dToken = new Token<TimelineDelegationTokenIdentifier>( timelineDT.getBytes(), new byte[0], timelineDT.getKind(), new Text()); // create a mock client YarnClientImpl client = spy(new YarnClientImpl() { @Override//from w w w.j av a 2 s. c o m TimelineClient createTimelineClient() throws IOException, YarnException { timelineClient = mock(TimelineClient.class); when(timelineClient.getDelegationToken(any(String.class))).thenReturn(dToken); return timelineClient; } @Override protected void serviceStart() throws Exception { rmClient = mock(ApplicationClientProtocol.class); } @Override protected void serviceStop() throws Exception { } @Override public ApplicationReport getApplicationReport(ApplicationId appId) { ApplicationReport report = mock(ApplicationReport.class); when(report.getYarnApplicationState()).thenReturn(YarnApplicationState.RUNNING); return report; } @Override public boolean isSecurityEnabled() { return true; } }); client.init(conf); client.start(); try { // when i == 0, timeline DT already exists, no need to get one more // when i == 1, timeline DT doesn't exist, need to get one more for (int i = 0; i < 2; ++i) { ApplicationSubmissionContext context = mock(ApplicationSubmissionContext.class); ApplicationId applicationId = ApplicationId.newInstance(0, i + 1); when(context.getApplicationId()).thenReturn(applicationId); DataOutputBuffer dob = new DataOutputBuffer(); Credentials credentials = new Credentials(); if (i == 0) { credentials.addToken(client.timelineService, dToken); } credentials.writeTokenStorageToStream(dob); ByteBuffer tokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); ContainerLaunchContext clc = ContainerLaunchContext.newInstance(null, null, null, null, tokens, null); when(context.getAMContainerSpec()).thenReturn(clc); client.submitApplication(context); if (i == 0) { // GetTimelineDelegationToken shouldn't be called verify(client, never()).getTimelineDelegationToken(); } // In either way, token should be there credentials = new Credentials(); DataInputByteBuffer dibb = new DataInputByteBuffer(); tokens = clc.getTokens(); if (tokens != null) { dibb.reset(tokens); credentials.readTokenStorageStream(dibb); tokens.rewind(); } Collection<Token<? extends TokenIdentifier>> dTokens = credentials.getAllTokens(); Assert.assertEquals(1, dTokens.size()); Assert.assertEquals(dToken, dTokens.iterator().next()); } } finally { client.stop(); } }
From source file:x10.x10rt.yarn.ApplicationMaster.java
protected void handleX10() { // handle X10 place requests Iterator<SelectionKey> events = null; while (running) { try {//w w w . jav a 2 s. co m SelectionKey key; // check for previously unhandled events if (events != null && events.hasNext()) { key = events.next(); events.remove(); } else if (selector.select() == 0) // check for new events continue; // nothing to process, go back and block on select again else { // select returned some events events = selector.selectedKeys().iterator(); key = events.next(); events.remove(); } // process the selectionkey if (key.isAcceptable()) { LOG.info("New connection from X10 detected"); // accept any connections on the server socket, and look for things to read from it ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); } if (key.isReadable()) { SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer incomingMsg; if (pendingReads.containsKey(sc)) incomingMsg = pendingReads.remove(sc); else incomingMsg = ByteBuffer.allocateDirect(headerLength).order(ByteOrder.nativeOrder()); LOG.info("Reading message from X10"); try { if (sc.read(incomingMsg) == -1) { // socket closed sc.close(); key.cancel(); pendingReads.remove(sc); } else if (incomingMsg.hasRemaining()) { LOG.info("Message header partially read. " + incomingMsg.remaining() + " bytes remaining"); pendingReads.put(sc, incomingMsg); } else { // buffer is full if (incomingMsg.capacity() == headerLength) { // check to see if there is a body associated with this message header int datalen = incomingMsg.getInt(headerLength - 4); //System.err.println("Byte order is "+incomingMsg.order()+" datalen="+datalen); if (datalen == 0) processMessage(incomingMsg, sc); else { // create a larger array to hold the header+body ByteBuffer newBuffer = ByteBuffer.allocateDirect(headerLength + datalen) .order(ByteOrder.nativeOrder()); incomingMsg.rewind(); newBuffer.put(incomingMsg); incomingMsg = newBuffer; sc.read(incomingMsg); // read in the body, if available if (incomingMsg.hasRemaining()) { LOG.info("Message partially read. " + incomingMsg.remaining() + " bytes remaining"); pendingReads.put(sc, incomingMsg); } else processMessage(incomingMsg, sc); } } } } catch (IOException e) { LOG.warn("Error reading in message from socket channel", e); } } } catch (IOException e) { LOG.warn("Error handling X10 links", e); } } }
From source file:com.healthmarketscience.jackcess.Table.java
/** * Writes a new table defined by the given TableCreator to the database. * @usage _advanced_method_/*from w w w . j a v a2 s .c o m*/ */ protected static void writeTableDefinition(TableCreator creator) throws IOException { // first, create the usage map page createUsageMapDefinitionBuffer(creator); // next, determine how big the table def will be (in case it will be more // than one page) JetFormat format = creator.getFormat(); int idxDataLen = (creator.getIndexCount() * (format.SIZE_INDEX_DEFINITION + format.SIZE_INDEX_COLUMN_BLOCK)) + (creator.getLogicalIndexCount() * format.SIZE_INDEX_INFO_BLOCK); int totalTableDefSize = format.SIZE_TDEF_HEADER + (format.SIZE_COLUMN_DEF_BLOCK * creator.getColumns().size()) + idxDataLen + format.SIZE_TDEF_TRAILER; // total up the amount of space used by the column and index names (2 // bytes per char + 2 bytes for the length) for (Column col : creator.getColumns()) { int nameByteLen = (col.getName().length() * JetFormat.TEXT_FIELD_UNIT_SIZE); totalTableDefSize += nameByteLen + 2; } for (IndexBuilder idx : creator.getIndexes()) { int nameByteLen = (idx.getName().length() * JetFormat.TEXT_FIELD_UNIT_SIZE); totalTableDefSize += nameByteLen + 2; } // now, create the table definition PageChannel pageChannel = creator.getPageChannel(); ByteBuffer buffer = pageChannel.createBuffer(Math.max(totalTableDefSize, format.PAGE_SIZE)); writeTableDefinitionHeader(creator, buffer, totalTableDefSize); if (creator.hasIndexes()) { // index row counts IndexData.writeRowCountDefinitions(creator, buffer); } // column definitions Column.writeDefinitions(creator, buffer); if (creator.hasIndexes()) { // index and index data definitions IndexData.writeDefinitions(creator, buffer); Index.writeDefinitions(creator, buffer); } //End of tabledef buffer.put((byte) 0xff); buffer.put((byte) 0xff); // write table buffer to database if (totalTableDefSize <= format.PAGE_SIZE) { // easy case, fits on one page buffer.putShort(format.OFFSET_FREE_SPACE, (short) (buffer.remaining() - 8)); // overwrite page free space // Write the tdef page to disk. pageChannel.writePage(buffer, creator.getTdefPageNumber()); } else { // need to split across multiple pages ByteBuffer partialTdef = pageChannel.createPageBuffer(); buffer.rewind(); int nextTdefPageNumber = PageChannel.INVALID_PAGE_NUMBER; while (buffer.hasRemaining()) { // reset for next write partialTdef.clear(); if (nextTdefPageNumber == PageChannel.INVALID_PAGE_NUMBER) { // this is the first page. note, the first page already has the // page header, so no need to write it here nextTdefPageNumber = creator.getTdefPageNumber(); } else { // write page header writeTablePageHeader(partialTdef); } // copy the next page of tdef bytes int curTdefPageNumber = nextTdefPageNumber; int writeLen = Math.min(partialTdef.remaining(), buffer.remaining()); partialTdef.put(buffer.array(), buffer.position(), writeLen); ByteUtil.forward(buffer, writeLen); if (buffer.hasRemaining()) { // need a next page nextTdefPageNumber = pageChannel.allocateNewPage(); partialTdef.putInt(format.OFFSET_NEXT_TABLE_DEF_PAGE, nextTdefPageNumber); } // update page free space partialTdef.putShort(format.OFFSET_FREE_SPACE, (short) (partialTdef.remaining() - 8)); // overwrite page free space // write partial page to disk pageChannel.writePage(partialTdef, curTdefPageNumber); } } }
From source file:com.healthmarketscience.jackcess.Table.java
/** * @param buffer Buffer to write to// ww w . ja va 2 s.c o m * @param columns List of Columns in the table */ private static void writeTableDefinitionHeader(TableCreator creator, ByteBuffer buffer, int totalTableDefSize) throws IOException { List<Column> columns = creator.getColumns(); //Start writing the tdef writeTablePageHeader(buffer); buffer.putInt(totalTableDefSize); //Length of table def buffer.putInt(MAGIC_TABLE_NUMBER); // seemingly constant magic value buffer.putInt(0); //Number of rows buffer.putInt(0); //Last Autonumber buffer.put((byte) 1); // this makes autonumbering work in access for (int i = 0; i < 15; i++) { //Unknown buffer.put((byte) 0); } buffer.put(Table.TYPE_USER); //Table type buffer.putShort((short) columns.size()); //Max columns a row will have buffer.putShort(Column.countVariableLength(columns)); //Number of variable columns in table buffer.putShort((short) columns.size()); //Number of columns in table buffer.putInt(creator.getLogicalIndexCount()); //Number of logical indexes in table buffer.putInt(creator.getIndexCount()); //Number of indexes in table buffer.put((byte) 0); //Usage map row number ByteUtil.put3ByteInt(buffer, creator.getUmapPageNumber()); //Usage map page number buffer.put((byte) 1); //Free map row number ByteUtil.put3ByteInt(buffer, creator.getUmapPageNumber()); //Free map page number if (LOG.isDebugEnabled()) { int position = buffer.position(); buffer.rewind(); LOG.debug("Creating new table def block:\n" + ByteUtil.toHexString(buffer, creator.getFormat().SIZE_TDEF_HEADER)); buffer.position(position); } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.TestRMRestart.java
@Test(timeout = 60000) public void testDelegationTokenRestoredInDelegationTokenRenewer() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 2); conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); UserGroupInformation.setConfiguration(conf); MockRM rm1 = new TestSecurityMockRM(conf); Assume.assumeFalse(rm1.getResourceScheduler() instanceof FairScheduler); rm1.start();//from w w w .j av a 2 s . c o m HashSet<Token<RMDelegationTokenIdentifier>> tokenSet = new HashSet<Token<RMDelegationTokenIdentifier>>(); // create an empty credential Credentials ts = new Credentials(); // create tokens and add into credential Text userText1 = new Text("user1"); RMDelegationTokenIdentifier dtId1 = new RMDelegationTokenIdentifier(userText1, new Text("renewer1"), userText1); Token<RMDelegationTokenIdentifier> token1 = new Token<RMDelegationTokenIdentifier>(dtId1, rm1.getRMContext().getRMDelegationTokenSecretManager()); SecurityUtil.setTokenService(token1, rmAddr); ts.addToken(userText1, token1); tokenSet.add(token1); Text userText2 = new Text("user2"); RMDelegationTokenIdentifier dtId2 = new RMDelegationTokenIdentifier(userText2, new Text("renewer2"), userText2); Token<RMDelegationTokenIdentifier> token2 = new Token<RMDelegationTokenIdentifier>(dtId2, rm1.getRMContext().getRMDelegationTokenSecretManager()); SecurityUtil.setTokenService(token2, rmAddr); ts.addToken(userText2, token2); tokenSet.add(token2); // submit an app with customized credential RMApp app = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false, "default", 1, ts); // assert app info is saved RMState rmState = rm1.getRMContext().getStateStore().loadState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); ApplicationStateData appState = rmAppState.get(app.getApplicationId()); Assert.assertNotNull(appState); // assert delegation tokens exist in rm1 DelegationTokenRenewr Assert.assertEquals(tokenSet, rm1.getRMContext().getDelegationTokenRenewer().getDelegationTokens()); // assert delegation tokens are saved DataOutputBuffer dob = new DataOutputBuffer(); ts.writeTokenStorageToStream(dob); ByteBuffer securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); securityTokens.rewind(); Assert.assertEquals(securityTokens, appState.getApplicationSubmissionContext().getAMContainerSpec().getTokens()); // start new RM MockRM rm2 = new TestSecurityMockRM(conf); rm2.start(); // Need to wait for a while as now token renewal happens on another thread // and is asynchronous in nature. waitForTokensToBeRenewed(rm2, tokenSet); // verify tokens are properly populated back to rm2 DelegationTokenRenewer Assert.assertEquals(tokenSet, rm2.getRMContext().getDelegationTokenRenewer().getDelegationTokens()); }
From source file:jp.queuelinker.system.net.SelectorThread.java
@Override public void run() { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); // I believe the inner try-catches does not cause overhead. // http://stackoverflow.com/questions/141560/ long sendCount = 0; SocketChannel currentChannel; SelectionKey key = null;//from www . java2s. c o m while (true) { try { selector.select(); // selector.selectNow(); } catch (ClosedSelectorException e) { logger.fatal("BUG: The selector is closed."); return; } catch (IOException e) { logger.fatal("An IOException occured while calling select()."); // Fatal Error. Notify the error to the users and leave the matter to them. for (ChannelState state : channels) { state.callBack.fatalError(); } return; } if (!requests.isEmpty()) { handleRequest(); continue; } if (stopRequested) { return; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); iter_loop: while (iter.hasNext()) { key = iter.next(); iter.remove(); // Required. Don't remove. if (key.isReadable()) { currentChannel = (SocketChannel) key.channel(); final ChannelState state = (ChannelState) key.attachment(); int valid; try { valid = currentChannel.read(buffer); } catch (IOException e) { logger.warn("An IOException happened while reading from a channel."); state.callBack.exceptionOccured(state.channelId, state.attachment); key.cancel(); continue; } if (valid == -1) { // Normal socket close? state.callBack.exceptionOccured(state.channelId, state.attachment); // cleanUpChannel(state.channelId); key.cancel(); continue; } buffer.rewind(); if (state.callBack.receive(state.channelId, buffer, valid, state.attachment) == false) { state.key.interestOps(state.key.interestOps() & ~SelectionKey.OP_READ); } buffer.clear(); } else if (key.isWritable()) { currentChannel = (SocketChannel) key.channel(); final ChannelState state = (ChannelState) key.attachment(); while (state.sendBuffer.readableSize() < WRITE_SIZE) { ByteBuffer newBuffer = state.callBack.send(state.channelId, state.attachment); if (newBuffer != null) { state.sendBuffer.write(newBuffer); if (++sendCount % 50000 == 0) { logger.info("Send Count: " + sendCount); } } else if (state.sendBuffer.readableSize() == 0) { key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); continue iter_loop; } else { break; } } final int available = state.sendBuffer.readableSize(); if (available >= WRITE_SIZE || ++state.noopCount >= HEURISTIC_WAIT) { int done; try { done = currentChannel.write(state.sendBuffer.getByteBuffer()); } catch (IOException e) { logger.warn("An IOException occured while writing to a channel."); state.callBack.exceptionOccured(state.channelId, state.attachment); key.cancel(); continue; } if (done < available) { state.sendBuffer.rollback(available - done); } state.sendBuffer.compact(); state.noopCount = 0; } } else if (key.isAcceptable()) { ServerSocketChannel channel = (ServerSocketChannel) key.channel(); ChannelState state = (ChannelState) key.attachment(); SocketChannel socketChannel; try { socketChannel = channel.accept(); socketChannel.configureBlocking(false); } catch (IOException e) { continue; // Do nothing. } state.callBack.newConnection(state.channelId, socketChannel, state.attachment); } } } }
From source file:MyZone.Settings.java
public byte[] readXML(String filename) { byte[] readIn = null; FileChannel channel = null;//from w w w . jav a 2 s. c om FileLock lock = null; FileInputStream fis = null; ByteArrayOutputStream baos = null; try { File file = new File(filename); if (!file.exists()) { return null; } fis = new FileInputStream(file); channel = fis.getChannel(); while ((lock = channel.tryLock(0L, Long.MAX_VALUE, true)) == null) { Thread.yield(); } baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; ByteBuffer buf = ByteBuffer.wrap(b); int count = 0; long fileLength = file.length(); while (fileLength > 0) { count = channel.read(buf); if (count >= 0) { fileLength -= count; baos.write(b, 0, count); buf.rewind(); } } readIn = baos.toByteArray(); } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } readIn = null; } finally { try { if (lock != null) { lock.release(); } if (channel != null) { channel.close(); } if (fis != null) { fis.close(); } if (baos != null) { baos.close(); } } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } readIn = null; } } return readIn; }
From source file:com.MainFiles.Functions.java
public int createStan() { int x = 0;/* w w w. j a v a 2s.c o m*/ String filename = COUNT_FILE; File inwrite = new File(filename); // Get a file channel for the file try { FileChannel channel = new RandomAccessFile(inwrite, "rw").getChannel(); // Use the file channel to create a lock on the file. // This method blocks until it can retrieve the lock. FileLock lock = channel.lock(); // if(!inwrite.exists()) { String s = ""; try { int fileSize = (int) channel.size(); // System.out.println("int is" + fileSize); ByteBuffer bafa = ByteBuffer.allocate(fileSize); int numRead = 0; while (numRead >= 0) { numRead = channel.read(bafa); bafa.rewind(); for (int i = 0; i < numRead; i++) { int b = (int) bafa.get(); char c = (char) b; s = s + c; } } x = Integer.parseInt(s); if (x > 999999) { x = 100000; } else if (x < 100000) { x = 100000; } x = ++x; String xx = String.valueOf(x); byte[] yy = xx.getBytes(); channel.truncate(0); channel.write(ByteBuffer.wrap(yy)); // channel.close(); } catch (IOException e) { e.printStackTrace(); } lock.release(); // Close the file channel.close(); } catch (FileNotFoundException e) { String message = "The file " + inwrite.getName() + " does not exist. So no input can be written on it"; System.out.println(message); e.printStackTrace(); //log to error file } catch (IOException e) { System.out.println("Problem writing to the logfile " + inwrite.getName()); } filename = ""; return x; }