List of usage examples for java.io ByteArrayOutputStream reset
public synchronized void reset()
From source file:com.amalto.core.server.DefaultItem.java
/** * Returns an ordered collection of results searched in a cluster and specifying an optional condition<br/> * The results are xml objects made of elements constituted by the specified viewablePaths * * @param dataClusterPOJOPK The Data Cluster where to run the query * @param forceMainPivot An optional pivot that will appear first in the list of pivots in the query<br> * : This allows forcing cartesian products: for instance Order Header vs Order Line * @param viewablePaths The list of elements returned in each result * @param whereItem The condition//from w ww . j ava 2 s . c o m * @param spellThreshold The condition spell checking threshold. A negative value de-activates spell * @param orderBy The full path of the item user to order * @param direction One of {@link com.amalto.xmlserver.interfaces.IXmlServerSLWrapper#ORDER_ASCENDING} or * {@link com.amalto.xmlserver.interfaces.IXmlServerSLWrapper#ORDER_DESCENDING} * @param start The first item index (starts at zero) * @param limit The maximum number of items to return * @param returnCount True if total search count should be returned as first result. * @return The ordered list of results * @throws com.amalto.core.util.XtentisException In case of error in MDM code. */ @Override public ArrayList<String> xPathsSearch(DataClusterPOJOPK dataClusterPOJOPK, String forceMainPivot, ArrayList<String> viewablePaths, IWhereItem whereItem, int spellThreshold, String orderBy, String direction, int start, int limit, boolean returnCount) throws XtentisException { try { if (viewablePaths.size() == 0) { String err = "The list of viewable xPaths must contain at least one element"; LOGGER.error(err); throw new XtentisException(err); } // Check if user is allowed to read the cluster ILocalUser user = LocalUser.getLocalUser(); boolean authorized = false; String dataModelName = dataClusterPOJOPK.getUniqueId(); if (MDMConfiguration.getAdminUser().equals(user.getUsername())) { authorized = true; } else if (user.userCanRead(DataClusterPOJO.class, dataModelName)) { authorized = true; } if (!authorized) { throw new XtentisException("Unauthorized read access on data cluster '" + dataModelName + "' by user '" + user.getUsername() + "'"); } Server server = ServerContext.INSTANCE.get(); String typeName = StringUtils.substringBefore(viewablePaths.get(0), "/"); //$NON-NLS-1$ StorageAdmin storageAdmin = server.getStorageAdmin(); Storage storage = storageAdmin.get(dataModelName, storageAdmin.getType(dataModelName)); MetadataRepository repository = storage.getMetadataRepository(); ComplexTypeMetadata type = repository.getComplexType(typeName); UserQueryBuilder qb = from(type); qb.where(UserQueryHelper.buildCondition(qb, whereItem, repository)); qb.start(start); qb.limit(limit); if (orderBy != null) { List<TypedExpression> fields = UserQueryHelper.getFields(type, StringUtils.substringAfter(orderBy, "/")); //$NON-NLS-1$ if (fields == null) { throw new IllegalArgumentException("Field '" + orderBy + "' does not exist."); } OrderBy.Direction queryDirection; if ("ascending".equals(direction)) { //$NON-NLS-1$ queryDirection = OrderBy.Direction.ASC; } else { queryDirection = OrderBy.Direction.DESC; } for (TypedExpression field : fields) { qb.orderBy(field, queryDirection); } } // Select fields for (String viewablePath : viewablePaths) { String viewableTypeName = StringUtils.substringBefore(viewablePath, "/"); //$NON-NLS-1$ String viewableFieldName = StringUtils.substringAfter(viewablePath, "/"); //$NON-NLS-1$ if (!viewableFieldName.isEmpty()) { qb.select(repository.getComplexType(viewableTypeName), viewableFieldName); } else { qb.selectId(repository.getComplexType(viewableTypeName)); // Select id if xPath is 'typeName' and not 'typeName/field' } } ArrayList<String> resultsAsString = new ArrayList<String>(); StorageResults results; try { storage.begin(); if (returnCount) { results = storage.fetch(qb.getSelect()); resultsAsString.add("<totalCount>" + results.getCount() + "</totalCount>"); //$NON-NLS-1$ //$NON-NLS-2$ } results = storage.fetch(qb.getSelect()); DataRecordWriter writer = new DataRecordDefaultWriter(); ByteArrayOutputStream output = new ByteArrayOutputStream(); for (DataRecord result : results) { try { writer.write(result, output); } catch (IOException e) { throw new XmlServerException(e); } String document = new String(output.toByteArray()); resultsAsString.add(document); output.reset(); } storage.commit(); } catch (Exception e) { storage.rollback(); throw new XmlServerException(e); } return resultsAsString; } catch (XtentisException e) { throw (e); } catch (Exception e) { String err = "Unable to single search: " + ": " + e.getClass().getName() + ": " + e.getLocalizedMessage(); LOGGER.error(err, e); throw new XtentisException(err, e); } }
From source file:org.apache.pig.piggybank.storage.XMLLoaderBufferedPositionedInputStream.java
/** * This is collect the from the matching tag. * This scans for the tags and do the pattern match byte by byte * This returns a part doc. it must be used along with * XMLLoaderBufferedPositionedInputStream#collectUntilEndTag * //from w w w . j a v a 2 s .c o m * @param tagName the start tag to search for * * @param limit the end pointer for the block for this mapper * * @return the byte array containing match of the tag. * * @see loader.XMLLoaderBufferedPositionedInputStream.collectUntilEndTag * */ private byte[] skipToTag(String tagName, long limit) throws IOException { //@todo use the charset and get the charset encoding from the xml encoding. byte[] tmp = tagName.getBytes(); byte[] tag = new byte[tmp.length + 1]; tag[0] = (byte) '<'; for (int i = 0; i < tmp.length; ++i) { tag[1 + i] = tmp[i]; } ByteArrayOutputStream matchBuf = new ByteArrayOutputStream(512); int idxTagChar = 0; int state = S_START; /* * Read till the tag is found in this block. If a partial tag block is found * then continue on to the next block.matchBuf contains the data that is currently * matched. If the read has reached the end of split and there are matched data * then continue on to the next block. */ while (splitBoundaryCriteria(wrapperIn) || (matchBuf.size() > 0)) { int b = -1; try { b = this.read(); ++bytesRead; // Increment the bytes read by 1 if (b == -1) { state = S_START; matchBuf.reset(); this.setReadable(false); break; } switch (state) { case S_START: // start to match the target open tag if (b == tag[idxTagChar]) { ++idxTagChar; matchBuf.write((byte) (b)); if (idxTagChar == tag.length) { state = S_MATCH_PREFIX; } } else { // mismatch idxTagChar = 0; matchBuf.reset(); } break; case S_MATCH_PREFIX: // tag match iff next character is whitespaces or close tag mark if (Character.isWhitespace(b) || b == '/' || b == '>') { matchBuf.write((byte) (b)); state = S_MATCH_TAG; } else { idxTagChar = 0; matchBuf.reset(); state = S_START; } break; case S_MATCH_TAG: // keep copy characters until we hit the close tag mark matchBuf.write((byte) (b)); break; default: throw new IllegalArgumentException("Invalid state: " + state); } if (state == S_MATCH_TAG && (b == '>' || Character.isWhitespace(b))) { break; } if (state != S_MATCH_TAG && this.getPosition() > limit) { // need to break, no record in this block break; } } catch (IOException e) { this.setReadable(false); return null; } } return matchBuf.toByteArray(); }
From source file:org.jboss.test.syslog.TCPSyslogSocketHandler.java
public void run() { try {/*from w ww . j a v a2s.c o m*/ final BufferedInputStream bis = new BufferedInputStream(socket.getInputStream()); int b = -1; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean firstByte = true; boolean octetCounting = false; StringBuilder octetLenStr = new StringBuilder(); do { b = bis.read(); if (firstByte && b >= '1' && b <= '9') { // handle Octet Counting messages (cf. rfc-6587) octetCounting = true; } firstByte = false; if (octetCounting) { if (b != ' ') { octetLenStr.append((char) b); } else { int len = Integer.parseInt(octetLenStr.toString()); handleSyslogMessage(IOUtils.toByteArray(bis, len)); // reset the stuff octetLenStr = new StringBuilder(); firstByte = true; octetCounting = false; } } else { // handle Non-Transparent-Framing messages (cf. rfc-6587) switch (b) { case -1: case '\r': case '\n': if (baos.size() > 0) { handleSyslogMessage(baos.toByteArray()); baos.reset(); firstByte = true; } break; default: baos.write(b); break; } } } while (b != -1); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(socket); sockets.remove(socket); } }
From source file:com.geoxp.oss.client.OSSClient.java
public static boolean init(String ossURL, byte[] secret, String sshKeyFingerprint) throws OSSException { SSHAgentClient agent = null;/*from www. ja va2 s. c o m*/ HttpClient httpclient = newHttpClient(); try { agent = new SSHAgentClient(); List<SSHKey> sshkeys = agent.requestIdentities(); // // If no SSH Key fingerprint was provided, try all SSH keys available in the agent // List<String> fingerprints = new ArrayList<String>(); if (null == sshKeyFingerprint) { for (SSHKey key : sshkeys) { fingerprints.add(key.fingerprint); } } else { fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", "")); } int idx = 0; for (String fingerprint : fingerprints) { idx++; // // Ask the SSH agent for the SSH key blob // byte[] keyblob = null; for (SSHKey key : sshkeys) { if (key.fingerprint.equals(fingerprint)) { keyblob = key.blob; break; } } // // Throw an exception if this condition is encountered as it can only happen if // there was a provided fingerprint which is not in the agent. // if (null == keyblob) { throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent."); } // // Retrieve OSS RSA key // RSAPublicKey pubkey = getOSSRSA(ossURL); // // Build the initialization token // // <TS> <SECRET> <SSH Signing Key Blob> <SSH Signature Blob> // ByteArrayOutputStream token = new ByteArrayOutputStream(); byte[] tsdata = nowBytes(); token.write(CryptoHelper.encodeNetworkString(tsdata)); token.write(CryptoHelper.encodeNetworkString(secret)); token.write(CryptoHelper.encodeNetworkString(keyblob)); byte[] sigblob = agent.sign(keyblob, token.toByteArray()); token.write(CryptoHelper.encodeNetworkString(sigblob)); // // Encrypt the token with a random AES256 key // byte[] aeskey = new byte[32]; CryptoHelper.getSecureRandom().nextBytes(aeskey); byte[] wrappedtoken = CryptoHelper.wrapAES(aeskey, token.toByteArray()); // // Encrypt the random key with OSS' RSA key // byte[] sealedaeskey = CryptoHelper.encryptRSA(pubkey, aeskey); // // Create the token // token.reset(); token.write(CryptoHelper.encodeNetworkString(wrappedtoken)); token.write(CryptoHelper.encodeNetworkString(sealedaeskey)); // // Base64 encode the encryptedtoken // String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8"); // // Send request to OSS // URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_INIT); builder.addParameter("token", b64token); URI uri = builder.build(); String qs = uri.getRawQuery(); HttpPost post = new HttpPost( uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath()); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity(qs)); httpclient = newHttpClient(); HttpResponse response = httpclient.execute(post); HttpEntity resEntity = response.getEntity(); String content = EntityUtils.toString(resEntity, "UTF-8"); post.reset(); if (HttpServletResponse.SC_ACCEPTED == response.getStatusLine().getStatusCode()) { return false; } else if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) { // Only throw an exception if this is the last SSH key we could try if (idx == fingerprints.size()) { throw new OSSException("None of the provided keys (" + idx + ") could be used to initialize this Open Secret Server. Latest error message was: " + response.getStatusLine().getReasonPhrase()); } else { continue; } } return true; } } catch (OSSException osse) { throw osse; } catch (Exception e) { throw new OSSException(e); } finally { if (null != httpclient) { httpclient.getConnectionManager().shutdown(); } if (null != agent) { agent.close(); } } return false; }
From source file:com.wwpass.connection.WWPassConnectionTest.java
@Test public void testWriteDataSP() throws WWPassProtocolException, UnsupportedEncodingException, IOException { byte[] pfid = conn.createPFID(); // Write and read string data case conn.writeDataSP(pfid, "test data"); /*String response = conn.readDataSP(pfid); assertArrayEquals("Expected readed data \"test data\", actual readed data is " + response, "test data".getBytes(), /* ww w .j a v a 2 s . co m*/ response.getBytes());*/ InputStream dataIs = conn.readDataSP(pfid); BufferedInputStream bis = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { bis = new BufferedInputStream(dataIs); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { baos.write(buffer, 0, bytesRead); } assertArrayEquals( "Expected readed data \"test data\", actual readed data is " + new String(baos.toByteArray()), "test data".getBytes(), baos.toByteArray()); } finally { bis.close(); baos.reset(); baos.close(); } try { conn.removePFID(pfid); } catch (WWPassProtocolException e) { fail("Expecting no exception while removing test PFIDs, but catched the WWPassProtocolException with message: " + e.getMessage()); } // Write and read byte data case pfid = conn.createPFID(); conn.writeDataSP(pfid, BYTE_DATA); /* byte[] byteResponse = conn.readDataBytesSP(pfid); assertArrayEquals("Writed and readed byte data are not equals", BYTE_DATA, byteResponse);*/ dataIs = conn.readDataSP(pfid); try { bis = new BufferedInputStream(dataIs); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { baos.write(buffer, 0, bytesRead); } assertArrayEquals( "Writed and readed byte data are not equals. Returned data: " + new String(baos.toByteArray()), BYTE_DATA, baos.toByteArray()); } finally { bis.close(); baos.reset(); baos.close(); } try { conn.removePFID(pfid); } catch (WWPassProtocolException e) { fail("Expecting no exception while removing test PFIDs, but catched the WWPassProtocolException with message: " + e.getMessage()); } // Write and read large byte data (JPG image) case pfid = conn.createPFID(); conn.writeDataSP(pfid, imgData); /* byte[] newImgData = conn.readDataBytesSP(pfid); assertArrayEquals("Writed and readed byte data are not equals", imgData, newImgData);*/ dataIs = conn.readDataSP(pfid); try { bis = new BufferedInputStream(dataIs); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { baos.write(buffer, 0, bytesRead); } assertArrayEquals("Writed and readed byte data are not equals", imgData, baos.toByteArray()); } finally { bis.close(); baos.reset(); baos.close(); } try { conn.removePFID(pfid); } catch (WWPassProtocolException e) { fail("Expecting no exception while removing test PFIDs, but catched the WWPassProtocolException with message: " + e.getMessage()); } // Write and read String data case pfid = conn.createPFID("test data"); String stringData = conn.readDataSPasString(pfid); assertArrayEquals("Expected that readed and writed string data are equal", "test data".getBytes(), stringData.getBytes()); // Test for read String and lock SP conn.readDataSPasStringAndLock(pfid, 3); try { conn.lockSP(pfid, 1); fail("Expected WWPassProtocolException while trying to lock already locked SP container"); } catch (WWPassProtocolException e) { assertTrue("Expected message: \"Already locked\", actual message: " + e.getMessage(), e.getMessage().contains("Already locked")); } try { conn.removePFID(pfid); } catch (WWPassProtocolException e) { fail("Expecting no exception while removing test PFIDs, but catched the WWPassProtocolException with message: " + e.getMessage()); } }
From source file:org.jboss.as.test.integration.logging.syslogserver.TCPSyslogSocketHandler.java
public void run() { try {/* w w w . ja v a 2 s. c om*/ final BufferedInputStream bis = new BufferedInputStream(socket.getInputStream()); int b = -1; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean firstByte = true; boolean octetCounting = false; StringBuilder octetLenStr = new StringBuilder(); do { b = bis.read(); if (firstByte && b >= '1' && b <= '9') { // handle Octet Counting messages (cf. rfc-6587) octetCounting = true; } firstByte = false; if (octetCounting) { if (b != ' ') { octetLenStr.append((char) b); } else { int len = Integer.parseInt(octetLenStr.toString()); handleSyslogMessage(IOUtils.toByteArray(bis, len)); // reset the stuff octetLenStr = new StringBuilder(); firstByte = true; octetCounting = false; } } else { // handle Non-Transparent-Framing messages (cf. rfc-6587) switch (b) { case -1: case '\r': case '\n': if (baos.size() > 0) { handleSyslogMessage(baos.toByteArray()); baos.reset(); firstByte = true; } break; default: baos.write(b); break; } } } while (b != -1); } catch (IOException e) { LOGGER.warn("IOException occurred", e); } finally { IOUtils.closeQuietly(socket); sockets.remove(socket); } }
From source file:org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPTransport.java
private void readHTTPResponseHeader(InputStream is, HTTPResponse resp) throws IOException { byte b = 0;//w w w .java 2s . co m int len = 0; int colonIndex = -1; String key; String value; boolean readTooMuch = false; ByteArrayOutputStream baos; for (baos = new ByteArrayOutputStream(4096);;) { if (!readTooMuch) b = (byte) is.read(); if (b == -1) break; readTooMuch = false; if ((b != R) && (b != N)) { if ((b == COLON) && (colonIndex == -1)) colonIndex = len; len++; baos.write(b); } else if (b == R) continue; else // b == N { if (len == 0) break; b = (byte) is.read(); readTooMuch = true; // A space or tab at the begining of a line means the header continues. if ((b == SPACE) || (b == TAB)) continue; baos.close(); byte[] bArray = baos.toByteArray(); baos.reset(); if (colonIndex != -1) { key = new String(bArray, 0, colonIndex, DEFAULT_HTTP_HEADER_ENCODING); value = new String(bArray, colonIndex + 1, len - 1 - colonIndex, DEFAULT_HTTP_HEADER_ENCODING); colonIndex = -1; } else { key = new String(bArray, 0, len, DEFAULT_HTTP_HEADER_ENCODING); value = EMPTY_STRING; } if (!resp.isStatusSet()) { // Reader status code int start = key.indexOf(SPACE) + 1; String s = key.substring(start).trim(); int end = s.indexOf(SPACE); if (end != -1) s = s.substring(0, end); try { resp.setStatusCode(Integer.parseInt(s)); } catch (NumberFormatException nfe) { resp.setStatusCode(-1); } resp.setStatusMessage(key.substring(start + end + 1)); } else resp.addHeader(key.toLowerCase().trim(), value.trim()); len = 0; } } baos.close(); }
From source file:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java
/** * Tests that the PurchaseOrderService would performPrintPurchaseOrderPDFOnly * * @throws Exception/* w w w . ja va 2 s . c om*/ */ public void testPerformPrintPurchaseOrderPDFOnly() throws Exception { PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS .createPurchaseOrderDocument(); po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN); po.refreshNonUpdateableReferences(); po.prepareForSave(); AccountingDocumentTestUtils.saveDocument(po, docService); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try { DateTimeService dtService = SpringContext.getBean(DateTimeService.class); StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_PO_QUOTE_REQUEST_LIST"); sbFilename.append(po.getPurapDocumentIdentifier()); sbFilename.append("_"); sbFilename.append(dtService.getCurrentDate().getTime()); sbFilename.append(".pdf"); poService.performPrintPurchaseOrderPDFOnly(po.getDocumentNumber(), baosPDF); assertTrue(baosPDF.size() > 0); } catch (ValidationException e) { LOG.warn("Caught ValidationException while trying to retransmit PO with doc id " + po.getDocumentNumber()); } finally { if (baosPDF != null) { baosPDF.reset(); } } }
From source file:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java
/** * Tests that the PurchaseOrderService would performPurchaseOrderPreviewPrinting * * @throws Exception//from w w w . j a va2 s . c om */ public void testPerformPurchaseOrderPreviewPrinting() throws Exception { PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS .createPurchaseOrderDocument(); po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN); po.refreshNonUpdateableReferences(); po.prepareForSave(); AccountingDocumentTestUtils.saveDocument(po, docService); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try { DateTimeService dtService = SpringContext.getBean(DateTimeService.class); StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_PO_QUOTE_REQUEST_LIST"); sbFilename.append(po.getPurapDocumentIdentifier()); sbFilename.append("_"); sbFilename.append(dtService.getCurrentDate().getTime()); sbFilename.append(".pdf"); poService.performPurchaseOrderPreviewPrinting(po.getDocumentNumber(), baosPDF); assertTrue(baosPDF.size() > 0); } catch (ValidationException e) { LOG.warn("Caught ValidationException while trying to retransmit PO with doc id " + po.getDocumentNumber()); } finally { if (baosPDF != null) { baosPDF.reset(); } } }
From source file:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java
/** * Tests that the PurchaseOrderService would performPurchaseOrderFirstTransmitViaPrinting * * * @throws Exception/*from www . j a va 2 s. c o m*/ */ public void testPerformPurchaseOrderFirstTransmitViaPrinting() throws Exception { PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS .createPurchaseOrderDocument(); po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN); po.refreshNonUpdateableReferences(); po.prepareForSave(); AccountingDocumentTestUtils.saveDocument(po, docService); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try { DateTimeService dtService = SpringContext.getBean(DateTimeService.class); StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_PO_QUOTE_REQUEST_LIST"); sbFilename.append(po.getPurapDocumentIdentifier()); sbFilename.append("_"); sbFilename.append(dtService.getCurrentDate().getTime()); sbFilename.append(".pdf"); poService.performPurchaseOrderFirstTransmitViaPrinting(po.getDocumentNumber(), baosPDF); assertTrue(baosPDF.size() > 0); } catch (ValidationException e) { LOG.warn("Caught ValidationException while trying to retransmit PO with doc id " + po.getDocumentNumber()); } finally { if (baosPDF != null) { baosPDF.reset(); } } }