file download angularjs and servlets - javascript

I have an image stored in a database table, with primary key for a particular number. That image below the database to a folder of the java project by means of a servlet.
So far, so good.
My problem is that I need to download that image to the user and I can not do it.
My steps are as follows:
JSP:
$scope.downloadFile = function(){
var tkAct = $scope.ticketActual.tknum;
var param = {
nroTk: tkAct
};
var res = $http.post($scope.testHost +"/downloadAttachment",JSON.stringify(param));
});
res.error(function(data, status, headers, config) {
alert("failure message: " + JSON.stringify({data: data}));
});
}
SERVLET:
#WebServlet("/downloadAttachment")
public class downloadAttachment extends HttpServlet {
// size of byte buffer to send file
private static final int BUFFER_SIZE = 4096;
private final int BYTES_DOWNLOAD=1024;
public static final String FILE_SEPARATOR = System.getProperty("file.separator");
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession sess = request.getSession();
Controller ctrl = Controller.get();
ServletContext sc = getServletContext();
//int nroTicket=-1;
//nroTicket = 104;
System.out.println(request.getParameter("NroTk"));
System.out.println(request.getAttribute("NroTk"));
JSONObject joParam = getParametrosJo(request);
Long lNroTk = (Long) joParam.get("nroTk");
int nroTicket = lNroTk.intValue();
Vector<String> vNamesFile = ctrl.getFile(nroTicket,sc.getRealPath("/downloads"));
if(vNamesFile.size()==1){
String archivo = vNamesFile.get(0);
File downloadFile = new File(archivo);
String nombreFile = getNombreFileEnvio(nroTicket,downloadFile.getName());
// if you want to use a relative path to context root:
String relativePath = getServletContext().getRealPath("/downloads/");
System.out.println("relativePath = " + relativePath);
// obtains ServletContext
ServletContext context = getServletContext();
String mimeType = context.getMimeType(nombreFile);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setHeader("Content-Disposition","attachment;filename="+nombreFile);
System.out.println("Obteniendo el Stream...");
System.out.println("nombre del file es: "+nombreFile);
InputStream is = sc.getResourceAsStream("/downloads/" + downloadFile.getName());
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream(relativePath+downloadFile.getName());
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
}else{
byte[] zip = zipFiles(getServletContext().getRealPath("/downloads/"),vNamesFile, 95);
ServletOutputStream sos = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=AdjuntosTicket95" + ".ZIP");
sos.write(zip);
sos.flush();
}
}
private JSONObject getParametrosJo(HttpServletRequest request) throws IOException{
StringBuilder buffer = new StringBuilder();
BufferedReader joParam = request.getReader();
String texto="";
String str = null;
while ((str = joParam.readLine()) != null) {
buffer.append(str);
//texto+=str;
}
texto = buffer.toString();
System.out.println(texto);
if(!texto.equalsIgnoreCase("")){
JSONObject obj = JSONObject.parse(texto);
return obj;
}else{
return null;
}
}
private byte[] zipFiles(String path, Vector<String> vNamesFile, int nroTk) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
byte bytes[] = new byte[2048];
for (String fileName : vNamesFile) {
FileInputStream fis = new FileInputStream(fileName);
BufferedInputStream bis = new BufferedInputStream(fis);
zos.putNextEntry(new ZipEntry(getNombreFileEnvio(nroTk,fileName)));
int bytesRead;
while ((bytesRead = bis.read(bytes)) != -1) {
zos.write(bytes, 0, bytesRead);
}
zos.closeEntry();
bis.close();
fis.close();
}
zos.flush();
baos.flush();
zos.close();
baos.close();
return baos.toByteArray();
}
private String getNombreFileEnvio(int nroTk, String nombreEnFS){
String[] aNombreFile = nombreEnFS.split("%");
String nombreFile = aNombreFile[1];
return nombreFile;
}
}
How do I recover that image from the database to the folder / downloads / and deliver it to the user?
Thank you

Related

Kleopatra: Decryption failed: invalid data

