Pastebin

Paste #1475: java close

< previous paste - next paste>

Pasted by tdn

Download View as text

/*
 * Copyright (C) Responsfabrikken A/S. All Rights Reserved.
 *
 * [Description...]
 * @author kim@responsfabrikken.dk
 * @since x.y
 * @version $Revision: 1.2 $, $Date: 2007/11/21 08:12:47 $
 *
 */
package rf.smsoutbox;

import java.io.IOException;
import java.io.InputStream;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicLong;

import net.tambur.wbxml.messages.ServiceIndicationMessage;

import org.apache.log4j.Logger;

import dk.responsfabrikken.lang.Sms;
import dk.responsfabrikken.util.DateTimeKit;

public class SonofonCode implements Code {

    private Logger log = null;
    private String user;

    private String replaceWithUID = "#-#replaceWithUID#-#";
    private static AtomicLong counter = new AtomicLong();

    public static final String authenticateStart = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><root><authentication><UserName>";
    public static final String authenticateEnd = "</UserName></authentication>";

	private static final String MPAYMENT_CHANNEL_1410 = "1410";
	private static final String MPAYMENT_CHANNEL_1292 = "1292";

    public SonofonCode(String name, String username) {
        user = username;
        log = Logger.getLogger("smsoutbox.rf.smsoutbox.SonofonCode."+name);
    }

    public byte[] get(int type) throws CodeException {
        if(log.isDebugEnabled()){
            log.debug("Request message of type: "+type);
          }
          byte[] result = null;

          switch( type) {
          case Code.LOGIN_PACKET :
            result = (authenticateStart+user+authenticateEnd+"\r\n").getBytes();
            break;
          case Code.ALIVE_REQUEST :
            result = ("<cpaCall><method name=\"Ping\"/><input><seqNo>"+replaceWithUID+"</seqNo></input></cpaCall>\r\n").getBytes();
            break;
          default:
            throw new CodeException("Unknown type: "+type);
          }
          return result;
    }

    public CodePacket decode(byte[] receivedPacket) throws CodeException {
        String tmp = new String(receivedPacket);
        if(tmp.startsWith("<sms ")){
            int index = tmp.indexOf("sno=")+5;
            int index2 = tmp.indexOf("\"",index);
            String channel = tmp.substring(index,index2);

            index = tmp.indexOf("uid=")+5;
            index2 = tmp.indexOf("\"",index);
            String mobile = tmp.substring(index,index2);

            index = tmp.indexOf(">");
            //index2 = tmp.indexOf("<",index);
            index2 = tmp.indexOf("</sms>",index);
            String txt = tmp.substring(index+1,index2);

            txt = txt.replaceAll("&amp;","&");
            txt = txt.replaceAll("&lt;","<");
            txt = txt.replaceAll("&gt;",">");
            txt = txt.replaceAll("&quot;","\"");
            txt = txt.replaceAll("&apos;","'");
            txt = txt.replaceAll("<br/>","\n");
            txt = txt.replaceAll("<sp/>"," ");
            txt = txt.replaceAll("&aelig;","æ");
            txt = txt.replaceAll("&Aelig;","Æ");
            txt = txt.replaceAll("&oslash;","ø");
            txt = txt.replaceAll("&Oslash;","Ø");
            txt = txt.replaceAll("&aring;","å");
            txt = txt.replaceAll("&Aring;","Å");

            Message payload = new Message(System.currentTimeMillis(),
                    mobile,
                    channel,
                    txt,
                    "sonofon");

            return new CodePacket(MESSAGE, receivedPacket, payload);
        }else if(tmp.startsWith("<ping/>")){
            return new CodePacket(ALIVE_REQUEST,receivedPacket);
        }else if(tmp.startsWith("<close/>")){
            return new CodePacket(NO_ACTION,receivedPacket);
        }else if(tmp.startsWith("<response>")){
            if(tmp.contains("method name=\"Ping\"")){
                return new CodePacket(ALIVE_REPLY,receivedPacket);
            }else if(tmp.contains("<seqNo>")){
                int index = tmp.indexOf("<seqNo>")+7;
                int index2 = tmp.indexOf("</",index);
                String seqNo = tmp.substring(index,index2);

                boolean status = false;
                if(tmp.contains("<status>true</status>")){
                    status = true;
                }

                CodePacket cp = new CodePacket(MESSAGE_RECEIVED,receivedPacket, seqNo, status);
                cp.setSmscID(seqNo);
                return cp;
            }
        }else if(tmp.contains("<validation>")){
            //login reply
            return new CodePacket(LOGIN_REPLY,receivedPacket,tmp.contains("<status>true</status>"));
        }else if(tmp.startsWith("<cpaCall>")){
            if(tmp.contains("<methodName>DeliveryControl</") || tmp.contains("<methodName>DELIVERYCONTROL</")){
                boolean status = false;
                if(tmp.contains("<status>true</status>")){
                    status = true;
                }

                int index = tmp.indexOf("<state id=\"")+10;
                int index2 = tmp.indexOf("</",index);
                String reason = tmp.substring(index,index2);

                index = tmp.indexOf("<seqNo>")+7;
                index2 = tmp.indexOf("</",index);
                String seqNo = tmp.substring(index,index2);

                CodePacket cp = new CodePacket(NOTIFICATION,receivedPacket);
                cp.setSmscID(seqNo);

                cp.setStatus(status?Sms.MESSAGE_DELIVERED_TO_MOBILE:Sms.MESSAGE_UNSPECIFIED_ERROR_TELCO,reason);
                return cp;
            }else if(tmp.contains("<method name=\"Ping\"")){
                return new CodePacket(Code.ALIVE_REPLY,receivedPacket);
            }else{
                log.error("Received unknow cpa packet: ["+tmp+"]");
            }
        }else{
            log.error("Received unknow packet: ["+tmp+"]");
        }
        return null;
    }

