message not being submitted to handset using jsmpp - jsmpp

I am trying to send a message to the handset using the following code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jsmsoutgoing;
import java.io.IOException;
import java.util.Date;
import org.jsmpp.InvalidResponseException;
import org.jsmpp.PDUException;
import org.jsmpp.bean.Alphabet;
import org.jsmpp.bean.BindType;
import org.jsmpp.bean.ESMClass;
import org.jsmpp.bean.GeneralDataCoding;
import org.jsmpp.bean.MessageClass;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.RegisteredDelivery;
import org.jsmpp.bean.ReplaceIfPresentFlag;
import org.jsmpp.bean.SMSCDeliveryReceipt;
import org.jsmpp.bean.TypeOfNumber;
import org.jsmpp.examples.MessageReceiverListenerImpl;
import org.jsmpp.extra.NegativeResponseException;
import org.jsmpp.extra.ResponseTimeoutException;
import org.jsmpp.session.BindParameter;
import org.jsmpp.session.SMPPSession;
import org.jsmpp.util.AbsoluteTimeFormatter;
import org.jsmpp.util.MessageId;
import org.jsmpp.util.TimeFormatter;
public class Jsmsoutgoing {
/**
* #param args the command line arguments
*/
private static TimeFormatter timeFormatter = new AbsoluteTimeFormatter();
public static void main(String[] args) {
// TODO code application logic here
SMPPSession session = new SMPPSession();
session.setMessageReceiverListener(new MessageReceiverListenerImpl());
String host = "X";
int port = y;
String userName = "user";
String password = "pass";
String TON = "0";
String NPI = "1";
String systemType = "generic";
try {
session.connectAndBind(
host,
port,
BindType.BIND_TRX,
userName,
password,
systemType,
TypeOfNumber.INTERNATIONAL,
NumberingPlanIndicator.ISDN,
null);
System.out.println("Session Connected");
} catch (IOException e) {
System.out.println("Failed connect and bind to host");
e.printStackTrace();
}
try {
String messageId = session.submitShortMessage(
"CMT",
TypeOfNumber.INTERNATIONAL,
NumberingPlanIndicator.UNKNOWN,
"SENDERNUMBER",
TypeOfNumber.INTERNATIONAL,
NumberingPlanIndicator.UNKNOWN,
"RECEIVERNUMBER",
new ESMClass(),
(byte)0,
(byte)1,
null,
null,
new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE),
(byte)0,
new GeneralDataCoding(false, true, MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT),
(byte)0,
"Test from TEST".getBytes()
);
System.out.println("Message submitted, message_id is " + messageId);
//System.out.println("Message submitted, message_id is " + messageId);
Thread.sleep(2000);
}
catch(PDUException e)
{
System.out.println("PDU Exeption");
e.printStackTrace();
}
catch (ResponseTimeoutException e) {
// Response timeout
System.out.println("Response timeout");
e.printStackTrace();
} catch (InvalidResponseException e) {
// Invalid response
System.out.println("Receive invalid respose");
e.printStackTrace();
} catch (NegativeResponseException e) {
// Receiving negative response (non-zero command_status)
System.out.println("Receive negative response");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO error occur");
e.printStackTrace();
}
catch (InterruptedException e) {
System.out.println("Thread interrupted");
e.printStackTrace();
}
session.unbindAndClose();
}
}
Anyone , any idea ?
Thanks

Related

Oracle : Send latest insert/update to JMS

