Big HTTP header parsing refactoring

This commit is contained in:
Ziver Koc 2016-02-19 20:28:26 +01:00
parent 946953699f
commit 862bc7763e
50 changed files with 3114 additions and 3072 deletions

View file

@ -27,11 +27,7 @@ package zutil;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Objects;
/** /**
* This class include some utility functions for classes * This class include some utility functions for classes

View file

@ -27,7 +27,6 @@ package zutil;
import zutil.converters.Converter; import zutil.converters.Converter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
/** /**

View file

@ -29,6 +29,8 @@ import zutil.parser.Base64Decoder;
import java.io.*; import java.io.*;
import java.util.BitSet; import java.util.BitSet;
import java.util.Iterator;
import java.util.Map;
public class Converter { public class Converter {
private Converter(){} private Converter(){}
@ -265,6 +267,35 @@ public class Converter {
return ret.toString(); return ret.toString();
} }
/**
* Generates a comma separated string with key and value pairs
*
* @return a comma separated String
*/
public static String toString(Map map){
StringBuilder tmp = new StringBuilder();
tmp.append("{");
Iterator<Object> it = map.keySet().iterator();
while(it.hasNext()){
Object key = it.next();
Object value = map.get(key);
tmp.append(key);
if (value != null) {
if (value instanceof String)
tmp.append(": \"").append(value).append("\"");
else
tmp.append(value);
}
else
tmp.append("null");
if(it.hasNext())
tmp.append(", ");
}
tmp.append('}');
return tmp.toString();
}
/** /**
* Converts a BitSet to a Integer * Converts a BitSet to a Integer
* *

View file

@ -31,7 +31,6 @@ import javax.naming.InitialContext;
import javax.naming.NamingException; import javax.naming.NamingException;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.io.Closeable; import java.io.Closeable;
import java.math.BigInteger;
import java.sql.*; import java.sql.*;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;

View file

@ -25,7 +25,6 @@
package zutil.db; package zutil.db;
import zutil.StringUtil; import zutil.StringUtil;
import zutil.db.handler.ListSQLResult;
import zutil.db.handler.SimpleSQLResult; import zutil.db.handler.SimpleSQLResult;
import zutil.log.LogUtil; import zutil.log.LogUtil;
@ -37,7 +36,6 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
/** /**

View file

@ -24,7 +24,6 @@
package zutil.db.bean; package zutil.db.bean;
import zutil.ClassUtil;
import zutil.log.LogUtil; import zutil.log.LogUtil;
import java.lang.reflect.Field; import java.lang.reflect.Field;

View file

@ -31,7 +31,6 @@ import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Properties;
/** /**
* Adds the result of the query to a List. * Adds the result of the query to a List.

View file

@ -31,8 +31,6 @@ import zutil.log.LogUtil;
import java.io.*; import java.io.*;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.logging.Logger; import java.util.logging.Logger;

View file

@ -26,7 +26,6 @@ package zutil.log;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;

View file

@ -27,7 +27,6 @@ package zutil.log;
import zutil.io.file.FileUtil; import zutil.io.file.FileUtil;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.logging.*; import java.util.logging.*;
/** /**

View file

@ -25,7 +25,6 @@
package zutil.log; package zutil.log;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;

View file

@ -24,13 +24,6 @@
package zutil.log; package zutil.log;
import com.mysql.jdbc.log.Log;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* Created by Ziver on 2015-10-15. * Created by Ziver on 2015-10-15.
*/ */

View file

@ -25,7 +25,6 @@
package zutil.net.dns; package zutil.net.dns;
import zutil.parser.binary.BinaryStruct; import zutil.parser.binary.BinaryStruct;
import zutil.parser.binary.BinaryStruct.*;
/** /**
* Created by Ziver on 2016-02-09. * Created by Ziver on 2016-02-09.

View file

@ -0,0 +1,176 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.http;
import zutil.converters.Converter;
import java.util.HashMap;
import java.util.Iterator;
public class HttpHeader {
// HTTP info
private String type;
private String url;
private HashMap<String, String> urlAttributes;
private float version;
private int httpCode;
// Parameters
private HashMap<String, String> headers;
private HashMap<String, String> cookies;
protected HttpHeader(){
urlAttributes = new HashMap<String, String>();
headers = new HashMap<String, String>();
cookies = new HashMap<String, String>();
}
/**
* @return the HTTP message type( ex. GET,POST...)
*/
public String getRequestType(){
return type;
}
/**
* @return the HTTP version of this header
*/
public float getHTTPVersion(){
return version;
}
/**
* @return the HTTP Return Code from a Server
*/
public int getHTTPCode(){
return httpCode;
}
/**
* @return the URL that the client sent the server
*/
public String getRequestURL(){
return url;
}
/**
* @return a Iterator with all defined url keys
*/
public Iterator<String> getURLAttributeKeys(){
return urlAttributes.keySet().iterator();
}
/**
* Returns the URL attribute value of the given name.
*
* returns null if there is no such attribute
*/
public String getURLAttribute(String name){
return urlAttributes.get( name );
}
/**
* @return a Iterator with all defined headers
*/
public Iterator<String> getHeaderKeys(){
return headers.keySet().iterator();
}
/**
* Returns the HTTP attribute value of the given name.
*
* returns null if there is no such attribute
*/
public String getHeader(String name){
return headers.get( name.toUpperCase() );
}
/**
* @return a Iterator with all defined cookies
*/
public Iterator<String> getCookieKeys(){
return cookies.keySet().iterator();
}
/**
* Returns the cookie value of the given name.
*
* returns null if there is no such attribute
*/
public String getCookie(String name){
return cookies.get( name );
}
protected HashMap<String,String> getCookieMap(){
return cookies;
}
protected HashMap<String,String> getUrlAttributeMap(){
return urlAttributes;
}
protected void setRequestType(String type){
this.type = type.trim();
}
protected void setHTTPVersion(float version){
this.version = version;
}
protected void setHTTPCode(int code){
this.httpCode = code;
}
protected void setRequestURL(String url){
this.url = url.trim().replaceAll("//", "/");
}
protected void putCookie(String key, String value){
cookies.put(key.trim(), value.trim());
}
protected void putURLAttribute(String key, String value){
urlAttributes.put(key.trim(), value.trim());
}
protected void putHeader(String key, String value){
headers.put(key.trim(), value.trim());
}
public String toString(){
StringBuilder tmp = new StringBuilder();
tmp.append("{Type: ").append(type);
tmp.append(", HTTP_version: HTTP/").append(version);
if(url == null)
tmp.append(", URL: null");
else
tmp.append(", URL: \"").append(url).append('\"');
tmp.append(", URL_attr: ").append(toStringAttributes());
tmp.append(", Headers: ").append(toStringHeaders());
tmp.append(", Cookies: ").append(toStringCookies());
tmp.append('}');
return tmp.toString();
}
public String toStringHeaders(){
return Converter.toString(headers);
}
public String toStringCookies(){
return Converter.toString(cookies);
}
public String toStringAttributes(){
return Converter.toString(urlAttributes);
}
}