    public CodePacket[] encode(Sms message) throws CodeException {
    	
    	//calculate message length
    	byte[] GSM7 = GSM7Encoder.encodeToGSM7(message.getMessage());//encode to GSM7 to know the length
    	
        StringBuffer str = new StringBuffer(/*authenticateStart+user+authenticateEnd+*/"<cpaMessage><seqNo>").append(replaceWithUID).append("</seqNo>");
        str.append("<serviceId>").append(message.getServiceKey()).append("</serviceId>");
        str.append("<serviceName>").append(message.getPrefix()).append("</serviceName>").append("<listMsisdn>");
        str.append("<msisdn no=\"").append(message.getMobile()).append("\" />").append("</listMsisdn>");
        //log.debug("JACOBBillingCode:"+message.getPrice()+";");
        if(!message.getPrice().equals("0.00")){
			if( message.getAppnr().equals(MPAYMENT_CHANNEL_1410) || message.getAppnr().equals(MPAYMENT_CHANNEL_1292) ) {
				str.append("<billingcode>").append(getBillingCode(message.getPrice(),message.getDonation(),"mpayment")).append("</billingcode>");
			} else {
				str.append("<billingcode>").append(getBillingCode(message.getPrice(),message.getDonation(),message.getType())).append("</billingcode>");
			}
        }

        if(message.getType().equals(Sms.TYPE_TEXT)){
            String txt = xmlEncode(message.getMessage());

            str.append("<msg>").append(txt).append("</msg>");
            
            //check for length and use CONCTEXT if over 160 character, else use TEXT 
            if(GSM7.length > 160){
            	str.append("<type>").append("CONCTEXT").append("</type>");
            } else {
            	str.append("<type>").append("TEXT").append("</type>");
            }
            
            if(message.getPrice().equals("0.00") && message.getServiceFrom() != null && message.getServiceFrom().length() > 0 && !message.getServiceFrom().equals(message.getAppnr())){
                str.append("<source addr=\"").append(message.getServiceFrom()).append("\" />");
            }
        }else if(message.getType().equals(Sms.TYPE_WAPPUSH)){
            String txt = xmlEncode(message.getMessage());

            if(message.getPrice() == null || (message.getPrice().equals("0.00"))){

            	//setup different call for wap push
                StringBuffer strWapPush = new StringBuffer(/*authenticateStart+user+authenticateEnd*/);
                strWapPush.append("<cpaCall>");
                strWapPush.append("<method name=\"wappushsi\" />");
                strWapPush.append("<input>");
                strWapPush.append("<seqNo>").append(replaceWithUID).append("</seqNo>");
                strWapPush.append("<msisdn no=\"").append(message.getMobile()).append("\" />");
                strWapPush.append("<dc/>");
                strWapPush.append("<si><indication href=\"").append(message.getWapurl()).append("\">").append(txt).append("</indication></si>");
                strWapPush.append("</input>");
                strWapPush.append("</cpaCall>");

                //get wap push as bytes
                byte[] resultWapPush = strWapPush.toString().getBytes();

                //return wap push
                return new CodePacket[]{new CodePacket(MESSAGE, resultWapPush)};

            }else{
                //Send raw message
                ServiceIndicationMessage si = new ServiceIndicationMessage();
                si.setMessage(message.getMessage());
                si.setHref(message.getWapurl());

                byte[] b = null;
                try{
                    b = si.toByteArray();
                }catch(Exception e){
                    throw new FatalCodeException("Unable to encode message",e);
                }
                String text = RealtimeGateway.toHexString(b);
                if(text.length() > 266){
                    int length = text.length()/254+(text.length()%254==0?0:1);
                    str.append("<msg>");
                    for(int i = 0; i < length;i++){
                        //0B05040B8423F0 050003000"+cpA.length+"0"+(i+1)
                        if(text.length() > 254){
                            str.append("<raw dcs=\"F5\" esm=\"40\">0B05040B8423F00003000").append(length).append("0").append((i+1)).append(text.substring(0,254)).append("</raw>");
                            text = text.substring(254);
                        }else{
                            str.append("<raw dcs=\"F5\" esm=\"40\">0B05040B8423F00003000").append(length).append("0").append((i+1)).append(text).append("</raw>");
                        }
                    }
                    str.append("</msg>").append("<type>").append("RAW").append("</type>");
                }else{
                    text = "0605040B8423F0"+text;
                    str.append("<msg><raw dcs=\"F5\">").append(text).append("</raw></msg>");
                    str.append("<type>").append("RAW").append("</type>");
                }


            }
            if(message.getPrice().equals("0.00") && message.getServiceFrom() != null && message.getServiceFrom().length() > 0 && !message.getServiceFrom().equals(message.getAppnr())){
                str.append("<source addr=\"").append(message.getServiceFrom()).append("\" />");
            }
        }else if(message.getType().equals(Sms.TYPE_RAW)){
        	String txt = message.getMessage();

        	String header = null;
        	StringTokenizer st = new StringTokenizer(txt, ":");
        	header = st.nextToken();
        	log.debug("Header: " + header);
        	String data = st.nextToken();
        	log.debug("Data: " + data);

            str.append("<msg><raw dcs=\"F5\">").append(header+data).append("</raw></msg>");
            str.append("<type>").append("RAW").append("</type>");
            if(message.getPrice().equals("0.00") && message.getServiceFrom() != null && message.getServiceFrom().length() > 0 && !message.getServiceFrom().equals(message.getAppnr())){
                str.append("<source addr=\"").append(message.getServiceFrom()).append("\" />");
            }
        }else{
            log.error("Trying to send unsupported type: "+message.getType()+"["+message+"]");
            throw new CodeException("Trying to send unsupported type: "+message.getType()+"["+message+"]");
        }
        str.append("<dc/>");
        str.append("</cpaMessage>");
        //log.debug("Message: " + str.toString());
        byte[] result = str.toString().getBytes();
        return new CodePacket[]{new CodePacket(MESSAGE, result)};
    }