I have an insert/update trigger for a Oracle table.
Is there a way to send the details of the affected row(all columns) as a message to JMS?
I can write a Java Program, 'loadjava' that and call from the trigger.
Does this way affect performance?
Is there any native way of achieving this?
There is indeed a native way: use AQ JMS from PL/SQL, see https://docs.oracle.com/database/121/ADQUE/jm_exmpl.htm#ADQUE1600. In short you create an AQ queue with a JMS payload type; then you can post messages with PL/SQL from the trigger. An external Java client can connect to the database and read the messages with JMS.
I don't know how much a call into Java would affect performance, but I try to avoid it. It was a nice idea but it never really caught on, so it remains a fringe case and at least early on there were always issues. PL/SQL on the other hand works.
If you need to send data to another message queue product (tags activemq and mq) you can read the messages in Java and forward them. It adds an extra step, but it is straightforward.
loadjava have many problems and not stable if there is many classes loaded and many business, take a look Calling Java from Oracle, PLSQL causing oracle.aurora.vm.ReadOnlyObjectException
Oracle AQ as i know is not free.
I have implemented the same need after trying many possibilities by creating only 1 class loaded to oracle with loadjava which is called as a procedure by a trigger and have the responsability to call an external java program with all needed parameters and log external process output to a table, as below.
i have encoded text mesage to BASE64 because i used JSON format and some specials caracters can causes problems as a parameters to external java program.
i have used "#*#jms_separator#*#" as a separator in the sent parameter string to parse the content if i need to send many parameters to the external program.
the whole duration of ShellExecutor.shellExec is around 500ms and running since 1 year without any problem.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Arrays;
import java.util.concurrent.FutureTask;
import sun.misc.BASE64Encoder;
public class ShellExecutor {
static {
System.setProperty("file.encoding", "UTF-8");
}
private static final String INSERT_LOGS_SQL = "INSERT INTO JMS_LOG (TEXT_LOG) VALUES (?) ";
private static final String DEFAULT_CONNECTION = "jdbc:default:connection:";
public static String SQLshellExec(String command) throws Exception {
long start = System.currentTimeMillis();
StringBuffer result = new StringBuffer();
ShellExecutor worker = new ShellExecutor();
try {
worker.shellExec(command, result);
} finally {
result.append("exe duration : " + (System.currentTimeMillis() - start + "\n"));
Connection dbConnection = null;
PreparedStatement logsStatement = null;
try {
dbConnection = DriverManager.getConnection(DEFAULT_CONNECTION);
logsStatement = dbConnection.prepareStatement(INSERT_LOGS_SQL);
logsStatement.clearParameters();
Clob clob = dbConnection.createClob();
clob.setString(1, result.toString());
logsStatement.setClob(1, clob);
logsStatement.executeUpdate();
} finally {
if (logsStatement != null) {
try {
logsStatement.close();
} catch (Exception e) {
}
}
}
}
return result.substring(result.length() - 3090);
}
public void shellExec(String command, StringBuffer result) throws Exception {
Process process = null;
int exit = -10;
try {
InputStream stdout = null;
String[] params = command.split("#*#jms_separator#*#");
BASE64Encoder benc = new BASE64Encoder();
for (int i = 0; i < params.length; i++) {
if (params[i].contains("{") || params[i].contains("}") || params[i].contains("<")
|| params[i].contains("/>")) {
params[i] = benc.encodeBuffer(params[i].getBytes("UTF-8"));
}
}
result.append("Using separator : " + "#*#jms_separator#*#").append("\n")
.append("Calling : " + Arrays.toString(params)).append("\n");
ProcessBuilder pb = new ProcessBuilder(params);
pb.redirectErrorStream(true);
process = pb.start();
stdout = process.getInputStream();
LogStreamReader lsr = new LogStreamReader(stdout, result);
FutureTask<String> stdoutFuture = new FutureTask<String>(lsr, null);
Thread thread = new Thread(stdoutFuture, "LogStreamReader");
thread.start();
try {
exit = process.waitFor();
} catch (InterruptedException e) {
try {
exit = process.waitFor();
} catch (Exception e1) {
}
}
stdoutFuture.get();
result.append("\n").append("exit code :").append(exit).append("\n");
if (exit != 0) {
throw new RuntimeException(result.toString());
}
} catch (Exception e) {
result.append("\nException(").append(e.toString()).append("):").append(e.getCause()).append("\n\n");
e.printStackTrace(System.err);
throw e;
} finally {
if (process != null) {
process.destroy();
}
}
}
}
class LogStreamReader implements Runnable {
private BufferedReader reader;
private StringBuffer result;
public LogStreamReader(InputStream is, StringBuffer result) {
this.reader = new BufferedReader(new InputStreamReader(is));
this.result = result;
}
public void run() {
try {
String line = null;
while ((line = reader.readLine()) != null) {
result.append(line).append("\n");
}
} catch (Exception e) {
result.append("\nException(").append(e.toString()).append("):").append(e.getCause()).append("\n\n");
e.printStackTrace(System.err);
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
The class of the external Java program packaged as an executable with all needed librairies, a simple JMS sender :
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;
import progress.message.jclient.ConnectionFactory;
import progress.message.jimpl.Connection;
public class JMSSender {
private static SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS");
public static void main(String[] args) throws Throwable {
doSend(args[0]);
}
public static void doSend(String text)
throws Throwable {
if (Base64.isBase64(text)) {
text = new String(Base64.decodeBase64(text));
}
String content = "\n\nsending message :" + text;
Connection con = null;
Session session = null;
try {
ConnectionFactory cf = new ConnectionFactory();
session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = session.createTopic(destination) ;
MessageProducer producer = session.createProducer(dest);
con.start();
JSONObject json = new JSONObject();
json.put("content", text);
json.put("date", sdf.format(new Date()));
TextMessage tm = session.createTextMessage(json.toString());
producer.send(tm);
content += " \n\n" + "sent message :" + json.toString();
} catch (Throwable e) {
content += " \n\n" + e.toString() + " \n\n" + Arrays.toString(e.getStackTrace());
if (e.getCause() != null) {
content += " \n\nCause : " + e.getCause().toString() + " \n\n"
+ Arrays.toString(e.getCause().getStackTrace());
}
e.printStackTrace(System.err);
throw e;
} finally {
write("steps on sending message : " + content);
if (session != null) {
try {
session.commit();
session.close();
} catch (Exception e) {
}
session = null;
}
if (con != null) {
try {
con.stop();
con.close();
} catch (Exception e) {
}
}
}
}
private static void write(String log) {
try {
if (System.out != null) {
System.out.println(log);
}
} catch (Exception e2) {
}
}
}

logback dbappender very slow

I have a custom DB Appender which extends the logback DBAppender. My application has 100 parallel threads. These threads also log the events into database through the custom db appender while processing the requests.
The performance of the logback is so slow that with the logs disabled, the execution finishes in 20 mins. Whereas with the logs enabled, it takes almost 5 hours to finish most of the time waiting for the logs to be written to proceed to the next step as my logging is synchronous.
At first I thought the slow performance could be due to the synchronized doAppend method of logback appender. However, I later noticed that DB appender extends the
UnsynchronizedAppenderBase(public abstract class DBAppenderBase<E>
/* */ extends UnsynchronizedAppenderBase<E>).
Can anyone help me understand what could be the reason for this poor performance?
My DB Appender:
package com.test;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import org.omg.CORBA.TRANSACTION_UNAVAILABLE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.db.DBAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;
public class CustomDBAppender extends DBAppender {
final static Logger logger = LoggerFactory.getLogger("com.test");
protected String insertPropertiesSQL;
protected String insertExceptionSQL;
protected String insertSQL;
private CustomDBNameResolver dbNameResolver;
// default constructor
public CustomDBAppender() {
logger.debug("DB Appender instantiated");
}
// set dbNameResolver for getting table information
public void setCsiDbNameResolver(CustomDBNameResolver dbNameResolver) {
this.dbNameResolver = dbNameResolver;
}
#Override
public void start() {
super.start();
if (dbNameResolver == null)
dbNameResolver = new CustomDBNameResolver();
insertSQL = CustomSQLBuilder.buildInsertSQL(dbNameResolver);
}
#Override
protected void subAppend(ILoggingEvent event, Connection connection, PreparedStatement insertStatement)
throws Throwable {
logEvents(insertStatement, event);
// System.out.println("=== INSERT STATEMENT === " +
// insertStatement.toString());
int updateCount = -1;
try {
updateCount = insertStatement.executeUpdate();
} catch (Exception e) {
logger.error(" ERROR ");
e.printStackTrace();
}
logger.info(" updateCount = " + updateCount);
if (updateCount != 1) {
logger.error(" ERROR IT IS ");
addWarn("Failed to insert loggingEvent");
}
}
protected void secondarySubAppend(ILoggingEvent event, Connection connection, long eventId) throws Throwable {
}
// #override
private void logEvents(PreparedStatement stmt, ILoggingEvent event) throws SQLException {
logData(event, stmt);
}
private void logData(ILoggingEvent event, PreparedStatement stmt) throws SQLException {
try {
if (null != event && null != logMsgArgs && (event.getLoggerName().indexOf("com.test.beans.") != -1)) {
payload = null == logMsgArgs[0] ? "NA"
: (logMsgArgs[0].toString()).substring(0,
(logMsgArgs[0].toString().length() >= 4000 ? 3999 : logMsgArgs[0].toString().length()));
msgHeader = null == logMsgArgs[1] ? "NA"
: (logMsgArgs[1].toString()).substring(0,
(logMsgArgs[1].toString().length() >= 4000 ? 3999 : logMsgArgs[1].toString().length()));
currentStage = null == logMsgArgs[2] ? -1 : Integer.parseInt(logMsgArgs[2].toString());
currentEvent = null == logMsgArgs[3] ? null : logMsgArgs[3].toString();
trxId = null == logMsgArgs[4] ? null : logMsgArgs[4].toString();
batchId = null == logMsgArgs[5] ? null : logMsgArgs[5].toString();
headerId = null == logMsgArgs[6] ? null : logMsgArgs[6].toString();
}
stmt.setString(1, logLevel);
stmt.setObject(2, trxId);
stmt.setString(3, logMessage);
stmt.setDate(4, getSqlDate());
stmt.setString(5, event.getLoggerName());
stmt.setString(6, event.getThreadName());
stmt.setString(7, event.getLoggerContextVO().getName());
stmt.setString(8, logMessage.substring(0, logMessageLength));
stmt.setString(9, payload);
stmt.setString(10, msgHeader);
stmt.setInt(11, currentStage);
stmt.setString(12, currentEvent);
stmt.setString(13, batchId);
stmt.setString(14, headerId);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Exception while printing log:" + e.getMessage());
e.printStackTrace();
} finally {
}
}
private Object nvl(Object input) {
if (null == input) {
return null;
}
return input;
}
private java.sql.Date getSqlDate() {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSX");
String nowDateStr = sdf.format(now);
logger.info("nowDateStr = " + nowDateStr);
java.sql.Date toDB = null;
try {
toDB = new java.sql.Date(sdf.parse(nowDateStr).getTime());
logger.info("toDB = " + toDB);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return toDB;
}
#Override
protected String getInsertSQL() {
return insertSQL;
}
protected void insertProperties(Map<String, String> mergedMap, Connection connection, long eventId)
throws SQLException {
}
}
/* End of appender */

JMS-Loadtest using Gatling: unable to initialize ContextFactory of IBM MQ

I'm implementing a load test scenario against a IBM MQ with Gatling.
The setup is basically the same as mentioned here
Problem: I'm not able to initialize the required ContextFactory with IBM MQ - which should be com.ibm.mq.jms.context.WMQInitialContextFactory.
The WMQInitialContextFactory cannot be found.
But my build.sbt is containing the IBM MQ dependency correctly (being successfully retrieved by our internal Nexus :
"com.ibm.mq" % "com.ibm.mq" % "8.0.0.3"
My gatling scenario:
package com.myawesomecompany.loadtest
import com.ibm.mq._
import com.ibm.mq.jms.MQConnectionFactory
import com.ibm.mq.jms.JMSMQ_Messages
import com.ibm.msg.client.wmq.common.CommonConstants
import io.gatling.core.Predef._
import io.gatling.core.scenario.Simulation
import io.gatling.jms.Predef._
import javax.jms._
import scala.concurrent.duration._
class JMSLoadTest extends Simulation {
val jmsConfiguration = jms
.connectionFactoryName("ConnectionFactory")
.url("devmq01.company.dmz")
.credentials("mqm", "mqm")
.contextFactory(classOf[com.ibm.mq.jms.context.WMQInitialContrextFactory].getName)
.listenerCount(1)
.usePersistentDeliveryMode
val scn = scenario("Load testing GPRSForwarder").repeat(1) {
exec(jms("testing GPRSForwarder...").reqreply
.queue("COMPANY.TEST.QUEUE")
.textMessage("00001404020611100E033102C20EBB51CC1C036EFFFF00010002323802000200FE05001400000000FFFFFFFFFFFFFFFFFF040010038B0D6912EB10CE070206110F37298C")
.jmsType("test_jms_type")
)
}
setUp(scn.inject(rampUsersPerSec(10) to 1000 during (2 minutes)))
.protocols(jmsConfiguration)
}
The setup is equivalent to this one - but instead of using ActiveMQInitalContextFactory, I'm forced to use the "counterpart" of IBM MQ.
According to official docks the WMQInitialContextFactory should be in com.ibm.mq.jms.context but it is not. Ore is there some constant in CommonConstants which I can use to initialize a ContextFactory ?
Thanks a lot in advance.
Problem: I'm not able to initialize the required ContextFactory with
IBM MQ - which should be
com.ibm.mq.jms.context.WMQInitialContextFactory. The
WMQInitialContextFactory cannot be found.
Do not use WMQInitialContextFactory. It was an MQ SupportPac someone created where they wanted to use MQ as the JNDI repository. It is not a good idea plus the SupportPac does not support any form of security (i.e. SSL/TLS or security exit).
You should use a file based MQ JNDI. Here's a basic example:
import java.util.Hashtable;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.ibm.mq.MQException;
/**
* Program Name
* TestJMS01
*
* Description
* This java JMS class will connect to a remote queue manager
* using JNDI and put a message to a queue.
*
* Sample Command Line Parameters
* -x myQCF -q dev.test.q -f C:\JNDI-Directory\roger\mqjndi
*
* Sample MQ JNDI Commands:
* DEFINE QCF(myQCF) QMANAGER(MQA1) CHANNEL(TEST.CHL) HOSTNAME(127.0.0.1) PORT(1415) TRANSPORT(CLIENT) FAILIFQUIESCE(YES)
* DEFINE Q(dev.test.q) QUEUE(TEST1) QMANAGER(MQA1) TARGCLIENT(JMS) FAILIFQUIESCE(YES)
*
* #author Roger Lacroix, Capitalware Inc.
*/
public class TestJMS01
{
private static final String JNDI_CONTEXT = "com.sun.jndi.fscontext.RefFSContextFactory";
private QueueConnectionFactory cf;
private Queue q;
private Hashtable<String,String> params = null;
private String userID = "tester";
private String password = "mypwd";
public TestJMS01() throws NamingException
{
super();
}
/**
* Make sure the required parameters are present.
* #return true/false
*/
private boolean allParamsPresent()
{
return (params.containsKey("-x") && params.containsKey("-q") && params.containsKey("-f"));
}
/**
* Extract the command-line parameters and initialize the MQ variables.
* #param args
* #throws IllegalArgumentException
*/
private void init(String[] args) throws IllegalArgumentException
{
params = new Hashtable<String,String>(10);
if (args.length > 0 && (args.length % 2) == 0)
{
for (int i = 0; i < args.length; i += 2)
{
params.put(args[i], args[i + 1]);
}
}
else
{
throw new IllegalArgumentException();
}
if (allParamsPresent())
{
Hashtable<String,Object> env = new Hashtable<String,Object>();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_CONTEXT);
env.put(Context.PROVIDER_URL, "file:/"+(String) params.get("-f"));
try
{
Context ctx = new InitialContext(env);
cf = (QueueConnectionFactory) ctx.lookup((String) params.get("-x"));
q = (Queue) ctx.lookup((String) params.get("-q"));
}
catch (NamingException e)
{
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
throw new IllegalArgumentException();
}
}
else
{
throw new IllegalArgumentException();
}
}
/**
* Test the connection to the queue manager.
* #throws MQException
*/
private void testConn() throws JMSException
{
QueueConnection connection = null;
QueueSession session = null;
try
{
connection = cf.createQueueConnection(userID, password);
connection.start();
session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
sendMsg(session);
}
catch (JMSException e)
{
System.err.println("getLinkedException()=" + e.getLinkedException());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
}
finally
{
try
{
session.close();
}
catch (Exception ex)
{
System.err.println("session.close() : " + ex.getLocalizedMessage());
}
try
{
connection.stop();
}
catch (Exception ex)
{
System.err.println("connection.stop() : " + ex.getLocalizedMessage());
}
try
{
connection.close();
}
catch (Exception ex)
{
System.err.println("connection.close() : " + ex.getLocalizedMessage());
}
}
}
/**
* Send a message to a queue.
* #throws MQException
*/
private void sendMsg(QueueSession session) throws JMSException
{
QueueSender sender = null;
try
{
TextMessage msg = session.createTextMessage();
msg.setText("Nice simple test. Time in 'ms' is -> " + System.currentTimeMillis());
// msg.setJMSReplyTo(tq);
// msg.setJMSDeliveryMode( DeliveryMode.NON_PERSISTENT);
System.out.println("Sending request to " + q.getQueueName());
System.out.println();
sender = session.createSender(q);
sender.send(msg);
}
catch (JMSException e)
{
System.err.println("getLinkedException()=" + e.getLinkedException());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
}
finally
{
try
{
sender.close();
}
catch (Exception ex)
{
System.err.println("sender.close() : " + ex.getLocalizedMessage());
}
}
}
/**
* main line
* #param args
*/
public static void main(String[] args)
{
try
{
TestJMS01 tj = new TestJMS01();
tj.init(args);
tj.testConn();
}
catch (IllegalArgumentException e)
{
System.err.println("Usage: java TestJMS01 -x QueueConnectionFactoryName -q JMS_Queue_Name -f path_to_MQ_JNDI");
System.exit(1);
}
catch (NamingException ex)
{
System.err.println(ex.getLocalizedMessage());
ex.printStackTrace();
}
catch (JMSException e)
{
System.err.println("getLinkedException()=" + e.getLinkedException());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
}
catch (Exception ex)
{
System.err.println(ex.getLocalizedMessage());
ex.printStackTrace();
}
}
}
Not directly related to your problem, but JMSToolBox with its scripting feature, is a tool that allows to perform bulk/load test on IBM MQ.
With it you can define a script, composed of steps, that will read a template with variable placeholders and repeatedly put messages in one or multiple destinations. It can also directly read saved messages from a directory etc.
You can download it from SourceForge here
Documentation of the script feature is here

PASS PARAMETERS TO ASYNC TASK

i have used httppost to send and retrive the data from the site.but when i run the program i m not getting the required data
package com.example.im3;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class Homepage extends Activity {
Button login1, login2;
LinearLayout l1;
RelativeLayout r1;
EditText un, pw;
private static final String TAG = "MyActivity";
Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
login2 = (Button) findViewById(R.id.button1);
login1 = (Button) findViewById(R.id.Login1);
l1 = (LinearLayout) findViewById(R.id.Homepage);
r1 = (RelativeLayout) findViewById(R.id.Loginpage2);
un = (EditText) findViewById(R.id.un);
pw = (EditText) findViewById(R.id.pw);
l1.setVisibility(l1.VISIBLE);
r1.setVisibility(r1.GONE);
login2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s1 = un.getText().toString();
String s2 = pw.getText().toString();
if(s1.matches("")){
Toast.makeText(Homepage.this, "enter something", toast.LENGTH_LONG).show();
}
Log.d(TAG, "second login page");
Abc task = new Abc();
task.execute(s1, s2);
}
});
login1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
l1.setVisibility(v.GONE);
r1.setVisibility(v.VISIBLE);
Log.d(TAG, "home page");
}
});
}
private class Abc extends AsyncTask<String, String, String> {
String s1,s2;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
s1=un.getText().toString();
s2=pw.getText().toString();
String urlParameters = s1,s2;
String request = "https://beta135.hamarisuraksha.com/web/webservice/HamariSurakshaMobile.asmx/getIMSafeAccountInfoOnLogon";
URL url;
try {
url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;");// boundary="+CommonFunctions.boundary
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
/*
* System.out.println("\nSending 'POST' request to URL : " +
* url); System.out.println("Post parameters : " +
* urlParameters);
*/
System.out.println("Response Code : " + responseCode);
InputStream errorstream = connection.getErrorStream();
BufferedReader br = null;
if (errorstream == null) {
InputStream inputstream = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream));
} else {
br = new BufferedReader(new InputStreamReader(errorstream));
}
String response = "";
String nachricht;
while ((nachricht = br.readLine()) != null) {
response += nachricht;
}
// print result
// System.out.println(response.toString());
return response.toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
protected void onPostExecute(String response)
{
// TODO Auto-generated method stub
super.onPostExecute(response);
Log.d(TAG,"on post execute");
Toast.makeText(Homepage.this, "finally", toast.LENGTH_LONG).show();
}
}
}
i have used httppost to send and retrive the data from the site.but when i run the program i m not getting the required data
i want to pass the s1 and s2 paramters to the htp post method.but i m nt getting how to do it
You have your parameters as the params in your doInBackground method here String... params. So you can use them like this:
protected String doInBackground(String... params) {
s1=params[0];
s2=params[1];
//...
}
Instead of:
protected String doInBackground(String... params) {
s1=un.getText().toString();
s2=pw.getText().toString();
//...
}

