Java Code Examples for com.sun.net.httpserver.Headers.get()

The following are Jave code examples for showing how to use get() of the com.sun.net.httpserver.Headers class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: openjdk-jdk10   File: HttpOnly.java   Source Code and License Vote up 8 votes
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 2
Project: jflask   File: App.java   Source Code and License Vote up 7 votes
private String getCookie(HttpExchange r, String name) {
  Headers headers = r.getRequestHeaders();
  if (headers != null) {
    List<String> cookies = headers.get("Cookie");
    if (cookies != null) {
      for (String cookieString : cookies) {
        String[] tokens = cookieString.split("\\s*;\\s*");
        for (String token : tokens) {
          if (token.startsWith(name) && token.charAt(name.length()) == '=') {
            return token.substring(name.length() + 1);
          }
        }
      }
    }
  }
  return null;
}
 
Example 3
Project: fourinone   File: ParkInetServer.java   Source Code and License Vote up 6 votes
public void handle(HttpExchange exchange) throws IOException
{
	String requestMethod = exchange.getRequestMethod();
	if(requestMethod.equalsIgnoreCase("GET"))
	{
		Headers responseHeaders = exchange.getResponseHeaders();
		responseHeaders.set("Content-Type", "text/plain");
		exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
		
		OutputStream responseBody = exchange.getResponseBody();
		Headers requestHeaders = exchange.getRequestHeaders();
		Set<String> keySet = requestHeaders.keySet();
		Iterator<String> iter = keySet.iterator();
		while (iter.hasNext()){
			String key = iter.next();
			List values = requestHeaders.get(key);
			String s = key + " = " + values.toString() + "\n";
			responseBody.write(s.getBytes());
		}
		responseBody.close();
	}
}
 
Example 4
Project: Fourinone   File: ParkInetServer.java   Source Code and License Vote up 6 votes
public void handle(HttpExchange exchange) throws IOException
{
	String requestMethod = exchange.getRequestMethod();
	if(requestMethod.equalsIgnoreCase("GET"))
	{
		Headers responseHeaders = exchange.getResponseHeaders();
		responseHeaders.set("Content-Type", "text/plain");
		exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
		
		OutputStream responseBody = exchange.getResponseBody();
		Headers requestHeaders = exchange.getRequestHeaders();
		Set<String> keySet = requestHeaders.keySet();
		Iterator<String> iter = keySet.iterator();
		while (iter.hasNext()){
			String key = iter.next();
			List values = requestHeaders.get(key);
			String s = key + " = " + values.toString() + "\n";
			responseBody.write(s.getBytes());
		}
		responseBody.close();
	}
}
 
Example 5
Project: health-and-care-developer-network   File: RequestHeadersHelper.java   Source Code and License Vote up 6 votes
@Nullable @NonNls
public static String validateZeroOrOneInstanceOfRequestHeader(@NotNull final Headers requestHeaders, @NotNull @RequestHeader final String requestHeader) throws BadRequestException
{
	@Nullable final List<String> strings = requestHeaders.get(requestHeader);
	if (strings == null)
	{
		return null;
	}
	final int size = strings.size();
	if (size == 1)
	{
		return strings.get(0);
	}
	if (size == 0)
	{
		return null;
	}
	throw new BadRequestException(format(ENGLISH, "More than one value for Request header %1$s", requestHeader));
}
 
Example 6
Project: jdk8u-jdk   File: HttpOnly.java   Source Code and License Vote up 5 votes
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 7
Project: openjdk9   File: HttpOnly.java   Source Code and License Vote up 5 votes
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 8
Project: DigitalMediaServer   File: RemoteUtil.java   Source Code and License Vote up 5 votes
public static Range.Byte parseRange(Headers hdr, long len) {
	if (hdr == null) {
		return nullRange(len);
	}
	List<String> r = hdr.get("Range");
	if (r == null) { // no range
		return nullRange(len);
	}
	// assume only one
	String range = r.get(0);
	String[] tmp = range.split("=")[1].split("-");
	long start = Long.parseLong(tmp[0]);
	long end = tmp.length == 1 ? len : Long.parseLong(tmp[1]);
	return new Range.Byte(start, end);
}
 
