/** Test of TCP socket programming. */ public void listen() { ServerSocket socket = null; try { socket = new ServerSocket(PORT_NO); System.out.println("Opened server socket"); socket.setSoTimeout(TIMEOUT); connection = socket.accept(); System.out.println("Server: Received connection from port " + connection.getPort()); System.out.println("Server: local port: " + connection.getLocalPort()); ObjectInputStream iStream = new ObjectInputStream(connection.getInputStream()); MessageObject message = (MessageObject) iStream.readObject(); System.out.println("message received... by server"); System.out.println( "Server: received object, item=" + message.getItem() + " count: " + message.getCount()); // sendResponse("'Acknowledging message: object, item=" + message.getItem() + " count: " // + message.getCount()+"'"); connection.close(); socket.close(); } catch (SocketTimeoutException ste) { System.out.println("Timed out after " + TIMEOUT + " ms"); } catch (Exception e) { System.out.println(e.getClass().getName() + " at server: " + e.getMessage()); } } /*
private void createRobotServerMappingFile(List<Element> msgElements, String module) throws Exception { List<MessageObject> toGSMsgs = new ArrayList<MessageObject>(); for (Iterator i = msgElements.iterator(); i.hasNext(); ) { Element message = (Element) i.next(); MessageObject msg = new MessageObject(); String msgType = message.getAttributeValue("type"); msg.setType(msgType); msg.setClassName(GeneratorHelper.generateServerClassName(msgType)); String msgTypePrefix = msgType.substring(1, 2); toGSMsgs.add(msg); } if (toGSMsgs.size() == 0) { return; } VelocityContext context = new VelocityContext(); context.put("module", module); String mappingClassName = StringUtils.upperCaseFirstCharOnly(module) + "MsgMappingProvider"; context.put("classname", mappingClassName); if (toGSMsgs.size() > 0) { context.put("msgs", toGSMsgs); String outputFile = robotRootPath + "msg" + File.separator + mappingClassName + ".java"; GeneratorHelper.generate(context, robotMappingTemplate_game, outputFile); } }
/** * Receives the bytes that have been sent over the connection, constructs a <code>Message</code> * object, and returns it. * * <p>If there are no <code>Message</code>s waiting on the connection, this method will block * until a message is received, or the <code>MessageConnection</code> is closed. * * @return a <code>Message</code> object * @exception IOException if an I/O error occurs. */ public synchronized Message receive() throws IOException { dgc.receive(mess); /* get message buffer and extract info */ byte[] buf = mess.getData(); SMSPacket packet = new SMSPacket(buf); int msgType = packet.getEncodingType(); int smsPort = packet.getPort(); long time = packet.getTimeStamp(); String address = packet.getAddress(); String phoneNumber = packet.getPhoneNumber(); int msgLen = packet.getMessageLength(); byte[] messg = packet.getMessage(msgLen); debug("SMS PACKET: encodingType = " + msgType); debug("SMS PACKET: port = " + smsPort); debug("SMS PACKET: time = " + time); debug("SMS PACKET: address = " + address); debug("SMS PACKET: Sender's phone number = " + phoneNumber); debug("SMS PACKET: message length = " + msgLen); debug("SMS PACKET: message:" + new String(messg)); Message msg = null; if (msgType == MessageTransportConstants.GSM_TEXT || msgType == MessageTransportConstants.GSM_UCS2) { TextMessage textmsg = (TextMessage) newMessage(MessageConnection.TEXT_MESSAGE, address); /* Always store text messages as UCS 2 bytes. */ if (msgType == MessageTransportConstants.GSM_TEXT) { messg = TextEncoder.decode(messg); } ((TextObject) textmsg).setPayloadData(messg); msg = textmsg; } else { BinaryMessage binmsg = (BinaryMessage) newMessage(MessageConnection.BINARY_MESSAGE, address); ((BinaryObject) binmsg).setPayloadData(messg); msg = binmsg; } ((MessageObject) msg).setTimeStamp(time); return msg; }
@SuppressLint("NewApi") private void createNotification(MessageObject messageObject) { String songName = messageObject.getMusicTitle(); String authorName = messageObject.getMusicAuthor(); AudioInfo audioInfo = MediaController.getInstance().getAudioInfo(); RemoteViews simpleContentView = new RemoteViews( getApplicationContext().getPackageName(), R.layout.player_small_notification); RemoteViews expandedView = null; if (supportBigNotifications) { expandedView = new RemoteViews( getApplicationContext().getPackageName(), R.layout.player_big_notification); } Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class); intent.setAction("com.tmessages.openplayer"); intent.setFlags(32768); PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, 0); Notification notification = new NotificationCompat.Builder(getApplicationContext()) .setSmallIcon(R.drawable.player) .setContentIntent(contentIntent) .setContentTitle(songName) .build(); notification.contentView = simpleContentView; if (supportBigNotifications) { notification.bigContentView = expandedView; } setListeners(simpleContentView); if (supportBigNotifications) { setListeners(expandedView); } Bitmap albumArt = audioInfo != null ? audioInfo.getSmallCover() : null; if (albumArt != null) { notification.contentView.setImageViewBitmap(R.id.player_album_art, albumArt); if (supportBigNotifications) { notification.bigContentView.setImageViewBitmap(R.id.player_album_art, albumArt); } } else { notification.contentView.setImageViewResource( R.id.player_album_art, R.drawable.nocover_small); if (supportBigNotifications) { notification.bigContentView.setImageViewResource( R.id.player_album_art, R.drawable.nocover_big); } } if (MediaController.getInstance().isDownloadingCurrentMessage()) { notification.contentView.setViewVisibility(R.id.player_pause, View.GONE); notification.contentView.setViewVisibility(R.id.player_play, View.GONE); notification.contentView.setViewVisibility(R.id.player_next, View.GONE); notification.contentView.setViewVisibility(R.id.player_previous, View.GONE); notification.contentView.setViewVisibility(R.id.player_progress_bar, View.VISIBLE); if (supportBigNotifications) { notification.bigContentView.setViewVisibility(R.id.player_pause, View.GONE); notification.bigContentView.setViewVisibility(R.id.player_play, View.GONE); notification.bigContentView.setViewVisibility(R.id.player_next, View.GONE); notification.bigContentView.setViewVisibility(R.id.player_previous, View.GONE); notification.bigContentView.setViewVisibility(R.id.player_progress_bar, View.VISIBLE); } } else { notification.contentView.setViewVisibility(R.id.player_progress_bar, View.GONE); notification.contentView.setViewVisibility(R.id.player_next, View.VISIBLE); notification.contentView.setViewVisibility(R.id.player_previous, View.VISIBLE); if (supportBigNotifications) { notification.bigContentView.setViewVisibility(R.id.player_next, View.VISIBLE); notification.bigContentView.setViewVisibility(R.id.player_previous, View.VISIBLE); notification.bigContentView.setViewVisibility(R.id.player_progress_bar, View.GONE); } if (MediaController.getInstance().isAudioPaused()) { notification.contentView.setViewVisibility(R.id.player_pause, View.GONE); notification.contentView.setViewVisibility(R.id.player_play, View.VISIBLE); if (supportBigNotifications) { notification.bigContentView.setViewVisibility(R.id.player_pause, View.GONE); notification.bigContentView.setViewVisibility(R.id.player_play, View.VISIBLE); } } else { notification.contentView.setViewVisibility(R.id.player_pause, View.VISIBLE); notification.contentView.setViewVisibility(R.id.player_play, View.GONE); if (supportBigNotifications) { notification.bigContentView.setViewVisibility(R.id.player_pause, View.VISIBLE); notification.bigContentView.setViewVisibility(R.id.player_play, View.GONE); } } } notification.contentView.setTextViewText(R.id.player_song_name, songName); notification.contentView.setTextViewText(R.id.player_author_name, authorName); if (supportBigNotifications) { notification.bigContentView.setTextViewText(R.id.player_song_name, songName); notification.bigContentView.setTextViewText(R.id.player_author_name, authorName); } notification.flags |= Notification.FLAG_ONGOING_EVENT; startForeground(5, notification); if (remoteControlClient != null) { RemoteControlClient.MetadataEditor metadataEditor = remoteControlClient.editMetadata(true); metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, authorName); metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, songName); if (audioInfo != null && audioInfo.getCover() != null) { try { metadataEditor.putBitmap( RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK, audioInfo.getCover()); } catch (Throwable e) { FileLog.e("tmessages", e); } } metadataEditor.apply(); } }
/** * 设置消息对象的字段 * * @param msgObj * @param msgElement */ private void setMsgObjFields( MessageObject msgObj, List fElements, boolean isClient, boolean isCppClient) { for (Iterator j = fElements.iterator(); j.hasNext(); ) { Element fElement = (Element) j.next(); FieldObject field = new FieldObject(); field.setType(fElement.getAttributeValue("type")); field.setClientType(fElement.getAttributeValue("clientType")); if (StringUtils.isEmpty(field.getClientType())) { field.setClientType(GeneratorHelper.getClientClassName(field.getType()) + "Data"); } field.setSmallName(fElement.getAttributeValue("name")); field.setComment(fElement.getAttributeValue("comment")); if (fElement.getAttribute("defaultValue") != null) { String defaultValue = fElement.getAttributeValue("defaultValue"); if (StringUtils.isEmpty(defaultValue)) { if (!TYPE_STRING.equals(field.getType())) { defaultValue = "0"; } else { defaultValue = ""; } } if (TYPE_STRING.equals(field.getType())) { defaultValue = "\"" + defaultValue + "\""; } field.setDefaultValue("=" + defaultValue); } else { field.setDefaultValue(""); } List<Element> subFieldElements = fElement.getChildren("field", NAME_SPACE); if (fElement.getAttributeValue("bytes") != null) { field.setBytes(fElement.getAttributeValue("bytes").equals("true") ? true : false); } if (fElement.getAttributeValue("list") != null) { field.setList(fElement.getAttributeValue("list").equals("true") ? true : false); msgObj.setHasListField(true); } boolean isSubMsg = "true".equalsIgnoreCase(fElement.getAttributeValue("subMsg")); field.setSubMsg(isSubMsg); if (isSubMsg) { field.setSubMsgType(GeneratorHelper.generateServerClassName(field.getType())); msgObj.setListMsg(true); if (isCppClient) { field.setList(true); msgObj.setHasListField(true); field.setType("_LZOBEX_" + field.getType()); } } // 如果不是系统定义的类型则说明是子消息 if (!new ArrayListWrapper(sysTypes).contains(field.getType())) { if (!isCppClient || !field.isSubMsg()) { field.setIsNewType(true); if (!isClient && field.getType().indexOf("_") > 0) { field.setType(GeneratorHelper.generateServerClassName(field.getType())); } } } if (subFieldElements.size() > 0) { this.setSubFields(field, subFieldElements); } else { if (isClient && field.getIsNewType()) { // 客户端生成消息的时候要为其补全 field.setSubFields(fields.get(field.getType())); } if (!isClient && field.getList() && field.getIsNewType()) { String type = field.getType(); field.setSubFields(msgs.get(type).getFields()); } } if (field.isSubMsg() && !isCppClient) { msgObj.addSubMsg(field); } else { msgObj.addField(field); } } }
/** * 生成客户端数据模型 * * @param messages */ private void createClientModel(List<MessageObject> messages, String module) { Map<String, FieldObject> newTypeFields = new HashMap<String, FieldObject>(); for (MessageObject msgObj : messages) { List<FieldObject> fields = msgObj.getFields(); for (FieldObject fieldObject : fields) { if (fieldObject.getIsNewType()) { // 先遍历它的子类型 for (FieldObject subfieldObject : fieldObject.getSubFields()) { if (subfieldObject.getIsNewType()) { // 先遍历子类型的子类型 for (FieldObject subsubfieldObject : subfieldObject.getSubFields()) { if (subsubfieldObject.getIsNewType()) { // 先遍历子类型的子类型 for (FieldObject sssfieldObject : subsubfieldObject.getSubFields()) { if (sssfieldObject.getIsNewType()) { sssfieldObject.setType(sssfieldObject.getClientType()); if (sssfieldObject.getClientType().contains(".")) { sssfieldObject.setType( GeneratorHelper.getClientClassName(sssfieldObject.getType())); continue; } newTypeFields.put(sssfieldObject.getClientType(), sssfieldObject); } } subsubfieldObject.setType(subsubfieldObject.getClientType()); if (subsubfieldObject.getClientType().contains(".")) { subsubfieldObject.setType( GeneratorHelper.getClientClassName(subsubfieldObject.getType())); continue; } newTypeFields.put(subsubfieldObject.getClientType(), subsubfieldObject); } } // subfieldObject.setType(subfieldObject.getClientType()); if (subfieldObject.getClientType().contains(".")) { subfieldObject.setType( GeneratorHelper.getClientClassName(subfieldObject.getType())); continue; } newTypeFields.put(subfieldObject.getClientType(), subfieldObject); } } fieldObject.setType(fieldObject.getClientType()); if (fieldObject.getClientType().contains(".")) { fieldObject.setType(GeneratorHelper.getClientClassName(fieldObject.getType())); continue; } newTypeFields.put(fieldObject.getClientType(), fieldObject); } } } for (FieldObject fieldObject : newTypeFields.values()) { VelocityContext context = new VelocityContext(); context.put("modulename", module); context.put("model", fieldObject); String outputFilePath; if (replaceDirectly) { outputFilePath = dataPath + fieldObject.getType() + ".as"; } else { outputFilePath = clientRootPath + File.separator + module + File.separator + "data" + File.separator + fieldObject.getType() + ".as"; } try { GeneratorHelper.generate(context, clientModelTemplate, outputFilePath); } catch (Exception e) { e.printStackTrace(); } } }
/** * 生成客户端文件,每个模块一个文件 * * @param msgElements * @throws Exception */ private void createClientFile( List<Element> msgElements, String module, List<Element> contantElements) throws Exception { List<MessageObject> cgMsgs = new ArrayList<MessageObject>(); List<MessageObject> gcMsgs = new ArrayList<MessageObject>(); List<MessageObject> allClientMsgs = new ArrayList<MessageObject>(); for (Iterator i = msgElements.iterator(); i.hasNext(); ) { Element mElement = (Element) i.next(); MessageObject msgObj = new MessageObject(); String msgType = mElement.getAttributeValue("type"); fields.put(msgType, msgObj.getFields()); msgObj.setType(msgType); msgObj.setClassName(GeneratorHelper.generateServerClassName(msgType)); msgObj.setModule(mElement.getAttributeValue("module")); msgObj.setComment(mElement.getAttributeValue("comment")); msgObj.setHandleMethodName(GeneratorHelper.generateHandleMethodName(msgType)); List fElements = mElement.getChildren("field", NAME_SPACE); this.setMsgObjFields(msgObj, fElements, true, false); if (msgType.substring(0, 2).equalsIgnoreCase("cg")) { cgMsgs.add(msgObj); } else if (msgType.substring(0, 2).equalsIgnoreCase("gc")) { gcMsgs.add(msgObj); } if (msgType.contains("c") || msgType.contains("C")) { allClientMsgs.add(msgObj); } } this.createClientModel(allClientMsgs, module); List<ConstantObject> contants = new ArrayList<ConstantObject>(); for (Iterator i = contantElements.iterator(); i.hasNext(); ) { Element constantElement = (Element) i.next(); String constantName = constantElement.getAttributeValue("name"); String constantDesc = constantElement.getValue(); ConstantObject constantObj = new ConstantObject( constantName, constantDesc .replaceAll(File.separator + "n", "") .replaceAll(File.separator + "r", "") .trim()); contants.add(constantObj); } VelocityContext context = new VelocityContext(); context.put("module", StringUtils.upperCaseFirstCharOnly(module)); context.put("modulename", module); for (String templateFileName : clientMsgTemplates) { String outputFileNameSuffix = null; String templatePrefix = templateFileName.substring(0, 2); if (templatePrefix.equals("gc")) { if (gcMsgs.size() == 0) { continue; } context.put("msgs", gcMsgs); outputFileNameSuffix = "GCMessage.as"; } else if (templatePrefix.equals("cg")) { if (cgMsgs.size() == 0) { continue; } context.put("msgs", cgMsgs); outputFileNameSuffix = "CGMessage.as"; } context.put("constants", contants); String outputFilePath; if (replaceDirectly) { outputFilePath = messagePath + StringUtils.upperCaseFirstCharOnly(module) + outputFileNameSuffix; } else { outputFilePath = clientRootPath + File.separator + module + File.separator + "message" + File.separator + StringUtils.upperCaseFirstCharOnly(module) + outputFileNameSuffix; } GeneratorHelper.generate(context, templateFileName, outputFilePath); } }
/** * 生成服务器端文件,每个消息一个文件 * * @param messages * @throws Exception */ private void createServerFiles(List<Element> messages, String module) throws Exception { for (Iterator i = messages.iterator(); i.hasNext(); ) { Element msgElement = (Element) i.next(); MessageObject msgObj = new MessageObject(); String msgType = msgElement.getAttributeValue("type"); msgObj.setType(msgType); msgObj.setClassName(GeneratorHelper.generateServerClassName(msgType)); msgObj.setModule(module); msgObj.setComment(msgElement.getAttributeValue("comment")); msgObj.setHandleMethodName(GeneratorHelper.generateHandleMethodName(msgType)); if (msgElement.getAttributeValue("playerQueue") != null) { msgObj.setPlayerQueue( msgElement.getAttributeValue("playerQueue").equals("true") ? true : false); } if (msgElement.getAttributeValue("friendQueue") != null) { msgObj.setFriendQueue(msgElement.getAttribute("friendQueue").getValue().equals("true")); } if (msgElement.getAttributeValue("guildQueue") != null) { msgObj.setGuildQueue(msgElement.getAttribute("guildQueue").getValue().equals("true")); } List fElements = msgElement.getChildren("field", NAME_SPACE); setMsgObjFields(msgObj, fElements, false, false); VelocityContext context = new VelocityContext(); context.put("message", msgObj); context.put("list", msgObj.getFields()); String templateFileName = ""; String outputFile = ""; for (int j = 0; j < serverMsgTemplates.length; j++) { String templateName = serverMsgTemplates[j]; if (templateName.substring(0, 2).equalsIgnoreCase(msgType.substring(0, 2))) { templateFileName = templateName; char lastCharOfTempate = templateName.charAt(templateName.length() - 4); switch (lastCharOfTempate) { case 'g': // 放在GameServer outputFile = gameRootPath + msgObj.getModule() + File.separator + "msg" + File.separator + msgObj.getClassName() + ".java"; break; default: throw new RuntimeException("模板名称非法," + templateName); } GeneratorHelper.generate(context, templateFileName, outputFile); // JavaGeneratorHelper.generateJavaFile(msgObj, outputFile + "0"); } } msgs.put(msgObj.getClassName(), msgObj); } }
public static void main(String[] args) { MessageObject messageObject = new MessageObject(1, 7654321, "/d/lv8918/123456", 5, 2, "OK", ""); System.out.println(messageObject.toJson()); }
/** * If NF_HEADER_LOCATION_PROP exists in context use as the header to forward to Gateway. If * IS_ASYNCHRONOUS_PROP exists in context then use that value to call either processAsync or * processSync * * @param input MessageObject containing the value to be processed * * @param mpcontext The context * @return Optional NVPair containing a Destination name and a MessageObject, or null if none. * @exception ProcessingException Thrown if processing fails. * @exception MessageException Thrown if bad message. */ public NVPair[] process(MessageProcessorContext ctx, MessageObject input) throws MessageException, ProcessingException { if (input == null) return null; try { serverName = getRequiredProperty(ctx, input, SERVER_NAME_PROP); } catch (MessageException me) { throw new ProcessingException(me.getMessage()); } if (StringUtils.hasValue(headerLocation)) { try { header = getString(headerLocation, ctx, input); } catch (MessageException me) { throw new ProcessingException(me.getMessage()); } } if (StringUtils.hasValue(isAsyncLocation)) { try { isAsync = StringUtils.getBoolean(getString(isAsyncLocation, ctx, input)); } catch (FrameworkException fe) { throw new ProcessingException( "Value of " + IS_ASYNCHRONOUS_LOCATION_PROP + " is not TRUE/FALSE. " + fe.getMessage()); } } // Fetch the alternate Orb Address, if one exists at the specified context location if (StringUtils.hasValue(orbAgentAddrLocation)) { try { if (exists(orbAgentAddrLocation, ctx, input, true)) { orbAgentAddr = getString(orbAgentAddrLocation, ctx, input); if (Debug.isLevelEnabled(Debug.MSG_STATUS)) Debug.log( Debug.MSG_STATUS, "RequestHandlerClient:: alternate orb exists with orb agent address [" + orbAgentAddr + "]"); } } catch (MessageException me) { throw new ProcessingException(me.getMessage()); } } // Fetch the alternate Orb Port, if one exists at the specified context location if (StringUtils.hasValue(orbAgentPortLocation)) { try { if (exists(orbAgentPortLocation, ctx, input, true)) { orbAgentPort = getString(orbAgentPortLocation, ctx, input); if (Debug.isLevelEnabled(Debug.MSG_STATUS)) Debug.log( Debug.MSG_STATUS, "RequestHandlerClient:: alternate orb exists with orb agent port [" + orbAgentPort + "]"); } } catch (MessageException me) { throw new ProcessingException(me.getMessage()); } } String msg = input.getString(); try { try { return (formatNVPair(makeClientCall(serverName, false, header, msg))); } catch (Exception e) { // Any of the following exceptions indicate that the failure might be due to // a CORBA communications issue (stale object reference) that should be retried. if ((e instanceof org.omg.CORBA.OBJECT_NOT_EXIST) || (e instanceof org.omg.CORBA.TRANSIENT) || (e instanceof org.omg.CORBA.COMM_FAILURE) || (e instanceof org.omg.CORBA.INV_OBJREF) || (e instanceof org.omg.CORBA.UNKNOWN)) { Debug.warning( "Caught the following CORBA communication error, so retrying:\n" + e.toString() + "\n" + Debug.getStackTrace(e)); return (formatNVPair(makeClientCall(serverName, true, header, msg))); } else { // It's not a communication exception indicating that retry is recommended, // so just re-throw it. throw e; } } } catch (Exception e) { if (e instanceof InvalidDataException) { Debug.error(e.toString() + "\n" + Debug.getStackTrace(e)); throw new MessageException(((InvalidDataException) e).errorMessage); } else { Debug.error(e.toString() + "\n" + Debug.getStackTrace(e)); throw new ProcessingException(e.toString()); } } }