    public byte[] reply(CodePacket packet) throws CodeException {
        byte[] result = null;
        switch(packet.getType()){
        case Code.ALIVE_REQUEST:
            //String seqNo = getTransNumber(packet.getOriginal());
            /*if(seqNo == null){
                log.error("Unable to get seqNo in packet: "+new String(packet.getOriginal()));
                return null;
            }*/
            //String timestamp = getTimeStamp();
            //result = ("<response><timestamp>"+timestamp.toString()+"</timestamp><status>true</status><seqNo>"+seqNo+"</seqNo><ping/></response>").getBytes();
            result = "<ping/>".getBytes();
          break;
        case Code.MESSAGE:
         //apperently no reply
          break;
        case Code.NOTIFICATION:
            result = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><cpaCall><response/></cpaCall>\n".getBytes();
            break;
        case Code.NO_ACTION:
            log.debug("HACK: sending <close/>");
            result = "<close/>".getBytes();
            break;
        case Code.ALIVE_REPLY:
            log.debug("HACK: sending <ping/>");
            result = "<ping/>".getBytes();
            break;
        case Code.LOGIN_REPLY:
        case Code.MESSAGE_RECEIVED:
          break;
        default:
          throw new CodeException("Unknown type: "+packet.getType());
        }
        if(log.isDebugEnabled()){
          log.debug("Reply is: "+result);
        }
        return result;
    }


    public byte[] finalize(byte[] packet) throws CodeException {
        String tmp = new String(packet);
        String uid = getUniqueID();
        return tmp.replace(replaceWithUID,uid).getBytes();
    }

    public String getTransNumber(byte[] packetI) {
        String packet = new String(packetI);

        int indexS = packet.indexOf("<seqNo>");
        int indexE = packet.indexOf("</seqNo");
        if(indexE == -1 || indexS == -1){
            return null;
        }
        return packet.substring(indexS+7,indexE);
    }

