I am trying to read the InputStream from IHTTPSession.getInputStream() using the following code but its gives Socket TimeOut Exception every time.
private String readInStream(InputStream in){
StringBuffer outBuffer=new StringBuffer();
BufferedInputStream bis=new BufferedInputStream(in);
try {
while(bis.available()>0){
int ch= bis.read();
outBuffer.append((char)ch);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("DATA_Length", "outputBuffer :"+outBuffer.toString().length());
return outBuffer.toString();
}
i also tried the following Method but the same exception arises
private String readInStream(InputStream in){
String line="";
StringBuffer outBuffer=new StringBuffer();
BufferedReader rd=new BufferedReader(new InputStreamReader(in));
try {
while((line=rd.readLine()) != null){
outBuffer.append(line);
}
} catch (IOException e) {
Log.e("IOException", "IOException in readInStream:");
e.printStackTrace();
}
Log.e("DATA_Length", "outputBuffer :"+outBuffer.toString().length());
return outBuffer.toString();
}
Getting the content length from the header and reading up to it solved the problem.
Can confirm the accepted answer works (getting content length from the header and reading up to it). Here is some example code to turn the InputStream into a String:
try {
int contentLength = Integer.valueOf(session.getHeaders().get("content-length"));
String msg = new String(in.readNBytes(contentLength)); // the request body
} catch (IOException e) {
e.printStackTrace();
}
If you want to prevent a NullPointerException here, check whether the content-length header actually exists before parsing it to an integer.
Related
Here is my code which reads excelsheet files.but i can see my other functions are working fine but when try to get resource as url it return null.
URL resource = null;
try {
System.out.println(file3);
resource = getServletContext().getResource(file3);
System.out.println("Problem with getting resource"+resource);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = null;
try {
System.out.println(resource.toURI());
file = new File(resource.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileInputStream input = null;
try {
input = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Workbook w;
w = Workbook.getWorkbook(input);
// Get the first sheet
Sheet sheet = w.getSheet(0);
return sheet;
I implemented servlet, that creates XLS file. I am making a request from UI (GWT, RequestBuilder). I get the response, but is it possible to get ready file (with auto "save as" dialog box)?
Should I somehow set headers or something?
Here is my code:
Request implementation
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, GWT.getModuleBaseURL() + "downloadLimitsFile");
try {
rb.setHeader("Content-type", "text/html");
Request response = rb.sendRequest("", new RequestCallback() {
public void onError(Request request, Throwable exception) {
Window.alert("fail");
}
public void onResponseReceived(Request request, Response response) {
Window.alert("file downloaded " + response.getText());
}
});
} catch (RequestException e) {
Window.alert("Failed to send the request: " + e.getMessage());
}
My servlet implementation
public void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setHeader("Content-Disposition", "attachment; filename=File.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
try {
workbook = fileExporter.prepareExcellFile();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
response.setStatus(HttpServletResponse.SC_OK);
OutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
response.flushBuffer();
}
It was working fine (auto file download) when I was using eg. Anchor with servlet URL, but I have to use RequestBuilder now to make a request.
Can someone help?
I am afraid it is not possible, at least you can use a third party library.
Adding the header "Content-Disposition" won't work.
I was googling for a long time, but still can't find a solution to my case.
My Tomcat sometimes returns an exception :
Error in postRequest(): Server returned HTTP response code: 400 for URL: http://localhost:80/CITIUS2/webresources/entities.personainterna/
Sometimes it works and sometimes it returns this exception, so I really don't know what is the reason...
Connection function:
public static String excutePost(String targetURL, String urlParameters) throws UnsupportedEncodingException {
URL url;
HttpURLConnection connection = null;
String responseXML = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
byte[] requestXML = urlParameters.getBytes();
connection.setRequestProperty("Content-Length", String.valueOf(requestXML.length));
connection.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
// Send the String that was read into postByte.
OutputStream out = connection.getOutputStream();
out.write(requestXML);
out.close();
// Read the response and write it to standard out.
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(isr);
String temp;
String tempResponse = "";
//Create a string using response from web services
while ((temp = br.readLine()) != null) {
tempResponse = tempResponse + temp;
}
responseXML = tempResponse;
br.close();
isr.close();
} catch (java.net.MalformedURLException e) {
System.out.println("Error in postRequest(): Secure Service Required");
} catch (Exception e) {
System.out.println("Error in postRequest(): " + e.getMessage());
}
return responseXML;
}
# Edit:
In general build is successful, there are no errors, only this one in the Apache Tomcat's output window.
Rest method:
#POST
#Consumes({"application/xml", "application/json"})
public Response create(Personainterna entity) {
try {
getJpaController().create(entity);
return Response.created(URI.create(entity.getPersonaId().toString())).build();
} catch (Exception ex) {
return Response.notModified(ex.getMessage()).build();
}
}
I've recently tried to encrypt Saml2 assertion using relaying-party service public key. Unfortunately I can't finalise even the test phase
here is my code
public class EncryptionTest {
public static void main(String args[]){
try {
// The Assertion to be encrypted
FileInputStream fis;
DataInputStream in, in2;
File f = new File("src/main/resources/AssertionTest");
byte[] buffer = new byte[(int) f.length()];
in = new DataInputStream(new FileInputStream(f));
in.readFully(buffer);
in.close();
//Assertion = DataInputStream.readUTF(in);
String in_assert = new String(buffer);
System.out.println(in_assert);
org.apache.axiom.om.OMElement OMElementAssertion = org.apache.axiom.om.util.AXIOMUtil.stringToOM(in_assert);
Assertion assertion = convertOMElementToAssertion2(OMElementAssertion);
// Assume this contains a recipient's RSA public key
Credential keyEncryptionCredential;
keyEncryptionCredential = getCredentialFromFilePath("src/main/resources/cert.pem");
EncryptionParameters encParams = new EncryptionParameters();
encParams.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);
KeyEncryptionParameters kekParams = new KeyEncryptionParameters();
kekParams.setEncryptionCredential(keyEncryptionCredential);
kekParams.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP);
KeyInfoGeneratorFactory kigf =
Configuration.getGlobalSecurityConfiguration()
.getKeyInfoGeneratorManager().getDefaultManager()
.getFactory(keyEncryptionCredential);
kekParams.setKeyInfoGenerator(kigf.newInstance());
Encrypter samlEncrypter = new Encrypter(encParams, kekParams);
samlEncrypter.setKeyPlacement(KeyPlacement.PEER);
EncryptedAssertion encryptedAssertion = samlEncrypter.encrypt(assertion);
System.out.println(encryptedAssertion);
} catch (EncryptionException e) {
e.printStackTrace();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (KeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (XMLStreamException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
public static Credential getCredentialFromFilePath(String certPath) throws IOException, CertificateException, KeyException {
InputStream inStream = new FileInputStream(certPath);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(inStream);
inStream.close();
//"Show yourself!"
System.out.println(cert.toString());
BasicX509Credential cred = new BasicX509Credential();
cred.setEntityCertificate((java.security.cert.X509Certificate) cert);
cred.setPrivateKey(null);
//System.out.println(cred.toString());
return cred;
//return (Credential) org.opensaml.xml.security.SecurityHelper.getSimpleCredential( (X509Certificate) cert, privatekey);
}
public static Assertion convertOMElementToAssertion2(OMElement element) {
Element assertionSAMLDOOM = (Element) new StAXOMBuilder(DOOMAbstractFactory.getOMFactory(), element.getXMLStreamReader()).getDocumentElement();
try {
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(Assertion.DEFAULT_ELEMENT_NAME);
return (Assertion) unmarshaller.unmarshall(assertionSAMLDOOM);
} catch (Exception e1) {
System.out.println("error: " + e1.toString());
}
return null;
}
}
I constantly recive Null pointer exception in
KeyInfoGeneratorFactory kigf =
Configuration.getGlobalSecurityConfiguration()
.getKeyInfoGeneratorManager().getDefaultManager()
.getFactory(keyEncryptionCredential);
kekParams.setKeyInfoGenerator(kigf.newInstance());
How can I set GlobalSecurityConfiguration or is there different approach of encrypting Assertion which will work?
This question was laying open for too long. The problem was initialization of OpenSaml.
Simple
DefaultBootstrap.bootstrap();
helped and solved problem.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I understand that there are already alot of web server out there.
But i feel like creating one for learning purpose.
Is it something i should try to figure out and any guides or tutorials on this?
In java:
Create a ServerSocket and have this continually listen for connections - when a connection request comes in handle it by by parsing the HTTP request header, get the resource indicated and add some header information before sending back to the client. eg.
public class Server implements Runnable {
protected volatile boolean keepProcessing = true;
protected ServerSocket serverSocket;
protected static final int DEFAULT_TIMEOUT = 100000;
protected ExecutorService executor = Executors.newCachedThreadPool();
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(DEFAULT_TIMEOUT);
}
#Override
public void run() {
while (keepProcessing) {
try {
Socket socket = serverSocket.accept();
System.out.println("client accepted");
executor.execute(new HttpRequest(socket));
} catch (Exception e) {
}
}
closeIgnoringException(serverSocket);
}
protected void closeIgnoringException(ServerSocket serverSocket) {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ignore) {
}
}
}
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
executor.execute(new WebServer(6789));
} catch (Exception e) {
e.printStackTrace();
}
}
}
final class HttpRequest implements Runnable {
final static String CRLF = "\r\n";
private Socket socket;
public HttpRequest(Socket socket) {
this.socket = socket;
}
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private void processRequest() throws Exception {
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
String requestLine = br.readLine();
System.out.println();
System.out.println(requestLine);
List<String> tokens = Arrays.asList(requestLine.split(" "));
Iterator<String> it = tokens.iterator();
it.next(); // skip over the method, which should be "GET"
String fileName = it.next();
fileName = "." + fileName;
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
String contentType = null;
if (fileExists) {
statusLine = "HTTP/1.0 200 OK";
contentType = contentType(fileName);
contentTypeLine = "Content-type: " + contentType + CRLF;
} else {
statusLine = "HTTP/1.0 404 NOT FOUND";
contentType = "text/html";
contentTypeLine = "Content-type: " + contentType + CRLF;
entityBody = "<HTML>" + "<HEAD><TITLE>Not Found</TITLE></HEAD>"
+ "<BODY>" + statusLine + " Not Found</BODY></HTML>";
}
os.writeBytes(statusLine);
os.writeBytes(contentTypeLine);
os.writeBytes(CRLF);
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes(entityBody);
}
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
os.close();
br.close();
socket.close();
}
private static void sendBytes(InputStream fis, DataOutputStream os)
throws Exception {
byte[] buffer = new byte[1024];
int bytes = 0;
while ((bytes = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytes);
}
}
private static String contentType(String fileName) {
if (fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html";
}
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
return "image/jpeg";
}
if (fileName.endsWith(".gif")) {
return "image/gif";
}
if (fileName.endsWith(".txt")) {
return "text/plain";
}
if (fileName.endsWith(".pdf")) {
return "application/pdf";
}
return "application/octet-stream";
}
}
A Simple Webserver in C++ for Windows
Hope this helps you ; )
Alternatives
This project contains a modular web server in CodePlex
This article explains how to write a simple web server application using C# from CodeGuru
Start with understanding TCP/IP and the whole Internet protocol suite.
Then learn the HTTP 1.0 and 1.1 protocols.
That should start you on the way to understanding what you need to write in order to create a webserver from scratch.
Try asio from boost!
Boost.Asio is a cross-platform C++ library for network and low-level I/O programming that provides developers with a consistent asynchronous model using a modern C++ approach.
Most scripting language are capable and have plenty of examples on writing web servers. This route will give you a gentle introduction.