Example 9
Project: jdk8u_jdk   File: HttpOnly.java   Source Code and License Vote up 5 votes
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 10
Project: lookaside_java-1.8.0-openjdk   File: HttpOnly.java   Source Code and License Vote up 5 votes
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 11
Project: mateplus   File: AbstractHandler.java   Source Code and License Vote up 5 votes
static String getHeader(HttpExchange exchange, String header) {
	Headers h = exchange.getRequestHeaders();
	List<String> values = h.get(header);
	if (values == null || values.size() == 0)
		return null;
	return values.get(0);
}
 
Example 12
Project: infobip-open-jdk-8   File: HttpOnly.java   Source Code and License Vote up 5 votes
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 13
Project: jdk8u-dev-jdk   File: HttpOnly.java   Source Code and License Vote up 5 votes
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 14
Project: Bitcoin-exchange   File: RequestHandler.java   Source Code and License Vote up 5 votes
@Override
public void handle(HttpExchange exchange) throws IOException {
	switch (exchange.getRequestMethod()) {
	
	// POST requests.
	case "POST":
		DataInputStream in = new DataInputStream(exchange.getRequestBody());
		String[] params = in.readUTF().split(",");
		orders.add(new Order(params[0], params[1], new BigDecimal(params[2]), new BigDecimal(params[3]), params[4]));
   		exchange.sendResponseHeaders(200, 0);
   		
	// GET requests.
	case "GET":
		orders.get(orders.indexOf(new Order("BTC", "", BigDecimal.ZERO, BigDecimal.ZERO, "")));
		textArea.appendText(exchange.getRequestURI().getQuery() + "\n");
		
		Headers responseHeaders = exchange.getResponseHeaders();
   	    responseHeaders.set("Content-Type", "text/plain");
   	    exchange.sendResponseHeaders(200, 0);
		
		OutputStream responseBody = exchange.getResponseBody();
		Headers requestHeaders = exchange.getRequestHeaders();
		
		Set<String> keySet = requestHeaders.keySet();
		
		Iterator<String> iter = keySet.iterator();
		while (iter.hasNext()) {
			String key = iter.next();
			List<String> values = requestHeaders.get(key);
			String s = key + " = " + values.toString() + "\n";
			responseBody.write(s.getBytes());
		}
		responseBody.close();
		
	// Unknown requests.
	default:
		exchange.sendResponseHeaders(400, 0);
	}
}
 
Example 15
Project: swift-explorer   File: AuthHttpServer.java   Source Code and License Vote up 5 votes
@Override
public void handle(HttpExchange exchange) throws IOException 
{
	String requestMethod = exchange.getRequestMethod();
	if (requestMethod.equalsIgnoreCase("GET")) 
	{
		Headers responseHeaders = exchange.getResponseHeaders();
		responseHeaders.set("Content-Type", "text/plain");
		exchange.sendResponseHeaders(200, 0);
		
		OutputStream responseBody = exchange.getResponseBody();
		Headers requestHeaders = exchange.getRequestHeaders();
		Set<String> keySet = requestHeaders.keySet();
		Iterator<String> iter = keySet.iterator();
		while (iter.hasNext()) {
			String key = iter.next();
			List<String> values = requestHeaders.get(key);
			String s = key + " = " + values.toString() + "\n";
			responseBody.write(s.getBytes());		
		}
		responseBody.close();
			
		if (sharedQueue != null)
		{
			String query = exchange.getRequestURI().getQuery() ;
			try 
			{
				sharedQueue.put(queryToParameterMap(query));
			} 
			catch (InterruptedException e) 
			{
				logger.error("Error occurred in the server handler", e);
			}
		}
	}
}
 