For encrypting files I use PKCS # 7 and the Javascript bundle forge.pki.
var forge = require('node-forge');
var contentBuffer = forge.util.createBuffer( forge.util.decode64( "fasdasd asdasdasda" ));
var cert = forge.pki.certificateFromPem(certPem);
var p7 = forge.pkcs7.createEnvelopedData();
p7.addRecipient(cert);
p7.content = contentBuffer;
console.log("Encrypt...");
p7.encrypt();
var asn1Cert = p7.toAsn1();
var derBuffer = forge.asn1.toDer(asn1Cert);
var p7mContent = derBuffer.toHex();
console.log(p7mContent);
I copy the hex value into my Java class as a string constant. Java saves then converts this into a .p7m file and stores it locally for me.
public void writeDocumentContent(String filename) throws Exception {
byte[] encryptedMessage = getP7MBytes(hex);
InputStream inputStream = new ByteArrayInputStream(encryptedMessage);
handleTransfer(inputStream, TransferKanal.HTML5);
}
private static byte[] getP7MBytes(String p7m) {
int len = p7m.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(p7m.charAt(i), 16) << 4) + Character.digit(p7m.charAt(i + 1), 16));
}
return data;
}
private void handleTransfer(InputStream inputStream, TransferKanal kanal) throws Exception {
String path = "C:TEMP/padline";
createDirectory(path);
String filename = "example." + kanal.getFileExtension();
File targetFile = new File(path, filename);
provideTransferData(inputStream, targetFile);
}
private void provideTransferData(InputStream inputStream, File targetFile) throws Exception {
try (InputStream bInputStream = new BufferedInputStream(inputStream, 20 * 8192)) {
provide(bInputStream, targetFile);
} catch (IOException e) {
throw new Exception("error while reading/writing transfer data", e);
}
}
private boolean createDirectory(String directory) {
File file = new File(directory);
if (!file.exists()) {
file.mkdirs();
return true;
}
return false;
}
private void provide(InputStream is, File finalFile) throws Exception {
try {
File destFile = new File(finalFile.getAbsolutePath());
FileOutputStream buffer = null;
try {
buffer = new FileOutputStream(destFile);
int nRead;
byte[] buf = new byte[2 * 16384];
while ((nRead = is.read(buf, 0, buf.length)) != -1) {
buffer.write(buf, 0, nRead);
}
} catch (Exception e) {
throw new Exception("provision location corrupted", e);
} finally {
if (buffer != null) {
buffer.close();
}
}
} catch (IOException e) {
throw new Exception("error copying file", e);
}
}
Before, I create a bundle of the certificate and the private key via openSSL with following command:
openssl pkcs12 -export -inkey private.key -in public.cert -out certificate.pfx
and imported it into Kleopatra as a .pfx file. Then I have the generated (encrypted) p7m file to decrypt in Cleopatra and pushed the following error message:
Decryption failed: invalid data

Java Server, html client, unable to send messages to server

