Simple Ajax Request

 IT  Kommentare deaktiviert für Simple Ajax Request
Jul 232013
 

Simple Ajax request example. This example is requesting the output of a cgi python script and inserts the result into an existing div:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My First Ajax Test</title>
</head>
<body>

	<script type="text/javascript">
		function showAjaxResults() {

			alert("Starting Ajax Result");
			myReq = new XMLHttpRequest();

			myReq.open("GET", "https://philipp-boss.de/cgi-bin/test.py", false);

			//set a custom HTTP Header
			myReq.setRequestHeader("myVeryCoolHeader",
					"this is the value of my custom header");
			myReq.send();

			//log to javascript console all headers - there you can find http status codes etc.
			console.log(myReq.getAllResponseHeaders());

			// now fill the results-div with the received text
			document.getElementById("results").innerHTML = myReq.responseText;

			// you could also replace the existing body with the received text
			//document.body.innerHTML = myReq.responseText;
		}
	</script>

	<button onclick="showAjaxResults()">Show me the Ajax Results</button>

	<div id="results">here you will find the results....</div>

</body>
</html>

To related python script is an really simple script, but nevertheless you can find the source below:

#!/usr/bin/python

import cgi
import cgitb
from symbol import or_test
cgitb.enable()

print "Content-type:text/html"
print 'Access-Control-Allow-Methods: POST, GET, OPTIONS'
print "Access-Control-Allow-Origin: *rn"
print ''
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'

In another Post I will explain why there are the Header with Access-Control-Allow *. They are required in case of cross site scripting.

Note: This example isn’t fully correct, because the returned text from the python class is a complete html text, but this is filled in an already existing html website.

The reason for that is, that I used ths python script for several different tests. To have a valid result after calling the ajax request in the first source, you should remove the <html> <head> <body> fragments from the python script.

 

HTTP Request using JSP

 IT, Java  Kommentare deaktiviert für HTTP Request using JSP
Jul 232013
 

In the last days I worked a lot around HTTP Request and Response stuff and here I would like to share some of the stuff.
The following code snippet shows a JSP page that sends an HTTP Request to a specified URL. It is also possible to specify custom headers (see myVeryCoolHeader) and it is also possible to send basix authentication for username/password secured websites:

<%@ page import="java.net.HttpURLConnection"%>
<%@ page import="java.net.URL"%>
<%@ page import="java.io.*" %>
<%
	
	URL myURL= new URL("http://mydummysite.org/testing/website.html");
	HttpURLConnection myconn = (HttpURLConnection) myURL.openConnection();

	String mybody = "This is the HTTP-Body. You can put here any text stuff you want";

	myconn.setRequestMethod("GET");
	myconn.setDoOutput(true);
	myconn.setUseCaches(false);
	myconn.setRequestProperty("myVeryCoolHeader", "My very cool header -value");
	
	
	// if the website requires basic authentication:
	boolean isSecuredWebsite = true;
	if (isSecuredWebsite){
		String login = "myUSER" + ":" + "myPassword";
		String loginEncoded = new sun.misc.BASE64Encoder().encode(login.getBytes());
		myconn.setRequestProperty("Authorization", "Basic " + loginEncoded);
	}
	
	// request the content as html text
	myconn.setRequestProperty("Content-Type", "text/html");
	myconn.setRequestProperty("Content-Length", String.valueOf(mybody.length()));
	
	// write the stuff to the output stream 
	OutputStreamWriter writer = new OutputStreamWriter(myconn.getOutputStream());
	writer.write("nn" + mybody);
	writer.flush();
	
	
	
	if(myconn.getResponseCode()== 200){
		// everyting ok, put the output from SAP into the HTTP Response
		BufferedReader reader = new BufferedReader(new InputStreamReader(myconn.getInputStream()));

		
		// write the stuff to the website
		String line = reader.readLine();
		while (line != null){
			out.println(line);
			line = reader.readLine();
		}
		reader.close();
		
	} else if(myconn.getResponseCode() == 401) {  
		// Catch the "not Authorized" Status code
		out.println("This Website is secured by Username and Password. <br>");
		
		out.println("<b>DEBUG-INFO</b>: <br>" +myconn.getHeaderField("WWW-Authenticate"));
		out.println("<br>URL: " + myURL.toString());
		out.println("<br>HTTP-Response Code: " + myconn.getResponseCode() + " " + myconn.getResponseMessage());


		
	} else{
		// all other errors like redirect, etc.
		out.println("An unexpected error appeared. Please inform your administrator about this issue. <br>");
		out.println("<b>DEBUG-INFO</b>: <br>");
		out.println("<br>URL: " + myURL.toString());
		out.println("<br>HTTP-Response Code: " + myconn.getResponseCode() + " " + myconn.getResponseMessage());
		
	}


	writer.close();
	myconn.disconnect();
	
%>

 

 

Apache Ant – Copy files to ftp server

 Eclipse, IT, Java  Kommentare deaktiviert für Apache Ant – Copy files to ftp server
Jul 162013
 

Sample for copying files to an FTP Server:

<?xml version="1.0" encoding="UTF-8"?>
<project name="project" basedir="." default="deploy">
	<target name="deploy">

		<ftp server="myserver.de"
	   port="21"
	   remotedir="/html/testing/"
	   userid="myUser"
	   password="myPassword"
	   passive="yes"
	   depends="yes"
	   binary="no">
			<fileset dir="Testing">
				<include name="*.php"/>
				<include name="*.js"/>
			</fileset>
		</ftp>

	</target>
</project>

