List of usage examples for java.io ObjectOutputStream flush
public void flush() throws IOException
From source file:org.openscore.engine.queue.entities.ExecutionMessageConverter.java
private byte[] objToBytes(Object obj) { ObjectOutputStream oos = null; try {/*from www . ja v a 2 s. c o m*/ ByteArrayOutputStream bout = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(bout); oos = new ObjectOutputStream(bos); oos.writeObject(obj); oos.flush(); return bout.toByteArray(); } catch (IOException ex) { throw new RuntimeException("Failed to serialize execution plan. Error: ", ex); } finally { IOUtils.closeQuietly(oos); } }
From source file:org.apache.lucene.replicator.http.ReplicationService.java
/** Executes the replication task. */ public void perform(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String[] pathElements = getPathElements(req); if (pathElements.length != 2) { throw new ServletException("invalid path, must contain shard ID and action, e.g. */s1/update"); }/*from w w w . java2 s.c o m*/ final ReplicationAction action; try { action = ReplicationAction.valueOf(pathElements[ACTION_IDX].toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException e) { throw new ServletException("Unsupported action provided: " + pathElements[ACTION_IDX]); } final Replicator replicator = replicators.get(pathElements[SHARD_IDX]); if (replicator == null) { throw new ServletException("unrecognized shard ID " + pathElements[SHARD_IDX]); } // SOLR-8933 Don't close this stream. ServletOutputStream resOut = resp.getOutputStream(); try { switch (action) { case OBTAIN: final String sessionID = extractRequestParam(req, REPLICATE_SESSION_ID_PARAM); final String fileName = extractRequestParam(req, REPLICATE_FILENAME_PARAM); final String source = extractRequestParam(req, REPLICATE_SOURCE_PARAM); InputStream in = replicator.obtainFile(sessionID, source, fileName); try { copy(in, resOut); } finally { in.close(); } break; case RELEASE: replicator.release(extractRequestParam(req, REPLICATE_SESSION_ID_PARAM)); break; case UPDATE: String currVersion = req.getParameter(REPLICATE_VERSION_PARAM); SessionToken token = replicator.checkForUpdate(currVersion); if (token == null) { resOut.write(0); // marker for null token } else { resOut.write(1); token.serialize(new DataOutputStream(resOut)); } break; } } catch (Exception e) { resp.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); // propagate the failure try { /* * Note: it is assumed that "identified exceptions" are thrown before * anything was written to the stream. */ ObjectOutputStream oos = new ObjectOutputStream(resOut); oos.writeObject(e); oos.flush(); } catch (Exception e2) { throw new IOException("Could not serialize", e2); } } finally { resp.flushBuffer(); } }
From source file:edu.vt.middleware.gator.server.SocketServerTest.java
/** * Tests connecting to the socket server and sending a logging event that * should be written to configured appenders. * * @throws Exception On errors./* ww w . jav a 2 s . co m*/ */ @Test public void testConnectAndLog() throws Exception { final Socket sock = new Socket(); try { final SocketAddress addr = new InetSocketAddress(InetAddress.getByName(server.getBindAddress()), server.getPort()); sock.connect(addr, SOCKET_CONNECT_TIMEOUT); // Allow the socket server time to build the hierarchy // before sending a test logging event Thread.sleep(2000); Assert.assertEquals(1, server.getLoggingEventHandlers().size()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending test logging event."); } final ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream()); oos.writeObject(new MockEvent(TEST_MESSAGE)); oos.flush(); } finally { if (sock.isConnected()) { sock.close(); } } // Pause to allow time for logging events to be written Thread.sleep(2000); // Client socket close should trigger cleanup of server handler mapping Assert.assertEquals(0, server.getLoggingEventHandlers().size()); // Ensure test message was written to file Assert.assertTrue(readTextFile(LOG_FILE).contains(TEST_MESSAGE)); }
From source file:org.apache.usergrid.persistence.qakka.serialization.queuemessages.DatabaseQueueMessageSerializationTest.java
/** * Persist to blob using Java serialization. *//*from w ww. j a v a 2 s.c o m*/ @Test public void persistJavaObjectData() throws Exception { QueueMessageSerialization queueMessageSerialization = getInjector() .getInstance(QueueMessageSerialization.class); // serialize Java object to byte buffer final ThingToSave data = new ThingToSave(); data.value = "my test data"; ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(data); oos.flush(); oos.close(); ByteBuffer byteBuffer = ByteBuffer.wrap(bos.toByteArray()); // write to Cassandra final DatabaseQueueMessageBody messageBody = new DatabaseQueueMessageBody(byteBuffer, "application/octet-stream"); UUID messageId = QakkaUtils.getTimeUuid(); queueMessageSerialization.writeMessageData(messageId, messageBody); // load from Cassandra final DatabaseQueueMessageBody returnedBody = queueMessageSerialization.loadMessageData(messageId); // deserialize byte buffer ByteBuffer messageData = returnedBody.getBlob(); ByteArrayInputStream bais = new ByteArrayInputStream(messageData.array()); // throws exception -> java.io.StreamCorruptedException: invalid stream header: 00000000 ObjectInputStream ios = new ObjectInputStream(bais); ThingToSave returnedData = (ThingToSave) ios.readObject(); assertEquals(data.value, returnedData.value); }
From source file:org.activiti.mule.MuleSendActivitiBehavior.java
public void execute(ActivityExecution execution) throws Exception { String endpointUrlValue = this.getStringFromField(this.endpointUrl, execution); String languageValue = this.getStringFromField(this.language, execution); String payloadExpressionValue = this.getStringFromField(this.payloadExpression, execution); String resultVariableValue = this.getStringFromField(this.resultVariable, execution); String usernameValue = this.getStringFromField(this.username, execution); String passwordValue = this.getStringFromField(this.password, execution); ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines(); Object payload = scriptingEngines.evaluate(payloadExpressionValue, languageValue, execution); if (endpointUrlValue.startsWith("vm:")) { LocalMuleClient client = this.getMuleContext().getClient(); MuleMessage message = new DefaultMuleMessage(payload, this.getMuleContext()); MuleMessage resultMessage = client.send(endpointUrlValue, message); Object result = resultMessage.getPayload(); if (resultVariableValue != null) { execution.setVariable(resultVariableValue, result); }/*from w w w.j ava2 s . c o m*/ } else { HttpClient client = new HttpClient(); PostMethod request = new PostMethod(endpointUrlValue); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(payload); oos.flush(); oos.close(); request.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray())); } catch (Exception e) { throw new ActivitiException("Error setting message payload", e); } if (usernameValue != null && passwordValue != null) { client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(new AuthScope("localhost", -1, "mule-realm"), new UsernamePasswordCredentials(usernameValue, passwordValue)); request.setDoAuthentication(true); } byte[] response = null; try { // execute the POST request client.executeMethod(request); response = request.getResponseBody(); } finally { // release any connection resources used by the method request.releaseConnection(); } if (response != null) { try { ByteArrayInputStream in = new ByteArrayInputStream(response); ObjectInputStream is = new ObjectInputStream(in); Object result = is.readObject(); if (resultVariableValue != null) { execution.setVariable(resultVariableValue, result); } } catch (Exception e) { throw new ActivitiException("Failed to read response value", e); } } } this.leave(execution); }
From source file:pt.webdetails.cdc.hazelcast.CfgTestApp.java
private byte[] serializeObject(Object obj) { ByteArrayOutputStream bos = null; ObjectOutputStream out = null; try {//from w w w . jav a 2 s . c o m bos = new ByteArrayOutputStream(); out = new ObjectOutputStream(bos); out.writeObject(obj); out.flush(); bos.flush(); return bos.toByteArray(); } catch (IOException e) { println(e); return null; } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(bos); } }
From source file:org.vietspider.server.handler.DataContentHandler.java
@SuppressWarnings("unused") public void execute(final HttpRequest request, final HttpResponse response, final HttpContext context, OutputStream output) throws Exception { Header header = request.getFirstHeader("action"); String action = header.getValue(); byte[] bytes = getRequestData(request); String value = new String(bytes, Application.CHARSET).trim(); if ("load.new.list.metas".equals(action)) { String alert = SystemProperties.getInstance().getValue("alert.new.articles"); if ("false".equals(alert) || (Application.LICENSE == Install.SEARCH_SYSTEM && (alert == null || alert.trim().isEmpty()))) { ArticleCollection collection = new ArticleCollection(); String text = Object2XML.getInstance().toXMLDocument(collection).getTextValue(); output.write(text.getBytes(Application.CHARSET)); return; }//from w ww. j av a 2 s . co m /* MetaList metas = new MetaList("vietspider"); metas.setPageSize(10); metas.setCurrentPage(1); Calendar calendar = Calendar.getInstance(); String date = CalendarUtils.getDateFormat().format(calendar.getTime()); //working with entry EntryReader entryReader = new EntryReader(); IEntryDomain entryDomain = null; entryDomain = new SimpleEntryDomain(date, null, null); entryReader.read(entryDomain, metas, -1);*/ ArticleCollection collection = new ArticleCollection(); AlertQueue.createInstance().get(collection); // List<Article> articles = metas.getData(); // collection.get().addAll(articles); String text = Object2XML.getInstance().toXMLDocument(collection).getTextValue(); output.write(text.getBytes(Application.CHARSET)); return; } if ("load.article".equals(action)) { Article article = null; try { article = DatabaseService.getLoader().loadArticle(value); StringBuilder builder = new StringBuilder(article.getMeta().getTitle()); builder.append('\n').append(article.getMeta().getDesc()); output.write(builder.toString().getBytes(Application.CHARSET)); } catch (SQLException e) { output.write(("error\n" + e.toString()).getBytes()); } catch (Exception e) { output.write(("error\n" + e.toString()).getBytes()); } return; } if ("load.article.by.url".equals(action)) { // if(!DataGetter.class.isInstance(DatabaseService.getLoader())) { if (DatabaseService.isMode(DatabaseService.RDBMS)) { output.write(new byte[0]); return; } TextSpliter spliter = new TextSpliter(); String[] elements = spliter.toArray(value, '\n'); if (elements.length != 2) { output.write(new byte[0]); return; } String articleId = DatabaseService.getLoader().loadIdByURL(elements[1]); if (articleId == null) { output.write(new byte[0]); return; } Article article = null; try { article = DatabaseService.getLoader().loadArticle(articleId); if (article == null) { output.write(new byte[0]); return; } if (!article.getDomain().getGroup().equals(elements[0])) { output.write(new byte[0]); return; } ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOutputStream); out.writeObject(article); out.flush(); out.close(); bytes = byteOutputStream.toByteArray(); bytes = new GZipIO().zip(bytes); output.write(bytes); } catch (SQLException e) { output.write(new byte[0]); } catch (Exception e) { output.write(new byte[0]); } return; } }
From source file:org.apache.storm.hive.security.AutoHive.java
@SuppressWarnings("unchecked") protected byte[] getHadoopCredentials(Map<String, Object> conf, final Configuration configuration) { try {//from w w w . j ava 2 s .c om if (UserGroupInformation.isSecurityEnabled()) { String topologySubmitterUser = (String) conf.get(Config.TOPOLOGY_SUBMITTER_PRINCIPAL); String hiveMetaStoreURI = getMetaStoreURI(configuration); String hiveMetaStorePrincipal = getMetaStorePrincipal(configuration); HiveConf hcatConf = createHiveConf(hiveMetaStoreURI, hiveMetaStorePrincipal); login(configuration); UserGroupInformation currentUser = UserGroupInformation.getCurrentUser(); UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(topologySubmitterUser, currentUser); try { Token<DelegationTokenIdentifier> delegationTokenId = getDelegationToken(hcatConf, hiveMetaStorePrincipal, topologySubmitterUser); proxyUser.addToken(delegationTokenId); LOG.info("Obtained Hive tokens, adding to user credentials."); Credentials credential = proxyUser.getCredentials(); ByteArrayOutputStream bao = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bao); credential.write(out); out.flush(); out.close(); return bao.toByteArray(); } catch (Exception ex) { LOG.debug(" Exception" + ex.getMessage()); throw ex; } } else { throw new RuntimeException("Security is not enabled for Hadoop"); } } catch (Exception ex) { throw new RuntimeException("Failed to get delegation tokens.", ex); } }
From source file:com.github.stephanarts.cas.ticket.registry.RegistryClient.java
/** * updateTicket Method./*from ww w. j a v a2s .c om*/ * * @param ticket CAS Ticket object * * @return Response Object * * @throws JSONRPCException Throws JSONRPCException containing any error. */ public final JSONObject updateTicket(final Ticket ticket) throws JSONRPCException { byte[] serializedTicket = {}; JSONObject params = new JSONObject(); try { ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream so = new ObjectOutputStream(bo); so.writeObject(ticket); so.flush(); serializedTicket = bo.toByteArray(); } catch (final Exception e) { throw new JSONRPCException(-32501, "Could not decode Ticket"); } params.put("ticket-id", ticket.getId()); params.put("ticket", DatatypeConverter.printBase64Binary(serializedTicket)); return this.call("cas.updateTicket", params); }
From source file:org.apache.jcs.auxiliary.lateral.socket.tcp.discovery.UDPDiscoverySender.java
/** * Send messages./*from w w w .j av a 2s .c om*/ * * @param message * @throws IOException */ public void send(UDPDiscoveryMessage message) throws IOException { if (this.m_localSocket == null) { throw new IOException("Socket is null, cannot send message."); } // TODO when we move to jdk 1.4 reinstate the isClosed check // if (this.m_localSocket.isClosed() ) // { // throw new IOException( "Socket is closed, cannot send message." ); // } if (log.isDebugEnabled()) { log.debug("sending UDPDiscoveryMessage, message = " + message); } try { // write the object to a byte array. final MyByteArrayOutputStream byteStream = new MyByteArrayOutputStream(); final ObjectOutputStream objectStream = new ObjectOutputStream(byteStream); objectStream.writeObject(message); objectStream.flush(); final byte[] bytes = byteStream.getBytes(); // put the byte array in a packet final DatagramPacket packet = new DatagramPacket(bytes, bytes.length, m_multicastAddress, m_multicastPort); m_localSocket.send(packet); } catch (IOException e) { log.error("Error sending message", e); throw e; } }