    private String getTimeStamp(){
        GregorianCalendar gc = new GregorianCalendar();
        StringBuffer timestamp = new StringBuffer(gc.get(GregorianCalendar.YEAR)).append("-");

        int month = gc.get(GregorianCalendar.MONTH)+1;
        if(month < 9){
            timestamp.append("0");
        }
        timestamp.append(month).append("-");
        month = gc.get(GregorianCalendar.DAY_OF_MONTH);
        if(month < 9){
            timestamp.append("0");
        }
        timestamp.append(month).append("T");

        month = gc.get(GregorianCalendar.HOUR);
        if(month < 9){
            timestamp.append("0");
        }
        timestamp.append(month).append(":");

        month = gc.get(GregorianCalendar.MINUTE);
        if(month < 9){
            timestamp.append("0");
        }
        timestamp.append(month).append(":");

        month = gc.get(GregorianCalendar.SECOND);
        if(month < 9){
            timestamp.append("0");
        }
        timestamp.append(month);

        return timestamp.toString();
    }

    private static String getUniqueID(){
        return DateTimeKit.getTimestamp()+"."+counter.getAndIncrement();
    }

    private static String getBillingCode(String price, boolean donation, String type){
        String result = null;
	if(type.equals("mpayment")) {
		result = "V";
        }else if(type.equals("mms")){
            result = "M";
        }else if(type.equals("wapbilling")){
            result = "W";
        }else if(donation){
            result = "D";
        }else{
            result = "C";
        }

        StringTokenizer st = new StringTokenizer(price,".");
        String tmp = st.nextToken()+st.nextToken();
        while(tmp.length() < 6){
            tmp = "0"+tmp;
        }
        
        return result+tmp;
    }

    private String xmlEncode(String txt){
        txt = txt.replaceAll("&","&amp;");
        txt = txt.replaceAll("<","&lt;");
        txt = txt.replaceAll(">","&gt;");
        txt = txt.replaceAll("\"","&quot;");
        txt = txt.replaceAll("'","&apos;");
        txt = txt.replaceAll("\n","<br/>");
        txt = txt.replaceAll(" ","<sp/>");
        /*txt = txt.replaceAll("Æ","&Aelig;");*/
        txt = txt.replaceAll("ø","&oslash;");
        txt = txt.replaceAll("Ø","&Oslash;");
        txt = txt.replaceAll("å","&aring;");
        return txt.replaceAll("Å","&Aring;");
    }
    public byte[] read(InputStream in, SocketHandler sh) throws IOException{
        StringBuffer sb = new StringBuffer();
        int i;
        char c;

        StringBuffer temp = new StringBuffer();
        do {
          i = in.read();
          temp.append((char)i);
          if (i < 0) {
            log.debug("Stream closed before getting start byte - received: "+temp.toString());
            sh.reportError();
            return new byte[0];
          }
          c = (char) i;
          //log.debug(""+c);//nice to have when debuging a connection
        } while (c != '<');
        sb.append(c);

        c = sh.charRead(in);
        if(c == '?'){
            sb.append(c);
            //start tag, we really ought to read the encoding somehow.
            boolean cont = true;
            c = sh.charRead(in);
            sb.append(c);
            while(cont){
                if(c == '?'){
                    c = sh.charRead(in);
                    sb.append(c);
                    if(c == '>'){
                        log.debug("read starttag: "+sb.toString()+"...dropping");
                        return read(in,sh);
                    }
                }else{
                    c = sh.charRead(in);
                    sb.append(c);
                }
            }
        }

        //get tag
        while(c != '>' &&  c != ' '){
            sb.append(c);
            c = sh.charRead(in);
        }
        String tag = sb.toString();
        if(!tag.startsWith("<ping")){
            log.debug("Tag is: "+tag);
        }
        sb.append(c);
        if(tag.equals("<root")){
            log.debug("read: "+sb.toString()+"...dropping");
            return read(in,sh);
        }
        if(tag.charAt(tag.length()-1) == '/'){
            //Only this tag
        }else{
            //read until we meet the tag again
            tag = tag.substring(1);
            int goal = tag.length()+2; //<.length()+/.length()+tag.length()+>.length()-1
            int complete = 0;

            while(complete <= goal){
                c = sh.charRead(in);
                sb.append(c);

                if((complete == 0 && c == '<') || (complete == 1 && c == '/') || (complete > 1 && complete < goal && c == tag.charAt(complete-2))){
                    complete++;
                }else if(complete == goal && c == '>'){
                    //All read
                    break;
                }else{
                    complete = 0;
                }
            }
        }

        String result = sb.toString();
        if(log.isDebugEnabled() && !tag.startsWith("<ping")){
            log.debug("<< "+result);
        }
        return result.getBytes();

    }
}

New Paste


Do not write anything in this field if you're a human.

Go to most recent paste.