@Override public boolean deleteUser(Integer id) throws Exception { dLog.info("Entering method deleteUser | User ID:" + id); boolean result = false; Session session = null; try { session = getSession(); String hql = "delete from User where id = " + id.toString(); Query query = session.createQuery(hql); int row = query.executeUpdate(); if (row > 0) { result = true; } } catch (Exception e) { dLog.error("Exception in deleteUser", e); } finally { // ensure that session is close regardless of the errors in try/catch if (session != null) { session.close(); } } return result; }
@Override public List<Forum> getForumsOfaUser(int userId) { // TODO Auto-generated method stub List<Forum> forums = new ArrayList<Forum>(); Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Query query = session.createQuery("from Subscription where userId = :userId"); query.setString("userId", String.valueOf(userId)); List<Subscription> userSubscribedGroups = query.list(); for (Subscription subsc : userSubscribedGroups) { query = session.createQuery("from Forum where forumId = :forumId"); query.setParameter("forumId", subsc.getForumId()); // add this to a list variable query.uniqueResult(); forums.add((Forum) query.uniqueResult()); } } catch (HibernateException e) { if (tx != null) { tx.rollback(); e.printStackTrace(); } } finally { session.close(); } return forums; }
public DigitalLibraryServer() { try { Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces"); properties.put(Context.PROVIDER_URL, "localhost"); InitialContext jndi = new InitialContext(properties); ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup("XAConnectionFactory"); connection = conFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { counterTopic = (Topic) jndi.lookup("counterTopic"); } catch (NamingException NE1) { System.out.println("NamingException: " + NE1 + " : Continuing anyway..."); } if (null == counterTopic) { counterTopic = session.createTopic("counterTopic"); jndi.bind("counterTopic", counterTopic); } consumer = session.createConsumer(counterTopic); consumer.setMessageListener(this); System.out.println("Server started waiting for client requests"); connection.start(); } catch (NamingException NE) { System.out.println("Naming Exception: " + NE); } catch (JMSException JMSE) { System.out.println("JMS Exception: " + JMSE); JMSE.printStackTrace(); } }
@Override public List<Reply> getRepliesToPost(int postId) { // TODO Auto-generated method stub Session session = sessionFactory.openSession(); Transaction tx = null; List<Reply> replyArr = new ArrayList<Reply>(); try { tx = session.beginTransaction(); Query query = session.createQuery("from Reply where postId = :postId order by createdDate desc"); query.setParameter("postId", postId); replyArr = query.list(); /* for(Reply reply : replyArr){ System.out.println("Reply - id----"+reply.getReplyId()); System.out.println("Reply - Description----"+reply.getDescription()); System.out.println("Reply - Post id----"+reply.getPostId()); }*/ } catch (HibernateException e) { if (tx != null) { tx.rollback(); e.printStackTrace(); } } finally { session.close(); } return replyArr; }
public int getCountOfSubscribers(int forumId, int userId) { // TODO Auto-generated method stub Session session = this.sessionFactory.openSession(); Transaction tx = null; int countOfSubscribers = 0; try { tx = session.beginTransaction(); Query query = null; if (userId == 0) { query = session.createQuery("select count(*) from Subscription where forumId = :forumId"); query.setParameter("forumId", forumId); } else { query = session.createQuery( "select count(*) from Subscription where forumId = :forumId and userId = :userId"); query.setParameter("forumId", forumId); query.setParameter("userId", userId); } Long count = (Long) query.uniqueResult(); countOfSubscribers = count.intValue(); // System.out.println("No of subscribers.."+countOfSubscribers); } catch (HibernateException e) { if (tx != null) { tx.rollback(); e.printStackTrace(); } } finally { session.close(); } return countOfSubscribers; }
public void save(Treatment treatment) { Session session = this.sessionFactory.openSession(); Transaction tx = session.beginTransaction(); session.persist(treatment); tx.commit(); session.close(); }
/** {@inheritDoc} */ @Override public void close(final CameraSession session) { final Session s = (Session) session; try { lock.acquire(); if (s.captureSession != null) { closeLatch = new CountDownLatch(1); s.captureSession.close(); closeLatch.await(2, TimeUnit.SECONDS); s.captureSession = null; } if (s.cameraDevice != null) { s.cameraDevice.close(); s.cameraDevice = null; } if (s.reader != null) { s.reader.close(); } Descriptor camera = (Descriptor) session.getDescriptor(); camera.setDevice(null); getBus().post(new ClosedEvent()); } catch (Exception e) { getBus().post(new ClosedEvent(e)); } finally { lock.release(); } }
public static void main(String[] args) throws JMSException { // Getting JMS connection from the server ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); Connection connection = connectionFactory.createConnection(); connection.start(); // Creating session for seding messages Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Getting the queue 'JMSBEGINQUEUE' Destination destination = session.createQueue(subject); // MessageConsumer is used for receiving (consuming) messages MessageConsumer consumer = session.createConsumer(destination); // Here we receive the message. // By default this call is blocking, which means it will wait // for a message to arrive on the queue. Message message = consumer.receive(); // There are many types of Message and TextMessage // is just one of them. Producer sent us a TextMessage // so we must cast to it to get access to its .getText() // method. if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; System.out.println("Received message '" + textMessage.getText() + "'"); } connection.close(); }
/* * Initiate the snapshot by sending a Marker message to one of the Players (Player0) * Any Player could have been used to initiate the snapshot. */ private void sendInitSnapshot() { try { // Gather necessary JMS resources Context ctx = new InitialContext(); ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/myConnectionFactory"); Queue q = (Queue) ctx.lookup("jms/PITplayer0"); Connection con = cf.createConnection(); Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer writer = session.createProducer(q); /* * As part of the snapshot algorithm, players need to record * what other Players they receive markers from. * "-1" indicates to the PITplayer0 that this marker is coming from * the monitor, not another Player. */ Marker m = new Marker(-1); ObjectMessage msg = session.createObjectMessage(m); System.out.println("Initiating Snapshot"); writer.send(msg); con.close(); } catch (JMSException e) { System.out.println("JMS Exception thrown" + e); } catch (Throwable e) { System.out.println("Throwable thrown" + e); } }
private void route(String consumerSource, String producerTarget, String routingKey, boolean succeed) throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Consumer c = s.createConsumer(consumerSource, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); Producer p = s.createProducer(producerTarget, QoS.AT_LEAST_ONCE); AMQPMessage msg = msg(); AmqpValue sentinel = new AmqpValue(new AMQPDouble(Math.random())); msg.setAmqpValue(sentinel); Properties props = new Properties(); props.setSubject(new AMQPString(routingKey)); msg.setProperties(props); p.send(msg); if (succeed) { AMQPMessage m = c.receive(); assertNotNull(m); assertEquals(sentinel.getValue().getValueString(), m.getAmqpValue().getValue().getValueString()); m.accept(); } else { assertNull(get(c)); } c.close(); p.close(); conn.close(); }
private <N> void discoverResourceConfiguration( ID resourceId, ResourceType<L> type, L parentAddress, N baseNode, Resource.Builder<L> builder, Session<L> session) { Collection<ResourceConfigurationPropertyType<L>> confPropTypes = type.getResourceConfigurationPropertyTypes(); for (ResourceConfigurationPropertyType<L> confPropType : confPropTypes) { try { final AttributeLocation<L> location = confPropType.getAttributeLocation(); final LocationResolver<L> locationResolver = session.getLocationResolver(); final AttributeLocation<L> instanceLocation = locationResolver.absolutize(parentAddress, location); final Driver<L> driver = session.getDriver(); String resConfPropValue; if (!locationResolver.isMultiTarget(instanceLocation.getLocation())) { Object o = driver.fetchAttribute(instanceLocation); resConfPropValue = ((o == null) ? null : o.toString()); } else { // This resource config is a conglomeration of attrib values across multiple locations. We // need to // aggregate them all into a map and store the map as the resource configuration property // value. Map<L, Object> attribMap = driver.fetchAttributeAsMap(instanceLocation); if (attribMap == null || attribMap.isEmpty()) { resConfPropValue = null; } else { Map<String, String> resConfigPropMap = new HashMap<>(attribMap.size()); L multiTargetLocation = instanceLocation.getLocation(); for (Map.Entry<L, Object> entry : attribMap.entrySet()) { L singleLocation = entry.getKey(); String attribValue = String.valueOf(entry.getValue()); String attribKey = locationResolver.findWildcardMatch(multiTargetLocation, singleLocation); resConfigPropMap.put(attribKey, attribValue); } resConfPropValue = Util.toJson(resConfigPropMap); } } ResourceConfigurationPropertyInstance<L> cpi = new ResourceConfigurationPropertyInstance<>( ID.NULL_ID, confPropType.getName(), instanceLocation, confPropType, resConfPropValue); builder.resourceConfigurationProperty(cpi); } catch (Exception e) { log.warnf( e, "Failed to discover config [%s] for resource [%s]", confPropType, parentAddress); } } }
public void testRedelivery() throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Producer p = s.createProducer(QUEUE, QoS.AT_MOST_ONCE); p.send(msg()); p.close(); Consumer c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage m1 = c.receive(); assertTrue(m1.getHeader().getFirstAcquirer().getValue()); assertFalse(m1.isSettled()); s.close(); s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage m2 = c.receive(); m2.accept(); assertTrue(compareMessageData(m1, m2)); assertFalse(m2.getHeader().getFirstAcquirer().getValue()); assertNull(get(c)); conn.close(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String channelid = request.getParameter("channelid"); String tokenId = request.getParameter("token"); // check if token exists in the request attribute Session session = null; Token token = (Token) request.getAttribute("TOKEN"); if (token == null) { session = sockets.getSession(channelid); token = session.findToken(tokenId); if (token == null) token = session.add(tokenId); request.setAttribute("TOKEN", token); } else { session = token.getSession(); } if (token.hasMessages()) { String msg = token.getMessage(); writeMessage(response, msg); } else { Continuation continuation = ContinuationSupport.getContinuation(request); if (continuation.isInitial()) { // No chat in queue, so suspend and wait for timeout or chat continuation.setTimeout(20000); continuation.suspend(); token.setContinuation(continuation); } else { writeMessage(response, "{status: 'closed'}"); } } }
@Override public boolean storeUser(User u) throws Exception { dLog.info("Entering method storeUser | User ID: " + u.getId()); boolean result = false; Session session = null; try { // ensure we were passed a valid object before attempting to write if (u.validate()) { session = getSession(); Transaction tranx = session.beginTransaction(); session.save(u); tranx.commit(); result = tranx.wasCommitted(); dLog.info("Was committed: " + result); } } catch (Exception e) { dLog.error("Exception in storeUser", e); } finally { // ensure that session is close regardless of the errors in try/catch if (session != null) { session.close(); } } return result; }
@Test public void receiveMessagesAckCheck() throws Exception { BlockingQueue<MmsMessage> q = new LinkedBlockingQueue<>(); Session s = connectNormally(msg -> q.add(msg)); t.send(new Broadcast().setSenderId("abc"), 1, 0); MmsMessage mm = q.poll(2, TimeUnit.SECONDS); assertEquals(1, mm.getMessageId()); assertEquals(0, mm.getLatestReceivedId()); assertEquals("abc", mm.cast(Broadcast.class).getSenderId()); // We need to acquire this lock to make sure we are out of the receiving loop (last ack adjusted s.receiveLock.lock(); s.receiveLock.unlock(); CompletableFuture<Void> cf = new CompletableFuture<>(); s.sendMessage(new Broadcast().setSenderId("cba"), cf); mm = t.t(); assertEquals(1, mm.getMessageId()); assertEquals(1, mm.getLatestReceivedId()); assertEquals("cba", mm.cast(Broadcast.class).getSenderId()); s.closeSession(MmsConnectionClosingCode.NORMAL); }
@Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.user_friends); m = new Menu(this); sess = new Session(FriendList.this); HashMap<String, String> map = sess.getUserDetails(); idd = map.get(Session.KEY_ID); il = new ImageLoader(FriendList.this); try { HashMap<String, Integer> map2 = sess.getBG(); int st = map2.get(Session.KEY_POS); Log.i("jkkk", "" + st); RelativeLayout rel = (RelativeLayout) findViewById(R.id.rel); rel.setBackgroundResource(icons[st]); } catch (Exception e) { e.printStackTrace(); } list1 = (GridView) findViewById(R.id.gridView1); friend(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.package.ACTION_LOGOUT"); registerReceiver(log, intentFilter); }
public Session startSession(SocketIOClient client) { Preconditions.checkNotNull(client); Session session = new Session(client.getRemoteAddress(), cateScraper, timetableScraper); sessions.put(client.getSessionId(), session); session.addSessionEventListener( new SessionEventListener() { @Override public void authSuccess(UserInfo userInfo) { if (motd != null) { session.motd(motd); } } @Override public void authLoginFailed() {} @Override public void authKick() {} @Override public void updateWork(WorkInfo work) {} @Override public void updateTimetable(Timetable timetable) {} @Override public void motd(String motd) {} }); return session; }
/** * NOTE: This method is intended for internal use. * * @param session - the Session that will process the message * @param messageString * @return the parsed message * @throws InvalidMessage */ public static Message parse(Session session, String messageString) throws InvalidMessage { final String beginString = getStringField(messageString, BeginString.FIELD); final String msgType = getMessageType(messageString); ApplVerID applVerID; if (FixVersions.BEGINSTRING_FIXT11.equals(beginString)) { applVerID = getApplVerID(session, messageString); } else { applVerID = toApplVerID(beginString); } final MessageFactory messageFactory = session.getMessageFactory(); final DataDictionaryProvider ddProvider = session.getDataDictionaryProvider(); final DataDictionary sessionDataDictionary = ddProvider == null ? null : ddProvider.getSessionDataDictionary(beginString); final DataDictionary applicationDataDictionary = ddProvider == null ? null : ddProvider.getApplicationDataDictionary(applVerID); final quickfix.Message message = messageFactory.create(beginString, msgType); final DataDictionary payloadDictionary = MessageUtils.isAdminMessage(msgType) ? sessionDataDictionary : applicationDataDictionary; message.parse( messageString, sessionDataDictionary, payloadDictionary, payloadDictionary != null); return message; }
public FacturaAlmacen actualiza(FacturaAlmacen otraFactura, Usuario usuario) throws NoEstaAbiertaException { FacturaAlmacen factura = (FacturaAlmacen) currentSession().get(FacturaAlmacen.class, otraFactura.getId()); switch (factura.getEstatus().getNombre()) { case Constantes.ABIERTA: Session session = currentSession(); factura.setVersion(otraFactura.getVersion()); factura.setFecha(otraFactura.getFecha()); factura.setComentarios(otraFactura.getComentarios()); factura.setIva(otraFactura.getIva()); factura.setTotal(otraFactura.getTotal()); factura.setCliente(otraFactura.getCliente()); Date fecha = new Date(); factura.setFechaModificacion(fecha); session.update(factura); audita(factura, usuario, Constantes.ACTUALIZAR, fecha); session.flush(); return factura; default: throw new NoEstaAbiertaException("No se puede actualizar una factura que no este abierta"); } }
/** {@inheritDoc} */ @SuppressWarnings({"unchecked", "RedundantTypeArguments"}) @Override public V load(@Nullable GridCacheTx tx, K key) throws GridException { init(); if (log.isDebugEnabled()) log.debug("Store load [key=" + key + ", tx=" + tx + ']'); Session ses = session(tx); try { GridCacheHibernateBlobStoreEntry entry = (GridCacheHibernateBlobStoreEntry) ses.get(GridCacheHibernateBlobStoreEntry.class, toBytes(key)); if (entry == null) return null; return fromBytes(entry.getValue()); } catch (HibernateException e) { rollback(ses, tx); throw new GridException("Failed to load value from cache store with key: " + key, e); } finally { end(ses, tx); } }
private void capture(Session s) { try { CaptureRequest.Builder captureBuilder = s.cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); captureBuilder.addTarget(s.reader.getSurface()); captureBuilder.set( CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); captureBuilder.set( CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); Descriptor camera = (Descriptor) s.getDescriptor(); CameraCharacteristics cc = mgr.getCameraCharacteristics(camera.cameraId); s.addToCaptureRequest(cc, camera.isFacingFront, captureBuilder); s.captureSession.stopRepeating(); s.captureSession.capture(captureBuilder.build(), new CapturePictureTransaction(s), null); } catch (Exception e) { getBus().post(new PictureTakenEvent(e)); if (isDebug()) { Log.e(getClass().getSimpleName(), "Exception running capture", e); } } }
/** {@inheritDoc} */ @Override public void put(@Nullable GridCacheTx tx, K key, @Nullable V val) throws GridException { init(); if (log.isDebugEnabled()) log.debug("Store put [key=" + key + ", val=" + val + ", tx=" + tx + ']'); if (val == null) { remove(tx, key); return; } Session ses = session(tx); try { GridCacheHibernateBlobStoreEntry entry = new GridCacheHibernateBlobStoreEntry(toBytes(key), toBytes(val)); ses.saveOrUpdate(entry); } catch (HibernateException e) { rollback(ses, tx); throw new GridException( "Failed to put value to cache store [key=" + key + ", val" + val + "]", e); } finally { end(ses, tx); } }
@Override public void deleteSubscription(int userId, int forumId) { // TODO Auto-generated method stub Session session = this.sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Query query = session.createQuery( "delete from Subscription where userId = :userId and forumId = :forumId"); query.setParameter("userId", userId); query.setParameter("forumId", forumId); int result = query.executeUpdate(); System.out.println("Execute query.."); if (result > 0) { tx.commit(); // System.out.println("Subscription Removed.."); } else { // System.out.println("Subscription does not exist"); tx.rollback(); } } catch (HibernateException e) { if (tx != null) { tx.rollback(); e.printStackTrace(); } } finally { session.close(); } }
/** {@inheritDoc} */ @Override public void txEnd(GridCacheTx tx, boolean commit) throws GridException { init(); Session ses = tx.removeMeta(ATTR_SES); if (ses != null) { Transaction hTx = ses.getTransaction(); if (hTx != null) { try { if (commit) { ses.flush(); hTx.commit(); } else hTx.rollback(); if (log.isDebugEnabled()) log.debug("Transaction ended [xid=" + tx.xid() + ", commit=" + commit + ']'); } catch (HibernateException e) { throw new GridException( "Failed to end transaction [xid=" + tx.xid() + ", commit=" + commit + ']', e); } finally { ses.close(); } } } }
@Override public void saveEventDetails(Event event) { // TODO Auto-generated method stub // Opening a session to create a database connection Session session = this.sessionFactory.openSession(); // for CRUD operations, we need to create a transaction Transaction tx = null; // adding a try catch block for maintaining the atomicity of transaction try { tx = session.beginTransaction(); System.out.println("DbHelper..saveEventDetails"); // session save inserts the object into DB session.save(event); tx.commit(); System.out.println("Event saved"); } catch (HibernateException e) { if (tx != null) { tx.rollback(); e.printStackTrace(); } } finally { session.close(); } }
/** * Gets Hibernate session. * * @param tx Cache transaction. * @return Session. */ Session session(@Nullable GridCacheTx tx) { Session ses; if (tx != null) { ses = tx.meta(ATTR_SES); if (ses == null) { ses = sesFactory.openSession(); ses.beginTransaction(); // Store session in transaction metadata, so it can be accessed // for other operations on the same transaction. tx.addMeta(ATTR_SES, ses); if (log.isDebugEnabled()) log.debug("Hibernate session open [ses=" + ses + ", tx=" + tx.xid() + "]"); } } else { ses = sesFactory.openSession(); ses.beginTransaction(); } return ses; }
public List<User> getUserSearchResults(int topicId) { // TODO Auto-generated method stub List<User> userArr = new ArrayList<User>(); Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Query query1 = session.createQuery("select userId from UserTopic where topicId = :topicId"); query1.setString("topicId", String.valueOf(topicId)); Query query2 = session.createQuery("from User where userId in (:userList)"); query2.setParameterList("userList", query1.list()); userArr = query2.list(); /*for(Topic topic : topicArr){ System.out.println("Topic Description----"+topic.getTopicDescription()); System.out.println("Topic Id----"+topic.getTopicId()); }*/ } catch (HibernateException e) { if (tx != null) { tx.rollback(); e.printStackTrace(); } } finally { session.close(); } return userArr; }
@Test public void sendMessageCompletable() throws Exception { BlockingQueue<MmsMessage> q = new LinkedBlockingQueue<>(); Session s = connectNormally(msg -> q.add(msg)); CompletableFuture<Void> cf = new CompletableFuture<>(); s.sendMessage(new Broadcast().setSenderId("abc"), cf); t.t(); // take and ignore t.send(new Broadcast().setSenderId("abc"), 1, 1); cf.get(2, TimeUnit.SECONDS); for (int i = 2; i < 100; i++) { cf = new CompletableFuture<>(); s.sendMessage(new Broadcast().setSenderId("abc" + i), cf); MmsMessage mm = t.t(); assertEquals(i, mm.getMessageId()); t.send(new Broadcast().setSenderId("abc"), i, mm.getMessageId()); cf.get(2, TimeUnit.SECONDS); } // if this breaks it is a timeing issue, just keep trying until its 99 assertEquals(99, s.latestReceivedId); s.closeSession(MmsConnectionClosingCode.NORMAL); }
@Override public HTTPSession createSession() { Session session = new Session(); session.setMaxContentLength(_maxContentLength); session.setAcceptedContentTypes(_acceptedContentTypes); return session; }
public List<TbAplicativo> datbAplicativos() { sesion = sessionFactory.openSession(); Query query = sesion.getNamedQuery("TbAplicativo.findAll"); List<TbAplicativo> tbAplicativo = query.list(); sesion.close(); return tbAplicativo; }