i got a little problem with my project. I have a Server written in Java and some clients written in html/js. Connecting works somehow, but as soon as i want to send a message from the client to the server it returns an error: "Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state"
Hopefully some of you awesome guys can look over my code and help me :)
Server Code:
Server.java
public class Server {
static ArrayList<Clients> clientsArrayList = new ArrayList<>();
private static int clientCount = 1;
private static int port;
private static ServerSocket ss;
private Socket socket;
private Clients clienthandler;
static boolean isRunning = true;
public Server(int port) throws IOException {
this.port = port;
setSs(new ServerSocket(port));
}
public void run() throws IOException {
while (isRunning) {
log("Listening on " + port + "...");
socket = getSs().accept();
log("Receiving client... " + socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
String s;
while ((s = in.readLine()) != null) {
log(s);
if (s.isEmpty()) {
break;
}
}
log("Creating a new handler for this client...");
clienthandler = new Clients(socket, "Client " + clientCount, in, out);
Thread t = new Thread(clienthandler);
clientsArrayList.add(clienthandler);
log("Added to client list");
t.start();
clientCount++;
GUI.texttoclientlog();
}
}
public static ServerSocket getSs() {
return ss;
}
public static void setSs(ServerSocket ss) {
Server.ss = ss;
}
public void log(String logtext) {
System.out.println(logtext);
GUI.texttolog(logtext);
}
}
Clients.java
public class Clients implements Runnable {
private String name;
final BufferedReader in;
final PrintWriter out;
Socket socket;
boolean isloggedin;
public Clients(Socket socket, String name, BufferedReader in, PrintWriter out) {
this.out = out;
this.in = in;
this.name = name;
this.socket = socket;
this.isloggedin = true;
}
#Override
public void run() {
String received;
while (true) {
try {
// receive the string
received = in.readLine();
System.out.println(received);
GUI.messagehandler(this.getName() + ": " + received);
if (received.equals("logout")) {
this.isloggedin = false;
this.socket.close();
break;
}
this.in.close();
this.out.close();
this.out.flush();
this.out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getName() {
return name;
}
}
And the JS client code:
<script>
var connection;
connection = new WebSocket("ws://localhost:6788/");
console.log("connection established");
connection.onmessage = function (e) { console.log(e.data); };
connection.onopen = () => conn.send("Connection established");
connection.onerror = function (error) {
console.log("WebSocket Error" + error);
};
function Send() {
if (connection.readyState === 1) {
connection.send("test");
}
console.log("error sending");
}
</script>
The WebSocket session is established via a handshake.
Post the handshake is complete and the connection is upgraded, the server and client can send messages. Here is a sample WebSocket server in Java.
Update the clients run method to
public void run() {
int len = 0;
byte[] b = new byte[80];
while(true){
try {
len = in.read(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(len!=-1){
byte rLength = 0;
int rMaskIndex = 2;
int rDataStart = 0;
//b[0] is always text in my case so no need to check;
byte data = b[1];
byte op = (byte) 127;
rLength = (byte) (data & op);
if(rLength==(byte)126) rMaskIndex=4;
if(rLength==(byte)127) rMaskIndex=10;
byte[] masks = new byte[4];
int j=0;
int i=0;
for(i=rMaskIndex;i<(rMaskIndex+4);i++){
masks[j] = b[i];
j++;
}
rDataStart = rMaskIndex + 4;
int messLen = len - rDataStart;
byte[] message = new byte[messLen];
for(i=rDataStart, j=0; i<len; i++, j++){
message[j] = (byte) (b[i] ^ masks[j % 4]);
}
System.out.println(new String(message));
b = new byte[80];
}
}
}
based on this SO answer
In my opinion you can leverage the Spring WebSocket support, rather than writing your own. I had created one which also uses ProtoBuf or you can look at the Spring WebSocket getting started guide here
Thats the updated code. it receives the bytes from the html clients. but i have no clue how to decode them :)
Server.java
public class Server {
static ArrayList<Clients> clientsArrayList = new ArrayList<>();
private static int clientCount = 1;
private static int port;
private static ServerSocket ss;
private Socket socket;
private Clients clienthandler;
static boolean isRunning = true;
private InputStream in;
private OutputStream out;
public Server(int port) throws IOException {
Server.port = port;
setSs(new ServerSocket(port));
}
public void run() throws IOException, NoSuchAlgorithmException {
while (isRunning) {
log("Listening on " + port + "...");
socket = getSs().accept();
log("Receiving client... " + socket);
in = socket.getInputStream();
out = socket.getOutputStream();
#SuppressWarnings("resource")
String data = new Scanner(in, "UTF-8").useDelimiter("\\r\\n\\r\\n").next();
Matcher get = Pattern.compile("^GET").matcher(data);
if (get.find()) {
Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
match.find();
byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n" + "Connection: Upgrade\r\n"
+ "Upgrade: websocket\r\n" + "Sec-WebSocket-Accept: "
+ DatatypeConverter.printBase64Binary(MessageDigest.getInstance("SHA-1")
.digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8")))
+ "\r\n\r\n").getBytes("UTF-8");
out.write(response, 0, response.length);
log("Creating a new handler for this client...");
clienthandler = new Clients(socket, "Client " + clientCount, in, out);
Thread t = new Thread(clienthandler);
clientsArrayList.add(clienthandler);
log("Added to client list");
t.start();
clientCount++;
GUI.texttoclientlog();
} else {
log("Handshake failed");
}
}
}
public static ServerSocket getSs() {
return ss;
}
public static void setSs(ServerSocket ss) {
Server.ss = ss;
}
public void log(String logtext) {
System.out.println(logtext);
GUI.texttolog(logtext);
}
}
Clients.java
public class Clients implements Runnable {
private String name;
final InputStream in;
final OutputStream out;
Socket socket;
boolean isloggedin;
public Clients(Socket socket, String name, InputStream in, OutputStream out) {
this.out = out;
this.in = in;
this.name = name;
this.socket = socket;
this.isloggedin = true;
}
#Override
public void run() {
int received;
while (true) {
try {
received = in.read();
//how to decode??
System.out.println(received);
GUI.messagehandler(this.getName() + ": " + received);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getName() {
return name;
}
}

Encoding in JavaScript

I'm very new in programming with Javascript and stuck in encoding my data.
I have done this as per need in my Android App, but could not able to do the same in JavaScript for my web portal.
The code which I'm using in Android App:
public void encryptdata(byte[] data) {
Encrypter encrypter = new Encrypter();
HashGenerator hashGenerator = new HashGenerator();
try {
byte[] e = encrypter.generateSessionKey();
byte[] encryptedData = encrypter.encryptUsingSessionKey(e, data);
byte[] hmac = hashGenerator.generateSha256Hash(data);
byte[] encryptedHmacBytes = encrypter.encryptUsingSessionKey(e, hmac);
this.encodedSessionKey = encodeBase64(e);
this.encodedHmac = encodeBase64(encryptedHmacBytes);
this.encodedData = encodeBase64(encryptedData);
} catch (Exception var6) {
var6.printStackTrace();
throw new RuntimeException(var6);
}
}
Encrypter.java
class Encrypter {
private static final String JCE_PROVIDER = "BC";
private static final int SYMMETRIC_KEY_SIZE = 256;
Encrypter() {
}
public byte[] generateSessionKey() throws NoSuchAlgorithmException, NoSuchProviderException {
KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
kgen.init(256);
SecretKey key = kgen.generateKey();
byte[] symmKey = key.getEncoded();
return symmKey;
}
public byte[] encryptUsingSessionKey(byte[] skey, byte[] data) throws InvalidCipherTextException {
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new AESEngine(), new PKCS7Padding());
cipher.init(true, new KeyParameter(skey));
int outputSize = cipher.getOutputSize(data.length);
byte[] tempOP = new byte[outputSize];
int processLen = cipher.processBytes(data, 0, data.length, tempOP, 0);
int outputLen = cipher.doFinal(tempOP, processLen);
byte[] result = new byte[processLen + outputLen];
System.arraycopy(tempOP, 0, result, 0, result.length);
return result;
}
static {
Security.addProvider(new BouncyCastleProvider());
}
}
HashGenerator.java
class HashGenerator {
public HashGenerator() {
}
public byte[] generateSha256Hash(byte[] message) {
String var2 = "SHA-256";
String var3 = "BC";
byte[] var4 = null;
try {
MessageDigest var7 = MessageDigest.getInstance(var2, var3);
var7.reset();
var4 = var7.digest(message);
} catch (Exception var6) {
var6.printStackTrace();
}
return var4;
}
}
These piece of code encoding the data and giving me HMAC as per my need, but I am not able to do same with JavaScript.
Can anyone give any reference or code on for JavaScript client.
Any help will be appreciated.
Thanks for down-voting the question, may be a not great question, but here I done it myself
this.doEncryption = function (data) {
var key = btoa(this.generateRandomString());
var Encryptionkey = CryptoJS.enc.Base64.parse(key);
var encryptedPid = CryptoJS.AES.encrypt(data,Encryptionkey,{ mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
var sha256 = CryptoJS.SHA256(data);
var encryptedHmac = CryptoJS.AES.encrypt(sha256,Encryptionkey,{ mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
return {
encryptionKey : key,
encryptedPid : encryptedPid.toString(),
encryptedHmac : encryptedHmac.toString()
};

react-native AES Encryption matching Java Decryption algorithm

The Full code of my Java Encryption/Decryption algorithm:
public class AESEncryptUtil {
private static AESEncryptUtil instance = new AESEncryptUtil();
private String password = "123456";
private Key key;
private Cipher cipher;
public AESEncryptUtil(){
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
key = new SecretKeySpec(enCodeFormat, "AES");
cipher = Cipher.getInstance("AES");
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] encrypt(String content) throws Exception {
byte[] byteContent = content.getBytes("utf-8");
instance.cipher.init(Cipher.ENCRYPT_MODE, instance.key);
byte[] result = instance.cipher.doFinal(byteContent);
return result;
}
public static byte[] decrypt(byte[] content) throws Exception {
instance.cipher.init(Cipher.DECRYPT_MODE, instance.key);
byte[] result = instance.cipher.doFinal(content);
return result;
}
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
public static String getNonce() {
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 16; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
String content = "test";
System.out.println("content: " + content);
byte[] encryptResult = encrypt(content);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println("encryptResultStr: " + encryptResultStr);
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte[] decryptResult = decrypt(decryptFrom);
System.out.println("decryptResult: " + new String(decryptResult));
}
}
I've tried many times and many ways to match the Java algorithm, but the result are always different. Which module should I use to do this ? Can anyone help me to deal it ? Thanks a lot !
I found the right way to match two algorithm:
Java part:
public static String encrypt() throws Exception {
try {
String data = "123456";
String key = "1234567812345678";
String iv = "1234567812345678";
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return new sun.misc.BASE64Encoder().encode(encrypted);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String desEncrypt() throws Exception {
String encrypted = encrypt() ;
try
{
String data = encrypted ;
String key = "1234567812345678";
String iv = "1234567812345678";
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
React native part:
pre coding: npm install crypto-js
import CryptoJS from 'crypto-js' ;
encryptFun() {
var data = "123456";
var key = CryptoJS.enc.Latin1.parse('1234567812345678');
var iv = CryptoJS.enc.Latin1.parse('1234567812345678');
var encrypted = CryptoJS.AES.encrypt(
data,
key,
{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.ZeroPadding
});
console.log('encrypted: ' + encrypted) ;
var decrypted = CryptoJS.AES.decrypt(encrypted,key,{iv:iv,padding:CryptoJS.pad.ZeroPadding});
console.log('decrypted: '+decrypted.toString(CryptoJS.enc.Utf8));
}
the result :
encrypted: aK7+UX24ttBgfTnAndz9aQ==
decrypted: 123456
I hope my code would help someone:)

The SmartSource Data collector JavaScript Tag, could be inserted from Java?

I'm totally new in Webtrends, I have read that The SmartSource Data collector JavaScript Tag, could be inserted from Java or HTML. does anyone know how to inser it from Java, I found the below class, is this class does the job? please provide some samples. Thanks in advance
public class DC {
public DC() {
super();
}
public String post_url(String connUrl, Map<String, String> bodyref) {
String response = "";
String responseCode = "";
try {
HttpURLConnection conn = null;
// construct data
String data = "";
Iterator<String> i = bodyref.keySet().iterator();
boolean ampersand = false;
while (i.hasNext()) {
if (ampersand) {
data += "&";
} else {
ampersand = true;
}
String b = i.next();
data += b + "=" + bodyref.get(b);
}
System.out.println();
System.out.println("[Request]");
System.out.println("(Url)");
System.out.println(connUrl);
System.out.println("(Body)");
System.out.println(data);
// send data
URL url = new URL(connUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
try {
// get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response += line;
response += "\n";
}
rd.close();
} catch (IOException e1) {
if (conn != null) {
// get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String line;
while ((line = rd.readLine()) != null) {
response += line;
response += "\n";
}
}
}
System.out.println();
System.out.println("[Response]");
System.out.println("(Status)");
System.out.printf("%s %s\n", conn.getResponseCode(), conn.getResponseMessage());
System.out.println("(Message)");
System.out.println(conn.getResponseMessage());
System.out.println("(Body)");
System.out.println(response);
System.out.flush();
wr.close();
} catch (Exception e) {
System.out.println();
System.out.println("[Response]");
System.out.println("(Status)");
System.out.println(e.toString());
System.out.println("(Message)");
System.out.println(e.getMessage());
System.out.flush();
}
return response;
}
public static void main(String[] args) {
DC dc = new DC();
// customer-specific DCSID
String dcsid = "dcslbiart00000gwngvpqkrcn_2u3z";
// base portion of DC API url
String base_url = "http://dc.webtrends.com/v1/" + dcsid;
// post body
Map<String, String> body1 = new HashMap();
// post query string
String querystring = "";
// compose urls
String id_url = base_url + "/ids.svc" + querystring;
String event_url = base_url + "/events.svc" + querystring;
// get visitor identifier
String id = dc.post_url(id_url, body1);
// post body
Map<String, String> body = new HashMap();
// initialize post body
body.put("dcsuri", "/MyJavaTest");
body.put("dcssip", "localhost");
body.put("WT.ti", "MyJavaTest");
body.put("WT.co_f", id);
body.put("dcsverbose", "true");
// submit event data
dc.post_url(event_url, body);
}

Categories

Resources