JAI tiff image conversion producing bigger file size on windows 7

Trying to compress the image using JAI with TIFF format. It works fine on Windows XP, But it produces 10 times bigger size file on Windows 7 compared to Windows XP.
Using JAI 1.1 and JRE 1.6_0_16
What might be the issue? Appreciate your assistance.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Locale;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import com.sun.media.imageio.plugins.tiff.TIFFImageWriteParam;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
File image = new File("abc.tiff");
File tempFile = new File("compressed.tiff");
try {
BufferedImage bi = ImageIO.read(image);
byte[] tiffArray = toTiff(bi, tempFile,"packBits" );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] toTiff(BufferedImage bi, File tempFile, String compType) {
byte[] bImg = null;
try{
tempFile.delete();
String format = "TIF";
Iterator writers = ImageIO.getImageWritersByFormatName(format);
if(writers == null || !writers.hasNext()) {
throw new IllegalArgumentException("Unsupported format (" + format + ")");
}
ImageWriter writer = (ImageWriter)writers.next();
IIOImage iioImg = new IIOImage(bi, null, null);
TIFFImageWriteParam writeParam = new TIFFImageWriteParam(Locale.ENGLISH);
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionType(compType);
ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);
writer.setOutput(ios);
writer.write(null, iioImg, writeParam);
ios.close();
writer.dispose();
bImg = readImage(tempFile);
}catch(Exception e){
e.printStackTrace();
}
return bImg;
}
public static byte[] readImage(File f) throws Exception {
byte[] bImg = null;
try {
long fLength = f.length();
if(fLength > Integer.MAX_VALUE){
throw new RuntimeException("File is too large to upload....!");
}
bImg = new byte[(int)fLength];
FileInputStream fin = new FileInputStream(f);
fin.read(bImg);
fin.close();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return bImg;
}
}

Resources