By default, ant is not able to process this, because the ftp classes are not included by the typical ant installation.

To enable ant to use ftp tasks, you have to download the apache commons ftp package. The dependencies of Apache Ant can be found here: http://ant.apache.org/manual/Tasks/ftp.html

Place the downlaoded commons-net.jar file into the lib folder of your ant installation. Now you can execute the ant tasks in your cmd shell.

If you have placed the jar-file outside the ant-lib directory you can run the ant-script with the lib-parameter:

ant -lib "/home/philipp/java/libs/commons-net-3.3/commons-net-3.3.jar"

Links:

Apache commons net: http://ant.apache.org/manual/install.html#commons-net

Ant FTP Task: http://ant.apache.org/manual/Tasks/ftp.html

ActiveMQ Simple Authentication for Consumers and Producers

 IT, Java  Kommentare deaktiviert für ActiveMQ Simple Authentication for Consumers and Producers
Jul 032013
 

By default, ActiveMQ does not request a Username or password for consumers and producers. That means, everyone who knows your broker URL is able to connect to your broker and read your messages and/or send messages. For personal development this isn’t a big issue, but for business applications security plays an important role.

Because of that, I have played around with the authentication of consumers and producers on ActiveMQ brokers.

First of all you should know, that ActiveMQ supports a users and groups based authentication.In our example we would like to have two groups:

  • senders: they are allowed to send messages into queues (write access)
  • receivers: they are allowed to consume the messages (read access)

Setup groups and users for Receiver and Consumer:

To setup those two groups and one user for each group you have to add these lines (starting with „plugins“)  to your activemq.xml :

ATTENTION:  in earlier versions (I tested it also with 5.5.1) you have to insert the plugins-element in the correct alphabetical order. See also: http://activemq.apache.org/xml-reference.html –> Alphabetically ordered xml elements (5.4 – 5.5.1)

    <!--
        The <broker> element is used to configure the ActiveMQ broker.
    -->
    <broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}">

      <plugins>
        <simpleAuthenticationPlugin>
            <users>
                <authenticationUser username="superman" password="boss" groups="senders,receivers,admins" />
                <authenticationUser username="mySendingApp" password="manager" groups="senders" />
                <authenticationUser username="myReceivingApp" password="manager" groups="receivers" />
            </users>
        </simpleAuthenticationPlugin>
      </plugins>

Link groups and users to queues and topics

After that you need to grant rights to the created groups „senders“ , „receivers“ and „admins“. Add the following lines after the closing </simpleAuthenticationPlugin> tag:

<authorizationPlugin>
   <map>
       <authorizationMap>
           <authorizationEntries>
               <authorizationEntry queue=">" write="senders" read="receivers" admin="admins" />
	       <authorizationEntry topic="ActiveMQ.Advisory.>" write="senders" read="receivers" admin="admins,senders,receivers" />
           </authorizationEntries>
       </authorizationMap>
   </map>
</authorizationPlugin>

Explanation: You can specify different access rights for the single queues. In my example I allow all users from group „senders“ to write inside all queues. queue=“>“ stands for all queues. ActiveMQ uses the „>“ as Wildcard (see also the website-link below). Also I allow all receivers to read from the queue.

Maybe you are wondering about the second <authorizationEntry> . ActiveMQ-Clients creating Advisory-Topics for several reasons. For each queue a client connects to, the client tries to create a Advisory-Topic. That is the reason why I added the second line. This line defines that all clients (with correct password and username) are able to create Topics that are named „ActiveMQ.Advisory.*“.  More about ActiveMQs advisory stuff see website link below.

Now you can restart the ActiveMQ broker in order to read the new configuration.

Client side: connect to a username/password protected queue

Now we have to setup the client side to connect to a secured broker. The ConnectionFactory class provides a method called „createConnection“. There is an overloaded method of this: createConnection(String arg1 , String arg2) where arg1 is the username and arg2 is the password.

Here a short example for a listener connecting to a secured broker:

public void startListener() throws NamingException, JMSException, InterruptedException {

	// Create a JNDI API InitialContext object
	Properties props = new Properties();
	props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
	props.setProperty(Context.PROVIDER_URL, "tcp://" + server + ":61616");

	jndiContext = new InitialContext(props);
	connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");
	destination = (Destination) jndiContext.lookup("dynamicQueues/" + queueName);

	// Connect to ActiveMQ
	connection = connectionFactory.createConnection(username, password);
	connection.setClientID(clientID);
	// this helps to ensure, that not 2 instances can connect to the broker simultaneously
	// because it is not allowed to connect to the same broker with the same clientID
	connection.start();
	session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

	MessageConsumer subscriber = session.createConsumer(destination);
	subscriber.setMessageListener(new MessageListener() {

		@Override
		public void onMessage(Message msg) {
			try {
				System.out.println("Message arrived by consumer-ID : " + clientID + " CONTENT = " + ((TextMessage) msg).getText());
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	});

	for (int i = 0; i &lt; 100; i++) {
		System.out.println("still alive .... " + i);
		Thread.sleep(10 * 1000);
	}
}

 

Have fun with simple secured JMS 😉

——————————————————————

Sources / Websites:

ActiveMQ Wildcards: http://activemq.apache.org/wildcards.html

ActiveMQ Sample Borker Config for secured JMS Connections: http://activemq.apache.org/complex-single-broker-configuration-stomp-only.html

ActiveMQ Advisory Topics: http://activemq.apache.org/advisory-message.html

Java API for ConnectionFactory:  http://docs.oracle.com/javaee/1.4/api/javax/jms/ConnectionFactory.html