View file

@ -28,72 +28,55 @@ import zutil.parser.URLDecoder;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.io.StringReader;
import java.util.Scanner;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class HttpHeaderParser { public class HttpHeaderParser {
// Some Cached regex's public static final String HEADER_COOKIE = "COOKIE";
private static final Pattern colonPattern = Pattern.compile(":");
private static final Pattern equalPattern = Pattern.compile("=");
private static final Pattern andPattern = Pattern.compile("&");
private static final Pattern semiColonPattern = Pattern.compile(";");
// HTTP info private static final Pattern PATTERN_COLON = Pattern.compile(":");
private String type; private static final Pattern PATTERN_EQUAL = Pattern.compile("=");
private String url; private static final Pattern PATTERN_AND = Pattern.compile("&");
private HashMap<String, String> url_attr; private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
private float version;
private int httpCode;
private BufferedReader in;
// Parameters
private HashMap<String, String> headers;
private HashMap<String, String> cookies;
/** /**
* Parses the HTTP header information from a stream * Parses the HTTP header information from a stream
* *
* @param in is the stream * @param in is the stream
* @throws IOException
*/ */
public HttpHeaderParser(BufferedReader in) throws IOException{ public HttpHeaderParser(BufferedReader in){
url_attr = new HashMap<String, String>(); this.in = in;
headers = new HashMap<String, String>();
cookies = new HashMap<String, String>();
String tmp = null;
if( (tmp=in.readLine()) != null && !tmp.isEmpty() ){
parseStatusLine( tmp );
while( (tmp=in.readLine()) != null && !tmp.isEmpty() ){
parseLine( tmp );
}
}
parseCookies();
} }
/** /**
* Parses the HTTP header information from an String * Parses the HTTP header information from a String
* *
* @param in is the string * @param in is the String
*/ */
public HttpHeaderParser(String in){ public HttpHeaderParser(String in){
url_attr = new HashMap<String, String>(); this.in = new BufferedReader(new StringReader(in));
headers = new HashMap<String, String>(); }
cookies = new HashMap<String, String>();
Scanner sc = new Scanner(in);
sc.useDelimiter("\n"); public HttpHeader read() throws IOException {
String tmp = null; HttpHeader header = null;
if( sc.hasNext() && !(tmp=sc.next()).isEmpty() ){ String line = null;
parseStatusLine( tmp ); if( (line=in.readLine()) != null && !line.isEmpty() ){
while( sc.hasNext() && !(tmp=sc.next()).isEmpty() ){ header = new HttpHeader();
parseLine( tmp ); parseStatusLine(header, line);
while( (line=in.readLine()) != null && !line.isEmpty() ){
parseLine(header, line);
} }
parseCookies(header);
} }
sc.close(); return header;
parseCookies();
} }
/** /**
* Parses the first header line and ads the values to * Parses the first header line and ads the values to
* the map and returns the file name and path * the map and returns the file name and path
@ -101,62 +84,28 @@ public class HttpHeaderParser {
* @param line The header String * @param line The header String
* @return The path and file name as a String * @return The path and file name as a String
*/ */
protected void parseStatusLine(String line){ protected static void parseStatusLine(HttpHeader header, String line){
// Server Response // Server Response
if( line.startsWith("HTTP/") ){ if( line.startsWith("HTTP/") ){
version = Float.parseFloat( line.substring( 5 , 8) ); header.setHTTPVersion( Float.parseFloat( line.substring( 5 , 8)));
httpCode = Integer.parseInt( line.substring( 9, 12 )); header.setHTTPCode( Integer.parseInt( line.substring( 9, 12 )));
} }
// Client Request // Client Request
else if(line.contains("HTTP/")){ else if(line.contains("HTTP/")){
type = (line.substring(0, line.indexOf(" "))).trim(); header.setRequestType( line.substring(0, line.indexOf(" ")));
version = Float.parseFloat( line.substring(line.lastIndexOf("HTTP/")+5 , line.length()).trim() ); header.setHTTPVersion( Float.parseFloat( line.substring(line.lastIndexOf("HTTP/")+5 , line.length()).trim()));
line = (line.substring(type.length()+1, line.lastIndexOf("HTTP/"))).trim(); line = (line.substring(header.getRequestType().length()+1, line.lastIndexOf("HTTP/")));
// parse URL and attributes // parse URL and attributes
int index = line.indexOf('?'); int index = line.indexOf('?');
if(index > -1){ if(index > -1){
url = line.substring(0, index ); header.setRequestURL( line.substring(0, index));
line = line.substring( index+1, line.length()); line = line.substring( index+1, line.length());
parseURLParameters(line, url_attr); parseURLParameters(header, line);
} }
else{ else{
url = line; header.setRequestURL(line);
} }
url = url.replaceAll("//", "/");
}
}
/**
* Parses a String with variables from a get or post
* that was sent from a client and puts the data into a HashMap
*
* @param attributes is the String containing all the attributes
*/
public static HashMap<String, String> parseURLParameters( String attributes ){
HashMap<String, String> map = new HashMap<String, String>();
parseURLParameters(attributes, map);
return map;
}
/**
* Parses a String with variables from a get or post
* that was sent from a client and puts the data into a HashMap
*
* @param attributes is the String containing all the attributes
* @param map is the HashMap to put all the values into
*/
public static void parseURLParameters(String attributes, HashMap<String, String> map){
String[] tmp;
attributes = URLDecoder.decode(attributes);
// get the variables
String[] data = andPattern.split( attributes );
for(String element : data){
tmp = equalPattern.split(element, 2);
map.put(
tmp[0].trim(), // Key
(tmp.length>1 ? tmp[1] : "").trim()); //Value
} }
} }
@ -165,26 +114,23 @@ public class HttpHeaderParser {
* *
* @param line is the next line in the header * @param line is the next line in the header
*/ */
protected void parseLine(String line){ protected void parseLine(HttpHeader header, String line){
String[] data = colonPattern.split( line, 2 ); String[] data = PATTERN_COLON.split( line, 2 );
headers.put( header.putHeader(
data[0].trim().toUpperCase(), // Key data[0].trim().toUpperCase(), // Key
(data.length>1 ? data[1] : "").trim()); //Value (data.length>1 ? data[1] : "").trim()); //Value
} }
/** /**
* Parses the attribute "Cookie" and returns a HashMap * Parses the header "Cookie" and stores all cookies in the HttpHeader object
* with the values
*
* @return a HashMap with cookie values
*/ */
protected void parseCookies(){ protected void parseCookies(HttpHeader header){
if( headers.containsKey("COOKIE") ){ String cookieHeader = header.getHeader(HEADER_COOKIE);
String[] tmp = semiColonPattern.split( headers.get("COOKIE") ); if(cookieHeader != null && !cookieHeader.isEmpty()){
String[] tmp2; String[] tmp = PATTERN_SEMICOLON.split(cookieHeader);
for(String cookie : tmp){ for(String cookie : tmp){
tmp2 = equalPattern.split(cookie, 2); String[] tmp2 = PATTERN_EQUAL.split(cookie, 2);
cookies.put( header.putCookie(
tmp2[0].trim(), // Key tmp2[0].trim(), // Key
(tmp2.length>1 ? tmp2[1] : "").trim()); //Value (tmp2.length>1 ? tmp2[1] : "").trim()); //Value
} }
@ -192,106 +138,21 @@ public class HttpHeaderParser {
} }
/** /**
* @return the HTTP message type( ex. GET,POST...) * Parses a String with variables from a get or post
*/ * that was sent from a client
public String getRequestType(){
return type;
}
/**
* @return the HTTP version of this header
*/
public float getHTTPVersion(){
return version;
}
/**
* @return the HTTP Return Code from a Server
*/
public float getHTTPCode(){
return httpCode;
}
/**
* @return the URL that the client sent the server
*/
public String getRequestURL(){
return url;
}
/**
* Returns the URL attribute value of the given name.
* *
* returns null if there is no such attribute * @param attributes is the String containing all the attributes
*/ */
public String getURLAttribute(String name){ protected static void parseURLParameters(HttpHeader header, String attributes){
return url_attr.get( name ); String[] tmp;
attributes = URLDecoder.decode(attributes);
// get the variables
String[] data = PATTERN_AND.split( attributes );
for(String element : data){
tmp = PATTERN_EQUAL.split(element, 2);
header.putURLAttribute(
tmp[0].trim(), // Key
(tmp.length>1 ? tmp[1] : "").trim()); //Value
} }
/**
* Returns the HTTP attribute value of the given name.
*
* returns null if there is no such attribute
*/
public String getHeader(String name){
return headers.get( name.toUpperCase() );
}
/**
* Returns the cookie value of the given name.
*
* returns null if there is no such attribute
*/
public String getCookie(String name){
return cookies.get( name );
}
/**
* @return a map of the parsed cookies
*/
public HashMap<String, String> getCookies(){
return cookies;
}
/**
* @return a map of the parsed URL attributes
*/
public HashMap<String, String> getURLAttributes(){
return url_attr;
}
/**
* @return a map of the parsed headers
*/
public HashMap<String, String> getHeaders(){
return headers;
}
public String toString(){
StringBuilder tmp = new StringBuilder();
tmp.append("{Type: ").append(type);
tmp.append(", HTTP_version: HTTP/").append(version);
if(url == null)
tmp.append(", URL: null");
else
tmp.append(", URL: \"").append(url).append('\"');
tmp.append(", URL_attr: { ");
for( String key : url_attr.keySet() ){
tmp.append(key).append(": \"");
tmp.append(url_attr.get(key)).append("\", ");
}
tmp.append('}');
tmp.append(", Headers: {");
for( String key : headers.keySet() ){
tmp.append(key).append(": \"");
tmp.append( headers.get(key) ).append("\", ");
}
tmp.append('}');
tmp.append(", Cookies: {");
for( String key : cookies.keySet() ){
tmp.append(key).append(": \"");
tmp.append( cookies.get(key) ).append("\", ");
}
tmp.append('}');
tmp.append('}');
return tmp.toString();
} }
} }

9
src/zutil/net/http/HttpPage.java Normal file → Executable file
View file

@ -38,14 +38,15 @@ public interface HttpPage{
* This method has to be implemented for every page. * This method has to be implemented for every page.
* This method is called when a client wants a response * This method is called when a client wants a response
* from this specific page. * from this specific page.
* @param out is the PrintStream to the client *
* @param client_info is information about the client * @param out is a output stream to the client
* @param session is session values for the client * @param headers is the header received from the client
* @param session is the session associated with the current client
* @param cookie is cookie information from the client * @param cookie is cookie information from the client
* @param request is POST and GET requests from the client * @param request is POST and GET requests from the client
*/ */
public abstract void respond(HttpPrintStream out, public abstract void respond(HttpPrintStream out,
HttpHeaderParser client_info, HttpHeader headers,
Map<String,Object> session, Map<String,Object> session,
Map<String,String> cookie, Map<String,String> cookie,
Map<String,String> request) throws IOException; Map<String,String> request) throws IOException;

View file

@ -24,6 +24,8 @@
package zutil.net.http; package zutil.net.http;
import zutil.converters.Converter;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintStream; import java.io.PrintStream;
@ -66,7 +68,7 @@ public class HttpPrintStream extends OutputStream{
* Creates an new instance of HttpPrintStream with * Creates an new instance of HttpPrintStream with
* message type of RESPONSE and buffering disabled. * message type of RESPONSE and buffering disabled.
* *
* @param out is the OutputStream to send the message * @param out is the OutputStream where the data will be written to
*/ */
public HttpPrintStream(OutputStream out) { public HttpPrintStream(OutputStream out) {
this( out, HttpMessageType.RESPONSE ); this( out, HttpMessageType.RESPONSE );
@ -75,7 +77,7 @@ public class HttpPrintStream extends OutputStream{
* Creates an new instance of HttpPrintStream with * Creates an new instance of HttpPrintStream with
* message type buffering disabled. * message type buffering disabled.
* *
* @param out is the OutputStream to send the message * @param out is the OutputStream where the data will be written to
* @param type is the type of message * @param type is the type of message
*/ */
public HttpPrintStream(OutputStream out, HttpMessageType type) { public HttpPrintStream(OutputStream out, HttpMessageType type) {
@ -107,7 +109,7 @@ public class HttpPrintStream extends OutputStream{
* *
* @param key is the name of the cookie * @param key is the name of the cookie
* @param value is the value of the cookie * @param value is the value of the cookie
* @throws IOException Throws exception if the header has already been sent * @throws IOException if the header has already been sent
*/ */
public void setCookie(String key, String value) throws IOException{ public void setCookie(String key, String value) throws IOException{
if(cookies == null) if(cookies == null)
@ -120,7 +122,7 @@ public class HttpPrintStream extends OutputStream{
* *
* @param key is the header name * @param key is the header name
* @param value is the value of the header * @param value is the value of the header
* @throws IOException Throws exception if the header has already been sent * @throws IOException if the header has already been sent
*/ */
public void setHeader(String key, String value) throws IOException{ public void setHeader(String key, String value) throws IOException{
if(headers == null) if(headers == null)
@ -325,24 +327,16 @@ public class HttpPrintStream extends OutputStream{
str.append(", req_url: null"); str.append(", req_url: null");
else else
str.append(", req_url: \"").append(req_url).append('\"'); str.append(", req_url: \"").append(req_url).append('\"');
} else { } else if (message_type == HttpMessageType.RESPONSE){
str.append(", status_code: ").append(res_status_code); str.append(", status_code: ").append(res_status_code);
str.append(", status_str: ").append(getStatusString(res_status_code)); str.append(", status_str: ").append(getStatusString(res_status_code));
} }
if (headers != null) { if (headers != null) {
str.append(", Headers: {"); str.append(", Headers: ").append(Converter.toString(headers));
for (String key : headers.keySet()) {
str.append(key).append(": \"").append(headers.get(key)).append("\", ");
}
str.append('}');
} }
if (cookies != null) { if (cookies != null) {
str.append(", Cookies: {"); str.append(", Cookies: ").append(Converter.toString(cookies));
for (String key : cookies.keySet()) {
str.append(key).append(": \"").append(cookies.get(key)).append("\", ");
}
str.append('}');
} }
} }
else else

View file

@ -48,13 +48,16 @@ import java.util.logging.Logger;
*/ */
public class HttpServer extends ThreadedTCPNetworkServer{ public class HttpServer extends ThreadedTCPNetworkServer{
private static final Logger logger = LogUtil.getLogger(); private static final Logger logger = LogUtil.getLogger();
public static final String SERVER_VERSION = "Ziver HttpServer 1.0";
public static final int COOKIE_TTL = 200; public static final String SESSION_ID_KEY = "session_id";
public static final String SESSION_TTL_KEY = "session_ttl";
public static final String SERVER_VERSION = "Ziver HttpServer 1.1";
public static final int SESSION_TTL = 10*60*1000; // in milliseconds public static final int SESSION_TTL = 10*60*1000; // in milliseconds
private Map<String,HttpPage> pages; private Map<String,HttpPage> pages;
private HttpPage defaultPage; private HttpPage defaultPage;
private Map<String,Map<String,Object>> sessions; private Map<Integer,Map<String,Object>> sessions;
private int nextSessionId; private int nextSessionId;
/** /**
@ -77,12 +80,12 @@ public class HttpServer extends ThreadedTCPNetworkServer{
public HttpServer(int port, File keyStore, String keyStorePass){ public HttpServer(int port, File keyStore, String keyStorePass){
super( port, keyStore, keyStorePass ); super( port, keyStore, keyStorePass );
pages = new ConcurrentHashMap<String,HttpPage>(); pages = new ConcurrentHashMap<>();
sessions = new ConcurrentHashMap<String,Map<String,Object>>(); sessions = new ConcurrentHashMap<>();
nextSessionId = 0; nextSessionId = 0;
Timer timer = new Timer(); Timer timer = new Timer();
timer.schedule(new GarbageCollector(), 10000, SESSION_TTL / 2); timer.schedule(new SessionGarbageCollector(), 10000, SESSION_TTL / 2);
logger.info("HTTP"+(keyStore==null?"":"S")+" Server ready!"); logger.info("HTTP"+(keyStore==null?"":"S")+" Server ready!");
} }
@ -93,14 +96,14 @@ public class HttpServer extends ThreadedTCPNetworkServer{
* *
* @author Ziver * @author Ziver
*/ */
private class GarbageCollector extends TimerTask { private class SessionGarbageCollector extends TimerTask {
public void run(){ public void run(){
Object[] keys = sessions.keySet().toArray(); Object[] keys = sessions.keySet().toArray();
for(Object key : keys){ for(Object key : keys){
Map<String,Object> client_session = sessions.get(key); Map<String,Object> session = sessions.get(key);
// Check if session is still valid // Check if session is still valid
if((Long)client_session.get("ttl") < System.currentTimeMillis()){ if((Long)session.get(SESSION_TTL_KEY) < System.currentTimeMillis()){
sessions.remove(key); sessions.remove(key);
logger.fine("Removing Session: "+key); logger.fine("Removing Session: "+key);
} }
@ -158,92 +161,87 @@ public class HttpServer extends ThreadedTCPNetworkServer{
public void run(){ public void run(){
String tmp = null; String tmp = null;
HttpHeaderParser headerParser = new HttpHeaderParser(in);
HashMap<String,String> cookie = new HashMap<String,String>();
HashMap<String,String> request = new HashMap<String,String>();
//**************************** REQUEST ********************************* //**************************** REQUEST *********************************
try { try {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
HttpHeaderParser parser = new HttpHeaderParser(in); HttpHeader header = headerParser.read();
request = parser.getURLAttributes(); if(header == null){
cookie = parser.getCookies(); logger.finer("No header received");
return;
//******* Read in the post data if available
if( parser.getHeader("Content-Length")!=null ){
// Reads the post data size
tmp = parser.getHeader("Content-Length");
int post_data_length = Integer.parseInt( tmp );
// read the data
StringBuffer tmpb = new StringBuffer();
// read the data
for(int i=0; i<post_data_length ;i++){
tmpb.append((char)in.read());
} }
tmp = parser.getHeader("Content-Type"); //******* Read in the post data if available
if( header.getHeader("Content-Length") != null ){
// Reads the post data size
tmp = header.getHeader("Content-Length");
int post_data_length = Integer.parseInt( tmp );
// read the data
StringBuilder tmpBuff = new StringBuilder();
// read the data
for(int i=0; i<post_data_length ;i++){
tmpBuff.append((char)in.read());
}
tmp = header.getHeader("Content-Type");
if( tmp.contains("application/x-www-form-urlencoded") ){ if( tmp.contains("application/x-www-form-urlencoded") ){
// get the variables // get the variables
HttpHeaderParser.parseURLParameters( tmpb.toString(), request ); HttpHeaderParser.parseURLParameters(header, tmpBuff.toString());
} }
else if( tmp.contains("application/soap+xml" ) || else if( tmp.contains("application/soap+xml" ) ||
tmp.contains("text/xml") || tmp.contains("text/xml") ||
tmp.contains("text/plain") ){ tmp.contains("text/plain") ){
// save the variables // save the variables
request.put( "" , tmpb.toString() ); header.putURLAttribute("" , tmpBuff.toString());
} }
else if( tmp.contains("multipart/form-data") ){ else if( tmp.contains("multipart/form-data") ){
// TODO: File upload // TODO: File upload
throw new Exception( "\"multipart-form-data\" Not implemented." ); throw new UnsupportedOperationException("HTTP Content-Type 'multipart-form-data' not supported." );
} }
} }
//**************************** HANDLE REQUEST ********************************* //**************************** HANDLE REQUEST *********************************
// Get the client session or create one // Get the client session or create one
Map<String, Object> client_session; Map<String, Object> session;
long ttl_time = System.currentTimeMillis()+SESSION_TTL; long ttlTime = System.currentTimeMillis() + SESSION_TTL;
if( cookie.containsKey("session_id") && sessions.containsKey(cookie.get("session_id")) ){ String sessionCookie = header.getCookie(SESSION_ID_KEY);
client_session = sessions.get( cookie.get("session_id") ); if( sessionCookie != null && sessions.containsKey(sessionCookie) &&
// Check if session is still valid (Long)sessions.get(sessionCookie).get(SESSION_TTL_KEY) < System.currentTimeMillis()){ // Check if session is still valid
if( (Long)client_session.get("ttl") < System.currentTimeMillis() ){
int session_id = (Integer)client_session.get("session_id"); session = sessions.get(sessionCookie);
client_session = Collections.synchronizedMap(new HashMap<String, Object>());
client_session.put( "session_id", session_id);
sessions.put( ""+session_id, client_session);
}
// renew the session TTL // renew the session TTL
client_session.put("ttl", ttl_time); session.put(SESSION_TTL_KEY, ttlTime);
} }
else{ else{
client_session = Collections.synchronizedMap(new HashMap<String, Object>()); session = Collections.synchronizedMap(new HashMap<String, Object>());
client_session.put( "session_id", nextSessionId ); session.put(SESSION_ID_KEY, nextSessionId );
client_session.put( "ttl", ttl_time ); session.put(SESSION_TTL_KEY, ttlTime );
sessions.put( ""+nextSessionId, client_session ); sessions.put(nextSessionId, session );
++nextSessionId; ++nextSessionId;
} }
//**************************** RESPONSE ************************************ //**************************** RESPONSE ************************************
out.setStatusCode(200); out.setStatusCode(200);
out.setHeader( "Server", SERVER_VERSION ); out.setHeader("Server", SERVER_VERSION);
out.setHeader( "Content-Type", "text/html" ); out.setHeader("Content-Type", "text/html");
out.setCookie( "session_id", ""+client_session.get("session_id") ); out.setCookie(SESSION_ID_KEY, ""+session.get(SESSION_ID_KEY));
if( parser.getRequestURL() != null && pages.containsKey(parser.getRequestURL()) ){ if( header.getRequestURL() != null && pages.containsKey(header.getRequestURL())){
HttpPage page = pages.get(parser.getRequestURL()); HttpPage page = pages.get(header.getRequestURL());
page.respond(out, parser, client_session, cookie, request); page.respond(out, header, session, header.getCookieMap(), header.getUrlAttributeMap());
if(LogUtil.isLoggable(page.getClass(), Level.FINER)) if(LogUtil.isLoggable(page.getClass(), Level.FINER))
logRequest(parser, client_session, cookie, request, time); logRequest(header, session, time);
} }
else if( parser.getRequestURL() != null && defaultPage != null ){ else if( header.getRequestURL() != null && defaultPage != null ){
defaultPage.respond(out, parser, client_session, cookie, request); defaultPage.respond(out, header, session, header.getCookieMap(), header.getUrlAttributeMap());
if(LogUtil.isLoggable(defaultPage.getClass(), Level.FINER)) if(LogUtil.isLoggable(defaultPage.getClass(), Level.FINER))
logRequest(parser, client_session, cookie, request, time); logRequest(header, session, time);
} }
else{ else{
out.setStatusCode( 404 ); out.setStatusCode(404);
out.println( "404 Page Not Found: "+parser.getRequestURL() ); out.println("404 Page Not Found: "+header.getRequestURL());
logger.warning("Page not defined: " + parser.getRequestURL()); logger.warning("Page not defined: " + header.getRequestURL());
} }
//******************************************************************************** //********************************************************************************
@ -263,7 +261,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
logger.log(Level.SEVERE, null, ioe); logger.log(Level.SEVERE, null, ioe);
} }
} }
finally {
try{ try{
out.close(); out.close();
in.close(); in.close();
@ -273,23 +271,27 @@ public class HttpServer extends ThreadedTCPNetworkServer{
} }
} }
} }
}
protected static void logRequest(HttpHeaderParser parser,
Map<String,Object> client_session, protected static void logRequest(HttpHeader header,
Map<String,String> cookie, Map<String,Object> session,
Map<String,String> request,
long time){ long time){
// Debug // Debug
if(logger.isLoggable(Level.FINEST) ){ if(logger.isLoggable(Level.FINEST) ){
logger.finer( StringBuilder buff = new StringBuilder();
"Received request: " + parser.getRequestURL() buff.append("Received request: ").append(header.getRequestURL());
+ " (client_session: " + client_session buff.append(", (");
+ ", cookie: " + cookie buff.append("request: ").append(header.toStringAttributes());
+ ", request: " + request + ")" buff.append(", cookies: ").append(header.toStringCookies());
+ ", time: "+ StringUtil.formatTimeToString(System.currentTimeMillis() - time)); buff.append(", session: ").append(session);
buff.append(")");
buff.append(", time: "+ StringUtil.formatTimeToString(System.currentTimeMillis() - time));
logger.finer(buff.toString());
} else if(logger.isLoggable(Level.FINER)){ } else if(logger.isLoggable(Level.FINER)){
logger.finer( logger.finer(
"Received request: " + parser.getRequestURL() "Received request: " + header.getRequestURL()
+ ", time: "+ StringUtil.formatTimeToString(System.currentTimeMillis() - time)); + ", time: "+ StringUtil.formatTimeToString(System.currentTimeMillis() - time));
} }
} }

4
src/zutil/net/http/multipart/MultipartParser.java Normal file → Executable file
View file

@ -25,7 +25,7 @@
package zutil.net.http.multipart; package zutil.net.http.multipart;
import zutil.ProgressListener; import zutil.ProgressListener;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeader;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -58,7 +58,7 @@ public class MultipartParser {
public MultipartParser(BufferedReader in, HttpHeaderParser header){ public MultipartParser(BufferedReader in, HttpHeader header){
this.in = in; this.in = in;
String cotype = header.getHeader("Content-type"); String cotype = header.getHeader("Content-type");

14
src/zutil/net/http/pages/HttpFilePage.java Normal file → Executable file
View file

@ -27,7 +27,7 @@ package zutil.net.http.pages;
import zutil.io.IOUtil; import zutil.io.IOUtil;
import zutil.io.file.FileUtil; import zutil.io.file.FileUtil;
import zutil.log.LogUtil; import zutil.log.LogUtil;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage; import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
@ -60,7 +60,7 @@ public class HttpFilePage implements HttpPage{
@Override @Override
public void respond(HttpPrintStream out, public void respond(HttpPrintStream out,
HttpHeaderParser client_info, HttpHeader headers,
Map<String, Object> session, Map<String, Object> session,
Map<String, String> cookie, Map<String, String> cookie,
Map<String, String> request) throws IOException{ Map<String, String> request) throws IOException{
@ -72,7 +72,7 @@ public class HttpFilePage implements HttpPage{
} }
else { // Resource root is a folder else { // Resource root is a folder
File file = new File(resource_root, File file = new File(resource_root,
client_info.getRequestURL()); headers.getRequestURL());
if(file.getCanonicalPath().startsWith(resource_root.getCanonicalPath())){ if(file.getCanonicalPath().startsWith(resource_root.getCanonicalPath())){
if(file.isDirectory() && showFolders){ if(file.isDirectory() && showFolders){
File indexFile = new File(file, "index.html"); File indexFile = new File(file, "index.html");
@ -82,10 +82,10 @@ public class HttpFilePage implements HttpPage{
} }
// Show folder contents // Show folder contents
else if(showFolders){ else if(showFolders){
out.println("<HTML><BODY><H1>Directory: " + client_info.getRequestURL() + "</H1>"); out.println("<HTML><BODY><H1>Directory: " + headers.getRequestURL() + "</H1>");
out.println("<HR><UL>"); out.println("<HR><UL>");
for (String f : file.list()) { for (String f : file.list()) {
String url = client_info.getRequestURL(); String url = headers.getRequestURL();
out.println("<LI><A href='" + out.println("<LI><A href='" +
url + (url.charAt(url.length()-1)=='/'?"":"/")+ f url + (url.charAt(url.length()-1)=='/'?"":"/")+ f
+"'>" + f + "</A></LI>"); +"'>" + f + "</A></LI>");
@ -109,12 +109,12 @@ public class HttpFilePage implements HttpPage{
if(!out.isHeaderSent()) if(!out.isHeaderSent())
out.setStatusCode(404); out.setStatusCode(404);
log.log(Level.WARNING, e.getMessage()); log.log(Level.WARNING, e.getMessage());
out.println("404 Page Not Found: " + client_info.getRequestURL()); out.println("404 Page Not Found: " + headers.getRequestURL());
}catch (SecurityException e){ }catch (SecurityException e){
if(!out.isHeaderSent()) if(!out.isHeaderSent())
out.setStatusCode(404); out.setStatusCode(404);
log.log(Level.WARNING, e.getMessage()); log.log(Level.WARNING, e.getMessage());
out.println("404 Page Not Found: " + client_info.getRequestURL() ); out.println("404 Page Not Found: " + headers.getRequestURL() );
}catch (IOException e){ }catch (IOException e){
if(!out.isHeaderSent()) if(!out.isHeaderSent())
out.setStatusCode(500); out.setStatusCode(500);

View file

@ -26,6 +26,7 @@ package zutil.net.ssdp;
import zutil.io.StringOutputStream; import zutil.io.StringOutputStream;
import zutil.log.LogUtil; import zutil.log.LogUtil;
import zutil.net.http.HttpHeader;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeaderParser;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
import zutil.net.threaded.ThreadedUDPNetwork; import zutil.net.threaded.ThreadedUDPNetwork;
@ -189,40 +190,45 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork
* Location: http://localhost:80 * Location: http://localhost:80
*/ */
public void receivedPacket(DatagramPacket packet, ThreadedUDPNetwork network) { public void receivedPacket(DatagramPacket packet, ThreadedUDPNetwork network) {
try {
String msg = new String(packet.getData(), packet.getOffset(), packet.getLength()); String msg = new String(packet.getData(), packet.getOffset(), packet.getLength());
HttpHeaderParser header = new HttpHeaderParser( msg ); HttpHeaderParser headerParser = new HttpHeaderParser(msg);
logger.log(Level.FINEST, "Received(from: "+packet.getAddress()+"): "+ header); HttpHeader header = headerParser.read();
logger.log(Level.FINEST, "Received(from: " + packet.getAddress() + "): " + header);
String usn = header.getHeader("USN"); String usn = header.getHeader("USN");
String st = header.getHeader("ST"); String st = header.getHeader("ST");
boolean newService = false; boolean newService = false;
StandardSSDPInfo service; StandardSSDPInfo service;
// Get existing service // Get existing service
if( services_usn.containsKey( usn )){ if (services_usn.containsKey(usn)) {
service = services_usn.get( usn ); service = services_usn.get(usn);
} }
// Add new service // Add new service
else{ else {
newService = true; newService = true;
service = new StandardSSDPInfo(); service = new StandardSSDPInfo();
services_usn.put( usn, service); services_usn.put(usn, service);
if( !services_st.containsKey(st) ) if (!services_st.containsKey(st))
services_st.put( st, new LinkedList<StandardSSDPInfo>() ); services_st.put(st, new LinkedList<StandardSSDPInfo>());
services_st.get( header.getHeader("ST") ).add( service ); services_st.get(header.getHeader("ST")).add(service);
} }
service.setLocation( header.getHeader("LOCATION") ); service.setLocation(header.getHeader("LOCATION"));
service.setST( st ); service.setST(st);
service.setUSN( usn ); service.setUSN(usn);
service.setInetAddress(packet.getAddress()); service.setInetAddress(packet.getAddress());
if(header.getHeader("Cache-Control") != null) { if (header.getHeader("Cache-Control") != null) {
service.setExpirationTime( service.setExpirationTime(
System.currentTimeMillis() + 1000 * getCacheTime(header.getHeader("Cache-Control"))); System.currentTimeMillis() + 1000 * getCacheTime(header.getHeader("Cache-Control")));
} }
service.readHeaders(header); service.readHeaders(header);
if(listener != null && newService) if (listener != null && newService)
listener.newService(service); listener.newService(service);
} catch (IOException e){
logger.log(Level.SEVERE, null, e);
}
} }
private long getCacheTime(String cache_control){ private long getCacheTime(String cache_control){

View file

@ -24,7 +24,7 @@
package zutil.net.ssdp; package zutil.net.ssdp;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
/** /**
@ -32,7 +32,7 @@ import zutil.net.http.HttpPrintStream;
*/ */
public interface SSDPCustomInfo extends SSDPServiceInfo{ public interface SSDPCustomInfo extends SSDPServiceInfo{
public void readHeaders(HttpHeaderParser http); public void readHeaders(HttpHeader http);
public void writeHeaders(HttpPrintStream http); public void writeHeaders(HttpPrintStream http);
} }

View file

@ -27,6 +27,7 @@ package zutil.net.ssdp;
import zutil.StringUtil; import zutil.StringUtil;
import zutil.io.StringOutputStream; import zutil.io.StringOutputStream;
import zutil.log.LogUtil; import zutil.log.LogUtil;
import zutil.net.http.HttpHeader;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeaderParser;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
import zutil.net.threaded.ThreadedUDPNetwork; import zutil.net.threaded.ThreadedUDPNetwork;
@ -168,7 +169,8 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork
public void receivedPacket(DatagramPacket packet, ThreadedUDPNetwork network) { public void receivedPacket(DatagramPacket packet, ThreadedUDPNetwork network) {
try { try {
String msg = new String( packet.getData(), packet.getOffset(), packet.getLength() ); String msg = new String( packet.getData(), packet.getOffset(), packet.getLength() );
HttpHeaderParser header = new HttpHeaderParser( msg ); HttpHeaderParser headerParser = new HttpHeaderParser( msg );
HttpHeader header = headerParser.read();
// ******* Respond // ******* Respond
// Check that the message is an ssdp discovery message // Check that the message is an ssdp discovery message

View file

@ -24,8 +24,6 @@
package zutil.net.ssdp; package zutil.net.ssdp;
import java.net.InetAddress;
/** /**
* This class contains information about a service from * This class contains information about a service from
* or through the SSDP protocol * or through the SSDP protocol

View file

@ -24,13 +24,14 @@
package zutil.net.ssdp; package zutil.net.ssdp;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID; import java.util.UUID;
/** /**
@ -145,10 +146,12 @@ public class StandardSSDPInfo implements SSDPServiceInfo, SSDPCustomInfo{
} }
} }
@Override @Override
public void readHeaders(HttpHeaderParser http) { public void readHeaders(HttpHeader header) {
HashMap<String,String> httpHeaders = http.getHeaders(); Iterator<String> it = header.getHeaderKeys();
for (String key : httpHeaders.keySet()) while (it.hasNext()) {
headers.put(key, httpHeaders.get(key)); String key = it.next();
headers.put(key, header.getHeader(key));
}
} }
public InetAddress getInetAddress(){ public InetAddress getInetAddress(){

8
src/zutil/net/upnp/UPnPMediaServer.java Normal file → Executable file
View file

@ -24,7 +24,7 @@
package zutil.net.upnp; package zutil.net.upnp;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
import java.io.IOException; import java.io.IOException;
@ -47,8 +47,10 @@ public class UPnPMediaServer extends UPnPRootDevice{
url = location; url = location;
} }
public void respond(HttpPrintStream out, HttpHeaderParser clientInfo, public void respond(HttpPrintStream out,
Map<String, Object> session, Map<String, String> cookie, HttpHeader headers,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request) throws IOException { Map<String, String> request) throws IOException {
out.enableBuffering(true); out.enableBuffering(true);

7
src/zutil/net/upnp/services/UPnPContentDirectory.java Normal file → Executable file
View file

@ -26,7 +26,7 @@ package zutil.net.upnp.services;
import org.dom4j.DocumentException; import org.dom4j.DocumentException;
import zutil.io.file.FileUtil; import zutil.io.file.FileUtil;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage; import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
import zutil.net.upnp.UPnPService; import zutil.net.upnp.UPnPService;
@ -154,8 +154,9 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface
@WSDisabled @WSDisabled
public void respond(HttpPrintStream out, HttpHeaderParser clientInfo, public void respond(HttpPrintStream out, HttpHeader headers,
Map<String, Object> session, Map<String, String> cookie, Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request) throws IOException { Map<String, String> request) throws IOException {
out.enableBuffering(true); out.enableBuffering(true);

View file

@ -25,7 +25,6 @@
package zutil.net.ws; package zutil.net.ws;
import zutil.log.LogUtil; import zutil.log.LogUtil;
import zutil.net.ws.soap.SOAPClientInvocationHandler;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationHandler;

View file

@ -26,14 +26,16 @@ package zutil.net.ws.rest;
import zutil.converters.Converter; import zutil.converters.Converter;
import zutil.io.StringOutputStream; import zutil.io.StringOutputStream;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage; import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
import zutil.net.ws.*; import zutil.net.ws.WSInterface;
import zutil.net.ws.WSMethodDef;
import zutil.net.ws.WSParameterDef;
import zutil.net.ws.WebServiceDef;
import zutil.parser.json.JSONObjectOutputStream; import zutil.parser.json.JSONObjectOutputStream;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map; import java.util.Map;
/** /**
@ -55,13 +57,13 @@ public class RestHttpPage implements HttpPage {
@Override @Override
public void respond(HttpPrintStream out, public void respond(HttpPrintStream out,
HttpHeaderParser client_info, HttpHeader headers,
Map<String, Object> session, Map<String, Object> session,
Map<String, String> cookie, Map<String, String> cookie,
Map<String, String> request) throws IOException { Map<String, String> request) throws IOException {
try { try {
out.println( out.println(
execute(client_info.getRequestURL(), request)); execute(headers.getRequestURL(), request));
} catch (Throwable throwable) { } catch (Throwable throwable) {
throw new IOException(throwable); throw new IOException(throwable);
} }

View file

@ -29,11 +29,7 @@ import zutil.net.ws.WSClientFactory;
import zutil.net.ws.WSInterface; import zutil.net.ws.WSInterface;
import zutil.net.ws.WebServiceDef; import zutil.net.ws.WebServiceDef;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.net.URL; import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
/** /**

View file

@ -33,7 +33,7 @@ import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import zutil.converters.Converter; import zutil.converters.Converter;
import zutil.log.LogUtil; import zutil.log.LogUtil;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage; import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
import zutil.net.ws.*; import zutil.net.ws.*;
@ -113,7 +113,7 @@ public class SOAPHttpPage implements HttpPage{
public void respond(HttpPrintStream out, public void respond(HttpPrintStream out,
HttpHeaderParser client_info, HttpHeader headers,
Map<String, Object> session, Map<String, Object> session,
Map<String, String> cookie, Map<String, String> cookie,
Map<String, String> request) { Map<String, String> request) {

2
src/zutil/osal/app/linux/ProcStat.java Normal file → Executable file
View file

@ -24,8 +24,8 @@
package zutil.osal.app.linux; package zutil.osal.app.linux;
import zutil.log.LogUtil;
import zutil.Timer; import zutil.Timer;
import zutil.log.LogUtil;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileReader; import java.io.FileReader;

2
src/zutil/osal/app/windows/TypePerf.java Normal file → Executable file
View file

@ -30,8 +30,6 @@ import zutil.parser.DataNode;
import java.io.IOException; import java.io.IOException;
import java.io.StringReader; import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
/** /**
* Created by ezivkoc on 2015-07-30. * Created by ezivkoc on 2015-07-30.

2
src/zutil/parser/CSVParser.java Normal file → Executable file
View file

@ -24,8 +24,6 @@
package zutil.parser; package zutil.parser;
import zutil.struct.MutableInt;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import java.io.StringReader; import java.io.StringReader;

3
src/zutil/parser/Parser.java Normal file → Executable file
View file

@ -24,10 +24,7 @@
package zutil.parser; package zutil.parser;
import zutil.struct.MutableInt;
import java.io.IOException; import java.io.IOException;
import java.io.StringReader;
/** /**
* Created by Ziver * Created by Ziver

View file

@ -24,15 +24,15 @@
package zutil.parser.binary; package zutil.parser.binary;
import zutil.ByteUtil;
import zutil.converters.Converter;
import zutil.parser.binary.BinaryStruct.BinaryField;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import zutil.ByteUtil;
import zutil.converters.Converter;
import zutil.parser.binary.BinaryStruct.*;
/** /**
* Created by Ziver on 2016-01-28. * Created by Ziver on 2016-01-28.
*/ */

View file

@ -32,7 +32,9 @@ import zutil.parser.DataNode;
import javax.activation.UnsupportedDataTypeException; import javax.activation.UnsupportedDataTypeException;
import java.io.*; import java.io.*;
import java.lang.reflect.*; import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;

View file

@ -29,7 +29,6 @@ import zutil.ClassUtil;
import zutil.parser.Base64Encoder; import zutil.parser.Base64Encoder;
import zutil.parser.DataNode; import zutil.parser.DataNode;
import zutil.parser.DataNode.DataType; import zutil.parser.DataNode.DataType;
import static zutil.parser.json.JSONObjectInputStream.*;
import javax.activation.UnsupportedDataTypeException; import javax.activation.UnsupportedDataTypeException;
import java.io.*; import java.io.*;
@ -40,6 +39,9 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static zutil.parser.json.JSONObjectInputStream.MD_CLASS;
import static zutil.parser.json.JSONObjectInputStream.MD_OBJECT_ID;
public class JSONObjectOutputStream extends OutputStream implements ObjectOutput, Closeable{ public class JSONObjectOutputStream extends OutputStream implements ObjectOutput, Closeable{
/** If the generated JSON should contain class def meta-data **/ /** If the generated JSON should contain class def meta-data **/
private boolean generateMetaData = true; private boolean generateMetaData = true;

1
src/zutil/parser/json/JSONWriter.java Normal file → Executable file
View file

@ -29,7 +29,6 @@ import zutil.parser.DataNode;
import zutil.parser.DataNode.DataType; import zutil.parser.DataNode.DataType;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.Writer; import java.io.Writer;
import java.util.Iterator; import java.util.Iterator;

4
src/zutil/parser/wsdl/WSDLHttpPage.java Normal file → Executable file
View file

@ -24,7 +24,7 @@
package zutil.parser.wsdl; package zutil.parser.wsdl;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage; import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
import zutil.net.ws.WebServiceDef; import zutil.net.ws.WebServiceDef;
@ -44,7 +44,7 @@ public class WSDLHttpPage implements HttpPage {
} }
public void respond(HttpPrintStream out, public void respond(HttpPrintStream out,
HttpHeaderParser client_info, HttpHeader headers,
Map<String, Object> session, Map<String, Object> session,
Map<String, String> cookie, Map<String, String> cookie,
Map<String, String> request) throws IOException{ Map<String, String> request) throws IOException{

View file

@ -24,10 +24,7 @@
package zutil.struct; package zutil.struct;
import java.util.AbstractSet;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
/** /**
* This is a timed HashSet. Each entry has a limited time to live. * This is a timed HashSet. Each entry has a limited time to live.

View file

@ -28,7 +28,8 @@ import org.junit.Test;
import zutil.parser.binary.BinaryStruct; import zutil.parser.binary.BinaryStruct;
import zutil.parser.binary.BinaryStructParser; import zutil.parser.binary.BinaryStructParser;
import static junit.framework.TestCase.*; import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
/** /**
* Created by Ziver on 2016-01-28. * Created by Ziver on 2016-01-28.

View file

@ -26,7 +26,7 @@ package zutil.test;
import org.junit.Test; import org.junit.Test;
import zutil.Encrypter; import zutil.Encrypter;
import zutil.Encrypter.*; import zutil.Encrypter.Algorithm;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;

View file

@ -24,7 +24,7 @@
package zutil.test; package zutil.test;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage; import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
import zutil.net.http.HttpServer; import zutil.net.http.HttpServer;
@ -43,7 +43,7 @@ public class HTTPGuessTheNumber implements HttpPage{
} }
public void respond(HttpPrintStream out, public void respond(HttpPrintStream out,
HttpHeaderParser client_info, HttpHeader client_info,
Map<String, Object> session, Map<String, Object> session,
Map<String, String> cookie, Map<String, String> cookie,
Map<String, String> request) throws IOException { Map<String, String> request) throws IOException {

View file

@ -24,7 +24,7 @@
package zutil.test; package zutil.test;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage; import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
import zutil.net.http.HttpServer; import zutil.net.http.HttpServer;
@ -42,7 +42,7 @@ public class HTTPUploaderTest implements HttpPage{
} }
public void respond(HttpPrintStream out, public void respond(HttpPrintStream out,
HttpHeaderParser client_info, HttpHeader client_info,
Map<String, Object> session, Map<String, Object> session,
Map<String, String> cookie, Map<String, String> cookie,
Map<String, String> request) throws IOException { Map<String, String> request) throws IOException {

View file

@ -24,19 +24,19 @@
package zutil.test; package zutil.test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Parameterized.Parameters;
import zutil.converters.NumberToWordsConverter; import zutil.converters.NumberToWordsConverter;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(Parameterized.class) @RunWith(Parameterized.class)
public class NumberToWordsConverterTest { public class NumberToWordsConverterTest {

View file

@ -27,7 +27,6 @@ package zutil.test;
import org.dom4j.Document; import org.dom4j.Document;
import org.dom4j.io.OutputFormat; import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter; import org.dom4j.io.XMLWriter;
import zutil.net.nio.message.type.SystemMessage;
import zutil.net.ws.WSInterface; import zutil.net.ws.WSInterface;
import zutil.net.ws.WSInterface.WSNamespace; import zutil.net.ws.WSInterface.WSNamespace;
import zutil.net.ws.WSReturnObject; import zutil.net.ws.WSReturnObject;

View file

@ -29,7 +29,6 @@ import zutil.net.ssdp.SSDPServer;
import zutil.net.ssdp.StandardSSDPInfo; import zutil.net.ssdp.StandardSSDPInfo;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level; import java.util.logging.Level;
/** /**

View file

@ -28,7 +28,6 @@ import org.junit.Test;
import zutil.StringUtil; import zutil.StringUtil;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;

View file

@ -27,7 +27,7 @@ package zutil.test;
import org.junit.Test; import org.junit.Test;
import zutil.struct.TimedHashSet; import zutil.struct.TimedHashSet;
import static org.junit.Assert.*; import static org.junit.Assert.assertFalse;
/** /**
* Created by Ziver on 2015-11-20. * Created by Ziver on 2015-11-20.