Example 16
Project: OLD-OpenJDK8   File: HttpOnly.java   Source Code and License Vote up 5 votes
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 17
Project: openjdk-jdk7u-jdk   File: HttpOnly.java   Source Code and License Vote up 5 votes
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 18
Project: openjdk-icedtea7   File: HttpOnly.java   Source Code and License Vote up 5 votes
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 19
Project: LIMES   File: SimpleServer.java   Source Code and License Vote up 4 votes
@Override
public void handle(HttpExchange t) throws IOException {
    if (t.getRequestMethod().equals("POST")) {
        Headers headers = t.getRequestHeaders();
        String boundary = "boundary=";
        for (String s : headers.get("Content-type")) {
            int i = s.indexOf(boundary);
            if (i > -1) {
                boundary = s.substring(i + boundary.length());
                break;
            }
        }
        String id = writeConfigFile(t.getRequestBody(), boundary);
        jobs.put(Long.parseLong(id), 0);
        String response = id + "\n";
        t.sendResponseHeaders(200, response.length());
        logger.info("New Job: " + id);
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
        AConfigurationReader reader = new XMLConfigurationReader(STORAGE_DIR_PATH + CONFIG_FILE_PREFIX + id + ".xml");
        Configuration config = reader.read();
        jobs.put(Long.parseLong(id), 1);
        ResultMappings mappings = Controller.getMapping(config);
        String outputFormat = config.getOutputFormat();
        ISerializer output = SerializerFactory.createSerializer(outputFormat);
        output.setPrefixes(config.getPrefixes());
        File tempDir = new File(STORAGE_DIR_PATH + id + "/");
        File lockDir = new File(tempDir + LOCK_DIR_PATH);
        if (!lockDir.exists()) {
            lockDir.mkdirs();
        }
        File _verificationFile = new File(lockDir + "/" + config.getVerificationFile());
        File _acceptanceFile = new File(lockDir + "/" + config.getAcceptanceFile());
        File verificationFile = new File(tempDir + "/" + config.getVerificationFile());
        File acceptanceFile = new File(tempDir + "/" + config.getAcceptanceFile());
        output.writeToFile(mappings.getVerificationMapping(), config.getVerificationRelation(),
                _verificationFile.getAbsolutePath());
        output.writeToFile(mappings.getAcceptanceMapping(), config.getAcceptanceRelation(),
                _acceptanceFile.getAbsolutePath());
        _verificationFile.renameTo(verificationFile);
        _acceptanceFile.renameTo(acceptanceFile);
        lockDir.delete();
        jobs.put(Long.parseLong(id), 2);
    } else {
        // we only accept POST requests here, anything else gets code "405 - Method Not Allowed"
        t.sendResponseHeaders(405 ,-1);
        logger.info("Bad request: HTTP VERB must be POST for " + t.getRequestURI());
    }
}
 
