private void setTextArea() { String date = ""; String from = ""; String to = ""; to = removeFirstSpace(messageHandler.getToText()); try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/YYYY hh:mm a"); date = simpleDateFormat.format(message.getSentDate()); from = getFrom(); } catch (MessagingException e) { e.printStackTrace(); } referenceTextArea = textArea; textArea.setText( "\n\n\n" + ">Date: " + date + "\n" + ">From: " + from + "\n>To: " + to + "\n>" + messageHandler.getText()); textArea.setCaretPosition(0); }
protected void buildConstructorHeader() throws IOException { constructor1.append( "\n" + Def.TAB + "/**\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment.constr", symboleName) + "\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment.noRegistration") + "\n" + Def.TAB + " */\n"); constructor1.append(Def.TAB + Def.PUBLIC + symboleName + "(SnmpMib myMib)" + Def.LBRACE); constructor2.append( "\n" + Def.TAB + "/**\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment.constr", symboleName) + "\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment.registration") + "\n" + Def.TAB + " */\n"); constructor2.append( Def.TAB + Def.PUBLIC + symboleName + "(SnmpMib myMib, MBeanServer server)" + Def.LBRACE); }
private void addRowStatusSetter( Context ctxt, MibNode node, String description, String syntax, String var, StringBuffer buff) { buff.append( Def.TAB + "/**\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment.setter", var) + "\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment." + "setter.rs.nochecker") + "\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment." + "checker.rs.override") + "\n" + Def.TAB + " */\n"); buff.append( Def.TAB + Def.PUBLIC + Def.VOID + Def.SET + var + "(" + syntax + "x) " + accessThrows); buff.append(Def.TAB2 + var + " = x" + Def.SEMICOLON); buff.append(Def.TAB + Def.RBRACE + "\n"); }
/** Generates the code for the checker. */ protected void addChecker( Context ctxt, MibNode node, String description, String syntax, String var, StringBuffer buff) { buff.append( Def.TAB + "/**\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment.checker", var) + "\n" + Def.TAB + " */\n"); buff.append( Def.TAB + Def.PUBLIC + Def.VOID + Def.CHECK + var + "(" + syntax + "x) " + accessThrows); buff.append( Def.TAB2 + "//\n" + Def.TAB2 + "// " + MessageHandler.getMessage("generate.mbean.comment.checker.policy") + "\n" + Def.TAB2 + "//\n"); buff.append(Def.TAB + Def.RBRACE + "\n"); }
@Override protected void processCommand(int command) throws IOException { // System.out.println(command + " processing"); if (isFileBased(command) || command == ServerMethod.SAVE_PROJECT_WINDOW_BOUNDS || command == ServerMethod.CALLBACK || command == ServerMethod.UNREGISTER_LIBRARY_SETS || command == ServerMethod.LOG_WARNING) { super.processCommand(command); return; } switch (command) { case ServerMethod.SHOW_ERROR: final String errorMessage = reader.readUTF(); if (expectedError == null) { throw new TraceLessAssertionError(errorMessage); } else { if (!errorMessage.startsWith(expectedError)) { throw new TraceLessAssertionError( "Expected error message " + expectedError + ", but got " + errorMessage); } expectedError = null; } break; default: if (customMessageHandler != null && customMessageHandler.getExpectedCommand() == command) { customMessageHandler.process(); customMessageHandler = null; } else { throw new TraceLessAssertionError("Unexpected server command: " + command); } } }
// this is usually called OnMessage event public synchronized void notifyHandlers(Object data) { for (MessageHandler mh : handlers) { if (mh.accept(data)) { mh.onMessage(data); } } }
@Override public void execute(Message message) { if (!(message instanceof UserMessage)) return; UserMessage userMessage = (UserMessage) message; MessageHandler messageHandler = bot.getMessageHandler(); messageHandler.sendMessage(Tools.getCorrectTarget(userMessage), userMessage.getMessage()); }
/** {@inheritDoc} */ @Override public void close() { for (final MessageHandlerResult result : this.messageHandlers.keySet()) { for (final MessageHandler messageHandler : this.messageHandlers.get(result)) { messageHandler.close(); } } }
@Override public void disableHandler(String handlerId) { for (MessageHandler handler : handlers) { if (handler.getID().equals(handlerId)) { handler.disable(); } } }
@Test public void test_incorrect() { System.out.println("--- Testing with incorrect input values --- "); final String inputMessage = "{\"sum\":123,\"days\":-5}"; handler.setPublisher( new Publisher() { public boolean publish(String message) { assert false; return true; } public void setQueue(String queue) {} }); try { handler.getMessage(inputMessage); assert false; } catch (Exception e) { System.out.println(e.getMessage()); assert true; } final String inputMessage2 = "{\"sum\":-123,\"days\":5}"; try { handler.getMessage(inputMessage2); assert false; } catch (Exception e) { System.out.println(e.getMessage()); assert true; } final String inputMessage3 = "{\"sum\":0,\"days\":5}"; try { handler.getMessage(inputMessage3); assert false; } catch (Exception e) { System.out.println(e.getMessage()); assert true; } final String inputMessage4 = "{\"sum\":123,\"days\":0}"; try { handler.getMessage(inputMessage4); assert false; } catch (Exception e) { System.out.println(e.getMessage()); assert true; } System.out.println("--- End of test ---"); System.out.println(); }
private void createCcField() { if (!removeFirstSpace(messageHandler.getCcText()).equals("")) { ccField = new JTextField(removeBrackets(removeFirstSpace(messageHandler.getCcText()))); } else { ccField = new JTextField("Enter an address!"); } }
public void notify(Packet packet) { Log.trace("Register handling " + packet.toString()); String type = packet.getType(); Packet query = packet.getFirstChild("query"); if (type.equals("get")) { required.setSession(packet.getSession()); required.setID(packet.getID()); MessageHandler.deliverPacket(required); return; } else if (type.equals("set")) { // type == set String username = query.getChildValue("username"); User user = userIndex.getUser(username); if (user != null) { // user exists if (packet.getSession().getStatus() != Session.AUTHENTICATED || !username.equals(packet.getSession().getJID().getUser())) { Packet iq = new Packet("iq"); iq.setSession(packet.getSession()); iq.setID(packet.getID()); ErrorTool.setError(iq, 401, "User account already exists"); MessageHandler.deliverPacket(iq); return; } } else { user = userIndex.addUser(username); } user.setPassword(query.getChildValue("password")); user.setHash(query.getChildValue("hash")); user.setSequence(query.getChildValue("sequence")); user.setToken(query.getChildValue("token")); if (user.getHash() == null || user.getSequence() == null || user.getToken() == null) { if (user.getPassword() != null) { user.setToken(Authenticator.randomToken()); user.setSequence("99"); user.setHash( auth.getZeroKHash(100, user.getToken().getBytes(), user.getPassword().getBytes())); } } else { user.setSequence(Integer.toString(Integer.parseInt(user.getSequence()) - 1)); } Packet iq = new Packet("iq"); iq.setSession(packet.getSession()); iq.setID(packet.getID()); iq.setType("result"); // success MessageHandler.deliverPacket(iq); Log.trace( "Register successfully registered " + username + " with password " + query.getChildValue("password")); } else { Log.info("Register ignoring " + packet.toString()); } }
@Override public void setHandlerConfiguration(ProxyConfiguration configuration) { for (MessageHandler handler : this.handlers) { try { handler.setHandlerConfiguration(configuration); } catch (Exception ex) { logger.warn("An error occurs during the execution of the handler", ex); } } }
/** * Handle the message via {@link #innerHandle(AjahMessage)} and then call handle on child * handlers. * * @see com.ajah.rfcmail.fetch.MessageHandler#handle(AjahMimeMessage) */ @Override public final MessageHandlerResponse handle(final AjahMimeMessage message) throws MessagingException { AjahUtils.requireParam(message, "message"); AjahUtils.requireParam(message.getId(), "message.id"); final MessageHandlerResponse response = innerHandle(message); for (final MessageHandler messageHandler : this.messageHandlers.getList(response.getResult())) { messageHandler.handle(message); } return null; }
@Override public void handleMessage(InMessage inMessage, OutMessage outMessage) throws Exception { logger.debug("Message received, calling registered handlers"); for (MessageHandler handler : this.handlers) { try { handler.handleMessage(inMessage, outMessage); } catch (Exception ex) { logger.warn("An error occurs during the execution of the handler", ex); } } }
@Override public void close() throws IOException { bout.close(); output.close(); Iterator<MessageHandler> it = config.getMessagerHandlers(); while (it.hasNext()) { MessageHandler handler = it.next(); handler.handleRequest(url, bout.toByteArray()); } }
@Bindable // TODO: migrate to CSV datasource public void finish() { if (finishButton.isDisabled()) { return; } finishButton.setDisabled(true); final String datasourceName = this.wizardModel.getDatasourceName(); // Validating whether the datasource name contains any illegal characters if (isDatasourceNameValid(datasourceName)) { UIDatasourceServiceManager manager = UIDatasourceServiceManager.getInstance(); manager.getIds( new XulServiceCallback<List<IDatasourceInfo>>() { @Override public void success(List<IDatasourceInfo> datasourceInfos) { finishButton.setDisabled(false); boolean isEditing = wizardModel.isEditing(); List<String> datasourceNames = new ArrayList<String>(); for (IDatasourceInfo datasourceInfo : datasourceInfos) { if (datasourceInfo.getType().equals("Data Source Wizard") || datasourceInfo.getType().equals("Analysis")) { datasourceNames.add(datasourceInfo.getName()); } } if (datasourceNames.contains(datasourceName) && !isEditing) { showWarningDialog(); } else { setFinished(); } } @Override public void error(String s, Throwable throwable) { finishButton.setDisabled(false); throwable.printStackTrace(); MessageHandler.getInstance().showErrorDialog(throwable.getMessage()); } }); } else { finishButton.setDisabled(false); MessageHandler.getInstance() .showErrorDialog( "Error", MessageHandler //$NON-NLS-1$ .getString( "DatasourceEditor.ERROR_0005_INVALID_DATASOURCE_NAME", NameUtils.reservedCharListForDisplay(" ")), true); //$NON-NLS-1$ } }
private void respondToQuery(Query query) { handler.identifyKeyword(query); String response = handler.getResponse(query); try { connection.sendSms(query.getPhoneNumber(), response); query.setTimeResponded(new Date()); query.setResponse(response); log(query); } catch (SmsSendException e) { // TODO error log this e.printStackTrace(); } }
public void init() throws ServletException { ServletContext ctx = getServletContext(); remoteHost = ctx.getInitParameter("RMI_SERVER"); // Reads the value from the <context-param> in web.xml mh = new MessageHandler(); // Instantiate message handler on service start vmh = new VigenereRequestManager( mh.getQueue(), mh.getMap(), remoteHost); // Instansiate Request manager at service start with references to same // queue and map as message handler executorService.execute(vmh); // Run the Request service daemon }
@Override public InputStream getContent() throws IOException { InputStream in; try { successful = true; in = connection.getInputStream(); } catch (IOException e) { successful = false; in = connection.getErrorStream(); if (in == null) { throw e; } } String encoding = connection.getHeaderField("Content-Encoding"); if (config.getMaxResponseSize() > 0) { in = new LimitingInputStream(config.getMaxResponseSize(), in); } if ("gzip".equals(encoding)) { in = new GZIPInputStream(in); } if (config.hasMessageHandlers() || config.isTraceMessage()) { byte[] bytes = FileUtil.toBytes(in); in = new ByteArrayInputStream(bytes); if (config.hasMessageHandlers()) { Iterator<MessageHandler> it = config.getMessagerHandlers(); while (it.hasNext()) { MessageHandler handler = it.next(); if (handler instanceof MessageHandlerWithHeaders) { ((MessageHandlerWithHeaders) handler) .handleResponse(url, bytes, connection.getHeaderFields()); } else { handler.handleResponse(url, bytes); } } } if (config.isTraceMessage()) { new TeeInputStream(config, bytes); } } return in; }
public MbeanGenerator(ResourceManager mgr, MibNode aGroup, Context ctxt) throws IOException { super(mgr, aGroup, ctxt); gentype = ctxt.gentype; // Specify oid of the current bean ... // oid = node.getComputedOid(); // Try to find a symbol to associate to the group // varName = node.getSymbolName(); if (varName == null) varName = getClassName(node.getComputedOid()); symboleName = getNodeSymbolName(node); Trace.info(MessageHandler.getMessage("generate.info.var", varName)); // Open the file which will represent the M-bean. // out = openFile(symboleName + Def.JAVA); // Write generic header ... // writeHeader(); // write our own header ... // writeClassDeclaration(); // write the beginning of the constructor // buildConstructorHeader(); }
/** * Called when data arrives from the a user. In this case, this is called any time the client * associated with this <code>Player</code> sends a message directly to the server (i.e., not a * broadcast message like a chat comment). This method, therefore, is the handler for all client * messages, and so we hold the lock on the <code>Player</code> and not some more generally shared * logic while we're processing messages. * * <p>Note that this method only gets called when the client sends messages via the <code> * ClientConnectionManager.sendToServer</code> method. For details about broadcast messages, see * this class' implementation of <code>dataArrivedFromChannel</code> * * @param uid the user id, which is always this <code>Player</code>'s current uid * @param data the message */ public void receivedMessage(ByteBuffer message) { // call the message handler to interpret the message ... note that the // proxy model here means that we're blocking the player, and not the // game itself, while we're handling the message byte[] messageBytes = new byte[message.remaining()]; message.get(messageBytes); messageHandler.handleMessage(this, messageBytes); }
private void addRowStatusChecker( Context ctxt, MibNode node, String description, String syntax, String var, StringBuffer buff) { buff.append( Def.TAB + "/**\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment.checker", var) + "\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment.checker.rs.deprecated") + "\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment.checker.rs.override") + "\n" + Def.TAB + " */\n"); buff.append( Def.TAB + Def.PUBLIC + Def.VOID + Def.CHECK + var + "(" + syntax + "x) " + BeanGenerator.accessThrows); buff.append( Def.TAB2 + "//\n" + Def.TAB2 + "// " + MessageHandler.getMessage("generate.mbean.comment.checker.rs.policy") + "\n" + Def.TAB2 + "//\n"); buff.append(Def.TAB + Def.RBRACE + "\n"); }
// Register all the exposed APIs TO message handler. // @handler the message handler APIs will be registered in. // @object the target object of the handler. public static void registerHandlers( ReflectionHelper reflection, MessageHandler handler, Object object) { if (reflection == null || handler == null) return; for (String key : reflection.getMembers().keySet()) { MemberInfo m = reflection.getMembers().get(key); handler.register(m.jsName, m.javaName, m.type, object, reflection); } }
@Override public void onReceive(Context context, Intent intent) { preferencesManager = PreferencesManager.getInstance(context); String action = intent.getAction(); if (action.compareTo("android.provider.Telephony.SMS_RECEIVED") == 0) { // Check if the SMS trigger is enabled if (!preferencesManager.smsTriggerEnabled()) return; Bundle bundle = intent.getExtras(); SmsMessage[] messages = null; String message = ""; if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); messages = new SmsMessage[pdus.length]; for (int i = 0; i < messages.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); message = messages[i].getMessageBody().toString(); String source = messages[i].getOriginatingAddress(); if (MessageHandler.processMessage(context, new SmsReceiver(), message, source)) // Drop the SMS message so it doesn't go to the user's inbox this.abortBroadcast(); } } } else { int resultCode = getResultCode(); String message = getResultData(); String source; if (intent.hasExtra("source")) source = intent.getStringExtra("source"); else // If there is no source in the intent, there is no way to send a reply return; if (intent.getAction().compareTo("com.dririan.RingyDingyDingy.COMMAND_HELP") == 0) message = context.getString(R.string.sms_help); else if (message == null) { switch (resultCode) { case Activity.RESULT_OK: message = context.getString(R.string.sms_success); break; case ApiHandler.RESULT_UNKNOWN_COMMAND: message = context.getString(R.string.sms_unknown_command); break; default: message = context.getString(R.string.sms_unknown_error); break; } } sendSms(context, source, message.replace("<code>", preferencesManager.getCode())); } }
// once-per-game initialization private void initOnce() { initialized = true; log.info("initOnce()"); visualizerService.newRun(); // registrations for message listeners: Collection<MessageHandler> handlers = context.getBeansOfType(MessageHandler.class).values(); for (MessageHandler handler : handlers) { log.debug("initializing..." + handler.getClass().getName()); handler.initialize(); } Collection<DomainRepo> repos = context.getBeansOfType(DomainRepo.class).values(); for (DomainRepo repo : repos) { log.debug("recycling..." + repos.getClass().getName()); repo.recycle(); } }
@Override public void handleMessage(Socket socket) { log(Level.DEBUG, MSG_TYPE.REC, socket, "JOIN_GAME"); String startLocation = PropertiesLoader.getInstance().load("server.properties").getProperty("startlocation", ""); String startMap = startLocation; int startX = 5, startY = 5; if (startLocation.contains(",")) { startMap = startLocation.split(",")[0].trim(); startX = Integer.valueOf(startLocation.split(",")[1].trim()); startY = Integer.valueOf(startLocation.split(",")[2].trim()); } // Load the player from the database String playerName = socket.getInetAddress().getHostAddress(); Player yourPlayer = new Player(playerName, "knightImage", startMap); if ((int) (Math.random() * 2) == 0) yourPlayer.setRef("mageImage"); yourPlayer.setLocation(startX, startY); try { sendTo(socket, "SET_REF:YOU," + yourPlayer.getRef()); sendTo(socket, "SET_NAME:YOU," + yourPlayer.getName()); synchronized (this) { // Add the player to the game players.put(socket, yourPlayer); String joinGameMessage = "CHAT:BROADCAST,#00FF00," + yourPlayer.getName() + " has joined the game!"; String welcomeMessage = "CHAT:BROADCAST,#00FFFF,Welcome to SimpleOrpg!"; sendTo(socket, welcomeMessage); WhoHandler whoHandler = new WhoHandler(); whoHandler.handleMessage(socket); sendAll(joinGameMessage); } MessageHandler joinMapHandler = new JoinMapHandler(); joinMapHandler.handleMessage(socket); } catch (Exception ex) { log(Level.ERROR, socket, ex.getMessage(), ex.getCause()); } }
protected void addCacheVar(MibNode node, String syntax, long fixed, String init, String var) throws IOException { // Put some comments ... // var_list.append( Def.TAB + "/**\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment.varUse", var) + "\n" + Def.TAB + " * " + MessageHandler.getMessage("generate.mbean.comment.varOid", node.getOid()) + "\n" + Def.TAB); if (fixed != -1) { var_list.append( " * " + MessageHandler.getMessage("generate.mbean.comment.varFix", String.valueOf(fixed)) + "\n" + Def.TAB); } // Shall we put the description in the generated code ? // if yes call the formatDescription method ... // The answer is yes if requested ! if (mib.isDescriptionOn()) { // Get the object definition associated to the node // ASTObjectTypeDefinition definition = node.getObjectType(); String description = definition.getDefinition().getDescription(); var_list.append(formatDescription(description)); } var_list.append(" */\n"); if (init == null) init = ""; // Declare the variable // var_list.append(Def.TAB + Def.PROTECTED + syntax + var + init + Def.SEMICOLON + "\n"); }
/** * Initializes the Transfer manager to use a protocol to open connections. * * @param protocol Protocol to be used * @param properties Location of the properties files * @param mh Handler for the events produced by the connections */ public static void init(String protocol, String properties, MessageHandler mh) { if (protocol.contentEquals("NIO")) { em = new NIOEventManager(mh); } try { em.init(properties); } catch (Exception e) { LOGGER.error(PROPERTIES_ERROR, e); } mh.init(); em.start(); }
@Override public void run() { try { try { if (flShowProgress) MessageHandler.obtainMessage(MESSAGE_PROGRESSBAR_SHOW).sendToTarget(); try { TTracker Tracker = TTracker.GetTracker(TSensorsMetersPanel.this.getApplicationContext()); if (Tracker == null) throw new Exception(getString(R.string.STrackerIsNotInitialized)); // . => Device = Tracker.GeoLog; // . MetersInfo = Device.SensorsModule.Meters.Items_GetList(); } finally { if (flShowProgress) MessageHandler.obtainMessage(MESSAGE_PROGRESSBAR_HIDE).sendToTarget(); } // . MessageHandler.obtainMessage(MESSAGE_COMPLETED).sendToTarget(); } catch (InterruptedException E) { } catch (IOException E) { MessageHandler.obtainMessage(MESSAGE_EXCEPTION, E).sendToTarget(); } catch (Throwable E) { MessageHandler.obtainMessage(MESSAGE_EXCEPTION, new Exception(E.getMessage())) .sendToTarget(); } } finally { MessageHandler.obtainMessage(MESSAGE_FINISHED).sendToTarget(); } }