Example 20
Project: fourinone   File: ParkInetServer.java   Source Code and License Vote up 4 votes
public void handle(HttpExchange exchange) throws IOException
{
	try{
		boolean authflag = false;
		Headers hds = exchange.getRequestHeaders();
		List<String> auth = hds.get("Authorization");
		String requesturi = exchange.getRequestURI().getPath();
		String requestparam = exchange.getRequestURI().getQuery();
		//System.out.println(requesturi+",param:"+requestparam);//new String(.getBytes("UTF-8"))
		if(auth!=null){
			String authstr = new String(ObjectBytes.decode(auth.get(0).split("\u0020")[1].toCharArray()));
			//System.out.println("Authorization:"+authstr);
			//System.out.println(ObjectBytes.encodeurl("root"));
			//System.out.println(ObjectBytes.decodeurl("cm9vdA%3D%3D"));
			if(authstr!=null){
				String[] autharr = authstr.split("\u003A");
				//System.out.println("autharr.length:"+autharr.length);
				if(autharr.length==2){
					String authpwd = ConfigContext.getUsersConfig().getString(autharr[0]);
					if(authpwd!=null&&authpwd.equals(autharr[1]))
						authflag = true;
				}
			}
			//System.out.println("authflag:"+authflag);
		}
		
		Headers responseHeaders = exchange.getResponseHeaders();
		responseHeaders.set("Content-Type", "text/html;charset=UTF-8");
		String response = "";
		if(authflag){
			if(requesturi.equals(ConfigContext.getProp("REQFTTP")))
				response = ConfigContext.getRequest(ConfigContext.getProp("RSPFTTPJSP"));
			else if(requesturi.equals(ConfigContext.getProp("REQGETFTTP"))&&requestparam!=null){
				String[] rqsarrstr = requestparam.split("&");
				String rqtid = rqsarrstr[0].replaceAll("tid=","");
				String tid = ObjectBytes.getViewUtf8UrlString(rqtid);//getViewUrlString ObjectBytes.decodeReplace(tid);
				//System.out.println("requesttreeId:"+rqtid);
				//System.out.println("treeId:"+tid);
				int tn = Integer.parseInt(rqsarrstr[1].replaceAll("tn=",""));
				//System.out.println("tn:"+tn);
				String eid = rqsarrstr[2].replaceAll("eid=","");
				response =  getResponse(tid, tn, eid);
			}
			exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
		}else{
			response = ConfigContext.getRequest(ConfigContext.getProp("RSPE401"));
			responseHeaders.set("WWW-Authenticate", "Basic realm='Fttp Admin'");
			exchange.sendResponseHeaders(HttpURLConnection.HTTP_UNAUTHORIZED, response.length());
		}
		OutputStream os = exchange.getResponseBody();
	    os.write(response.getBytes("UTF-8"));
	    os.close();
	}catch(Exception e){
	   LogUtil.info("[InetServer]", "[HandlerAuth]", e.getMessage());
	   throw new IOException(e);
	}  
}
 
Example 21
Project: CS414_ColoState   File: CustomerPointUpdate_Server.java   Source Code and License Vote up 4 votes
@Override
public void handle(HttpExchange arg0) throws IOException {
    // Retrieve request headers
    Headers reqHeaders = arg0.getRequestHeaders();
    Iterator<String> iterator = reqHeaders.keySet().iterator();
    System.out.println();
    while(iterator.hasNext()) {
        String key = iterator.next();
        List value = reqHeaders.get(key);

        System.out.printf("%s:", key);
        for(int i = 0; i < value.size(); i++) {
            System.out.printf(" %s", value.get(i));
        }
        System.out.print("\n");
    }

    InputStreamReader isr = new InputStreamReader(arg0.getRequestBody(), "utf-8");
    BufferedReader streamReader = new BufferedReader(isr);
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;
    while((inputStr = streamReader.readLine()) != null) {
        responseStrBuilder.append(inputStr);
    }

    System.out.println("Request received by Customer point updating server.");
    String membershipID = "";
    int point = 0;
    try {
        JSONObject object = new JSONObject(responseStrBuilder.toString());
        point = object.getInt("updatedPoint");
        membershipID = object.get("membershipID").toString();

        c = this.store.getMember(membershipID);
        c.setRewardsPoint(point);
        //c = new Customer(firstName, lastName, customerPhoneNumber, this.store);
    } catch(JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if(c != null) {
        System.out.println("Request received. Customer found with ID:" + c.getMemberShipNumber() + " and point" + store.getMember(membershipID).getRewardsPoint());
        Gson gson = new GsonBuilder().create();
        String customer = gson.toJson(c);
        arg0.sendResponseHeaders(200, customer.length());
        OutputStream os = arg0.getResponseBody();
        os.write(customer.getBytes());
        os.close();

    } else {
        System.out.println("Request received. But no customer point is updated");

    }
}
 
Example 22
Project: CS414_ColoState   File: CustomerController_Server.java   Source Code and License Vote up 4 votes
@Override
public void handle(HttpExchange arg0) throws IOException {
    // Retrieve request headers
    Headers reqHeaders = arg0.getRequestHeaders();
    Iterator<String> iterator = reqHeaders.keySet().iterator();
    System.out.println();
    while(iterator.hasNext()) {
        String key = iterator.next();
        List value = reqHeaders.get(key);

        System.out.printf("%s:", key);
        for(int i = 0; i < value.size(); i++) {
            System.out.printf(" %s", value.get(i));
        }
        System.out.print("\n");
    }

    InputStreamReader isr = new InputStreamReader(arg0.getRequestBody(), "utf-8");
    BufferedReader streamReader = new BufferedReader(isr);
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;
    while((inputStr = streamReader.readLine()) != null) {
        responseStrBuilder.append(inputStr);
    }

    Customer c = null;

    System.out.println("Request received by Customer creating server.");

    try {
        JSONObject object = new JSONObject(responseStrBuilder.toString());
        String firstName = object.get("firstName").toString();
        String lastName = object.get("lastName").toString();
        String customerPhoneNumber = object.get("customerPhoneNumber").toString();

        c = this.store.addNewMember(firstName, lastName, customerPhoneNumber);
        //c = new Customer(firstName, lastName, customerPhoneNumber, this.store);
    } catch(JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if(c != null) {
        System.out.println("Request received. Customer is created with ID:" + c.getMemberShipNumber());
        Gson gson = new GsonBuilder().create();
        String customer = gson.toJson(c);
        arg0.sendResponseHeaders(200, customer.length());
        OutputStream os = arg0.getResponseBody();
        os.write(customer.getBytes());
        os.close();

    } else {
        System.out.println("Request received. But no customer is created");

    }

}
 
Example 23
Project: CS414_ColoState   File: CustomerPointUpdate_Server.java   Source Code and License Vote up 4 votes
@Override
public void handle(HttpExchange arg0) throws IOException {
    // Retrieve request headers
    Headers reqHeaders = arg0.getRequestHeaders();
    Iterator<String> iterator = reqHeaders.keySet().iterator();
    System.out.println();
    while(iterator.hasNext()) {
        String key = iterator.next();
        List value = reqHeaders.get(key);

        System.out.printf("%s:", key);
        for(int i = 0; i < value.size(); i++) {
            System.out.printf(" %s", value.get(i));
        }
        System.out.print("\n");
    }

    InputStreamReader isr = new InputStreamReader(arg0.getRequestBody(), "utf-8");
    BufferedReader streamReader = new BufferedReader(isr);
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;
    while((inputStr = streamReader.readLine()) != null) {
        responseStrBuilder.append(inputStr);
    }

    System.out.println("Request received by Customer point updating server.");
    String membershipID = "";
    int point = 0;
    try {
        JSONObject object = new JSONObject(responseStrBuilder.toString());
        point = object.getInt("updatedPoint");
        membershipID = object.get("membershipID").toString();

        c = this.store.getMember(membershipID);
        c.setRewardsPoint(point);
        //c = new Customer(firstName, lastName, customerPhoneNumber, this.store);
    } catch(JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if(c != null) {
        System.out.println("Request received. Customer found with ID:" + c.getMemberShipNumber() + " and point" + store.getMember(membershipID).getRewardsPoint());
        Gson gson = new GsonBuilder().create();
        String customer = gson.toJson(c);
        arg0.sendResponseHeaders(200, customer.length());
        OutputStream os = arg0.getResponseBody();
        os.write(customer.getBytes());
        os.close();

    } else {
        System.out.println("Request received. But no customer point is updated");

    }
}
 
Example 24
Project: CS414_ColoState   File: CustomerController_Server.java   Source Code and License Vote up 4 votes
@Override
public void handle(HttpExchange arg0) throws IOException {
    // Retrieve request headers
    Headers reqHeaders = arg0.getRequestHeaders();
    Iterator<String> iterator = reqHeaders.keySet().iterator();
    System.out.println();
    while(iterator.hasNext()) {
        String key = iterator.next();
        List value = reqHeaders.get(key);

        System.out.printf("%s:", key);
        for(int i = 0; i < value.size(); i++) {
            System.out.printf(" %s", value.get(i));
        }
        System.out.print("\n");
    }

    InputStreamReader isr = new InputStreamReader(arg0.getRequestBody(), "utf-8");
    BufferedReader streamReader = new BufferedReader(isr);
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;
    while((inputStr = streamReader.readLine()) != null) {
        responseStrBuilder.append(inputStr);
    }

    Customer c = null;

    System.out.println("Request received by Customer creating server.");

    try {
        JSONObject object = new JSONObject(responseStrBuilder.toString());
        String firstName = object.get("firstName").toString();
        String lastName = object.get("lastName").toString();
        String customerPhoneNumber = object.get("customerPhoneNumber").toString();

        c = this.store.addNewMember(firstName, lastName, customerPhoneNumber);
        //c = new Customer(firstName, lastName, customerPhoneNumber, this.store);
    } catch(JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if(c != null) {
        System.out.println("Request received. Customer is created with ID:" + c.getMemberShipNumber());
        Gson gson = new GsonBuilder().create();
        String customer = gson.toJson(c);
        arg0.sendResponseHeaders(200, customer.length());
        OutputStream os = arg0.getResponseBody();
        os.write(customer.getBytes());
        os.close();

    } else {
        System.out.println("Request received. But no customer is created");

    }

}
 
Example 25
Project: Fourinone   File: ParkInetServer.java   Source Code and License Vote up 4 votes
public void handle(HttpExchange exchange) throws IOException
{
	try{
		boolean authflag = false;
		Headers hds = exchange.getRequestHeaders();
		List<String> auth = hds.get("Authorization");
		String requesturi = exchange.getRequestURI().getPath();
		String requestparam = exchange.getRequestURI().getQuery();
		//System.out.println(requesturi+",param:"+requestparam);//new String(.getBytes("UTF-8"))
		if(auth!=null){
			String authstr = new String(ObjectBytes.decode(auth.get(0).split("\u0020")[1].toCharArray()));
			//System.out.println("Authorization:"+authstr);
			//System.out.println(ObjectBytes.encodeurl("root"));
			//System.out.println(ObjectBytes.decodeurl("cm9vdA%3D%3D"));
			if(authstr!=null){
				String[] autharr = authstr.split("\u003A");
				//System.out.println("autharr.length:"+autharr.length);
				if(autharr.length==2){
					String authpwd = ConfigContext.getUsersConfig().getString(autharr[0]);
					if(authpwd!=null&&authpwd.equals(autharr[1]))
						authflag = true;
				}
			}
			//System.out.println("authflag:"+authflag);
		}
		
		Headers responseHeaders = exchange.getResponseHeaders();
		responseHeaders.set("Content-Type", "text/html;charset=UTF-8");
		String response = "";
		if(authflag){
			if(requesturi.equals(ConfigContext.getProp("REQFTTP")))
				response = ConfigContext.getRequest(ConfigContext.getProp("RSPFTTPJSP"));
			else if(requesturi.equals(ConfigContext.getProp("REQGETFTTP"))&&requestparam!=null){
				String[] rqsarrstr = requestparam.split("&");
				String rqtid = rqsarrstr[0].replaceAll("tid=","");
				String tid = ObjectBytes.getViewUtf8UrlString(rqtid);//getViewUrlString ObjectBytes.decodeReplace(tid);
				//System.out.println("requesttreeId:"+rqtid);
				//System.out.println("treeId:"+tid);
				int tn = Integer.parseInt(rqsarrstr[1].replaceAll("tn=",""));
				//System.out.println("tn:"+tn);
				String eid = rqsarrstr[2].replaceAll("eid=","");
				response =  getResponse(tid, tn, eid);
			}
			exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
		}else{
			response = ConfigContext.getRequest(ConfigContext.getProp("RSPE401"));
			responseHeaders.set("WWW-Authenticate", "Basic realm='Fttp Admin'");
			exchange.sendResponseHeaders(HttpURLConnection.HTTP_UNAUTHORIZED, response.length());
		}
		OutputStream os = exchange.getResponseBody();
	    os.write(response.getBytes("UTF-8"));
	    os.close();
	}catch(Exception e){
	   LogUtil.info("[InetServer]", "[HandlerAuth]", e.getMessage());
	   throw new IOException(e);
	}  
}