code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.Constants; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class Proxy { static Logger logger = Logger.getLogger(Proxy.class); static int defaultCachingTime = Constants.COAP_DEFAULT_MAX_AGE_S; public static void main(String[] args) { CommandLineParser cmdParser = new GnuParser(); Options options = new Options(); /* Add command line options */ options.addOption("c", "default-cache-time", true, "Default caching time in seconds"); CommandLine cmd = null; try { cmd = cmdParser.parse(options, args); } catch (ParseException e) { System.out.println( "Unexpected exception:" + e.getMessage() ); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "jCoAP-Proxy", options ); System.exit(-1); } /* evaluate command line */ if(cmd.hasOption("c")) { try { defaultCachingTime = Integer.parseInt(cmd.getOptionValue("c")); if (defaultCachingTime == 0){ ProxyMapper.getInstance().setCacheEnabled(false); } System.out.println("Set caching time to " + cmd.getOptionValue("c") + " seconds (0 disables the cache)"); } catch (NumberFormatException e) { System.out.println( "Unexpected exception:" + e.getMessage() ); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "jCoAP-Proxy", options ); System.exit(-1); } } logger.addAppender(new ConsoleAppender(new SimpleLayout())); // ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF: logger.setLevel(Level.ALL); HttpServerNIO httpserver = new HttpServerNIO(); HttpClientNIO httpclient = new HttpClientNIO(); CoapClientProxy coapclient = new CoapClientProxy(); CoapServerProxy coapserver = new CoapServerProxy(); ProxyMapper.getInstance().setHttpServer(httpserver); ProxyMapper.getInstance().setHttpClient(httpclient); ProxyMapper.getInstance().setCoapClient(coapclient); ProxyMapper.getInstance().setCoapServer(coapserver); httpserver.start(); httpclient.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("===END==="); try { Thread.sleep(500); } catch (InterruptedException e) { } } }); ProxyRestInterface restInterface = new ProxyRestInterface(); restInterface.start(); } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.io.IOException; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.entity.ContentListener; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.nio.util.SimpleInputBuffer; /** * This class is used to consume an entity and get the entity-data as byte-array. * The only other class which implements ContentListener is SkipContentListener. * SkipContentListener is ignoring all content. * Look at Apache HTTP Components Core NIO Framework -> Java-Documentation of SkipContentListener. */ /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ class ByteContentListener implements ContentListener { final SimpleInputBuffer input = new SimpleInputBuffer(2048, new HeapByteBufferAllocator()); public void consumeContent(ContentDecoder decoder, IOControl ioctrl) throws IOException { input.consumeContent(decoder); } public void finish() { input.reset(); } byte[] getContent() throws IOException { byte[] b = new byte[input.length()]; input.read(b); return b; } @Override public void contentAvailable(ContentDecoder decoder, IOControl arg1) throws IOException { input.consumeContent(decoder); } @Override public void finished() { input.reset(); } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import net.sf.ehcache.Element; import org.apache.http.Header; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.ParseException; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.AbstractCoapMessage.CoapHeaderOptionType; import org.ws4d.coap.messages.BasicCoapRequest; import org.ws4d.coap.messages.BasicCoapResponse; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapRequestCode; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class ProxyMapper { static Logger logger = Logger.getLogger(Proxy.class); static final int DEFAULT_MAX_AGE_MS = 60000; //Max Age Default in ms //introduce other needed classes for communication private CoapClientProxy coapClient; private CoapServerProxy coapServer; private HttpServerNIO httpServer; private HttpClientNIO httpClient; private static ProxyCache cache; private static ProxyMapper instance; /*for statistics*/ private int httpRequestCount = 0; private int coapRequestCount = 0; private int servedFromCacheCount = 0; public synchronized static ProxyMapper getInstance() { if (instance == null) { instance = new ProxyMapper(); } return instance; } private ProxyMapper() { cache = new ProxyCache(); } /* * Server Client * +------+ +------+ RequestTime * InRequ --->| |----+-->Requ.Trans.-------->| |--->OutReq * | | | | | * | | | | | * | | ERROR | | * | | | | | * | | +<---ERROR -----+ | | * | | | | | | ResponseTime * OutResp<---| +<---+<--Resp.Trans.-+-------+ |<---InResp * +------+ +------+ * * HTTP -----------------------------> CoAP * * CoAP -----------------------------> HTTP * * CoAP -----------------------------> CoAP */ public void handleHttpServerRequest(ProxyMessageContext context) { httpRequestCount++; // do not translate methods: OPTIONS,TRACE,CONNECT -> error // "Not Implemented" if (isHttpRequestMethodSupported(context.getInHttpRequest())) { // perform request-transformation /* try to get from cache */ ProxyResource resource = null; if (context.getInHttpRequest().getRequestLine().getMethod().toLowerCase().equals("get")){ resource = cache.get(context); } if (resource != null) { /* answer from cache */ resourceToHttp(context, resource); context.setCached(true); // avoid "recaching" httpServer.sendResponse(context); logger.info("served HTTP request from cache"); servedFromCacheCount++; } else { /* not cached -> forward request */ try { coapClient.createChannel(context); //channel must be created first transRequestHttpToCoap(context); context.setRequestTime(System.currentTimeMillis()); coapClient.sendRequest(context); } catch (Exception e) { logger.warn("HTTP to CoAP Request failed: " + e.getMessage()); /* close if a channel was connected */ if (context.getOutCoapClientChannel() != null){ context.getOutCoapClientChannel().close(); } sendDirectHttpError(context, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); } } } else { /* method not supported */ sendDirectHttpError(context, HttpStatus.SC_NOT_IMPLEMENTED, "Not Implemented"); } } public void handleCoapServerRequest(ProxyMessageContext context) { coapRequestCount++; ProxyResource resource = null; if (context.getInCoapRequest().getRequestCode() == CoapRequestCode.GET){ resource = cache.get(context); } if (context.isTranslate()) { /* coap to http */ if (resource != null) { /* answer from cache */ resourceToHttp(context, resource); context.setCached(true); // avoid "recaching" httpServer.sendResponse(context); logger.info("served CoAP request from cache"); servedFromCacheCount++; } else { /* translate CoAP Request -> HTTP Request */ try { transRequestCoapToHttp(context); context.setRequestTime(System.currentTimeMillis()); httpClient.sendRequest(context); } catch (Exception e) { logger.warn("CoAP to HTTP Request translation failed: " + e.getMessage()); sendDirectCoapError(context, CoapResponseCode.Not_Found_404); } } } else { /* coap to coap */ if (resource != null) { /* answer from cache */ resourceToCoap(context, resource); context.setCached(true); // avoid "recaching" coapServer.sendResponse(context); logger.info("served from cache"); servedFromCacheCount++; } else { /* translate CoAP Request -> CoAP Request */ try { coapClient.createChannel(context); //channel must be created first transRequestCoapToCoap(context); context.setRequestTime(System.currentTimeMillis()); coapClient.sendRequest(context); } catch (Exception e) { logger.warn("CoAP to CoAP Request forwarding failed: " + e.getMessage()); sendDirectCoapError(context, CoapResponseCode.Not_Found_404); } } } } public void handleCoapClientResponse(ProxyMessageContext context) { context.setResponseTime(System.currentTimeMillis()); if (!context.isCached() && context.getInCoapResponse() !=null ) { // avoid recaching cache.cacheCoapResponse(context); } if (context.isTranslate()) { /* coap to HTTP */ try { transResponseCoapToHttp(context); } catch (Exception e) { logger.warn("CoAP to HTTP Response translation failed: " + e.getMessage()); context.setOutHttpResponse(new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error")); } httpServer.sendResponse(context); } else { /* coap to coap */ try { transResponseCoapToCoap(context); } catch (Exception e) { logger.warn("CoAP to CoAP Response forwarding failed: " + e.getMessage()); context.getOutCoapResponse().setResponseCode(CoapResponseCode.Internal_Server_Error_500); } coapServer.sendResponse(context); } } public void handleHttpClientResponse(ProxyMessageContext context) { context.setResponseTime(System.currentTimeMillis()); if (!context.isCached()) { cache.cacheHttpResponse(context); } try { transResponseHttpToCoap(context); } catch (Exception e) { logger.warn("HTTP to CoAP Response translation failed: " + e.getMessage()); context.getOutCoapResponse().setResponseCode(CoapResponseCode.Internal_Server_Error_500); } coapServer.sendResponse(context); } /* ------------------------------------ Translate Functions -----------------------------------*/ public static void transRequestCoapToCoap(ProxyMessageContext context){ CoapRequest in = context.getInCoapRequest(); CoapClientChannel channel = context.getOutCoapClientChannel(); context.setOutCoapRequest(channel.createRequest(CoapClientProxy.RELIABLE, in.getRequestCode())); CoapRequest out = context.getOutCoapRequest(); /*TODO: translate not using copy header options */ ((BasicCoapRequest) out).copyHeaderOptions((BasicCoapRequest)in); /* TODO: check if the next hop is a proxy or the final serer * implement coapUseProxy option for proxy */ out.removeOption(CoapHeaderOptionType.Proxy_Uri); out.setUriPath(context.getUri().getPath()); if (context.getUri().getQuery() != null){ out.setUriQuery(context.getUri().getQuery()); } out.removeOption(CoapHeaderOptionType.Token); out.setPayload(in.getPayload()); } public static void transRequestHttpToCoap(ProxyMessageContext context) throws IOException { HttpRequest httpRequest = context.getInHttpRequest(); boolean hasContent = false; CoapRequestCode requestCode; String method; method = httpRequest.getRequestLine().getMethod().toLowerCase(); if (method.contentEquals("get")) { requestCode = CoapRequestCode.GET; } else if (method.contentEquals("put")) { requestCode = CoapRequestCode.PUT; hasContent = true; } else if (method.contentEquals("post")) { requestCode = CoapRequestCode.POST; hasContent = true; } else if (method.contentEquals("delete")) { requestCode = CoapRequestCode.DELETE; } else if (method.contentEquals("head")) { // if we have a head request, coap should handle it as a get, // but without any message-body requestCode = CoapRequestCode.GET; context.setHttpHeadMethod(true); } else { throw new IllegalStateException("unknown message code"); } CoapClientChannel channel = context.getOutCoapClientChannel(); context.setOutCoapRequest(channel.createRequest(CoapClientProxy.RELIABLE, requestCode)); // Translate Headers CoapRequest coapRequest = context.getOutCoapRequest(); URI uri = null; // construct uri for later use uri = resolveHttpRequestUri(httpRequest); // Content-Type is in response only // Max-Age is in response only // Proxy-Uri doesn't matter for this purpose // ETag: if (httpRequest.containsHeader("Etag")) { Header[] headers = httpRequest.getHeaders("Etag"); if (headers.length > 0) { for (int i = 0; i < headers.length; i++) { String etag = headers[i].getValue(); coapRequest.addETag(etag.getBytes()); } } } // Uri-Host: // don't needs to be there // Location-Path is in response-only // Location-Query is in response-only // Uri-Path: // this is the implementation according to coap-rfc section 6.4 // first check if uri is absolute and that it has no fragment if (uri.isAbsolute() && uri.getFragment() == null) { coapRequest.setUriPath(uri.getPath()); } else { throw new IllegalStateException("uri has wrong format"); } // Token is the same number as msgID, not needed now // in future development it should be generated here // Accept: possible values are numeric media-types if (httpRequest.containsHeader("Accept")) { Header[] headers = httpRequest.getHeaders("Accept"); if (headers.length > 0) { for (int i = 0; i < headers.length; i++) { httpMediaType2coapMediaType(headers[i].getValue(), coapRequest); } } } // TODO: if-match: // if (request.containsHeader("If-Match")) { // Header[] headers = request.getHeaders("If-Match"); // if (headers.length > 0) { // for (int i=0; i < headers.length; i++) { // String header_value = headers[i].getValue(); // CoapHeaderOption option_ifmatch = new // CoapHeaderOption(CoapHeaderOptionType.If_Match, // header_value.getBytes()); // header.addOption(option_ifmatch ); // } // } // } // Uri-Query: // this is the implementation according to coap-rfc section 6.4 // first check if uri is absolute and that it has no fragment if (uri.isAbsolute() && uri.getFragment() == null) { if (uri.getQuery() != null) { // only add options if there are // some coapRequest.setUriQuery(uri.getQuery()); } } else { throw new IllegalStateException("uri has wrong format"); } // TODO: If-None-Match: // if (request.containsHeader("If-None-Match")) { // Header[] headers = request.getHeaders("If-None-Match"); // if (headers.length > 0) { // if (headers.length > 1) { // System.out.println("multiple headers in request, ignoring all except the first"); // } // String header_value = headers[0].getValue(); // CoapHeaderOption option_ifnonematch = new // CoapHeaderOption(CoapHeaderOptionType.If_None_Match, // header_value.getBytes()); // header.addOption(option_ifnonematch); // } // } // pass-through the payload if (hasContent){ BasicHttpEntityEnclosingRequest entirequest = (BasicHttpEntityEnclosingRequest) httpRequest; ConsumingNHttpEntityTemplate entity = (ConsumingNHttpEntityTemplate) entirequest.getEntity(); ByteContentListener listener = (ByteContentListener) entity.getContentListener(); byte[] data = listener.getContent(); context.getOutCoapRequest().setPayload(data); } } public static void transRequestCoapToHttp(ProxyMessageContext context) throws UnsupportedEncodingException{ HttpUriRequest httpRequest; CoapRequest request = context.getInCoapRequest(); CoapRequestCode code = request.getRequestCode(); //TODO:translate header options from coap-request to http-request NStringEntity entity; entity = new NStringEntity(new String(request.getPayload())); switch (code) { case GET: httpRequest = new HttpGet(context.getUri().toString()); break; case PUT: httpRequest = new HttpPut(context.getUri().toString()); ((HttpPut)httpRequest).setEntity(entity); break; case POST: httpRequest = new HttpPost(context.getUri().toString()); ((HttpPost)httpRequest).setEntity(entity); break; case DELETE: httpRequest = new HttpDelete(context.getUri().toString()); default: throw new IllegalStateException("unknown request code"); } context.setOutHttpRequest(httpRequest); } public static void transResponseCoapToCoap(ProxyMessageContext context){ CoapResponse in = context.getInCoapResponse(); CoapResponse out = context.getOutCoapResponse(); /*TODO: translate not using copy header options */ ((BasicCoapResponse) out).copyHeaderOptions((BasicCoapResponse)in); out.setResponseCode(in.getResponseCode()); out.removeOption(CoapHeaderOptionType.Token); out.setPayload(in.getPayload()); } public static void transResponseCoapToHttp(ProxyMessageContext context) throws UnsupportedEncodingException{ CoapResponse coapResponse = context.getInCoapResponse(); //create a response-object, set http version and assume a default state of ok HttpResponse httpResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); // differ between methods is necessary to set the right status-code String requestMethod = context.getInHttpRequest().getRequestLine().getMethod(); if (requestMethod.toLowerCase().contains("get")){ // set status code and reason phrase setHttpMsgCode(coapResponse, "get", httpResponse); // pass-through the payload, if we do not answer a head-request if (!context.isHttpHeadMethod()) { NStringEntity entity; entity = new NStringEntity(new String(coapResponse.getPayload()), "UTF-8"); entity.setContentType("text/plain"); httpResponse.setEntity(entity); } } else if (requestMethod.toLowerCase().contains("put")){ setHttpMsgCode(coapResponse, "put", httpResponse); } else if (requestMethod.toLowerCase().contains("post")){ setHttpMsgCode(coapResponse, "post", httpResponse); } else if (requestMethod.toLowerCase().contains("delete")){ setHttpMsgCode(coapResponse, "delete", httpResponse); } else { throw new IllegalStateException("unknown request method"); } // set Headers headerTranslateCoapToHttp(coapResponse, httpResponse); context.setOutHttpResponse(httpResponse); } public static void transResponseHttpToCoap(ProxyMessageContext context) throws ParseException, IOException{ //set the response-code according to response-code-mapping-table CoapResponse coapResponse = context.getOutCoapResponse(); coapResponse.setResponseCode(getCoapResponseCode(context)); //throws an exception if mapping failed //TODO: translate header-options //assume in this case a string-entity //TODO: add more entity-types coapResponse.setContentType(CoapMediaType.text_plain); String entity = ""; entity = EntityUtils.toString(context.getInHttpResponse().getEntity()); coapResponse.setPayload(entity); } /* these functions are called if the request translation fails and no message was forwarded */ public void sendDirectHttpError(ProxyMessageContext context,int code, String reason){ HttpResponse httpResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, code, reason); context.setOutHttpResponse(httpResponse); httpServer.sendResponse(context); } /* these functions are called if the request translation fails and no message was forwarded */ public void sendDirectCoapError(ProxyMessageContext context, CoapResponseCode code){ CoapServerChannel channel = (CoapServerChannel) context.getInCoapRequest().getChannel(); CoapResponse response = channel.createResponse(context.getInCoapRequest(), code); context.setInCoapResponse(response); coapServer.sendResponse(context); } public static void resourceToHttp(ProxyMessageContext context, ProxyResource resource){ /* TODO: very rudimentary implementation */ HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); try { NStringEntity entity; entity = new NStringEntity(new String(resource.getValue()), "UTF-8"); entity.setContentType("text/plain"); response.setEntity(entity); } catch (UnsupportedEncodingException e) { logger.error("HTTP entity creation failed"); } context.setOutHttpResponse(response); } public static void resourceToCoap(ProxyMessageContext context, ProxyResource resource){ CoapResponse response = context.getOutCoapResponse(); //already generated /* response code */ response.setResponseCode(CoapResponseCode.Content_205); /* payload */ response.setPayload(resource.getValue()); /* mediatype */ if (resource.getCoapMediaType() != null) { response.setContentType(resource.getCoapMediaType()); } /* Max-Age */ int maxAge = (int)(resource.expires() - System.currentTimeMillis()) / 1000; if (maxAge < 0){ /* should never happen because the function is only called if the resource is valid. * However, processing time can be an issue */ logger.warn("return expired resource (Max-Age = 0)"); maxAge = 0; } response.setMaxAge(maxAge); } public static void setHttpMsgCode(CoapResponse coapResponse, String requestMethod, HttpResponse httpResponse) { CoapResponseCode responseCode = coapResponse.getResponseCode(); switch(responseCode) { // case OK_200: { //removed from CoAP draft // httpResponse.setStatusCode(HttpStatus.SC_OK); // httpResponse.setReasonPhrase("Ok"); // break; // } case Created_201: { if (requestMethod.contains("post") || requestMethod.contains("put")) { httpResponse.setStatusCode(HttpStatus.SC_CREATED); httpResponse.setReasonPhrase("Created"); } else { System.out.println("wrong msgCode for request-method!"); httpResponse.setStatusCode(HttpStatus.SC_METHOD_FAILURE); httpResponse.setReasonPhrase("Method Failure"); } break; } case Deleted_202: { if (requestMethod.contains("delete")) { httpResponse.setStatusCode(HttpStatus.SC_NO_CONTENT); httpResponse.setReasonPhrase("No Content"); } else { System.out.println("wrong msgCode for request-method!"); httpResponse.setStatusCode(HttpStatus.SC_METHOD_FAILURE); httpResponse.setReasonPhrase("Method Failure"); } break; } case Valid_203: { httpResponse.setStatusCode(HttpStatus.SC_NOT_MODIFIED); httpResponse.setReasonPhrase("Not Modified"); break; } case Changed_204: { if (requestMethod.contains("post") || requestMethod.contains("put")) { httpResponse.setStatusCode(HttpStatus.SC_NO_CONTENT); httpResponse.setReasonPhrase("No Content"); } else { System.out.println("wrong msgCode for request-method!"); httpResponse.setStatusCode(HttpStatus.SC_METHOD_FAILURE); httpResponse.setReasonPhrase("Method Failure"); } break; } case Content_205: { if (requestMethod.contains("get")) { httpResponse.setStatusCode(HttpStatus.SC_OK); httpResponse.setReasonPhrase("OK"); } else { System.out.println("wrong msgCode for request-method!"); httpResponse.setStatusCode(HttpStatus.SC_METHOD_FAILURE); httpResponse.setReasonPhrase("Method Failure"); } break; } case Bad_Request_400: { httpResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); httpResponse.setReasonPhrase("Bad Request"); break; } case Unauthorized_401: { httpResponse.setStatusCode(HttpStatus.SC_UNAUTHORIZED); httpResponse.setReasonPhrase("Unauthorized"); break; } case Bad_Option_402: { httpResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); httpResponse.setReasonPhrase("Bad Option"); break; } case Forbidden_403: { httpResponse.setStatusCode(HttpStatus.SC_FORBIDDEN); httpResponse.setReasonPhrase("Forbidden"); break; } case Not_Found_404: { httpResponse.setStatusCode(HttpStatus.SC_NOT_FOUND); httpResponse.setReasonPhrase("Not Found"); break; } case Method_Not_Allowed_405: { httpResponse.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED); httpResponse.setReasonPhrase("Method Not Allowed"); break; } case Precondition_Failed_412: { httpResponse.setStatusCode(HttpStatus.SC_PRECONDITION_FAILED); httpResponse.setReasonPhrase("Precondition Failed"); break; } case Request_Entity_To_Large_413: { httpResponse.setStatusCode(HttpStatus.SC_REQUEST_TOO_LONG); httpResponse.setReasonPhrase("Request Too Long : Request entity too large"); break; } case Unsupported_Media_Type_415: { httpResponse.setStatusCode(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE); httpResponse.setReasonPhrase("Unsupported Media Type"); break; } case Internal_Server_Error_500: { httpResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); httpResponse.setReasonPhrase("Internal Server Error"); break; } case Not_Implemented_501: { httpResponse.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); httpResponse.setReasonPhrase("Not Implemented"); break; } case Bad_Gateway_502: { httpResponse.setStatusCode(HttpStatus.SC_BAD_GATEWAY); httpResponse.setReasonPhrase("Bad Gateway"); break; } case Service_Unavailable_503: { httpResponse.setStatusCode(HttpStatus.SC_SERVICE_UNAVAILABLE); httpResponse.setReasonPhrase("Service Unavailable"); break; } case Gateway_Timeout_504: { httpResponse.setStatusCode(HttpStatus.SC_GATEWAY_TIMEOUT); httpResponse.setReasonPhrase("Gateway Timeout"); break; } case Proxying_Not_Supported_505: { httpResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); httpResponse.setReasonPhrase("Internal Server Error : Proxying not supported"); break; } case UNKNOWN: { httpResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); httpResponse.setReasonPhrase("Bad Request : Unknown Coap Message Code"); break; } default: { httpResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); httpResponse.setReasonPhrase("Bad Request : Unknown Coap Message Code"); break; } } } //sets the coap-response code under use of http-status code; used in case coap-http public static CoapResponseCode getCoapResponseCode(ProxyMessageContext context) { HttpResponse httpResponse = context.getInHttpResponse(); //TODO: add cases in which http-code is the same, but coap-code is different, look at response-code-mapping-table switch(httpResponse.getStatusLine().getStatusCode()) { case HttpStatus.SC_CREATED: return CoapResponseCode.Created_201; case HttpStatus.SC_NO_CONTENT: if (context.getInCoapRequest().getRequestCode() == CoapRequestCode.DELETE) { return CoapResponseCode.Deleted_202; } else { return CoapResponseCode.Changed_204; } case HttpStatus.SC_NOT_MODIFIED: return CoapResponseCode.Valid_203; case HttpStatus.SC_OK: return CoapResponseCode.Content_205; case HttpStatus.SC_UNAUTHORIZED: return CoapResponseCode.Unauthorized_401; case HttpStatus.SC_FORBIDDEN:return CoapResponseCode.Forbidden_403; case HttpStatus.SC_NOT_FOUND:return CoapResponseCode.Not_Found_404; case HttpStatus.SC_METHOD_NOT_ALLOWED:return CoapResponseCode.Method_Not_Allowed_405; case HttpStatus.SC_PRECONDITION_FAILED: return CoapResponseCode.Precondition_Failed_412; case HttpStatus.SC_REQUEST_TOO_LONG: return CoapResponseCode.Request_Entity_To_Large_413; case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:return CoapResponseCode.Unsupported_Media_Type_415; case HttpStatus.SC_INTERNAL_SERVER_ERROR:return CoapResponseCode.Internal_Server_Error_500; case HttpStatus.SC_NOT_IMPLEMENTED:return CoapResponseCode.Not_Implemented_501; case HttpStatus.SC_BAD_GATEWAY:return CoapResponseCode.Bad_Gateway_502; case HttpStatus.SC_SERVICE_UNAVAILABLE:return CoapResponseCode.Service_Unavailable_503; case HttpStatus.SC_GATEWAY_TIMEOUT:return CoapResponseCode.Gateway_Timeout_504; default: throw new IllegalStateException("unknown HTTP response code"); } } //mediatype-mapping: public static void httpMediaType2coapMediaType(String mediatype, CoapRequest request) { String[] type_subtype = mediatype.split(","); for (String value : type_subtype) { if (value.toLowerCase().contains("text") && value.toLowerCase().contains("plain")) { request.addAccept(CoapMediaType.text_plain); } else if (value.toLowerCase().contains("application")) { // value is for example "application/xml;q=0.9" String[] subtypes = value.toLowerCase().split("/"); String subtype = ""; if (subtypes.length == 2) { subtype = subtypes[1]; // subtype is for example now "xml;q=0.9" } else { System.out.println("Error in reading Mediatypes!"); } // extract the subtype-name and remove the quality identifiers: String[] subname = subtype.split(";"); String name = ""; if (subname.length > 0) { name = subname[0]; // name is for example "xml" } else { System.out.println("Error in reading Mediatypes!"); } if (name.contentEquals("link-format")) { request.addAccept(CoapMediaType.link_format); } if (name.contentEquals("xml")) { request.addAccept(CoapMediaType.xml); } if (name.contentEquals("octet-stream")) { request.addAccept(CoapMediaType.octet_stream); } if (name.contentEquals("exi")) { request.addAccept(CoapMediaType.exi); } if (name.contentEquals("json")) { request.addAccept(CoapMediaType.json); } } } } // translate response-header-options in case of http-coap public static void headerTranslateCoapToHttp(CoapResponse coapResponse, HttpResponse httpResponse) { // investigate all coap-headers and set corresponding http-headers CoapMediaType contentType = coapResponse.getContentType(); if (contentType != null) { switch (contentType) { case text_plain: httpResponse.addHeader("Content-Type", "text/plain"); break; case link_format: httpResponse.addHeader("Content-Type", "application/link-format"); break; case json: httpResponse.addHeader("Content-Type", "application/json"); break; case exi: httpResponse.addHeader("Content-Type", "application/exi"); break; case octet_stream: httpResponse.addHeader("Content-Type", "application/octet-stream"); break; case xml: httpResponse.addHeader("Content-Type", "application/xml"); break; default: httpResponse.addHeader("Content-Type", "text/plain"); break; } } else { httpResponse.addHeader("Content-Type", "text/plain"); } long maxAge = coapResponse.getMaxAge(); if (maxAge < 0){ maxAge = DEFAULT_MAX_AGE_MS; } long maxAgeMs = maxAge * 1000; if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE){ httpResponse.addHeader("Retry-After", String.valueOf(maxAge)); } byte[] etag = coapResponse.getETag(); if (etag != null){ httpResponse.addHeader("Etag", new String(etag)); } //generate content-length-header if (httpResponse.getEntity() != null) httpResponse.addHeader("Content-length", "" + httpResponse.getEntity().getContentLength()); //set creation-date for Caching: httpResponse.addHeader("Date", "" + formatDate(new GregorianCalendar().getTime())); //expires-option is option-value (default is 60 secs) + current_date Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(calendar.getTimeInMillis() + maxAgeMs); String date = formatDate(calendar.getTime()); httpResponse.addHeader("Expires", date); } public static HttpResponse handleCoapDELETEresponse(CoapResponse response, HttpResponse httpResponse) { //set status code and reason phrase headerTranslateCoapToHttp(response, httpResponse); return httpResponse; } // //the mode is used to indicate for which case the proxy is listening to // //mode is unneccessary when proxy is listening to all cases, then there are more threads neccessary // public void setMode(Integer modenumber) { // mode = modenumber; // } //setter-functions to introduce other threads public void setHttpServer(HttpServerNIO server) { httpServer = server; } public void setHttpClient(HttpClientNIO client) { httpClient = client; } public void setCoapServer(CoapServerProxy server) { coapServer = server; } public void setCoapClient(CoapClientProxy client) { coapClient = client; } //exclude methods from processing:OPTIONS/TRACE/CONNECT public static boolean isHttpRequestMethodSupported(HttpRequest request) { String method = request.getRequestLine().getMethod().toLowerCase(); if (method.contentEquals("options") || method.contentEquals("trace") || method.contentEquals("connect")) return false; return true; } //makes a date to a string; http-header-values (expires, date...) must be a string in most cases public static String formatDate(Date date) { final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; if (date == null) { throw new IllegalArgumentException("date is null"); } SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_RFC1123, Locale.US); formatter.setTimeZone(TimeZone.getDefault()); //CEST String ret = formatter.format(date); return ret; } public static URI resolveHttpRequestUri(HttpRequest request){ URI uri = null; String uriString = request.getRequestLine().getUri(); /* make sure to have the scheme */ if (uriString.startsWith("coap://")){ /* do nothing */ } else if (uriString.startsWith("http://")){ uriString = "coap://" + uriString.substring(7); } else { /* not an absolute uri */ Header[] host = request.getHeaders("Host"); /* only one is accepted */ if (host.length <= 0){ /* error, unknown host*/ return null; } uriString = "coap://" + host[0].getValue() + uriString; } try { uri = new URI(uriString); } catch (URISyntaxException e) { return null; //indicates that resolve failed } return uri; } public static boolean isIPv4Address(InetAddress addr) { try { @SuppressWarnings("unused") //just to check if casting fails Inet4Address addr4 = (Inet4Address) addr; return true; } catch (ClassCastException ex) { return false; } } public static boolean isIPv6Address(InetAddress addr) { try { @SuppressWarnings("unused") //just to check if casting fails Inet6Address addr6 = (Inet6Address) addr; return true; } catch (ClassCastException ex) { return false; } } public int getHttpRequestCount() { return httpRequestCount; } public int getCoapRequestCount() { return coapRequestCount; } public int getServedFromCacheCount() { return servedFromCacheCount; } public void resetCounter(){ httpRequestCount = 0; coapRequestCount = 0; servedFromCacheCount = 0; } public void setCacheEnabled(boolean enabled) { cache.setEnabled(enabled); } public CoapClientProxy getCoapClient() { return coapClient; } public CoapServerProxy getCoapServer() { return coapServer; } public HttpServerNIO getHttpServer() { return httpServer; } public HttpClientNIO getHttpClient() { return httpClient; } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import org.apache.log4j.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapResponse; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class CoapClientProxy implements CoapClient{ static Logger logger = Logger.getLogger(Proxy.class); ProxyMapper mapper = ProxyMapper.getInstance(); static final boolean RELIABLE = true; //use CON as client (NON has no timeout!!!) /* creates a client channel and stores it in the context*/ public void createChannel(ProxyMessageContext context){ // create channel CoapClientChannel channel; channel = BasicCoapChannelManager.getInstance().connect(this, context.getServerAddress(), context.getServerPort()); if (channel != null) { channel.setTrigger(context); context.setOutCoapClientChannel(channel); } else { throw new IllegalStateException("CoAP client connect() failed"); } } public void closeChannel(ProxyMessageContext context){ context.getOutCoapClientChannel().close(); } public void sendRequest(ProxyMessageContext context) { context.getOutCoapRequest().getChannel().sendMessage(context.getOutCoapRequest()); } @Override public void onResponse(CoapClientChannel channel, CoapResponse response) { ProxyMessageContext context = (ProxyMessageContext) channel.getTrigger(); channel.close(); if (context != null) { context.setInCoapResponse(response); mapper.handleCoapClientResponse(context); } } @Override public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) { ProxyMessageContext context = (ProxyMessageContext) channel.getTrigger(); channel.close(); if (context != null) { logger.warn("Coap client connection failed (e.g., timeout)!"); context.setInCoapResponse(null); // null indicates no response mapper.handleCoapClientResponse(context); } } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.DefaultServerIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.protocol.NHttpRequestHandler; import org.apache.http.nio.protocol.NHttpRequestHandlerRegistry; import org.apache.http.nio.protocol.NHttpResponseTrigger; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.nio.reactor.ListeningIOReactor; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.SyncBasicHttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.ResponseConnControl; import org.apache.log4j.Logger; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> * * TODO: IMPROVE Async Server Implementation, avoid ModifiedAsyncNHttpServiceHandler and deprecated function calls */ public class HttpServerNIO extends Thread{ static Logger logger = Logger.getLogger(Proxy.class); static private int PORT = 8080; ProxyMapper mapper = ProxyMapper.getInstance(); //interface-function for other classes/modules public void sendResponse(ProxyMessageContext context) { HttpResponse httpResponse = context.getOutHttpResponse(); NHttpResponseTrigger trigger = context.getTrigger(); trigger.submitResponse(httpResponse); } public void run() { this.setName("HTTP_NIO_Server"); //parameters for connection HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 50000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); //needed by framework, don't need any processors except the connection-control HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseConnControl() }); //create own service-handler with bytecontentlistener-class ModifiedAsyncNHttpServiceHandler handler = new ModifiedAsyncNHttpServiceHandler( httpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params); // Set up request handlers, use the same request-handler for all uris NHttpRequestHandlerRegistry reqistry = new NHttpRequestHandlerRegistry(); reqistry.register("*", new ProxyHttpRequestHandler()); handler.setHandlerResolver(reqistry); try { //create and start responder-thread //ioreactor is used by nio-framework to listen and react to http connections //2 dispatcher-threads are used to do the work ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params); IOEventDispatch ioeventdispatch = new DefaultServerIOEventDispatch(handler, params); ioReactor.listen(new InetSocketAddress(PORT)); ioReactor.execute(ioeventdispatch); } catch (IOReactorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } static class ProxyHttpRequestHandler implements NHttpRequestHandler { public ProxyHttpRequestHandler() { super(); } @Override public ConsumingNHttpEntity entityRequest( HttpEntityEnclosingRequest arg0, HttpContext arg1) throws HttpException, IOException { return null; } //handle() is called when a request is received //response is automatically generated by HttpProcessor, but use response from mapper //trigger is used for asynchronous response, see java-documentation @Override public void handle(final HttpRequest request, final HttpResponse response, final NHttpResponseTrigger trigger, HttpContext con) throws HttpException, IOException { logger.info("incomming HTTP request"); URI uri = ProxyMapper.resolveHttpRequestUri(request); if (uri != null){ InetAddress serverAddress = InetAddress.getByName(uri.getHost()); //FIXME: blocking operation??? int serverPort = uri.getPort(); if (serverPort == -1) { serverPort = org.ws4d.coap.Constants.COAP_DEFAULT_PORT; } /* translate always */ ProxyMessageContext context = new ProxyMessageContext(request, true, uri, trigger); context.setServerAddress(serverAddress, serverPort); ProxyMapper.getInstance().handleHttpServerRequest(context); } else { trigger.submitResponse(new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "Bad Header: Host")); } } } }
Java
package org.ws4d.coap.client; import java.net.InetAddress; import java.net.UnknownHostException; import org.ws4d.coap.Constants; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapRequestCode; import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapBlockClient implements CoapClient { private static final String SERVER_ADDRESS = "129.132.15.80"; private static final int PORT = Constants.COAP_DEFAULT_PORT; static int counter = 0; CoapChannelManager channelManager = null; CoapClientChannel clientChannel = null; public static void main(String[] args) { System.out.println("Start CoAP Client"); BasicCoapBlockClient client = new BasicCoapBlockClient(); client.channelManager = BasicCoapChannelManager.getInstance(); client.runTestClient(); } public void runTestClient(){ try { clientChannel = channelManager.connect(this, InetAddress.getByName(SERVER_ADDRESS), PORT); CoapRequest coapRequest = clientChannel.createRequest(true, CoapRequestCode.GET); coapRequest.setUriPath("/large"); clientChannel.setMaxReceiveBlocksize(CoapBlockSize.BLOCK_64); clientChannel.sendMessage(coapRequest); System.out.println("Sent Request"); } catch (UnknownHostException e) { e.printStackTrace(); } } @Override public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) { System.out.println("Connection Failed"); } @Override public void onResponse(CoapClientChannel channel, CoapResponse response) { System.out.println("Received response"); System.out.println(response.toString()); System.out.println(new String(response.getPayload())); } }
Java
package org.ws4d.coap.client; import java.net.InetAddress; import java.net.UnknownHostException; import org.ws4d.coap.Constants; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapClient implements CoapClient { private static final String SERVER_ADDRESS = "localhost"; private static final int PORT = Constants.COAP_DEFAULT_PORT; static int counter = 0; CoapChannelManager channelManager = null; CoapClientChannel clientChannel = null; public static void main(String[] args) { System.out.println("Start CoAP Client"); BasicCoapClient client = new BasicCoapClient(); client.channelManager = BasicCoapChannelManager.getInstance(); client.runTestClient(); } public void runTestClient(){ try { clientChannel = channelManager.connect(this, InetAddress.getByName(SERVER_ADDRESS), PORT); CoapRequest coapRequest = clientChannel.createRequest(true, CoapRequestCode.GET); // coapRequest.setContentType(CoapMediaType.octet_stream); // coapRequest.setToken("ABCD".getBytes()); // coapRequest.setUriHost("123.123.123.123"); // coapRequest.setUriPort(1234); // coapRequest.setUriPath("/sub1/sub2/sub3/"); // coapRequest.setUriQuery("a=1&b=2&c=3"); // coapRequest.setProxyUri("http://proxy.org:1234/proxytest"); clientChannel.sendMessage(coapRequest); System.out.println("Sent Request"); } catch (UnknownHostException e) { e.printStackTrace(); } } @Override public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) { System.out.println("Connection Failed"); } @Override public void onResponse(CoapClientChannel channel, CoapResponse response) { System.out.println("Received response"); } }
Java
package org.ws4d.coap.udp; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class UDPRelay { public static final int SERVER_PORT = 6000; public static final int CLIENT_PORT = 8000; public static final int UDP_BUFFER_SIZE = 66000; // max UDP size = 65535 public static void main(String[] args) { if (args.length < 2){ System.out.println("expected parameter: server host and port, e.g. 192.168.1.1 1234"); System.exit(-1); } UDPRelay relay = new UDPRelay(); relay.run(new InetSocketAddress(args[0], Integer.parseInt(args[1]))); } private DatagramChannel serverChannel = null; private DatagramChannel clientChannel = null; ByteBuffer serverBuffer = ByteBuffer.allocate(UDP_BUFFER_SIZE); ByteBuffer clientBuffer = ByteBuffer.allocate(UDP_BUFFER_SIZE); Selector selector = null; InetSocketAddress clientAddr = null; public void run(InetSocketAddress serverAddr) { try { serverChannel = DatagramChannel.open(); serverChannel.socket().bind(new InetSocketAddress(SERVER_PORT)); serverChannel.configureBlocking(false); serverChannel.connect(serverAddr); clientChannel = DatagramChannel.open(); clientChannel.socket().bind(new InetSocketAddress(CLIENT_PORT)); clientChannel.configureBlocking(false); try { selector = Selector.open(); serverChannel.register(selector, SelectionKey.OP_READ); clientChannel.register(selector, SelectionKey.OP_READ); } catch (IOException e1) { e1.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); System.out.println("Initialization failed, Shut down"); System.exit(-1); } System.out.println("Start UDP Realy on Server Port " + SERVER_PORT + " and Client Port " + CLIENT_PORT); int serverLen = 0; while (true) { /* Receive Packets */ InetSocketAddress tempClientAddr = null; try { clientBuffer.clear(); tempClientAddr = (InetSocketAddress) clientChannel.receive(clientBuffer); clientBuffer.flip(); serverBuffer.clear(); serverLen = serverChannel.read(serverBuffer); serverBuffer.flip(); } catch (IOException e1) { e1.printStackTrace(); System.out.println("Read failed"); } /* forward/send packets client -> server*/ if (tempClientAddr != null) { /* the client address is obtained automatically by the first request of the client * clientAddr is the last known valid address of the client */ clientAddr = tempClientAddr; try { serverChannel.write(clientBuffer); System.out.println("Forwarded Message client ("+clientAddr.getHostName()+" "+clientAddr.getPort() + ") -> server (" + serverAddr.getHostName()+" " + serverAddr.getPort() + "): " + clientBuffer.limit() + " bytes"); } catch (IOException e) { e.printStackTrace(); System.out.println("Send failed"); } } /* forward/send packets server -> client*/ if (serverLen > 0) { try { clientChannel.send(serverBuffer, clientAddr); System.out.println("Forwarded Message server ("+serverAddr.getHostName()+" "+serverAddr.getPort() + ") -> client (" + clientAddr.getHostName()+" " + clientAddr.getPort() + "): " + serverBuffer.limit() + " bytes"); } catch (IOException e) { e.printStackTrace(); System.out.println("Send failed"); } } /* Select */ try { selector.select(2000); } catch (IOException e) { e.printStackTrace(); System.out.println("select failed"); } } } }
Java
package org.ws4d.coap.server; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.rest.BasicCoapResource; import org.ws4d.coap.rest.CoapResourceServer; import org.ws4d.coap.rest.ResourceHandler; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public class CoapSampleResourceServer { private static CoapSampleResourceServer sampleServer; private CoapResourceServer resourceServer; private static Logger logger = Logger .getLogger(CoapSampleResourceServer.class.getName()); /** * @param args */ public static void main(String[] args) { logger.addAppender(new ConsoleAppender(new SimpleLayout())); logger.setLevel(Level.INFO); logger.info("Start Sample Resource Server"); sampleServer = new CoapSampleResourceServer(); sampleServer.run(); } private void run() { if (resourceServer != null) resourceServer.stop(); resourceServer = new CoapResourceServer(); /* Show detailed logging of Resource Server*/ Logger resourceLogger = Logger.getLogger(CoapResourceServer.class.getName()); resourceLogger.setLevel(Level.ALL); /* add resources */ BasicCoapResource light = new BasicCoapResource("/test/light", "Content".getBytes(), CoapMediaType.text_plain); light.registerResourceHandler(new ResourceHandler() { @Override public void onPost(byte[] data) { System.out.println("Post to /test/light"); } }); light.setResourceType("light"); light.setObservable(true); resourceServer.createResource(light); try { resourceServer.start(); } catch (Exception e) { e.printStackTrace(); } int counter = 0; while(true){ try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } counter++; light.setValue(((String)"Message #" + counter).getBytes()); light.changed(); } } }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package org.ws4d.coap.server; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class SeparateResponseCoapServer implements CoapServer { private static final int PORT = 5683; static int counter = 0; CoapResponse response = null; CoapServerChannel channel = null; public static void main(String[] args) { System.out.println("Start CoAP Server on port " + PORT); SeparateResponseCoapServer server = new SeparateResponseCoapServer(); CoapChannelManager channelManager = BasicCoapChannelManager.getInstance(); channelManager.createServerListener(server, PORT); } @Override public CoapServer onAccept(CoapRequest request) { System.out.println("Accept connection..."); return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { System.out.println("Received message: " + request.toString()); this.channel = channel; response = channel.createSeparateResponse(request, CoapResponseCode.Content_205); Thread t = new Thread( new SendDelayedResponse() ); t.start(); } public class SendDelayedResponse implements Runnable { public void run() { response.setContentType(CoapMediaType.text_plain); response.setPayload("payload...".getBytes()); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } channel.sendSeparateResponse(response); } } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { System.out.println("Separate Response failed"); } }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package org.ws4d.coap.server; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapServer implements CoapServer { private static final int PORT = 5683; static int counter = 0; public static void main(String[] args) { System.out.println("Start CoAP Server on port " + PORT); BasicCoapServer server = new BasicCoapServer(); CoapChannelManager channelManager = BasicCoapChannelManager.getInstance(); channelManager.createServerListener(server, PORT); } @Override public CoapServer onAccept(CoapRequest request) { System.out.println("Accept connection..."); return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { System.out.println("Received message: " + request.toString()+ " URI: " + request.getUriPath()); CoapMessage response = channel.createResponse(request, CoapResponseCode.Content_205); response.setContentType(CoapMediaType.text_plain); response.setPayload("payload...".getBytes()); if (request.getObserveOption() != null){ System.out.println("Client wants to observe this resource."); } response.setObserveOption(1); channel.sendMessage(response); } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { System.out.println("Separate response transmission failed."); } }
Java
package b_Money; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class AccountTest { Currency SEK, DKK; Bank Nordea; Bank DanskeBank; Bank SweBank; Account testAccount; @Before public void setUp() throws Exception { SEK = new Currency("SEK", 0.15); SweBank = new Bank("SweBank", SEK); SweBank.openAccount("Alice"); testAccount = new Account("Hans", SEK); testAccount.deposit(new Money(10000000, SEK)); SweBank.deposit("Alice", new Money(1000000, SEK)); } @Test public void testAddRemoveTimedPayment() { fail("Write test case here"); } @Test public void testTimedPayment() throws AccountDoesNotExistException { fail("Write test case here"); } @Test public void testAddWithdraw() { fail("Write test case here"); } @Test public void testGetBalance() { fail("Write test case here"); } }
Java
package b_Money; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class CurrencyTest { Currency SEK, DKK, NOK, EUR; @Before public void setUp() throws Exception { /* Setup currencies with exchange rates */ SEK = new Currency("SEK", 0.15); DKK = new Currency("DKK", 0.20); EUR = new Currency("EUR", 1.5); } @Test public void testGetName() { fail("Write test case here"); } @Test public void testGetRate() { fail("Write test case here"); } @Test public void testSetRate() { fail("Write test case here"); } @Test public void testGlobalValue() { fail("Write test case here"); } @Test public void testValueInThisCurrency() { fail("Write test case here"); } }
Java
package b_Money; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class MoneyTest { Currency SEK, DKK, NOK, EUR; Money SEK100, EUR10, SEK200, EUR20, SEK0, EUR0, SEKn100; @Before public void setUp() throws Exception { SEK = new Currency("SEK", 0.15); DKK = new Currency("DKK", 0.20); EUR = new Currency("EUR", 1.5); SEK100 = new Money(10000, SEK); EUR10 = new Money(1000, EUR); SEK200 = new Money(20000, SEK); EUR20 = new Money(2000, EUR); SEK0 = new Money(0, SEK); EUR0 = new Money(0, EUR); SEKn100 = new Money(-10000, SEK); } @Test public void testGetAmount() { fail("Write test case here"); } @Test public void testGetCurrency() { fail("Write test case here"); } @Test public void testToString() { fail("Write test case here"); } @Test public void testGlobalValue() { fail("Write test case here"); } @Test public void testEqualsMoney() { fail("Write test case here"); } @Test public void testAdd() { fail("Write test case here"); } @Test public void testSub() { fail("Write test case here"); } @Test public void testIsZero() { fail("Write test case here"); } @Test public void testNegate() { fail("Write test case here"); } @Test public void testCompareTo() { fail("Write test case here"); } }
Java
package b_Money; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class BankTest { Currency SEK, DKK; Bank SweBank, Nordea, DanskeBank; @Before public void setUp() throws Exception { DKK = new Currency("DKK", 0.20); SEK = new Currency("SEK", 0.15); SweBank = new Bank("SweBank", SEK); Nordea = new Bank("Nordea", SEK); DanskeBank = new Bank("DanskeBank", DKK); SweBank.openAccount("Ulrika"); SweBank.openAccount("Bob"); Nordea.openAccount("Bob"); DanskeBank.openAccount("Gertrud"); } @Test public void testGetName() { fail("Write test case here"); } @Test public void testGetCurrency() { fail("Write test case here"); } @Test public void testOpenAccount() throws AccountExistsException, AccountDoesNotExistException { fail("Write test case here"); } @Test public void testDeposit() throws AccountDoesNotExistException { fail("Write test case here"); } @Test public void testWithdraw() throws AccountDoesNotExistException { fail("Write test case here"); } @Test public void testGetBalance() throws AccountDoesNotExistException { fail("Write test case here"); } @Test public void testTransfer() throws AccountDoesNotExistException { fail("Write test case here"); } @Test public void testTimedPayment() throws AccountDoesNotExistException { fail("Write test case here"); } }
Java
package b_Money; public class Currency { private String name; private Double rate; /** * New Currency * The rate argument of each currency indicates that Currency's "universal" exchange rate. * Imagine that we define the rate of each currency in relation to some universal currency. * This means that the rate of each currency defines its value compared to this universal currency. * * @param name The name of this Currency * @param rate The exchange rate of this Currency */ Currency (String name, Double rate) { this.name = name; this.rate = rate; } /** Convert an amount of this Currency to its value in the general "universal currency" * (As mentioned in the documentation of the Currency constructor) * * @param amount An amount of cash of this currency. * @return The value of amount in the "universal currency" */ public Integer universalValue(Integer amount) { } /** Get the name of this Currency. * @return name of Currency */ public String getName() { } /** Get the rate of this Currency. * * @return rate of this Currency */ public Double getRate() { } /** Set the rate of this currency. * * @param rate New rate for this Currency */ public void setRate(Double rate) { } /** Convert an amount from another Currency to an amount in this Currency * * @param amount Amount of the other Currency * @param othercurrency The other Currency */ public Integer valueInThisCurrency(Integer amount, Currency othercurrency) { } }
Java
package b_Money; import java.util.Hashtable; public class Account { private Money content; private Hashtable<String, TimedPayment> timedpayments = new Hashtable<String, TimedPayment>(); Account(String name, Currency currency) { this.content = new Money(0, currency); } /** * Add a timed payment * @param id Id of timed payment * @param interval Number of ticks between payments * @param next Number of ticks till first payment * @param amount Amount of Money to transfer each payment * @param tobank Bank where receiving account resides * @param toaccount Id of receiving account */ public void addTimedPayment(String id, Integer interval, Integer next, Money amount, Bank tobank, String toaccount) { TimedPayment tp = new TimedPayment(interval, next, amount, this, tobank, toaccount); timedpayments.put(id, tp); } /** * Remove a timed payment * @param id Id of timed payment to remove */ public void removeTimedPayment(String id) { timedpayments.remove(id); } /** * Check if a timed payment exists * @param id Id of timed payment to check for */ public boolean timedPaymentExists(String id) { return timedpayments.containsKey(id); } /** * A time unit passes in the system */ public void tick() { for (TimedPayment tp : timedpayments.values()) { tp.tick(); tp.tick(); } } /** * Deposit money to the account * @param money Money to deposit. */ public void deposit(Money money) { content = content.add(money); } /** * Withdraw money from the account * @param money Money to withdraw. */ public void withdraw(Money money) { content = content.sub(money); } /** * Get balance of account * @return Amount of Money currently on account */ public Money getBalance() { return content; } /* Everything below belongs to the private inner class, TimedPayment */ private class TimedPayment { private int interval, next; private Account fromaccount; private Money amount; private Bank tobank; private String toaccount; TimedPayment(Integer interval, Integer next, Money amount, Account fromaccount, Bank tobank, String toaccount) { this.interval = interval; this.next = next; this.amount = amount; this.fromaccount = fromaccount; this.tobank = tobank; this.toaccount = toaccount; } /* Return value indicates whether or not a transfer was initiated */ public Boolean tick() { if (next == 0) { next = interval; fromaccount.withdraw(amount); try { tobank.deposit(toaccount, amount); } catch (AccountDoesNotExistException e) { /* Revert transfer. * In reality, this should probably cause a notification somewhere. */ fromaccount.deposit(amount); } return true; } else { next--; return false; } } } }
Java
package b_Money; public class Money implements Comparable { private int amount; private Currency currency; /** * New Money * @param amount The amount of money * @param currency The currency of the money */ Money (Integer amount, Currency currency) { this.amount = amount; this.currency = currency; } /** * Return the amount of money. * @return Amount of money in Double type. */ public Integer getAmount() { } /** * Returns the currency of this Money. * @return Currency object representing the currency of this Money */ public Currency getCurrency() { } /** * Returns the amount of the money in the string form "(amount) (currencyname)", e.g. "10.5 SEK". * Recall that we represent decimal numbers with integers. This means that the "10.5 SEK" mentioned * above is actually represented as the integer 1050 * @return String representing the amount of Money. */ public String toString() { } /** * Gets the universal value of the Money, according the rate of its Currency. * @return The value of the Money in the "universal currency". */ public Integer universalValue() { } /** * Check to see if the value of this money is equal to the value of another Money of some other Currency. * @param other The other Money that is being compared to this Money. * @return A Boolean indicating if the two monies are equal. */ public Boolean equals(Money other) { } /** * Adds a Money to this Money, regardless of the Currency of the other Money. * @param other The Money that is being added to this Money. * @return A new Money with the same Currency as this Money, representing the added value of the two. * (Remember to convert the other Money before adding the amounts) */ public Money add(Money other) { } /** * Subtracts a Money from this Money, regardless of the Currency of the other Money. * @param other The money that is being subtracted from this Money. * @return A new Money with the same Currency as this Money, representing the subtracted value. * (Again, remember converting the value of the other Money to this Currency) */ public Money sub(Money other) { } /** * Check to see if the amount of this Money is zero or not * @return True if the amount of this Money is equal to 0.0, False otherwise */ public Boolean isZero() { } /** * Negate the amount of money, i.e. if the amount is 10.0 SEK the negation returns -10.0 SEK * @return A new instance of the money class initialized with the new negated money amount. */ public Money negate() { } /** * Compare two Monies. * compareTo is required because the class implements the Comparable interface. * (Remember the universalValue method, and that Integers already implement Comparable). * Also, since compareTo must take an Object, you will have to explicitly downcast it to a Money. * @return 0 if the values of the monies are equal. * A negative integer if this Money is less valuable than the other Money. * A positive integer if this Money is more valuiable than the other Money. */ public int compareTo(Object other) { } }
Java
package b_Money; public class AccountDoesNotExistException extends Exception { static final long serialVersionUID = 1L; }
Java
package b_Money; import java.util.Hashtable; public class Bank { private Hashtable<String, Account> accountlist = new Hashtable<String, Account>(); private String name; private Currency currency; /** * New Bank * @param name Name of this bank * @param currency Base currency of this bank (If this is a Swedish bank, this might be a currency class representing SEK) */ Bank(String name, Currency currency) { this.name = name; this.currency = currency; } /** * Get the name of this bank * @return Name of this bank */ public String getName() { return name; } /** * Get the Currency of this bank * @return The Currency of this bank */ public Currency getCurrency() { return currency; } /** * Open an account at this bank. * @param accountid The ID of the account * @throws AccountExistsException If the account already exists */ public void openAccount(String accountid) throws AccountExistsException { if (accountlist.containsKey(accountid)) { throw new AccountExistsException(); } else { accountlist.get(accountid); } } /** * Deposit money to an account * @param accountid Account to deposit to * @param money Money to deposit. * @throws AccountDoesNotExistException If the account does not exist */ public void deposit(String accountid, Money money) throws AccountDoesNotExistException { if (accountlist.containsKey(accountid)) { throw new AccountDoesNotExistException(); } else { Account account = accountlist.get(accountid); account.deposit(money); } } /** * Withdraw money from an account * @param accountid Account to withdraw from * @param money Money to withdraw * @throws AccountDoesNotExistException If the account does not exist */ public void withdraw(String accountid, Money money) throws AccountDoesNotExistException { if (!accountlist.containsKey(accountid)) { throw new AccountDoesNotExistException(); } else { Account account = accountlist.get(accountid); account.deposit(money); } } /** * Get the balance of an account * @param accountid Account to get balance from * @return Balance of the account * @throws AccountDoesNotExistException If the account does not exist */ public Integer getBalance(String accountid) throws AccountDoesNotExistException { if (!accountlist.containsKey(accountid)) { throw new AccountDoesNotExistException(); } else { return accountlist.get(accountid).getBalance().getAmount(); } } /** * Transfer money between two accounts * @param fromaccount Id of account to deduct from in this Bank * @param tobank Bank where receiving account resides * @param toaccount Id of receiving account * @param amount Amount of Money to transfer * @throws AccountDoesNotExistException If one of the accounts do not exist */ public void transfer(String fromaccount, Bank tobank, String toaccount, Money amount) throws AccountDoesNotExistException { if (!accountlist.containsKey(fromaccount) || !tobank.accountlist.containsKey(toaccount)) { throw new AccountDoesNotExistException(); } else { accountlist.get(fromaccount).withdraw(amount); tobank.accountlist.get(toaccount).deposit(amount); } } /** * Transfer money between two accounts on the same bank * @param fromaccount Id of account to deduct from * @param toaccount Id of receiving account * @param amount Amount of Money to transfer * @throws AccountDoesNotExistException If one of the accounts do not exist */ public void transfer(String fromaccount, String toaccount, Money amount) throws AccountDoesNotExistException { transfer(fromaccount, this, fromaccount, amount); } /** * Add a timed payment * @param accountid Id of account to deduct from in this Bank * @param payid Id of timed payment * @param interval Number of ticks between payments * @param next Number of ticks till first payment * @param amount Amount of Money to transfer each payment * @param tobank Bank where receiving account resides * @param toaccount Id of receiving account */ public void addTimedPayment(String accountid, String payid, Integer interval, Integer next, Money amount, Bank tobank, String toaccount) { Account account = accountlist.get(accountid); account.addTimedPayment(payid, interval, next, amount, tobank, toaccount); } /** * Remove a timed payment * @param accountid Id of account to remove timed payment from * @param id Id of timed payment */ public void removeTimedPayment(String accountid, String id) { Account account = accountlist.get(accountid); account.removeTimedPayment(id); } /** * A time unit passes in the system */ public void tick() throws AccountDoesNotExistException { for (Account account : accountlist.values()) { account.tick(); } } }
Java
package b_Money; public class AccountExistsException extends Exception { static final long serialVersionUID = 1L; }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.tesseract.android; import android.graphics.Bitmap; import android.graphics.Rect; import com.googlecode.leptonica.android.Pix; import com.googlecode.leptonica.android.Pixa; import com.googlecode.leptonica.android.ReadFile; import java.io.File; /** * Java interface for the Tesseract OCR engine. Does not implement all available * JNI methods, but does implement enough to be useful. Comments are adapted * from original Tesseract source. * * @author alanv@google.com (Alan Viverette) */ public class TessBaseAPI { /** * Used by the native implementation of the class. */ private int mNativeData; static { System.loadLibrary("lept"); System.loadLibrary("tess"); nativeClassInit(); } public static final class PageSegMode { /** Orientation and script detection only. */ public static final int PSM_OSD_ONLY = 0; /** * Automatic page segmentation with orientation and script detection. * (OSD) */ public static final int PSM_AUTO_OSD = 1; /** Automatic page segmentation, but no OSD, or OCR. */ public static final int PSM_AUTO_ONLY = 2; /** Fully automatic page segmentation, but no OSD. */ public static final int PSM_AUTO = 3; /** Assume a single column of text of variable sizes. */ public static final int PSM_SINGLE_COLUMN = 4; /** Assume a single uniform block of vertically aligned text. */ public static final int PSM_SINGLE_BLOCK_VERT_TEXT = 5; /** Assume a single uniform block of text. (Default.) */ public static final int PSM_SINGLE_BLOCK = 6; /** Treat the image as a single text line. */ public static final int PSM_SINGLE_LINE = 7; /** Treat the image as a single word. */ public static final int PSM_SINGLE_WORD = 8; /** Treat the image as a single word in a circle. */ public static final int PSM_CIRCLE_WORD = 9; /** Treat the image as a single character. */ public static final int PSM_SINGLE_CHAR = 10; /** Number of enum entries. */ public static final int PSM_COUNT = 11; } /** * Elements of the page hierarchy, used in {@link ResultIterator} to provide * functions that operate on each level without having to have 5x as many * functions. * <p> * NOTE: At present {@link #RIL_PARA} and {@link #RIL_BLOCK} are equivalent * as there is no paragraph internally yet. */ public static final class PageIteratorLevel { /** Block of text/image/separator line. */ public static final int RIL_BLOCK = 0; /** Paragraph within a block. */ public static final int RIL_PARA = 1; /** Line within a paragraph. */ public static final int RIL_TEXTLINE = 2; /** Word within a text line. */ public static final int RIL_WORD = 3; /** Symbol/character within a word. */ public static final int RIL_SYMBOL = 4; } /** Default accuracy versus speed mode. */ public static final int AVS_FASTEST = 0; /** Slowest and most accurate mode. */ public static final int AVS_MOST_ACCURATE = 100; /** Whitelist of characters to recognize. */ public static final String VAR_CHAR_WHITELIST = "tessedit_char_whitelist"; /** Blacklist of characters to not recognize. */ public static final String VAR_CHAR_BLACKLIST = "tessedit_char_blacklist"; /** Accuracy versus speed setting. */ public static final String VAR_ACCURACYVSPEED = "tessedit_accuracyvspeed"; /** * Constructs an instance of TessBaseAPI. */ public TessBaseAPI() { nativeConstruct(); } /** * Called by the GC to clean up the native data that we set up when we * construct the object. */ @Override protected void finalize() throws Throwable { try { nativeFinalize(); } finally { super.finalize(); } } /** * Initializes the Tesseract engine with a specified language model. Returns * <code>true</code> on success. * <p> * Instances are now mostly thread-safe and totally independent, but some * global parameters remain. Basically it is safe to use multiple * TessBaseAPIs in different threads in parallel, UNLESS you use SetVariable * on some of the Params in classify and textord. If you do, then the effect * will be to change it for all your instances. * <p> * The datapath must be the name of the parent directory of tessdata and * must end in / . Any name after the last / will be stripped. The language * is (usually) an ISO 639-3 string or <code>null</code> will default to * eng. It is entirely safe (and eventually will be efficient too) to call * Init multiple times on the same instance to change language, or just to * reset the classifier. * <p> * <b>WARNING:</b> On changing languages, all Tesseract parameters are reset * back to their default values. (Which may vary between languages.) * <p> * If you have a rare need to set a Variable that controls initialization * for a second call to Init you should explicitly call End() and then use * SetVariable before Init. This is only a very rare use case, since there * are very few uses that require any parameters to be set before Init. * * @param datapath the parent directory of tessdata ending in a forward * slash * @param language (optional) an ISO 639-3 string representing the language * @return <code>true</code> on success */ public boolean init(String datapath, String language) { if (datapath == null) { throw new IllegalArgumentException("Data path must not be null!"); } if (!datapath.endsWith(File.separator)) { datapath += File.separator; } File tessdata = new File(datapath + "tessdata"); if (!tessdata.exists() || !tessdata.isDirectory()) { throw new IllegalArgumentException("Data path must contain subfolder tessdata!"); } return nativeInit(datapath, language); } /** * Frees up recognition results and any stored image data, without actually * freeing any recognition data that would be time-consuming to reload. * Afterwards, you must call SetImage or SetRectangle before doing any * Recognize or Get* operation. */ public void clear() { nativeClear(); } /** * Closes down tesseract and free up all memory. End() is equivalent to * destructing and reconstructing your TessBaseAPI. * <p> * Once End() has been used, none of the other API functions may be used * other than Init and anything declared above it in the class definition. */ public void end() { nativeEnd(); } /** * Set the value of an internal "variable" (of either old or new types). * Supply the name of the variable and the value as a string, just as you * would in a config file. * <p> * Example: * <code>setVariable(VAR_TESSEDIT_CHAR_BLACKLIST, "xyz"); to ignore x, y and z. * setVariable(VAR_BLN_NUMERICMODE, "1"); to set numeric-only mode. * </code> * <p> * setVariable() may be used before open(), but settings will revert to * defaults on close(). * * @param var name of the variable * @param value value to set * @return false if the name lookup failed */ public boolean setVariable(String var, String value) { return nativeSetVariable(var, value); } /** * Sets the page segmentation mode. This controls how much processing the * OCR engine will perform before recognizing text. * * @param mode the page segmentation mode to set */ public void setPageSegMode(int mode) { nativeSetPageSegMode(mode); } /** * Sets debug mode. This controls how much information is displayed in the * log during recognition. * * @param enabled <code>true</code> to enable debugging mode */ public void setDebug(boolean enabled) { nativeSetDebug(enabled); } /** * Restricts recognition to a sub-rectangle of the image. Call after * SetImage. Each SetRectangle clears the recogntion results so multiple * rectangles can be recognized with the same image. * * @param rect the bounding rectangle */ public void setRectangle(Rect rect) { setRectangle(rect.left, rect.top, rect.width(), rect.height()); } /** * Restricts recognition to a sub-rectangle of the image. Call after * SetImage. Each SetRectangle clears the recogntion results so multiple * rectangles can be recognized with the same image. * * @param left the left bound * @param top the right bound * @param width the width of the bounding box * @param height the height of the bounding box */ public void setRectangle(int left, int top, int width, int height) { nativeSetRectangle(left, top, width, height); } /** * Provides an image for Tesseract to recognize. * * @param file absolute path to the image file */ public void setImage(File file) { Pix image = ReadFile.readFile(file); if (image == null) { throw new RuntimeException("Failed to read image file"); } nativeSetImagePix(image.getNativePix()); } /** * Provides an image for Tesseract to recognize. Does not copy the image * buffer. The source image must persist until after Recognize or * GetUTF8Chars is called. * * @param bmp bitmap representation of the image */ public void setImage(Bitmap bmp) { Pix image = ReadFile.readBitmap(bmp); if (image == null) { throw new RuntimeException("Failed to read bitmap"); } nativeSetImagePix(image.getNativePix()); } /** * Provides a Leptonica pix format image for Tesseract to recognize. Clones * the pix object. The source image may be destroyed immediately after * SetImage is called, but its contents may not be modified. * * @param image Leptonica pix representation of the image */ public void setImage(Pix image) { nativeSetImagePix(image.getNativePix()); } /** * Provides an image for Tesseract to recognize. Copies the image buffer. * The source image may be destroyed immediately after SetImage is called. * SetImage clears all recognition results, and sets the rectangle to the * full image, so it may be followed immediately by a GetUTF8Text, and it * will automatically perform recognition. * * @param imagedata byte representation of the image * @param width image width * @param height image height * @param bpp bytes per pixel * @param bpl bytes per line */ public void setImage(byte[] imagedata, int width, int height, int bpp, int bpl) { nativeSetImageBytes(imagedata, width, height, bpp, bpl); } /** * The recognized text is returned as a String which is coded as UTF8. * * @return the recognized text */ public String getUTF8Text() { // Trim because the text will have extra line breaks at the end String text = nativeGetUTF8Text(); return text.trim(); } public Pixa getRegions() { int pixa = nativeGetRegions(); if (pixa == 0) { return null; } return new Pixa(pixa, 0, 0); } public Pixa getWords() { int pixa = nativeGetWords(); if (pixa == 0) { return null; } return new Pixa(pixa, 0, 0); } /** * Returns the mean confidence of text recognition. * * @return the mean confidence */ public int meanConfidence() { return nativeMeanConfidence(); } /** * Returns all word confidences (between 0 and 100) in an array. The number * of confidences should correspond to the number of space-delimited words * in GetUTF8Text(). * * @return an array of word confidences (between 0 and 100) for each * space-delimited word returned by GetUTF8Text() */ public int[] wordConfidences() { int[] conf = nativeWordConfidences(); // We shouldn't return null confidences if (conf == null) { conf = new int[0]; } return conf; } public ResultIterator getResultIterator() { int nativeResultIterator = nativeGetResultIterator(); if (nativeResultIterator == 0) { return null; } return new ResultIterator(nativeResultIterator); } // ****************** // * Native methods * // ****************** /** * Initializes static native data. Must be called on object load. */ private static native void nativeClassInit(); /** * Initializes native data. Must be called on object construction. */ private native void nativeConstruct(); /** * Finalizes native data. Must be called on object destruction. */ private native void nativeFinalize(); private native boolean nativeInit(String datapath, String language); private native void nativeClear(); private native void nativeEnd(); private native void nativeSetImageBytes( byte[] imagedata, int width, int height, int bpp, int bpl); private native void nativeSetImagePix(int nativePix); private native void nativeSetRectangle(int left, int top, int width, int height); private native String nativeGetUTF8Text(); private native int nativeGetRegions(); private native int nativeGetWords(); private native int nativeMeanConfidence(); private native int[] nativeWordConfidences(); private native boolean nativeSetVariable(String var, String value); private native void nativeSetDebug(boolean debug); private native void nativeSetPageSegMode(int mode); private native int nativeGetResultIterator(); }
Java
/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.tesseract.android; import com.googlecode.tesseract.android.TessBaseAPI.PageIteratorLevel; public class PageIterator { static { System.loadLibrary("lept"); System.loadLibrary("tess"); } /** Pointer to native page iterator. */ private final int mNativePageIterator; /* package */PageIterator(int nativePageIterator) { mNativePageIterator = nativePageIterator; } /** * Resets the iterator to point to the start of the page. */ public void begin() { nativeBegin(mNativePageIterator); } /** * Moves to the start of the next object at the given level in the page * hierarchy, and returns false if the end of the page was reached. * <p> * NOTE that {@link PageIteratorLevel#RIL_SYMBOL} will skip non-text blocks, * but all other {@link PageIteratorLevel} level values will visit each * non-text block once. Think of non text blocks as containing a single * para, with a single line, with a single imaginary word. * <p> * Calls to {@link #next} with different levels may be freely intermixed. * <p> * This function iterates words in right-to-left scripts correctly, if the * appropriate language has been loaded into Tesseract. * * @param level the page iterator level. See {@link PageIteratorLevel}. * @return {@code false} if the end of the page was reached, {@code true} * otherwise. */ public boolean next(int level) { return nativeNext(mNativePageIterator, level); } private static native void nativeBegin(int nativeIterator); private static native boolean nativeNext(int nativeIterator, int level); }
Java
/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.tesseract.android; import com.googlecode.tesseract.android.TessBaseAPI.PageIteratorLevel; /** * Java interface for the ResultIterator. Does not implement all available JNI * methods, but does implement enough to be useful. Comments are adapted from * original Tesseract source. * * @author alanv@google.com (Alan Viverette) */ public class ResultIterator extends PageIterator { static { System.loadLibrary("lept"); System.loadLibrary("tess"); } /** Pointer to native result iterator. */ private final int mNativeResultIterator; /* package */ResultIterator(int nativeResultIterator) { super(nativeResultIterator); mNativeResultIterator = nativeResultIterator; } /** * Returns the text string for the current object at the given level. * * @param level the page iterator level. See {@link PageIteratorLevel}. * @return the text string for the current object at the given level. */ public String getUTF8Text(int level) { return nativeGetUTF8Text(mNativeResultIterator, level); } /** * Returns the mean confidence of the current object at the given level. The * number should be interpreted as a percent probability (0-100). * * @param level the page iterator level. See {@link PageIteratorLevel}. * @return the mean confidence of the current object at the given level. */ public float confidence(int level) { return nativeConfidence(mNativeResultIterator, level); } private static native String nativeGetUTF8Text(int nativeResultIterator, int level); private static native float nativeConfidence(int nativeResultIterator, int level); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Rect; /** * Java representation of a native Leptonica PIX object. * * @author alanv@google.com (Alan Viverette) */ public class Pix { static { System.loadLibrary("lept"); } /** Index of the image width within the dimensions array. */ public static final int INDEX_W = 0; /** Index of the image height within the dimensions array. */ public static final int INDEX_H = 1; /** Index of the image bit-depth within the dimensions array. */ public static final int INDEX_D = 2; /** Package-accessible pointer to native pix. */ final int mNativePix; private boolean mRecycled; /** * Creates a new Pix wrapper for the specified native PIX object. Never call * this twice on the same native pointer, because finalize() will attempt to * free native memory twice. * * @param nativePix A pointer to the native PIX object. */ public Pix(int nativePix) { mNativePix = nativePix; mRecycled = false; } public Pix(int width, int height, int depth) { if (width <= 0 || height <= 0) { throw new IllegalArgumentException("Pix width and height must be > 0"); } else if (depth != 1 && depth != 2 && depth != 4 && depth != 8 && depth != 16 && depth != 24 && depth != 32) { throw new IllegalArgumentException("Depth must be one of 1, 2, 4, 8, 16, or 32"); } mNativePix = nativeCreatePix(width, height, depth); mRecycled = false; } /** * Returns a pointer to the native Pix object. This is used by native code * and is only valid within the same process in which the Pix was created. * * @return a native pointer to the Pix object */ public int getNativePix() { return mNativePix; } /** * Return the raw bytes of the native PIX object. You can reconstruct the * Pix from this data using createFromPix(). * * @return a copy of this PIX object's raw data */ public byte[] getData() { int size = nativeGetDataSize(mNativePix); byte[] buffer = new byte[size]; if (!nativeGetData(mNativePix, buffer)) { throw new RuntimeException("native getData failed"); } return buffer; } /** * Returns an array of this image's dimensions. See Pix.INDEX_* for indices. * * @return an array of this image's dimensions or <code>null</code> on * failure */ public int[] getDimensions() { int[] dimensions = new int[4]; if (getDimensions(dimensions)) { return dimensions; } return null; } /** * Fills an array with this image's dimensions. The array must be at least 3 * elements long. * * @param dimensions An integer array with at least three elements. * @return <code>true</code> on success */ public boolean getDimensions(int[] dimensions) { return nativeGetDimensions(mNativePix, dimensions); } /** * Returns a clone of this Pix. This does NOT create a separate copy, just a * new pointer that can be recycled without affecting other clones. * * @return a clone (shallow copy) of the Pix */ @Override public Pix clone() { int nativePix = nativeClone(mNativePix); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Returns a deep copy of this Pix that can be modified without affecting * the original Pix. * * @return a copy of the Pix */ public Pix copy() { int nativePix = nativeCopy(mNativePix); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Inverts this Pix in-place. * * @return <code>true</code> on success */ public boolean invert() { return nativeInvert(mNativePix); } /** * Releases resources and frees any memory associated with this Pix. You may * not modify or access the pix after calling this method. */ public void recycle() { if (!mRecycled) { nativeDestroy(mNativePix); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } /** * Creates a new Pix from raw Pix data obtained from getData(). * * @param pixData Raw pix data obtained from getData(). * @param width The width of the original Pix. * @param height The height of the original Pix. * @param depth The bit-depth of the original Pix. * @return a new Pix or <code>null</code> on error */ public static Pix createFromPix(byte[] pixData, int width, int height, int depth) { int nativePix = nativeCreateFromData(pixData, width, height, depth); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Returns a Rect with the width and height of this Pix. * * @return a Rect with the width and height of this Pix */ public Rect getRect() { int w = getWidth(); int h = getHeight(); return new Rect(0, 0, w, h); } /** * Returns the width of this Pix. * * @return the width of this Pix */ public int getWidth() { return nativeGetWidth(mNativePix); } /** * Returns the height of this Pix. * * @return the height of this Pix */ public int getHeight() { return nativeGetHeight(mNativePix); } /** * Returns the depth of this Pix. * * @return the depth of this Pix */ public int getDepth() { return nativeGetDepth(mNativePix); } /** * Returns the {@link android.graphics.Color} at the specified location. * * @param x The x coordinate (0...width-1) of the pixel to return. * @param y The y coordinate (0...height-1) of the pixel to return. * @return The argb {@link android.graphics.Color} at the specified * coordinate. * @throws IllegalArgumentException If x, y exceeds the image bounds. */ public int getPixel(int x, int y) { if (x < 0 || x >= getWidth()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } else if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } return nativeGetPixel(mNativePix, x, y); } /** * Sets the {@link android.graphics.Color} at the specified location. * * @param x The x coordinate (0...width-1) of the pixel to set. * @param y The y coordinate (0...height-1) of the pixel to set. * @param color The argb {@link android.graphics.Color} to set at the * specified coordinate. * @throws IllegalArgumentException If x, y exceeds the image bounds. */ public void setPixel(int x, int y, int color) { if (x < 0 || x >= getWidth()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } else if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } nativeSetPixel(mNativePix, x, y, color); } // *************** // * NATIVE CODE * // *************** private static native int nativeCreatePix(int w, int h, int d); private static native int nativeCreateFromData(byte[] data, int w, int h, int d); private static native boolean nativeGetData(int nativePix, byte[] data); private static native int nativeGetDataSize(int nativePix); private static native int nativeClone(int nativePix); private static native int nativeCopy(int nativePix); private static native boolean nativeInvert(int nativePix); private static native void nativeDestroy(int nativePix); private static native boolean nativeGetDimensions(int nativePix, int[] dimensions); private static native int nativeGetWidth(int nativePix); private static native int nativeGetHeight(int nativePix); private static native int nativeGetDepth(int nativePix); private static native int nativeGetPixel(int nativePix, int x, int y); private static native void nativeSetPixel(int nativePix, int x, int y, int color); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.File; /** * Image input and output methods. * * @author alanv@google.com (Alan Viverette) */ public class ReadFile { static { System.loadLibrary("lept"); } /** * Creates a 32bpp Pix object from encoded data. Supported formats are BMP * and JPEG. * * @param encodedData JPEG or BMP encoded byte data. * @return a 32bpp Pix object */ public static Pix readMem(byte[] encodedData) { if (encodedData == null) throw new IllegalArgumentException("Image data byte array must be non-null"); final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ARGB_8888; final Bitmap bmp = BitmapFactory.decodeByteArray(encodedData, 0, encodedData.length, opts); final Pix pix = readBitmap(bmp); bmp.recycle(); return pix; } /** * Creates an 8bpp Pix object from raw 8bpp grayscale pixels. * * @param pixelData 8bpp grayscale pixel data. * @param width The width of the input image. * @param height The height of the input image. * @return an 8bpp Pix object */ public static Pix readBytes8(byte[] pixelData, int width, int height) { if (pixelData == null) throw new IllegalArgumentException("Byte array must be non-null"); if (width <= 0) throw new IllegalArgumentException("Image width must be greater than 0"); if (height <= 0) throw new IllegalArgumentException("Image height must be greater than 0"); if (pixelData.length < width * height) throw new IllegalArgumentException("Array length does not match dimensions"); int nativePix = nativeReadBytes8(pixelData, width, height); if (nativePix == 0) throw new RuntimeException("Failed to read pix from memory"); return new Pix(nativePix); } /** * Replaces the bytes in an 8bpp Pix object with raw grayscale 8bpp pixels. * Width and height be identical to the input Pix. * * @param pixs The Pix whose bytes will be replaced. * @param pixelData 8bpp grayscale pixel data. * @param width The width of the input image. * @param height The height of the input image. * @return an 8bpp Pix object */ public static boolean replaceBytes8(Pix pixs, byte[] pixelData, int width, int height) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixelData == null) throw new IllegalArgumentException("Byte array must be non-null"); if (width <= 0) throw new IllegalArgumentException("Image width must be greater than 0"); if (height <= 0) throw new IllegalArgumentException("Image height must be greater than 0"); if (pixelData.length < width * height) throw new IllegalArgumentException("Array length does not match dimensions"); if (pixs.getWidth() != width) throw new IllegalArgumentException("Source pix width does not match image width"); if (pixs.getHeight() != height) throw new IllegalArgumentException("Source pix width does not match image width"); return nativeReplaceBytes8(pixs.mNativePix, pixelData, width, height); } /** * Creates a Pixa object from encoded files in a directory. Supported * formats are BMP and JPEG. * * @param dir The directory containing the files. * @param prefix The prefix of the files to load into a Pixa. * @return a Pixa object containing one Pix for each file */ public static Pixa readFiles(File dir, String prefix) { if (dir == null) throw new IllegalArgumentException("Directory must be non-null"); if (!dir.exists()) throw new IllegalArgumentException("Directory does not exist"); if (!dir.canRead()) throw new IllegalArgumentException("Cannot read directory"); // TODO: Remove or fix this. throw new RuntimeException("readFiles() is not current supported"); } /** * Creates a Pix object from encoded file data. Supported formats are BMP * and JPEG. * * @param file The JPEG or BMP-encoded file to read in as a Pix. * @return a Pix object */ public static Pix readFile(File file) { if (file == null) throw new IllegalArgumentException("File must be non-null"); if (!file.exists()) throw new IllegalArgumentException("File does not exist"); if (!file.canRead()) throw new IllegalArgumentException("Cannot read file"); final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ARGB_8888; final Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath(), opts); final Pix pix = readBitmap(bmp); bmp.recycle(); return pix; } /** * Creates a Pix object from Bitmap data. Currently supports only * ARGB_8888-formatted bitmaps. * * @param bmp The Bitmap object to convert to a Pix. * @return a Pix object */ public static Pix readBitmap(Bitmap bmp) { if (bmp == null) throw new IllegalArgumentException("Bitmap must be non-null"); if (bmp.getConfig() != Bitmap.Config.ARGB_8888) throw new IllegalArgumentException("Bitmap config must be ARGB_8888"); int nativePix = nativeReadBitmap(bmp); if (nativePix == 0) throw new RuntimeException("Failed to read pix from bitmap"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeReadMem(byte[] data, int size); private static native int nativeReadBytes8(byte[] data, int w, int h); private static native boolean nativeReplaceBytes8(int nativePix, byte[] data, int w, int h); private static native int nativeReadFiles(String dirname, String prefix); private static native int nativeReadFile(String filename); private static native int nativeReadBitmap(Bitmap bitmap); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Wrapper for Leptonica's native BOX. * * @author alanv@google.com (Alan Viverette) */ public class Box { static { System.loadLibrary("lept"); } /** The index of the X coordinate within the geometry array. */ public static final int INDEX_X = 0; /** The index of the Y coordinate within the geometry array. */ public static final int INDEX_Y = 1; /** The index of the width within the geometry array. */ public static final int INDEX_W = 2; /** The index of the height within the geometry array. */ public static final int INDEX_H = 3; /** * A pointer to the native Box object. This is used internally by native * code. */ final int mNativeBox; private boolean mRecycled = false; /** * Creates a new Box wrapper for the specified native BOX. * * @param nativeBox A pointer to the native BOX. */ Box(int nativeBox) { mNativeBox = nativeBox; mRecycled = false; } /** * Creates a box with the specified geometry. All dimensions should be * non-negative and specified in pixels. * * @param x X-coordinate of the top-left corner of the box. * @param y Y-coordinate of the top-left corner of the box. * @param w Width of the box. * @param h Height of the box. */ public Box(int x, int y, int w, int h) { if (x < 0 || y < 0 || w < 0 || h < 0) { throw new IllegalArgumentException("All box dimensions must be non-negative"); } int nativeBox = nativeCreate(x, y, w, h); if (nativeBox == 0) { throw new OutOfMemoryError(); } mNativeBox = nativeBox; mRecycled = false; } /** * Returns the box's x-coordinate in pixels. * * @return The box's x-coordinate in pixels. */ public int getX() { return nativeGetX(mNativeBox); } /** * Returns the box's y-coordinate in pixels. * * @return The box's y-coordinate in pixels. */ public int getY() { return nativeGetY(mNativeBox); } /** * Returns the box's width in pixels. * * @return The box's width in pixels. */ public int getWidth() { return nativeGetWidth(mNativeBox); } /** * Returns the box's height in pixels. * * @return The box's height in pixels. */ public int getHeight() { return nativeGetHeight(mNativeBox); } /** * Returns an array containing the coordinates of this box. See INDEX_* * constants for indices. * * @return an array of box oordinates */ public int[] getGeometry() { int[] geometry = new int[4]; if (getGeometry(geometry)) { return geometry; } return null; } /** * Fills an array containing the coordinates of this box. See INDEX_* * constants for indices. * * @param geometry A 4+ element integer array to fill with coordinates. * @return <code>true</code> on success */ public boolean getGeometry(int[] geometry) { if (geometry.length < 4) { throw new IllegalArgumentException("Geometry array must be at least 4 elements long"); } return nativeGetGeometry(mNativeBox, geometry); } /** * Releases resources and frees any memory associated with this Box. */ public void recycle() { if (!mRecycled) { nativeDestroy(mNativeBox); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } // *************** // * NATIVE CODE * // *************** private static native int nativeCreate(int x, int y, int w, int h); private static native int nativeGetX(int nativeBox); private static native int nativeGetY(int nativeBox); private static native int nativeGetWidth(int nativeBox); private static native int nativeGetHeight(int nativeBox); private static native void nativeDestroy(int nativeBox); private static native boolean nativeGetGeometry(int nativeBox, int[] geometry); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image bit-depth conversion methods. * * @author alanv@google.com (Alan Viverette) */ public class Convert { static { System.loadLibrary("lept"); } /** * Converts an image of any bit depth to 8-bit grayscale. * * @param pixs Source pix of any bit-depth. * @return a new Pix image or <code>null</code> on error */ public static Pix convertTo8(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeConvertTo8(pixs.mNativePix); if (nativePix == 0) throw new RuntimeException("Failed to natively convert pix"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeConvertTo8(int nativePix); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Rect; import java.io.File; import java.util.ArrayList; import java.util.Iterator; /** * Java representation of a native PIXA object. This object contains multiple * PIX objects and their associated bounding BOX objects. * * @author alanv@google.com (Alan Viverette) */ public class Pixa implements Iterable<Pix> { static { System.loadLibrary("lept"); } /** A pointer to the native PIXA object. This is used internally by native code. */ final int mNativePixa; /** The specified width of this Pixa. */ final int mWidth; /** The specified height of this Pixa. */ final int mHeight; private boolean mRecycled; /** * Creates a new Pixa with the specified minimum capacity. The Pixa will * expand automatically as new Pix are added. * * @param size The minimum capacity of this Pixa. * @return a new Pixa or <code>null</code> on error */ public static Pixa createPixa(int size) { return createPixa(size, 0, 0); } /** * Creates a new Pixa with the specified minimum capacity. The Pixa will * expand automatically as new Pix are added. * <p> * If non-zero, the specified width and height will be used to specify the * bounds of output images. * * * @param size The minimum capacity of this Pixa. * @param width (Optional) The width of this Pixa, use 0 for default. * @param height (Optional) The height of this Pixa, use 0 for default. * @return a new Pixa or <code>null</code> on error */ public static Pixa createPixa(int size, int width, int height) { int nativePixa = nativeCreate(size); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, width, height); } /** * Creates a wrapper for the specified native Pixa pointer. * * @param nativePixa Native pointer to a PIXA object. * @param width The width of the PIXA. * @param height The height of the PIXA. */ public Pixa(int nativePixa, int width, int height) { mNativePixa = nativePixa; mWidth = width; mHeight = height; mRecycled = false; } /** * Returns a pointer to the native PIXA object. This is used by native code. * * @return a pointer to the native PIXA object */ public int getNativePixa() { return mNativePixa; } /** * Creates a shallow copy of this Pixa. Contained Pix are cloned, and the * resulting Pixa may be recycled separately from the original. * * @return a shallow copy of this Pixa */ public Pixa copy() { int nativePixa = nativeCopy(mNativePixa); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, mWidth, mHeight); } /** * Sorts this Pixa using the specified field and order. See * Constants.L_SORT_BY_* and Constants.L_SORT_INCREASING or * Constants.L_SORT_DECREASING. * * @param field The field to sort by. See Constants.L_SORT_BY_*. * @param order The order in which to sort. Must be either * Constants.L_SORT_INCREASING or Constants.L_SORT_DECREASING. * @return a sorted copy of this Pixa */ public Pixa sort(int field, int order) { int nativePixa = nativeSort(mNativePixa, field, order); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, mWidth, mHeight); } /** * Returns the number of elements in this Pixa. * * @return the number of elements in this Pixa */ public int size() { return nativeGetCount(mNativePixa); } /** * Recycles this Pixa and frees natively allocated memory. You may not * access or modify the Pixa after calling this method. * <p> * Any Pix obtained from this Pixa or copies of this Pixa will still be * accessible until they are explicitly recycled or finalized by the garbage * collector. */ public synchronized void recycle() { if (!mRecycled) { nativeDestroy(mNativePixa); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } /** * Merges the contents of another Pixa into this one. * * @param otherPixa * @return <code>true</code> on success */ public boolean join(Pixa otherPixa) { return nativeJoin(mNativePixa, otherPixa.mNativePixa); } /** * Adds a Pix to this Pixa. * * @param pix The Pix to add. * @param mode The mode in which to add this Pix, typically * Constants.L_CLONE. */ public void addPix(Pix pix, int mode) { nativeAddPix(mNativePixa, pix.mNativePix, mode); } /** * Adds a Box to this Pixa. * * @param box The Box to add. * @param mode The mode in which to add this Box, typically * Constants.L_CLONE. */ public void addBox(Box box, int mode) { nativeAddBox(mNativePixa, box.mNativeBox, mode); } /** * Adds a Pix and associated Box to this Pixa. * * @param pix The Pix to add. * @param box The Box to add. * @param mode The mode in which to add this Pix and Box, typically * Constants.L_CLONE. */ public void add(Pix pix, Box box, int mode) { nativeAdd(mNativePixa, pix.mNativePix, box.mNativeBox, mode); } /** * Returns the Box at the specified index, or <code>null</code> on error. * * @param index The index of the Box to return. * @return the Box at the specified index, or <code>null</code> on error */ public Box getBox(int index) { int nativeBox = nativeGetBox(mNativePixa, index); if (nativeBox == 0) { return null; } return new Box(nativeBox); } /** * Returns the Pix at the specified index, or <code>null</code> on error. * * @param index The index of the Pix to return. * @return the Pix at the specified index, or <code>null</code> on error */ public Pix getPix(int index) { int nativePix = nativeGetPix(mNativePixa, index); if (nativePix == 0) { return null; } return new Pix(nativePix); } /** * Returns the width of this Pixa, or 0 if one was not set when it was * created. * * @return the width of this Pixa, or 0 if one was not set when it was * created */ public int getWidth() { return mWidth; } /** * Returns the height of this Pixa, or 0 if one was not set when it was * created. * * @return the height of this Pixa, or 0 if one was not set when it was * created */ public int getHeight() { return mHeight; } /** * Returns a bounding Rect for this Pixa, which may be (0,0,0,0) if width * and height were not specified on creation. * * @return a bounding Rect for this Pixa */ public Rect getRect() { return new Rect(0, 0, mWidth, mHeight); } /** * Returns a bounding Rect for the Box at the specified index. * * @param index The index of the Box to get the bounding Rect of. * @return a bounding Rect for the Box at the specified index */ public Rect getBoxRect(int index) { int[] dimensions = getBoxGeometry(index); if (dimensions == null) { return null; } int x = dimensions[Box.INDEX_X]; int y = dimensions[Box.INDEX_Y]; int w = dimensions[Box.INDEX_W]; int h = dimensions[Box.INDEX_H]; Rect bound = new Rect(x, y, x + w, y + h); return bound; } /** * Returns a geometry array for the Box at the specified index. See * Box.INDEX_* for indices. * * @param index The index of the Box to get the geometry of. * @return a bounding Rect for the Box at the specified index */ public int[] getBoxGeometry(int index) { int[] dimensions = new int[4]; if (getBoxGeometry(index, dimensions)) { return dimensions; } return null; } /** * Fills an array with the geometry of the Box at the specified index. See * Box.INDEX_* for indices. * * @param index The index of the Box to get the geometry of. * @param dimensions The array to fill with Box geometry. Must be at least 4 * elements. * @return <code>true</code> on success */ public boolean getBoxGeometry(int index, int[] dimensions) { return nativeGetBoxGeometry(mNativePixa, index, dimensions); } /** * Returns an ArrayList of Box bounding Rects. * * @return an ArrayList of Box bounding Rects */ public ArrayList<Rect> getBoxRects() { final int pixaCount = nativeGetCount(mNativePixa); final int[] buffer = new int[4]; final ArrayList<Rect> rects = new ArrayList<Rect>(pixaCount); for (int i = 0; i < pixaCount; i++) { getBoxGeometry(i, buffer); final int x = buffer[Box.INDEX_X]; final int y = buffer[Box.INDEX_Y]; final Rect bound = new Rect(x, y, x + buffer[Box.INDEX_W], y + buffer[Box.INDEX_H]); rects.add(bound); } return rects; } /** * Replaces the Pix and Box at the specified index with the specified Pix * and Box, both of which may be recycled after calling this method. * * @param index The index of the Pix to replace. * @param pix The Pix to replace the existing Pix. * @param box The Box to replace the existing Box. */ public void replacePix(int index, Pix pix, Box box) { nativeReplacePix(mNativePixa, index, pix.mNativePix, box.mNativeBox); } /** * Merges the Pix at the specified indices and removes the Pix at the second * index. * * @param indexA The index of the first Pix. * @param indexB The index of the second Pix, which will be removed after * merging. */ public void mergeAndReplacePix(int indexA, int indexB) { nativeMergeAndReplacePix(mNativePixa, indexA, indexB); } /** * Writes the components of this Pix to a bitmap-formatted file using a * random color map. * * @param file The file to write to. * @return <code>true</code> on success */ public boolean writeToFileRandomCmap(File file) { return nativeWriteToFileRandomCmap(mNativePixa, file.getAbsolutePath(), mWidth, mHeight); } @Override public Iterator<Pix> iterator() { return new PixIterator(); } private class PixIterator implements Iterator<Pix> { private int mIndex; private PixIterator() { mIndex = 0; } @Override public boolean hasNext() { final int size = size(); return (size > 0 && mIndex < size); } @Override public Pix next() { return getPix(mIndex++); } @Override public void remove() { throw new UnsupportedOperationException(); } } // *************** // * NATIVE CODE * // *************** private static native int nativeCreate(int size); private static native int nativeCopy(int nativePixa); private static native int nativeSort(int nativePixa, int field, int order); private static native boolean nativeJoin(int nativePixa, int otherPixa); private static native int nativeGetCount(int nativePixa); private static native void nativeDestroy(int nativePixa); private static native void nativeAddPix(int nativePixa, int nativePix, int mode); private static native void nativeAddBox(int nativePixa, int nativeBox, int mode); private static native void nativeAdd(int nativePixa, int nativePix, int nativeBox, int mode); private static native boolean nativeWriteToFileRandomCmap( int nativePixa, String fileName, int width, int height); private static native void nativeReplacePix( int nativePixa, int index, int nativePix, int nativeBox); private static native void nativeMergeAndReplacePix(int nativePixa, int indexA, int indexB); private static native int nativeGetBox(int nativePix, int index); private static native int nativeGetPix(int nativePix, int index); private static native boolean nativeGetBoxGeometry(int nativePixa, int index, int[] dimensions); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Bitmap; import java.io.File; /** * @author alanv@google.com (Alan Viverette) */ public class WriteFile { static { System.loadLibrary("lept"); } /* Default JPEG quality */ public static final int DEFAULT_QUALITY = 85; /* Default JPEG progressive encoding */ public static final boolean DEFAULT_PROGRESSIVE = true; /** * Write an 8bpp Pix to a flat byte array. * * @param pixs The 8bpp source image. * @return a byte array where each byte represents a single 8-bit pixel */ public static byte[] writeBytes8(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int size = pixs.getWidth() * pixs.getHeight(); if (pixs.getDepth() != 8) { Pix pix8 = Convert.convertTo8(pixs); pixs.recycle(); pixs = pix8; } byte[] data = new byte[size]; writeBytes8(pixs, data); return data; } /** * Write an 8bpp Pix to a flat byte array. * * @param pixs The 8bpp source image. * @param data A byte array large enough to hold the pixels of pixs. * @return the number of bytes written to data */ public static int writeBytes8(Pix pixs, byte[] data) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int size = pixs.getWidth() * pixs.getHeight(); if (data.length < size) throw new IllegalArgumentException("Data array must be large enough to hold image bytes"); int bytesWritten = nativeWriteBytes8(pixs.mNativePix, data); return bytesWritten; } /** * Writes all the images in a Pixa array to individual files using the * specified format. The output file extension will be determined by the * format. * <p> * Output file names will take the format <path>/<prefix><index>.<extension> * * @param pixas The source Pixa image array. * @param path The output directory. * @param prefix The prefix to give output files. * @param format The format to use for output files. * @return <code>true</code> on success */ public static boolean writeFiles(Pixa pixas, File path, String prefix, int format) { if (pixas == null) throw new IllegalArgumentException("Source pixa must be non-null"); if (path == null) throw new IllegalArgumentException("Destination path non-null"); if (prefix == null) throw new IllegalArgumentException("Filename prefix must be non-null"); throw new RuntimeException("writeFiles() is not currently supported"); } /** * Write a Pix to a byte array using the specified encoding from * Constants.IFF_*. * * @param pixs The source image. * @param format A format from Constants.IFF_*. * @return a byte array containing encoded bytes */ public static byte[] writeMem(Pix pixs, int format) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); return nativeWriteMem(pixs.mNativePix, format); } /** * Writes a Pix to file using the file extension as the output format; * supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap. * <p> * Uses default quality and progressive encoding settings. * * @param pixs Source image. * @param file The file to write. * @return <code>true</code> on success */ public static boolean writeImpliedFormat(Pix pixs, File file) { return writeImpliedFormat(pixs, file, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE); } /** * Writes a Pix to file using the file extension as the output format; * supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap. * <p> * Notes: * <ol> * <li>This determines the output format from the filename extension. * <li>The last two args are ignored except for requests for jpeg files. * <li>The jpeg default quality is 75. * </ol> * * @param pixs Source image. * @param file The file to write. * @param quality (Only for lossy formats) Quality between 1 - 100, 0 for * default. * @param progressive (Only for JPEG) Whether to encode as progressive. * @return <code>true</code> on success */ public static boolean writeImpliedFormat( Pix pixs, File file, int quality, boolean progressive) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (file == null) throw new IllegalArgumentException("File must be non-null"); return nativeWriteImpliedFormat( pixs.mNativePix, file.getAbsolutePath(), quality, progressive); } /** * Writes a Pix to an Android Bitmap object. The output Bitmap will always * be in ARGB_8888 format, but the input Pixs may be any bit-depth. * * @param pixs The source image. * @return a Bitmap containing a copy of the source image, or <code>null * </code> on failure */ public static Bitmap writeBitmap(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); final int[] dimensions = pixs.getDimensions(); final int width = dimensions[Pix.INDEX_W]; final int height = dimensions[Pix.INDEX_H]; //final int depth = dimensions[Pix.INDEX_D]; final Bitmap.Config config = Bitmap.Config.ARGB_8888; final Bitmap bitmap = Bitmap.createBitmap(width, height, config); if (nativeWriteBitmap(pixs.mNativePix, bitmap)) { return bitmap; } bitmap.recycle(); return null; } // *************** // * NATIVE CODE * // *************** private static native int nativeWriteBytes8(int nativePix, byte[] data); private static native boolean nativeWriteFiles(int nativePix, String rootname, int format); private static native byte[] nativeWriteMem(int nativePix, int format); private static native boolean nativeWriteImpliedFormat( int nativePix, String fileName, int quality, boolean progressive); private static native boolean nativeWriteBitmap(int nativePix, Bitmap bitmap); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image binarization methods. * * @author alanv@google.com (Alan Viverette) */ public class Binarize { static { System.loadLibrary("lept"); } // Otsu thresholding constants /** Desired tile X dimension; actual size may vary */ public final static int OTSU_SIZE_X = 32; /** Desired tile Y dimension; actual size may vary */ public final static int OTSU_SIZE_Y = 32; /** Desired X smoothing value */ public final static int OTSU_SMOOTH_X = 2; /** Desired Y smoothing value */ public final static int OTSU_SMOOTH_Y = 2; /** Fraction of the max Otsu score, typically 0.1 */ public final static float OTSU_SCORE_FRACTION = 0.1f; /** * Performs locally-adaptive Otsu threshold binarization with default * parameters. * * @param pixs An 8 bpp PIX source image. * @return A 1 bpp thresholded PIX image. */ public static Pix otsuAdaptiveThreshold(Pix pixs) { return otsuAdaptiveThreshold( pixs, OTSU_SIZE_X, OTSU_SIZE_Y, OTSU_SMOOTH_X, OTSU_SMOOTH_Y, OTSU_SCORE_FRACTION); } /** * Performs locally-adaptive Otsu threshold binarization. * <p> * Notes: * <ol> * <li>The Otsu method finds a single global threshold for an image. This * function allows a locally adapted threshold to be found for each tile * into which the image is broken up. * <li>The array of threshold values, one for each tile, constitutes a * highly downscaled image. This array is optionally smoothed using a * convolution. The full width and height of the convolution kernel are (2 * * smoothX + 1) and (2 * smoothY + 1). * <li>The minimum tile dimension allowed is 16. If such small tiles are * used, it is recommended to use smoothing, because without smoothing, each * small tile determines the splitting threshold independently. A tile that * is entirely in the image bg will then hallucinate fg, resulting in a very * noisy binarization. The smoothing should be large enough that no tile is * only influenced by one type (fg or bg) of pixels, because it will force a * split of its pixels. * <li>To get a single global threshold for the entire image, use input * values of sizeX and sizeY that are larger than the image. For this * situation, the smoothing parameters are ignored. * <li>The threshold values partition the image pixels into two classes: one * whose values are less than the threshold and another whose values are * greater than or equal to the threshold. This is the same use of * 'threshold' as in pixThresholdToBinary(). * <li>The scorefract is the fraction of the maximum Otsu score, which is * used to determine the range over which the histogram minimum is searched. * See numaSplitDistribution() for details on the underlying method of * choosing a threshold. * <li>This uses enables a modified version of the Otsu criterion for * splitting the distribution of pixels in each tile into a fg and bg part. * The modification consists of searching for a minimum in the histogram * over a range of pixel values where the Otsu score is within a defined * fraction, scoreFraction, of the max score. To get the original Otsu * algorithm, set scoreFraction == 0. * </ol> * * @param pixs An 8 bpp PIX source image. * @param sizeX Desired tile X dimension; actual size may vary. * @param sizeY Desired tile Y dimension; actual size may vary. * @param smoothX Half-width of convolution kernel applied to threshold * array: use 0 for no smoothing. * @param smoothY Half-height of convolution kernel applied to threshold * array: use 0 for no smoothing. * @param scoreFraction Fraction of the max Otsu score; typ. 0.1 (use 0.0 * for standard Otsu). * @return A 1 bpp thresholded PIX image. */ public static Pix otsuAdaptiveThreshold( Pix pixs, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFraction) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixs.getDepth() != 8) throw new IllegalArgumentException("Source pix depth must be 8bpp"); int nativePix = nativeOtsuAdaptiveThreshold( pixs.mNativePix, sizeX, sizeY, smoothX, smoothY, scoreFraction); if (nativePix == 0) throw new RuntimeException("Failed to perform Otsu adaptive threshold on image"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeOtsuAdaptiveThreshold( int nativePix, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFract); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * @author alanv@google.com (Alan Viverette) */ public class Rotate { static { System.loadLibrary("lept"); } // Rotation default /** Default rotation quality is high. */ public static final boolean ROTATE_QUALITY = true; /** * Performs rotation using the default parameters. * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees) { return rotate(pixs, degrees, false); } /** * Performs rotation with resizing using the default parameters. * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @param quality Whether to use high-quality rotation. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees, boolean quality) { return rotate(pixs, degrees, quality, true); } /** * Performs basic image rotation about the center. * <p> * Notes: * <ol> * <li>Rotation is about the center of the image. * <li>For very small rotations, just return a clone. * <li>Rotation brings either white or black pixels in from outside the * image. * <li>Above 20 degrees, if rotation by shear is requested, we rotate by * sampling. * <li>Colormaps are removed for rotation by area map and shear. * <li>The dest can be expanded so that no image pixels are lost. To invoke * expansion, input the original width and height. For repeated rotation, * use of the original width and height allows the expansion to stop at the * maximum required size, which is a square with side = sqrt(w*w + h*h). * </ol> * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @param quality Whether to use high-quality rotation. * @param resize Whether to expand the output so that no pixels are lost. * <strong>Note:</strong> 1bpp images are always resized when * quality is {@code true}. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees, boolean quality, boolean resize) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeRotate(pixs.mNativePix, degrees, quality, resize); if (nativePix == 0) return null; return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeRotate(int nativePix, float degrees, boolean quality, boolean resize); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image rotation and skew detection methods. * * @author alanv@google.com (Alan Viverette) */ public class Skew { static { System.loadLibrary("lept"); } // Text alignment defaults /** Default range for sweep, will detect rotation of + or - 30 degrees. */ public final static float SWEEP_RANGE = 30.0f; /** Default sweep delta, reasonably accurate within 0.05 degrees. */ public final static float SWEEP_DELTA = 5.0f; /** Default sweep reduction, one-eighth the size of the original image. */ public final static int SWEEP_REDUCTION = 8; /** Default sweep reduction, one-fourth the size of the original image. */ public final static int SEARCH_REDUCTION = 4; /** Default search minimum delta, reasonably accurate within 0.05 degrees. */ public final static float SEARCH_MIN_DELTA = 0.01f; /** * Finds and returns the skew angle using default parameters. * * @param pixs Input pix (1 bpp). * @return the detected skew angle, or 0.0 on failure */ public static float findSkew(Pix pixs) { return findSkew(pixs, SWEEP_RANGE, SWEEP_DELTA, SWEEP_REDUCTION, SEARCH_REDUCTION, SEARCH_MIN_DELTA); } /** * Finds and returns the skew angle, doing first a sweep through a set of * equal angles, and then doing a binary search until convergence. * <p> * Notes: * <ol> * <li>In computing the differential line sum variance score, we sum the * result over scanlines, but we always skip: * <ul> * <li>at least one scanline * <li>not more than 10% of the image height * <li>not more than 5% of the image width * </ul> * </ol> * * @param pixs Input pix (1 bpp). * @param sweepRange Half the full search range, assumed about 0; in * degrees. * @param sweepDelta Angle increment of sweep; in degrees. * @param sweepReduction Sweep reduction factor = 1, 2, 4 or 8. * @param searchReduction Binary search reduction factor = 1, 2, 4 or 8; and * must not exceed redsweep. * @param searchMinDelta Minimum binary search increment angle; in degrees. * @return the detected skew angle, or 0.0 on failure */ public static float findSkew(Pix pixs, float sweepRange, float sweepDelta, int sweepReduction, int searchReduction, float searchMinDelta) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); return nativeFindSkew(pixs.mNativePix, sweepRange, sweepDelta, sweepReduction, searchReduction, searchMinDelta); } // *************** // * NATIVE CODE * // *************** private static native float nativeFindSkew(int nativePix, float sweepRange, float sweepDelta, int sweepReduction, int searchReduction, float searchMinDelta); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image adaptive mapping methods. * * @author alanv@google.com (Alan Viverette) */ public class AdaptiveMap { static { System.loadLibrary("lept"); } // Background normalization constants /** Image reduction value; possible values are 1, 2, 4, 8 */ private final static int NORM_REDUCTION = 16; /** Desired tile size; actual size may vary */ private final static int NORM_SIZE = 3; /** Background brightness value; values over 200 may result in clipping */ private final static int NORM_BG_VALUE = 200; /** * Normalizes an image's background using default parameters. * * @param pixs A source pix image. * @return the source pix image with a normalized background */ public static Pix backgroundNormMorph(Pix pixs) { return backgroundNormMorph(pixs, NORM_REDUCTION, NORM_SIZE, NORM_BG_VALUE); } /** * Normalizes an image's background to a specified value. * <p> * Notes: * <ol> * <li>This is a top-level interface for normalizing the image intensity by * mapping the image so that the background is near the input value 'bgval'. * <li>The input image is either grayscale or rgb. * <li>For each component in the input image, the background value is * estimated using a grayscale closing; hence the 'Morph' in the function * name. * <li>An optional binary mask can be specified, with the foreground pixels * typically over image regions. The resulting background map values will be * determined by surrounding pixels that are not under the mask foreground. * The origin (0,0) of this mask is assumed to be aligned with the origin of * the input image. This binary mask must not fully cover pixs, because then * there will be no pixels in the input image available to compute the * background. * <li>The map is computed at reduced size (given by 'reduction') from the * input pixs and optional pixim. At this scale, pixs is closed to remove * the background, using a square Sel of odd dimension. The product of * reduction * size should be large enough to remove most of the text * foreground. * <li>No convolutional smoothing needs to be done on the map before * inverting it. * <li>A 'bgval' target background value for the normalized image. This * should be at least 128. If set too close to 255, some clipping will occur * in the result. * </ol> * * @param pixs A source pix image. * @param normReduction Reduction at which morphological closings are done. * @param normSize Size of square Sel for the closing. * @param normBgValue Target background value. * @return the source pix image with a normalized background */ public static Pix backgroundNormMorph( Pix pixs, int normReduction, int normSize, int normBgValue) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeBackgroundNormMorph( pixs.mNativePix, normReduction, normSize, normBgValue); if (nativePix == 0) throw new RuntimeException("Failed to normalize image background"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeBackgroundNormMorph( int nativePix, int reduction, int size, int bgval); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image sharpening methods. * * @author alanv@google.com (Alan Viverette) */ public class Enhance { static { System.loadLibrary("lept"); } /** * Performs unsharp masking (edge enhancement). * <p> * Notes: * <ul> * <li>We use symmetric smoothing filters of odd dimension, typically use * sizes of 3, 5, 7, etc. The <code>halfwidth</code> parameter for these is * (size - 1)/2; i.e., 1, 2, 3, etc.</li> * <li>The <code>fract</code> parameter is typically taken in the range: 0.2 * &lt; <code>fract</code> &lt; 0.7</li> * </ul> * * @param halfwidth The half-width of the smoothing filter. * @param fraction The fraction of edge to be added back into the source * image. * @return an edge-enhanced Pix image or copy if no enhancement requested */ public static Pix unsharpMasking(Pix pixs, int halfwidth, float fraction) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeUnsharpMasking(pixs.mNativePix, halfwidth, fraction); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeUnsharpMasking(int nativePix, int halfwidth, float fract); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * JPEG input and output methods. * * @author alanv@google.com (Alan Viverette) */ public class JpegIO { static { System.loadLibrary("lept"); } /** Default quality is 85%, which is reasonably good. */ public static final int DEFAULT_QUALITY = 85; /** Progressive encoding is disabled by default to increase compatibility. */ public static final boolean DEFAULT_PROGRESSIVE = false; /** * Returns a compressed JPEG byte representation of this Pix using default * parameters. * * @param pixs * @return a compressed JPEG byte array representation of the Pix */ public static byte[] compressToJpeg(Pix pixs) { return compressToJpeg(pixs, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE); } /** * Returns a compressed JPEG byte representation of this Pix. * * @param pixs A source pix image. * @param quality The quality of the compressed image. Valid range is 0-100. * @param progressive Whether to use progressive compression. * @return a compressed JPEG byte array representation of the Pix */ public static byte[] compressToJpeg(Pix pixs, int quality, boolean progressive) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (quality < 0 || quality > 100) throw new IllegalArgumentException("Quality must be between 0 and 100 (inclusive)"); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); final Bitmap bmp = WriteFile.writeBitmap(pixs); bmp.compress(CompressFormat.JPEG, quality, byteStream); bmp.recycle(); final byte[] encodedData = byteStream.toByteArray(); try { byteStream.close(); } catch (IOException e) { e.printStackTrace(); } return encodedData; } // *************** // * NATIVE CODE * // *************** private static native byte[] nativeCompressToJpeg( int nativePix, int quality, boolean progressive); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Leptonica constants. * * @author alanv@google.com (Alan Viverette) */ public class Constants { /*-------------------------------------------------------------------------* * Access and storage flags * *-------------------------------------------------------------------------*/ /* * For Pix, Box, Pta and Numa, there are 3 standard methods for handling the * retrieval or insertion of a struct: (1) direct insertion (Don't do this * if there is another handle somewhere to this same struct!) (2) copy * (Always safe, sets up a refcount of 1 on the new object. Can be * undesirable if very large, such as an image or an array of images.) (3) * clone (Makes another handle to the same struct, and bumps the refcount up * by 1. Safe to do unless you're changing data through one of the handles * but don't want those changes to be seen by the other handle.) For Pixa * and Boxa, which are structs that hold an array of clonable structs, there * is an additional method: (4) copy-clone (Makes a new higher-level struct * with a refcount of 1, but clones all the structs in the array.) Unlike * the other structs, when retrieving a string from an Sarray, you are * allowed to get a handle without a copy or clone (i.e., that you don't * own!). You must not free or insert such a string! Specifically, for an * Sarray, the copyflag for retrieval is either: TRUE (or 1 or L_COPY) or * FALSE (or 0 or L_NOCOPY) For insertion, the copyflag is either: TRUE (or * 1 or L_COPY) or FALSE (or 0 or L_INSERT) Note that L_COPY is always 1, * and L_INSERT and L_NOCOPY are always 0. */ /* Stuff it in; no copy, clone or copy-clone */ public static final int L_INSERT = 0; /* Make/use a copy of the object */ public static final int L_COPY = 1; /* Make/use clone (ref count) of the object */ public static final int L_CLONE = 2; /* * Make a new object and fill with with clones of each object in the * array(s) */ public static final int L_COPY_CLONE = 3; /*--------------------------------------------------------------------------* * Sort flags * *--------------------------------------------------------------------------*/ /* Sort in increasing order */ public static final int L_SORT_INCREASING = 1; /* Sort in decreasing order */ public static final int L_SORT_DECREASING = 2; /* Sort box or c.c. by horiz location */ public static final int L_SORT_BY_X = 3; /* Sort box or c.c. by vert location */ public static final int L_SORT_BY_Y = 4; /* Sort box or c.c. by width */ public static final int L_SORT_BY_WIDTH = 5; /* Sort box or c.c. by height */ public static final int L_SORT_BY_HEIGHT = 6; /* Sort box or c.c. by min dimension */ public static final int L_SORT_BY_MIN_DIMENSION = 7; /* Sort box or c.c. by max dimension */ public static final int L_SORT_BY_MAX_DIMENSION = 8; /* Sort box or c.c. by perimeter */ public static final int L_SORT_BY_PERIMETER = 9; /* Sort box or c.c. by area */ public static final int L_SORT_BY_AREA = 10; /* Sort box or c.c. by width/height ratio */ public static final int L_SORT_BY_ASPECT_RATIO = 11; /* ------------------ Image file format types -------------- */ /* * The IFF_DEFAULT flag is used to write the file out in the same (input) * file format that the pix was read from. If the pix was not read from * file, the input format field will be IFF_UNKNOWN and the output file * format will be chosen to be compressed and lossless; namely, IFF_TIFF_G4 * for d = 1 and IFF_PNG for everything else. IFF_JP2 is for jpeg2000, which * is not supported in leptonica. */ public static final int IFF_UNKNOWN = 0; public static final int IFF_BMP = 1; public static final int IFF_JFIF_JPEG = 2; public static final int IFF_PNG = 3; public static final int IFF_TIFF = 4; public static final int IFF_TIFF_PACKBITS = 5; public static final int IFF_TIFF_RLE = 6; public static final int IFF_TIFF_G3 = 7; public static final int IFF_TIFF_G4 = 8; public static final int IFF_TIFF_LZW = 9; public static final int IFF_TIFF_ZIP = 10; public static final int IFF_PNM = 11; public static final int IFF_PS = 12; public static final int IFF_GIF = 13; public static final int IFF_JP2 = 14; public static final int IFF_DEFAULT = 15; public static final int IFF_SPIX = 16; }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image scaling methods. * * @author alanv@google.com (Alan Viverette) */ public class Scale { static { System.loadLibrary("lept"); } public enum ScaleType { /* Scale in X and Y independently, so that src matches dst exactly. */ FILL, /* * Compute a scale that will maintain the original src aspect ratio, but * will also ensure that src fits entirely inside dst. May shrink or * expand src to fit dst. */ FIT, /* * Compute a scale that will maintain the original src aspect ratio, but * will also ensure that src fits entirely inside dst. May shrink src to * fit dst, but will not expand it. */ FIT_SHRINK, } /** * Scales the Pix to a specified width and height using a specified scaling * type (fill, stretch, etc.). Returns a scaled image or a clone of the Pix * if no scaling is required. * * @param pixs * @param width * @param height * @param type * @return a scaled image or a clone of the Pix if no scaling is required */ public static Pix scaleToSize(Pix pixs, int width, int height, ScaleType type) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int pixWidth = pixs.getWidth(); int pixHeight = pixs.getHeight(); float scaleX = width / (float) pixWidth; float scaleY = height / (float) pixHeight; switch (type) { case FILL: // Retains default scaleX and scaleY values break; case FIT: scaleX = Math.min(scaleX, scaleY); scaleY = scaleX; break; case FIT_SHRINK: scaleX = Math.min(1.0f, Math.min(scaleX, scaleY)); scaleY = scaleX; break; } return scale(pixs, scaleX, scaleY); } /** * Scales the Pix to specified scale. If no scaling is required, returns a * clone of the source Pix. * * @param pixs the source Pix * @param scale dimension scaling factor * @return a Pix scaled according to the supplied factors */ public static Pix scale(Pix pixs, float scale) { return scale(pixs, scale, scale); } /** * Scales the Pix to specified x and y scale. If no scaling is required, * returns a clone of the source Pix. * * @param pixs the source Pix * @param scaleX x-dimension (width) scaling factor * @param scaleY y-dimension (height) scaling factor * @return a Pix scaled according to the supplied factors */ public static Pix scale(Pix pixs, float scaleX, float scaleY) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (scaleX <= 0.0f) throw new IllegalArgumentException("X scaling factor must be positive"); if (scaleY <= 0.0f) throw new IllegalArgumentException("Y scaling factor must be positive"); int nativePix = nativeScale(pixs.mNativePix, scaleX, scaleY); if (nativePix == 0) throw new RuntimeException("Failed to natively scale pix"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeScale(int nativePix, float scaleX, float scaleY); }
Java
import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class Client { /** * @param args * @throws IOException * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException, IOException { Socket socket = new Socket("127.0.0.1", 8080); Scanner socketIn = new Scanner(socket.getInputStream()); PrintWriter socketOut = new PrintWriter(socket.getOutputStream(), true); while (true) { try { Scanner s = new Scanner(System.in); String string = s.nextLine(); socketOut.println(string); } catch(Exception e) { } } } }
Java
import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8080); Socket socket = serverSocket.accept(); System.out.println("Server Started"); Scanner socketIn = new Scanner(socket.getInputStream()); PrintWriter socketOut = new PrintWriter(socket.getOutputStream(), true); while (true) { try { String line = socketIn.nextLine(); System.out.println(line); } catch(Exception e) { } } } }
Java
package DBComm; import java.util.Date; public class ChatMessage { private String mySender; private String myReciever; private String myText; private Long mySrvTimeStamp; private Long myClintTimeStamp; public ChatMessage(){ this.mySender = ""; this.setMyReciever(""); this.myText = ""; this.mySrvTimeStamp = System.currentTimeMillis(); } public ChatMessage(String sender, String reciever, String text){ this.mySender = sender; this.setMyReciever(reciever); this.myText = text; this.mySrvTimeStamp = System.currentTimeMillis(); } public String getMessage(){ return this.myText; } public void setMessage(String text){ this.myText = text; } public String getSender(){ return this.mySender; } public void setSender(String sender){ this.mySender = sender; } public Long getClientTimeStamp(){ return this.myClintTimeStamp; } public void setReciever(Long timeStamp){ this.myClintTimeStamp = timeStamp; } public Long getServerTimeStamp(){ return this.mySrvTimeStamp; } public void setMyReciever(String myReciever) { this.myReciever = myReciever; } public String getMyReciever() { return myReciever; } }
Java
package DBComm; // ReturnCodes.java // A class consisting of static return codes and nothing else // ex: return ReturnCodes.SUCCESS public class ReturnCodes { // general / server response code(s) public static int SERVER_ERROR = 0; public static int SUCCESS = 1; // specific login response code(s) public static int BAD_PASSWORD = 2; public static int INVALID_LOGIN = 3; // specific buddy list response code(s) public static int BUDDY_DOES_NOT_EXIST = 4; public static int FAILED_TO_ADD_BUDDY = 5; public static int FAILED_TO_DELETE_BUDDY = 6; // specific duplication response code(s) public static int EVENT_EXISTS_ALREADY = 7; }
Java
package DBComm; import java.util.ArrayList; //Dan Morgan public class Configuration { private ArrayList<String> _configuration; //index 0 = _clientID; //index 1 = _tabFill; //index 2 =_tabStroke; //index 3 = _windowFill; //index 4 = _windowStroke; //index 5 = _chatWindowColor; //index 6 = _textColor; //Constructor public Configuration(){ _configuration = new ArrayList<String>(7); //inserting dummy values because java is dumb for(int i = 0; i < 7; i++){ _configuration.add(null); } } //Provide a field to update and the update value public void updateConfiguration(int index, String update){ if(index >= 0 && index <= 6){ _configuration.set(index, update); } else{ System.err.println("Invalid input, please try again."); } } //if you want to get a specific configuration value, specify that field /* * Commenting this out for now as I figure you can just get the configuration array list and specify the index you want, it'd be faster. public String getConfigurationSetting(String field){ if(field.equals("clientID")){ return _configuration.get(0); } else if(field.equals("tabFill")){ return _configuration.get(1); } else if(field.equals("tabStroke")){ return _configuration.get(2); } else if(field.equals("windowFill")){ return _configuration.get(3); } else if(field.equals("windowStroke")){ return _configuration.get(4); } else if(field.equals("chatWindowColor")){ return _configuration.get(5); } else if(field.equals("textColor")){ return _configuration.get(6); } else{ System.err.println("Invalid input, please try again."); return field; } } */ public ArrayList<String> getConfiguration(){ return _configuration; } }
Java
package DBComm; //Hold Stats regarding IMing activity // //Scott J. Ditch public class Stats { private int messages; private int aveLength; private int fileShares; private int statusChanges; private int users; private int buddies; private int currentMessages; private long startTime; public Stats() { System.out.println("Building Stats"); startTime = System.currentTimeMillis(); } public void addMessage(int length) { messages++; currentMessages++; aveLength = ((messages * aveLength) + length)/ messages; } public void fileShared() { fileShares++; } public void changedStatus() { statusChanges++; } public void adduser() { users++; } public void moreBuddies() { buddies++; } public void removedBuddy() { buddies--; } //Give the time the program has been running in milliseconds. private long getTimeRunning() { return ((System.currentTimeMillis()) - startTime); } // //RETURN METHODS // // // public int getMessgaes() // { // return messages; // } // // public int getAverageLength() // { // return aveLength; // } // // public int getFilesShared() // { // return fileShares; // } // // public int getStatusChanges() // { // return statusChanges; // } public void printStats() { System.out.println("\n Stats: \n"); System.out.println(" The amount of messages sent: " + messages); System.out.println(" The average length of messages sent: " + aveLength); System.out.println(" The amount of files shared: " + fileShares); System.out.println(" The amount of status changes: " + statusChanges); System.out.println(" New users this session: " + users); System.out.println(" Buddies linked session: " + buddies); System.out.println(" Time the DBComm has been running (Milliseconds): " + getTimeRunning()); } }
Java
package DBComm; import java.sql.SQLException; import java.util.ArrayList; import messages.ChatMessage; // DBComm is the class responsible for reading and writing information to the database. An SQL implementation of a // database has been used for this project. A jdbc driver is also used and an additional library is needed to // establish this connection: mysql-connector-java-5.1.7-bin.jar. public class DBComm{ private java.sql.Connection con = null; private final String url = "jdbc:mysql://"; private final String serverName= "teambananas2.ics.uci.edu"; //Scott's Server IP: teambananas2.ics.uci.edu //Robert's IP 192.168.0.102 private final String portNumber = "987"; //MySQL: 987 (Robert), 3306 (Dan local). SQL Server 2008: 50479 private final String databaseName= "pIMp"; private final String userName = "pIMpAdmin"; //root private final String password = "ainteasy"; //Scott's root password: LopesSucksASS //pIMpAdmin: ainteasy private static Stats stats; //Hold the Statistics regarding IM activity to be reported to the admin //private final String selectMethod = "cursor"; // Constructor public DBComm(){ //Instantiate the database connection. //I think the max number of requests we can make to the MySQL server through one of these connections is 500 (at a time). //Or, we can make 500 max connections at a time. I know we can re-use connections; we don't have to make a new connection every time we want to do something //(and then close it afterward). This is easy for a small number of requests, but once we start scaling it up, I think we'll have to make multiple DBComm //objects, which will make multiple connections. //TODO test how many connections we can make. try{ con = this.getConnection(); } catch(Exception e){ e.printStackTrace(); } stats = new Stats(); } private String getConnectionUrl(){ //MS SQL Server //return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";"; //MySQL return url+serverName+":"+portNumber+"/"+databaseName+"?"; } private java.sql.Connection getConnection(){ try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password); if(con!=null) System.out.println("Connection Successful!" + "\n"); }catch(Exception e){ e.printStackTrace(); System.err.println("Error Trace in getConnection() : " + e.getMessage()); } return con; } // Robert Jolly // Method responsible for adding a chat message into the database. Returns a value of 1 if successful. Otherwise // it will need to return a number corresponding to the error message provided. public int addMessage(String from, String message, String to){ java.sql.Statement st = null; int retVal = 0; //SERVER ERROR String insertChat = "INSERT INTO chatlist (`from`, `messages`, `to`, `type`,`offline`) " + "VALUES ('" + from + "', '" + message + "', '" + to + "', 0, 1);"; int i; System.out.println(insertChat); try { st = con.createStatement(); i = st.executeUpdate(insertChat); if (i == 1){ retVal = 1; //SUCCESS System.out.println("Message Added."); //FOR STATS - Scott stats.addMessage(message.length()); } else{ retVal = 3; //Most likely to or from doesn't exist, so just say invalid login } st.close(); st = null; } catch (SQLException e) { retVal = 0; //Should be a server error...most likely it would be con.creatStatement() that failed. System.err.println(e); } addWebEvent(to, 1); return retVal; } // Robert Jolly // Method responsible for adding a chat message into the database. Returns a value of 1 if successful. Otherwise // it will need to return a number corresponding to the error message provided. public int addClientMessage(String from, String message, String to){ java.sql.Statement st = null; int retVal = 0; String insertChat = "INSERT INTO chatlist (`from`, `messages`, `to`, `type`) " + "VALUES ('" + from + "', '" + message + "', '" + to + "',0);"; int i; System.out.println(insertChat); try { st = con.createStatement(); i = st.executeUpdate(insertChat); if (i == 1){ retVal = 1; System.out.println("Message Added."); //FOR STATS - Scott stats.addMessage(message.length()); } else retVal = 0; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } addWebEvent(to, 1); return retVal; } // Robert Jolly // Method responsible for returning an ArrayList of Chat Message Objects. Each message is stored as one row in the // database table 'chatlog'. public ArrayList<ChatMessage> getMessage(String recipient){ ChatMessage chat = new ChatMessage(); ArrayList<ChatMessage> messages = new ArrayList<ChatMessage>(); java.sql.Statement st = null; java.sql.ResultSet rs = null; String getChat = "SELECT * FROM chatlist WHERE `to`='"+ recipient + "' AND type = 0;"; String updateChat = "UPDATE chatlist set type = 1 where chatlist.to = '" + recipient + "';"; try { st = con.createStatement(); rs = st.executeQuery(getChat); while (rs.next()){ System.out.println("from: " + rs.getString("from")); chat = new ChatMessage(rs.getString("from"), rs.getString("to"), rs.getString("messages")); messages.add(chat); } st = con.createStatement(); int i = st.executeUpdate(updateChat); if(i == 1){ //update successful } rs.close(); rs = null; st.close(); st = null; } catch (SQLException e) { System.err.println(e); } return messages; } // Robert Jolly // Method responsible for returning an ArrayList of Chat Message Objects. Each message is stored as one row in the // database table 'chatlog'. public ArrayList<ChatMessage> getClientMessage(String recipient){ ChatMessage chat = new ChatMessage(); ArrayList<ChatMessage> messages = new ArrayList<ChatMessage>(); java.sql.Statement st = null; java.sql.ResultSet rs = null; String getChat = "SELECT * FROM chatlist WHERE `to`='"+ recipient + "' AND type = 0; AND offline = 0"; String updateChat = "UPDATE chatlist set type = 1 where chatlist.to = '" + recipient + "';"; try { st = con.createStatement(); rs = st.executeQuery(getChat); while (rs.next()){ System.out.println("from: " + rs.getString("from")); chat = new ChatMessage(rs.getString("from"), rs.getString("to"), rs.getString("messages")); messages.add(chat); } st = con.createStatement(); int i = st.executeUpdate(updateChat); if(i == 1){ //update successful } rs.close(); rs = null; st.close(); st = null; } catch (SQLException e) { System.err.println(e); } return messages; } //Dan Morgan //This method updates the status, an integer, of the specified client. public int updateStatus(String clientid, int status){ int retVal = 0; //server error java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectClient = "SELECT * FROM client where clientid = '" + clientid + "';"; String updateStatus = "UPDATE client set status = '" + status + "' WHERE clientid = '" + clientid + "';"; try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectClient); //check if the clientid exists before updating the status if(rs.next()){ //if they exist, we can try to update their status try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. int i = st.executeUpdate(updateStatus); if(i == 1){ retVal = 1;//updateStatus successful System.out.println("updateStatus successful." + "\n"); //FOR STATS - SCOTT stats.changedStatus(); } } catch(Exception e) { System.err.println("updateStatus failed." + "\n"); System.err.println(e + "\n"); retVal = 0; //Server error...we found the client but the executeUpdate failed } } retVal = 3; //invalid login rs.close(); rs = null; st.close(); st = null; } else{ retVal = 0; //Server error...con.creatStatement most likely failed. System.out.println("Error: No active Connection" + "\n"); } }catch(Exception e){ retVal = 0; //server error, con not created System.err.println(e + "\n"); } this.updateBuddies(clientid); //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method gets the status, as an integer, of the specified client. //If this method returns -1, an error occured public int getStatus(String clientid){ int retVal = -1; //server error java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectStatus = "SELECT status FROM client where clientid = '" + clientid + "';"; try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectStatus); //rs.next() will return true if the client exists if(rs.next()){ //if it's true, we found the clientid, and can extract their status retVal = new Integer(rs.getString(1)).intValue(); } else{ System.err.println("That clientID does not exist. Please try another"); retVal = 3; //invalid login } rs.close(); rs = null; st.close(); st = null; }else{ retVal = 0; //server error System.err.println("Error: No active Connection" + "\n"); } }catch(Exception e){ System.err.println(e + "\n"); retVal = 0; //server error } return retVal; } //Robert Jolly // This will add a webevent to the database table. public int addWebEvent(String clientID, int type){ java.sql.Statement st = null; String insertEvent = "INSERT INTO event(ClientID, Type) " + "VALUES('" + clientID + "', " + type + ");"; String update1 = "UPDATE event SET Type=1 WHERE ClientID = '" + clientID + "';"; String update2 = "UPDATE event SET Type=2 WHERE ClientID = '" + clientID + "';"; String update3 = "UPDATE event SET Type=3 WHERE ClientID = '" + clientID + "';"; int retVal = 0; //Server Error try{ if(con!=null){ int checker = getWebEvent(clientID); System.out.println(checker); if (checker == 1 && type == 1){ st = con.createStatement(); st.executeUpdate(update1); retVal = 1; } else if (checker == 2 && type == 1){ st = con.createStatement(); st.executeUpdate(update3); retVal = 1; } else if (checker == 3 && type == 1){ st = con.createStatement(); st.executeUpdate(update3); retVal = 1; } else if (checker == 2 && type == 3){ st = con.createStatement(); st.executeUpdate(update2); retVal = 1; } else if (checker == 3 && type == 2){ st = con.createStatement(); st.executeUpdate(update3); retVal = 1; } else if (checker == 1 && type == 2){ st = con.createStatement(); st.executeUpdate(update3); retVal = 1; } else if (checker == 1 && type == 3){ System.out.println(update3); st = con.createStatement(); st.executeUpdate(update3); retVal = 1; } else if (checker == 3 && type == 3){ st = con.createStatement(); st.executeUpdate(update3); retVal = 1; } else st = con.createStatement(); st.executeUpdate(insertEvent); retVal = 1; //Currently 1 & add 1 //Currently 2 & add 1 make it a three //Currently 3 & add 1 make it a three //Current 2 & and add 2 stay a two //Currently 2 & add a three, becomes a three //Cureently 3 & add a two remains a three //Currently 1 & add a 2 it remains a three //Currently 1 and add a three it will become a three //Currently a three and want to add a three it will remain a three //if nothing then it will put in anything. } st.close(); st = null; } //if the event is already present, it will throw an exception catch(Exception e) { System.err.println("Your event is already present." + "\n"); System.err.println(e); retVal = 7; //Your event is already present } //return the error/success code to the caller so they can quickly parse what happened return retVal; } public int clearEvent(String clientID){ java.sql.Statement st = null; String deleteEvent = "DELETE FROM event WHERE ClientID='" + clientID + "';"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); retVal = st.executeUpdate(deleteEvent); } st.close(); st = null; } //if the event is already present, it will throw an exception catch(Exception e) { System.err.println("Event not found." + "\n"); System.err.println(e + "\n"); retVal = 7; //Your event is already present } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Chad Curtis // This will return a webevent from the database table. public int updateBuddies(String clientID){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectEvent = "SELECT clientID FROM Buddy b WHERE b.Buddy='" + clientID + "';"; System.out.println(selectEvent); int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectEvent); //iterate through the results and add them to the Events while(rs.next()){ //if it's true, we found the clientid, and can extract their status addWebEvent(rs.getString(1), 2); retVal = 1; } } rs.close(); rs = null; st.close(); st = null; } //if the event is already present, it will throw an exception catch(Exception e) { System.err.println("Your event is already present." + "\n"); System.err.println(e + "\n"); retVal = 7; //Your event is already present } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Robert Jolly // This will return a webevent from the database table. public int getWebEvent(String clientID){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectEvent = "SELECT type FROM event WHERE ClientID='" + clientID + "';"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectEvent); //rs.next() will return true if the client exists if(rs.next()){ //if it's true, we found the clientid, and can extract their status retVal = new Integer(rs.getString(1)).intValue(); } } rs.close(); rs = null; st.close(); st = null; } //if the event is already present, it will throw an exception catch(Exception e) { System.err.println("Your event is already present." + "\n"); System.err.println(e + "\n"); retVal = 7; //Your event is already present } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method will add a buddy to the buddy table. //ClientID is the person adding the buddy. //Buddy is...the buddy. //Group is their group in the buddy list (all buddies, friends, etc). public int addBuddy(String clientID, String buddy, String group){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectClient = "SELECT clientid FROM Client WHERE clientID = '" + clientID + "';"; String selectBuddy = "SELECT clientid FROM Client WHERE clientID = '" + buddy + "';"; String insertBuddy = "INSERT INTO buddy (clientid, buddy, usergroup) VALUES ('" + clientID + "','" + buddy + "','"+ group + "');"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectClient); //check if the original client exists //rs.next() will return true if the select statement found the client in the database, meaning he exists if(rs.next()){ //if he exists, now we check if the buddy we're adding exists rs = st.executeQuery(selectBuddy); if(rs.next()){ //if both exist, we can add the buddy try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. int i = st.executeUpdate(insertBuddy); if(i == 1){ retVal = 1;//addBuddy successful System.out.println("AddBuddy successful." + "\n"); //FOR STATS - Scott stats.moreBuddies(); } } //if the two are already buddies, it will throw an exception catch(Exception e) { //e.printStackTrace(); System.err.println("Your users are already buddies." + "\n"); System.err.println(e + "\n"); retVal = 5; //Your users are already buddies } } } else { retVal = 3;//Invalid ClientID } rs.close(); rs = null; st.close(); st = null; }else System.err.println("Error: No active Connection" + "\n"); }catch(Exception e){ e.printStackTrace(); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method will remove a buddy from the buddy table. //You must supply the ClientID (the person removing the buddy), the Buddy (the buddy to be removed), and the buddy's group (all buddies, friends, etc). //The reason is all three are primary keys in the database, so you must supply all three. public int removeBuddy(String clientID, String buddy, String group){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectBuddy = "SELECT ClientID, Buddy, UserGroup FROM Buddy WHERE ClientID = '" + clientID + "' AND Buddy = '" + buddy + "' AND UserGroup = '" + group + "';"; String deleteBuddy = "DELETE FROM buddy WHERE clientID = '" + clientID + "' AND buddy = '" + buddy + "' AND userGroup ='"+ group + "'"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectBuddy); //check and see if the buddy exists in the table //rs.next() will return true if the select statement found the buddy in the database, meaning he exists if(rs.next()){ //if they exist, we can try to delete the buddy try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. int i = st.executeUpdate(deleteBuddy); if(i == 1){ retVal = 1;//removeBuddy successful System.out.println("RemoveBuddy successful." + "\n"); } } catch(Exception e) { //e.printStackTrace(); System.err.println("Remove buddy failed." + "\n"); System.err.println(e + "\n"); retVal = 6; //TODO what is this error } } else { retVal = 3;//Invalid buddy, cannot delete because it doesn't exist } rs.close(); rs = null; st.close(); st = null; }else System.err.println("Error: No active Connection" + "\n"); }catch(Exception e){ //e.printStackTrace(); System.err.println(e + "\n"); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method will return a buddylist object, which is basically an arraylist of buddy strings. public BuddyList getBuddyList(String clientid){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectBuddys = "SELECT b.buddy, c.status FROM buddy b, client c WHERE b.clientid = '" + clientid + "' AND b.buddy = c.clientid;"; BuddyList buddyList = new BuddyList(); try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectBuddys); //iterate through the results and add them to the BuddyList while (rs.next()){ buddyList.addBuddy( new Buddy(rs.getString(1), Integer.parseInt(rs.getString(2)))); } rs.close(); rs = null; st.close(); st = null; }else System.out.println("Error: No active Connection" + "\n"); }catch(Exception e){ System.err.println(e + "\n"); } return buddyList; } // Robert Jolly public String getChatHistory(String clientID){ String history = ""; java.sql.ResultSet rs = null; java.sql.Statement st = null; String chatHistory = "SELECT ChatLog FROM chatlog WHERE ClientID = '" + clientID + "';"; try{ if (con!=null){ st = con.createStatement(); rs = st.executeQuery(chatHistory); history = rs.getString(1); } rs.close(); rs = null; st.close(); st = null; } catch(Exception e){ System.out.println("Unable to retrieve chat history."); System.err.println(e + "\n"); } return history; } public int verifyLogin(String loginID, String password){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectPassword = "SELECT password FROM Client WHERE clientID = '" + loginID + "' AND lockedout = 0;"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectPassword); //rs.next() will return true if the select statement found the client in the database, meaning he exists, and if the client is not locked out. if(rs.next()){ //if he exists, we check the password if(password.equals(rs.getString(1))){ retVal = 1;//Login successful } else{ retVal = 2;//Bad password } } else { retVal = 3;//Invalid ClientID, or the client is locked out. } rs.close(); rs = null; st.close(); st = null; }else System.err.println("Error: No active Connection" + "\n"); }catch(Exception e){ System.err.println(e + "\n"); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method will register a new user with the client. You must supply a clientID and a password. //adds a new user to the client table and sets default configurations in the configuration table //TODO for later would be allowing updating of email, status, and lockedout. public int registerUser(String clientID, String password){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectClient = "SELECT clientid FROM Client WHERE clientID = '" + clientID + "';"; //status and lockedout will default to 0 //email will default null //insert time timestamp when this method is called. long timestamp = System.currentTimeMillis(); String insertClient = "INSERT INTO Client (clientid, email, password, status, lockedout, timestamp) VALUES ('" + clientID + "',null,'"+ password + "',0,0,"+ timestamp + ");"; //the default configuration String insertConfiguration = "INSERT INTO configuration (clientid, tabfill, tabstroke, windowfill, windowstroke, chatwindowcolor, textcolor) VALUES" + " ('" + clientID + "','0x000000','0x000000','0x000000','0x000000','0x000000','0x000000');"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectClient); //check if the clientid already exists //rs.next() will return true if the select statement found the client in the database, meaning he exists //therefore, we want !rs.next() if(!rs.next()){ //if he doesn't exist, we can add him try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. //first we'll add the new client int i = st.executeUpdate(insertClient); if(i == 1){ System.out.println("RegisterUser successful."); //executeUpdate() returns an integer; a return of 1 means the insert was successful. //now we can set his initial configuration int j = st.executeUpdate(insertConfiguration); if(j == 1){ retVal = 1;//registerUser and setInitialConfig successful System.out.println("SetConfiguration successful."); System.out.println("New user and configuration successfully added." + "\n"); //FOR STATS - Scott stats.adduser(); } } } catch(Exception e) { System.err.println(e + "\n"); retVal = 0; //server error } } else { System.err.println("That ClientID already exists." + "\n"); retVal = 3;//Invalid ClientID } rs.close(); rs = null; st.close(); st = null; }else System.err.println("Error: No active Connection" + "\n"); }catch(Exception e){ System.err.println(e); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method will lock out a user from logging in to the chat system. //This should be called after 5 failed login attempts. The user will be unable to log in until unLockOutUser is called on their name. public int lockOutUser(String clientID){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectClient = "SELECT clientid FROM Client WHERE clientID = '" + clientID + "';"; String updateLockedOut = "UPDATE client set lockedout = 1 where clientid = '" + clientID + "';"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectClient); //check if the original client exists //rs.next() will return true if the select statement found the client in the database, meaning he exists if(rs.next()){ //if he exists, we can update his lockedout status try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. int i = st.executeUpdate(updateLockedOut); if(i == 1){ retVal = 1;//updateLockedOut successful System.out.println("lockOutUser successful." + "\n"); } } //MySQL doesn't seem to throw an error even if you give it an invalid clientid //It just says "Query OK, 0 rows affected" so I'm not expecting this to throw an error. catch(Exception e) { //e.printStackTrace(); System.err.println(e + "\n"); retVal = 0; //server error } } else { retVal = 3;//Invalid ClientID } rs.close(); rs = null; st.close(); st = null; }else System.err.println("Error: No active Connection" + "\n"); }catch(Exception e){ e.printStackTrace(); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //Removes the lock from the client's username so they can log in again. public int unLockOutUser(String clientID){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectClient = "SELECT clientid FROM Client WHERE clientID = '" + clientID + "';"; String updateLockedOut = "UPDATE client set lockedout = 0 where clientid = '" + clientID + "';"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectClient); //check if the original client exists //rs.next() will return true if the select statement found the client in the database, meaning he exists if(rs.next()){ //if he exists, we can update his lockedout status try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. int i = st.executeUpdate(updateLockedOut); if(i == 1){ retVal = 1;//updateLockedOut successful System.out.println("unLockOutUser successful." + "\n"); } } //MySQL doesn't seem to throw an error even if you give it an invalid clientid //It just says "Query OK, 0 rows affected" so I'm not expecting this to throw an error. catch(Exception e) { //e.printStackTrace(); System.err.println(e + "\n"); retVal = 0; //server error } } else { retVal = 3;//Invalid ClientID } rs.close(); rs = null; st.close(); st = null; }else System.err.println("Error: No active Connection" + "\n"); }catch(Exception e){ System.err.println(e); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method sets a client's configuration, or preferences, which you can see listed below (the index references). These are for colors in the chat client. //You must supply a Configuration object, which is basically an arraylist of strings of the below preferences. public int updateConfiguration(String clientID, Configuration _config){ //index 0 = _clientID; //index 1 = _tabFill; //index 2 =_tabStroke; //index 3 = _windowFill; //index 4 = _windowStroke; //index 5 = _chatWindowColor; //index 6 = _textColor; ArrayList<String> configList = _config.getConfiguration(); int retVal = 0; //Server error java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectClientID = "SELECT clientid FROM client where clientid = '" + clientID + "';"; String updateConfiguration = "UPDATE configuration set tabfill = '" + configList.get(1) + "', tabstroke = '" + configList.get(2) + "', windowfill = '" + configList.get(3) + "', windowstroke = '" + configList.get(4) + "', chatwindowcolor = '" + configList.get(5) + "', textcolor = '" + configList.get(6) + "' WHERE clientid = '" + clientID + "';"; try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectClientID); //check if the clientid exists before inputing into configuration table if(rs.next()){ //if they exist, we can try to set their configuration try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. int i = st.executeUpdate(updateConfiguration); if(i == 1){ retVal = 1;//updateConfiguration successful System.out.println("updateConfiguration successful." + "\n"); } } catch(Exception e) { //e.printStackTrace(); System.err.println("updateConfiguration failed." + "\n"); System.err.println(e + "\n"); retVal = 0; //server error } } rs.close(); rs = null; st.close(); st = null; }else System.out.println("Error: No active Connection" + "\n"); }catch(Exception e){ System.err.println(e + "\n"); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //this will return a configuration object full of nulls if the clientID doesn't exist...maybe we should fix this. //This is because making a new configuration creates an arraylist with 7 nulls inserted, since specifying a size of the list //wasn't enough to say _configuration.set(index, string)...it threw index out of bounds errors. public Configuration getConfiguration(String clientID){ java.sql.ResultSet rs = null; java.sql.Statement st = null; Configuration _configuration = new Configuration(); String selectConfiguration = "SELECT * from configuration WHERE clientid = '" + clientID + "';"; try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectConfiguration); //this will return true if the clientid exists in the table if(rs.next()){ //if they exist, we can iterate their configuration //iterate through the results and add them to a configuration object System.out.println("Creating the config object..."); _configuration.updateConfiguration(0, clientID); for(int i = 2; i < 8; i++){ _configuration.updateConfiguration(i-1, rs.getString(i)); } System.out.println("Creation completed." + "\n"); } else if(!rs.next()){ System.err.println("That ClientID does not exist."); } rs.close(); rs = null; st.close(); st = null; }else System.out.println("Error: No active Connection" + "\n"); }catch(Exception e){ System.err.println(e + "\n"); } return _configuration; } //Outputs the stats regaurding the IM activity from the stats obj. -Scott public static void outStats() { stats.printStats(); } //Dan Morgan //This method doesn't serve any practical purposes, but is nice for debugging. public void selectAllFrom(String table){ java.sql.ResultSetMetaData rsmd = null; java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectAllFromClient = "SELECT * FROM " + table; try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectAllFromClient); rsmd = rs.getMetaData(); System.out.println("Table: " + rsmd.getTableName(1)); System.out.println("********************************"); //iterate through the results and print them while (rs.next()){ for (int i = 1; i <= rsmd.getColumnCount(); i++){ System.out.println(" " + rsmd.getColumnName(i)+ ": " + rs.getString(i)); } System.out.println(""); } System.out.println("********************************" + "\n"); rs.close(); rs = null; rsmd = null; st.close(); st = null; }else System.out.println("Error: No active Connection" + "\n"); }catch(Exception e){ //e.printStackTrace(); System.err.println(e + "\n"); } } public void closeConnection(){ try{ this.outStats(); if(con!=null) con.close(); System.out.println("The connection has been closed." + "\n"); con=null; }catch(Exception e){ //e.printStackTrace(); System.err.println(e + "\n"); } } public static void main(String[] args) throws Exception { System.out.println("Database connection initializing...."); DBComm myDBComm = new DBComm(); //myDBComm.selectAllFrom("client"); myDBComm.addBuddy("number1pimp", "realnumber1pimp", "Buddies"); myDBComm.addBuddy("realnumber1pimp", "number1pimp", "Homies"); //myDBComm.selectAllFrom("buddy"); //Testing correct ClientID and Password int i = myDBComm.verifyLogin("number1pimp", "bigpimpin"); System.out.println("Number should be 1: "+ i); //Testing incorrect Password int j = myDBComm.verifyLogin("number1pimp", "asdlgkjaslg"); System.out.println("Number should be 2: "+ j); //Testing incorrect ClientID int k = myDBComm.verifyLogin("number2pimp", "bigpimpin"); System.out.println("Number should be 3: "+ k + "\n"); myDBComm.removeBuddy("number1pimp", "realnumber1pimp", "Buddies"); //myDBComm.selectAllFrom("buddy"); myDBComm.registerUser("Dan2", "test2"); //myDBComm.selectAllFrom("client"); myDBComm.addMessage("Robert", "Hey Jordan", "Jordan"); myDBComm.getMessage("Robert"); myDBComm.addWebEvent("Dan1", 1); BuddyList newBuddyList = myDBComm.getBuddyList("jordan"); System.out.println("jordan's BuddyList:" + "\n"); for(Buddy b: newBuddyList.getBuddyList()){ System.out.println(b.toString()); } System.out.println(""); Configuration commConfigTestInput = new Configuration(); commConfigTestInput.updateConfiguration(0, "Dan1"); commConfigTestInput.updateConfiguration(1, "tabFillTest1"); commConfigTestInput.updateConfiguration(2, "tabStrokeTest1"); commConfigTestInput.updateConfiguration(3, "windowFillTest1"); commConfigTestInput.updateConfiguration(4, "windowStrokeTest1"); commConfigTestInput.updateConfiguration(5, "chatWindowColorTest1"); commConfigTestInput.updateConfiguration(6, "textColorTest1"); myDBComm.updateConfiguration("Dan1", commConfigTestInput); Configuration commConfigTestOutput = myDBComm.getConfiguration("Dan1"); System.out.println("Configuration Testing"); System.out.println("**********************************"); for(String s: commConfigTestOutput.getConfiguration()){ System.out.println(s); } System.out.println("**********************************"); System.out.println(""); System.out.println("getStatus Testing"); System.out.println("**********************************"); System.out.println("Dan1: " + myDBComm.getStatus("Dan1")); System.out.println("ditch: " + myDBComm.getStatus("ditch")); System.out.println("Josh: " + myDBComm.getStatus("Josh")); System.out.println("Jordan1: " + myDBComm.getStatus("Jordan1")); System.out.println("**********************************"); System.out.println(""); System.out.println("updateStatus Testing"); System.out.println("**********************************"); myDBComm.updateStatus("Dan1", 1); myDBComm.updateStatus("ditch", 2); myDBComm.updateStatus("Josh", 3); myDBComm.updateStatus("Jordan1", 4); System.out.println("**********************************"); //myDBComm.selectAllFrom("client"); System.out.println(""); System.out.println("lockOutUser Testing"); System.out.println("**********************************"); myDBComm.lockOutUser("Dan4"); //Testing locked out int l = myDBComm.verifyLogin("Dan4", "test4"); System.out.println("Number should be 3: "+ l + "\n"); System.out.println("**********************************"); System.out.println(""); System.out.println("unLockOutUser Testing"); System.out.println("**********************************"); myDBComm.unLockOutUser("Dan4"); //Testing un locked out int m = myDBComm.verifyLogin("Dan4", "test4"); System.out.println("Number should be 1: "+ m + "\n"); System.out.println("**********************************"); System.out.println(""); myDBComm.getWebEvent(""); System.out.println(myDBComm.getWebEvent("George Washington")); myDBComm.addWebEvent("pyrobug", 3); System.out.println(myDBComm.addWebEvent("George Washington", 2)); myDBComm.getMessage("Jordan"); System.out.println(myDBComm.getMessage("Jordan")); myDBComm.closeConnection(); myDBComm = null; //STATS outStats(); } }
Java
package DBComm; public class DBExample{ private java.sql.Connection con = null; private final String url = "jdbc:mysql://"; private final String serverName= "192.168.0.102"; //Robert's IP 192.168.0.102 private final String portNumber = "3306"; //MySQL: 3306. SQL Server 2008: 50479 private final String databaseName= "pIMp"; private final String userName = "pIMpAdmin"; private final String password = "ainteasy"; private final String selectMethod = "cursor"; // Constructor public DBExample(){} private String getConnectionUrl(){ //return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";"; return url+serverName+":"+portNumber+"/"+databaseName+"?"; } private java.sql.Connection getConnection(){ try{ //Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); //Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); Class.forName("com.mysql.jdbc.Driver").newInstance(); con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password); if(con!=null) System.out.println("Connection Successful!"); }catch(Exception e){ e.printStackTrace(); System.out.println("Error Trace in getConnection() : " + e.getMessage()); } return con; } public void part1(){ java.sql.DatabaseMetaData dm = null; java.sql.ResultSet rs = null; java.sql.Statement st = null; String query = "SELECT * FROM client"; try{ con= this.getConnection(); //con.createStatement(); //System.out.println("empno \tname \tsalary"); if(con!=null){ st = con.createStatement(); rs = st.executeQuery(query); while(rs.next()){ System.out.print(rs.getString(1)); System.out.print("\t"+ rs.getString(2)); System.out.print("\t"+ rs.getString(3) + "\n"); System.out.print("\t"+ rs.getString(4) + "\n"); System.out.print("\t"+ rs.getString(5) + "\n"); } System.out.println(); rs.close(); rs = null; closeConnection(); }else System.out.println("Error: No active Connection"); }catch(Exception e){ e.printStackTrace(); } dm=null; } public void part2(){ java.sql.DatabaseMetaData dm = null; java.sql.ResultSet rs = null; java.sql.Statement st = null; String query = "SELECT distinct e.name FROM employee e inner join loan l on e.empno = l.empno, book b " + "Where b.isbn = l.isbn " + "And b.publisher = 'McGraw-Hill' " + "Group By e.name " + "Having count(b.isbn) = (Select count(isbn) from book where publisher = 'McGraw-Hill' ) "; try{ con= this.getConnection(); con.createStatement(); //Title bar System.out.println("name"); if(con!=null){ st = con.createStatement(); rs = st.executeQuery(query); while(rs.next()){ System.out.print(rs.getString(1) + "\n"); } System.out.println(); rs.close(); rs = null; closeConnection(); }else System.out.println("Error: No active Connection"); }catch(Exception e){ e.printStackTrace(); } dm=null; } public void part3(){ java.sql.DatabaseMetaData dm = null; java.sql.ResultSet rs = null; java.sql.Statement st = null; String query = "SELECT e.salary FROM employee e Order By e.salary"; try{ con= this.getConnection(); con.createStatement(); //Title bar System.out.println("salary"); if(con!=null){ st = con.createStatement(); rs = st.executeQuery(query); while(rs.next()){ System.out.print(rs.getString(1) + "\n"); } System.out.println(); rs.close(); rs = null; closeConnection(); }else System.out.println("Error: No active Connection"); }catch(Exception e){ e.printStackTrace(); } dm=null; } private void closeConnection(){ try{ if(con!=null) con.close(); con=null; }catch(Exception e){ e.printStackTrace(); } } public static void main(String[] args) throws Exception { DBExample myDbTest = new DBExample(); myDbTest.part1(); //myDbTest.part2(); //myDbTest.part3(); } }
Java
package DBComm; public class Scrubber { static public String scrub(String str) { str = replaceString(str,"&","&amp;"); str = replaceString(str,"<","&lt;"); str = replaceString(str,">","&gt;"); str = replaceString(str,"\"","&quot;"); str = replaceString(str,"'","&apos;"); return str; } // from StringW static public String replaceString(String text, String repl, String with) { return replaceString(text, repl, with, -1); } /** * Replace a string with another string inside a larger string, for * the first n values of the search string. * * @param text String to do search and replace in * @param repl String to search for * @param with String to replace with * @param n int values to replace * * @return String with n values replacEd */ static public String replaceString(String text, String repl, String with, int max) { if(text == null) { return null; } StringBuffer buffer = new StringBuffer(text.length()); int start = 0; int end = 0; while( (end = text.indexOf(repl, start)) != -1 ) { buffer.append(text.substring(start, end)).append(with); start = end + repl.length(); if(--max == 0) { break; } } buffer.append(text.substring(start)); return buffer.toString(); } }
Java
package DBComm; //Dan Morgan import java.util.ArrayList; public class BuddyList { private ArrayList<Buddy> buddyList = new ArrayList<Buddy>(); // private Buddy myBuddy; public BuddyList(){ // this.myBuddy = new Buddy(); } public void addBuddy(Buddy myBuddy ){ buddyList.add(myBuddy); } public ArrayList<Buddy> getBuddyList(){ return buddyList; } }
Java
package DBComm; public class Buddy { private String buddy; private int status; public Buddy(){ this.buddy = ""; this.status = 0; } public Buddy(String buddyName, int status){ this.buddy = buddyName; this.status = status; } public String toString() { return this.buddy + ":" + this.status; } public void setBuddy(String buddyName){ this.buddy = buddyName; } public String getBuddy(){ return this.buddy; } public void setStatus(int status){ this.status = status; } public int getStatus(){ return this.status; } }
Java
package DBComm; public class RobertsClass { }
Java
package DBComm; public class Core { }
Java
package responder; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import DBComm.BuddyList; import messages.ChatMessage; import DBComm.DBComm; public class WebResponder extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException{ DBComm dbcomm = new DBComm(); String type = req.getParameter("type"); PrintWriter out = resp.getWriter(); if (type.compareTo("addbuddy") == 0){ String clientID = req.getParameter("clientID"); String buddy = req.getParameter("buddy"); String group = req.getParameter("group"); int status = dbcomm.addBuddy(clientID, buddy, group); //out.println("addbuddy: " + clientID + ", " + buddy + ", " + group); out.println(status); } else if (type.compareTo("removebuddy") == 0){ String clientID = req.getParameter("clientID"); String buddy = req.getParameter("buddy"); String group = req.getParameter("group"); int status = dbcomm.removeBuddy(clientID, buddy, group); //out.println("removebuddy: " + clientID + ", " + buddy + ", " + group); out.println(status); } else if (type.compareTo("register") == 0){ String clientID = req.getParameter("clientID"); String password = req.getParameter("password"); int status = dbcomm.registerUser(clientID, password); //out.println("register: " + clientID + ", " + password); out.println(status); } else if (type.compareTo("getbuddylist") == 0){ String clientID = req.getParameter("clientID"); BuddyList bl = dbcomm.getBuddyList(clientID); String bljson = JSONGenerator.buddyListGenerator(bl); resp.setContentType("text/javascript"); out.println(bljson); } else if (type.compareTo("gethistory") == 0){ String clientID = req.getParameter("clientID"); dbcomm.getChatHistory(clientID); } else if (type.compareTo("login")==0){ String loginID = req.getParameter("loginID"); String password = req.getParameter("password"); int result = dbcomm.verifyLogin(loginID, password); out.println(result); } else if (type.compareTo("sendmessage") == 0){ String to = req.getParameter("to"); String from = req.getParameter("from"); String message = req.getParameter("message"); int result = dbcomm.addMessage(from, message, to); out.println(result); } else if (type.compareTo("time") == 0){ Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); out.println(sdf.format(cal.getTime())); } else if (type.compareTo("event") == 0){ String clientid = req.getParameter("clientid"); int count = 0; int eventCode; do { //check the database if there are any messages greater than lastid //if there is stuff in the DB, break out of this loop //otherwise, sleep, and check again! eventCode = dbcomm.getWebEvent(clientid); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } count++; } while (count < 29 && eventCode < 1); if (eventCode == 1){ //new messages //TODO: ArrayList<ChatMessage> messages = dbcomm.getMessage(clientid); String cm = JSONGenerator.messagesGenerator(messages); dbcomm.clearEvent(clientid); resp.setContentType("text/javascript"); out.println(cm); } else if (eventCode == 2){ BuddyList bl = dbcomm.getBuddyList(clientid); dbcomm.clearEvent(clientid); String bljson = JSONGenerator.buddyListGenerator(bl); resp.setContentType("text/javascript"); out.println(bljson); } else if (eventCode == 3){ //do both ArrayList<ChatMessage> messages = dbcomm.getMessage(clientid); BuddyList bl = dbcomm.getBuddyList(clientid); String stuff = JSONGenerator.messageAndStatus(messages, bl); resp.setContentType("text/javascript"); out.println(stuff); dbcomm.clearEvent(clientid); } else { out.println(0); } //out.println("eventcode: " +eventCode); } dbcomm.closeConnection(); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException{ DBComm dbcomm = new DBComm(); String type = req.getParameter("type"); String clientid = req.getParameter("clientid"); PrintWriter out = resp.getWriter(); if (type.compareTo("status") == 0){ int status = Integer.parseInt(req.getParameter("status")); dbcomm.updateStatus(clientid, status); } } }
Java
package org.json; /** * The JSONException is thrown by the JSON.org classes then things are amiss. * @author JSON.org * @version 2008-09-18 */ public class JSONException extends Exception { private Throwable cause; /** * Constructs a JSONException with an explanatory message. * @param message Detail about the reason for the exception. */ public JSONException(String message) { super(message); } public JSONException(Throwable t) { super(t.getMessage()); this.cause = t; } public Throwable getCause() { return this.cause; } }
Java
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONObject, * and to covert a JSONObject into an XML text. * @author JSON.org * @version 2008-10-14 */ public class XML { /** The Character '&'. */ public static final Character AMP = new Character('&'); /** The Character '''. */ public static final Character APOS = new Character('\''); /** The Character '!'. */ public static final Character BANG = new Character('!'); /** The Character '='. */ public static final Character EQ = new Character('='); /** The Character '>'. */ public static final Character GT = new Character('>'); /** The Character '<'. */ public static final Character LT = new Character('<'); /** The Character '?'. */ public static final Character QUEST = new Character('?'); /** The Character '"'. */ public static final Character QUOT = new Character('"'); /** The Character '/'. */ public static final Character SLASH = new Character('/'); /** * Replace special characters with XML escapes: * <pre> * &amp; <small>(ampersand)</small> is replaced by &amp;amp; * &lt; <small>(less than)</small> is replaced by &amp;lt; * &gt; <small>(greater than)</small> is replaced by &amp;gt; * &quot; <small>(double quote)</small> is replaced by &amp;quot; * </pre> * @param string The string to be escaped. * @return The escaped string. */ public static String escape(String string) { StringBuffer sb = new StringBuffer(); for (int i = 0, len = string.length(); i < len; i++) { char c = string.charAt(i); switch (c) { case '&': sb.append("&amp;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '"': sb.append("&quot;"); break; default: sb.append(c); } } return sb.toString(); } /** * Throw an exception if the string contains whitespace. * Whitespace is not allowed in tagNames and attributes. * @param string * @throws JSONException */ public static void noSpace(String string) throws JSONException { int i, length = string.length(); if (length == 0) { throw new JSONException("Empty string."); } for (i = 0; i < length; i += 1) { if (Character.isWhitespace(string.charAt(i))) { throw new JSONException("'" + string + "' contains a space character."); } } } /** * Scan the content following the named tag, attaching it to the context. * @param x The XMLTokener containing the source string. * @param context The JSONObject that will include the new material. * @param name The tag name. * @return true if the close tag is processed. * @throws JSONException */ private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { char c; int i; String n; JSONObject o = null; String s; Object t; // Test for and skip past these forms: // <!-- ... --> // <! ... > // <![ ... ]]> // <? ... ?> // Report errors for these forms: // <> // <= // << t = x.nextToken(); // <! if (t == BANG) { c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); return false; } x.back(); } else if (c == '[') { t = x.nextToken(); if (t.equals("CDATA")) { if (x.next() == '[') { s = x.nextCDATA(); if (s.length() > 0) { context.accumulate("content", s); } return false; } } throw x.syntaxError("Expected 'CDATA['"); } i = 1; do { t = x.nextMeta(); if (t == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (t == LT) { i += 1; } else if (t == GT) { i -= 1; } } while (i > 0); return false; } else if (t == QUEST) { // <? x.skipPast("?>"); return false; } else if (t == SLASH) { // Close tag </ t = x.nextToken(); if (name == null) { throw x.syntaxError("Mismatched close tag" + t); } if (!t.equals(name)) { throw x.syntaxError("Mismatched " + name + " and " + t); } if (x.nextToken() != GT) { throw x.syntaxError("Misshaped close tag"); } return true; } else if (t instanceof Character) { throw x.syntaxError("Misshaped tag"); // Open tag < } else { n = (String)t; t = null; o = new JSONObject(); for (;;) { if (t == null) { t = x.nextToken(); } // attribute = value if (t instanceof String) { s = (String)t; t = x.nextToken(); if (t == EQ) { t = x.nextToken(); if (!(t instanceof String)) { throw x.syntaxError("Missing value"); } o.accumulate(s, JSONObject.stringToValue((String)t)); t = null; } else { o.accumulate(s, ""); } // Empty tag <.../> } else if (t == SLASH) { if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } context.accumulate(n, o); return false; // Content, between <...> and </...> } else if (t == GT) { for (;;) { t = x.nextContent(); if (t == null) { if (n != null) { throw x.syntaxError("Unclosed tag " + n); } return false; } else if (t instanceof String) { s = (String)t; if (s.length() > 0) { o.accumulate("content", JSONObject.stringToValue(s)); } // Nested element } else if (t == LT) { if (parse(x, o, n)) { if (o.length() == 0) { context.accumulate(n, ""); } else if (o.length() == 1 && o.opt("content") != null) { context.accumulate(n, o.opt("content")); } else { context.accumulate(n, o); } return false; } } } } else { throw x.syntaxError("Misshaped tag"); } } } } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject. Some information may be lost in this transformation * because JSON is a data format and XML is a document format. XML uses * elements, attributes, and content text, while JSON uses unordered * collections of name/value pairs and arrays of values. JSON does not * does not like to distinguish between elements and attributes. * Sequences of similar elements are represented as JSONArrays. Content * text may be placed in a "content" member. Comments, prologs, DTDs, and * <code>&lt;[ [ ]]></code> are ignored. * @param string The source string. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject o = new JSONObject(); XMLTokener x = new XMLTokener(string); while (x.more() && x.skipPast("<")) { parse(x, o, null); } return o; } /** * Convert a JSONObject into a well-formed, element-normal XML string. * @param o A JSONObject. * @return A string. * @throws JSONException */ public static String toString(Object o) throws JSONException { return toString(o, null); } /** * Convert a JSONObject into a well-formed, element-normal XML string. * @param o A JSONObject. * @param tagName The optional name of the enclosing tag. * @return A string. * @throws JSONException */ public static String toString(Object o, String tagName) throws JSONException { StringBuffer b = new StringBuffer(); int i; JSONArray ja; JSONObject jo; String k; Iterator keys; int len; String s; Object v; if (o instanceof JSONObject) { // Emit <tagName> if (tagName != null) { b.append('<'); b.append(tagName); b.append('>'); } // Loop thru the keys. jo = (JSONObject)o; keys = jo.keys(); while (keys.hasNext()) { k = keys.next().toString(); v = jo.opt(k); if (v == null) { v = ""; } if (v instanceof String) { s = (String)v; } else { s = null; } // Emit content in body if (k.equals("content")) { if (v instanceof JSONArray) { ja = (JSONArray)v; len = ja.length(); for (i = 0; i < len; i += 1) { if (i > 0) { b.append('\n'); } b.append(escape(ja.get(i).toString())); } } else { b.append(escape(v.toString())); } // Emit an array of similar keys } else if (v instanceof JSONArray) { ja = (JSONArray)v; len = ja.length(); for (i = 0; i < len; i += 1) { v = ja.get(i); if (v instanceof JSONArray) { b.append('<'); b.append(k); b.append('>'); b.append(toString(v)); b.append("</"); b.append(k); b.append('>'); } else { b.append(toString(v, k)); } } } else if (v.equals("")) { b.append('<'); b.append(k); b.append("/>"); // Emit a new tag <k> } else { b.append(toString(v, k)); } } if (tagName != null) { // Emit the </tagname> close tag b.append("</"); b.append(tagName); b.append('>'); } return b.toString(); // XML does not have good support for arrays. If an array appears in a place // where XML is lacking, synthesize an <array> element. } else if (o instanceof JSONArray) { ja = (JSONArray)o; len = ja.length(); for (i = 0; i < len; ++i) { v = ja.opt(i); b.append(toString(v, (tagName == null) ? "array" : tagName)); } return b.toString(); } else { s = (o == null) ? "null" : escape(o.toString()); return (tagName == null) ? "\"" + s + "\"" : (s.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + s + "</" + tagName + ">"; } } }
Java
package org.json; /* Copyright (c) 2008 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONArray or * JSONObject, and to covert a JSONArray or JSONObject into an XML text using * the JsonML transform. * @author JSON.org * @version 2008-11-20 */ public class JSONML { /** * Parse XML values and store them in a JSONArray. * @param x The XMLTokener containing the source string. * @param arrayForm true if array form, false if object form. * @param ja The JSONArray that is containing the current tag or null * if we are at the outermost level. * @return A JSONArray if the value is the outermost tag, otherwise null. * @throws JSONException */ private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException { String attribute; char c; String closeTag = null; int i; JSONArray newja = null; JSONObject newjo = null; Object token; String tagName = null; // Test for and skip past these forms: // <!-- ... --> // <![ ... ]]> // <! ... > // <? ... ?> while (true) { token = x.nextContent(); if (token == XML.LT) { token = x.nextToken(); if (token instanceof Character) { if (token == XML.SLASH) { // Close tag </ token = x.nextToken(); if (!(token instanceof String)) { throw new JSONException( "Expected a closing name instead of '" + token + "'."); } if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped close tag"); } return token; } else if (token == XML.BANG) { // <! c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); } x.back(); } else if (c == '[') { token = x.nextToken(); if (token.equals("CDATA") && x.next() == '[') { if (ja != null) { ja.put(x.nextCDATA()); } } else { throw x.syntaxError("Expected 'CDATA['"); } } else { i = 1; do { token = x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (token == XML.LT) { i += 1; } else if (token == XML.GT) { i -= 1; } } while (i > 0); } } else if (token == XML.QUEST) { // <? x.skipPast("?>"); } else { throw x.syntaxError("Misshaped tag"); } // Open tag < } else { if (!(token instanceof String)) { throw x.syntaxError("Bad tagName '" + token + "'."); } tagName = (String)token; newja = new JSONArray(); newjo = new JSONObject(); if (arrayForm) { newja.put(tagName); if (ja != null) { ja.put(newja); } } else { newjo.put("tagName", tagName); if (ja != null) { ja.put(newjo); } } token = null; for (;;) { if (token == null) { token = x.nextToken(); } if (token == null) { throw x.syntaxError("Misshaped tag"); } if (!(token instanceof String)) { break; } // attribute = value attribute = (String)token; if (!arrayForm && (attribute == "tagName" || attribute == "childNode")) { throw x.syntaxError("Reserved attribute."); } token = x.nextToken(); if (token == XML.EQ) { token = x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } newjo.accumulate(attribute, JSONObject.stringToValue((String)token)); token = null; } else { newjo.accumulate(attribute, ""); } } if (arrayForm && newjo.length() > 0) { newja.put(newjo); } // Empty tag <.../> if (token == XML.SLASH) { if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped tag"); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } // Content, between <...> and </...> } else { if (token != XML.GT) { throw x.syntaxError("Misshaped tag"); } closeTag = (String)parse(x, arrayForm, newja); if (closeTag != null) { if (!closeTag.equals(tagName)) { throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); } tagName = null; if (!arrayForm && newja.length() > 0) { newjo.put("childNodes", newja); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } } } } } else { if (ja != null) { ja.put(token instanceof String ? JSONObject.stringToValue((String)token) : token); } } } } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONArray using the JsonML transform. Each XML tag is represented as * a JSONArray in which the first element is the tag name. If the tag has * attributes, then the second element will be JSONObject containing the * name/value pairs. If the tag contains children, then strings and * JSONArrays will represent the child tags. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param string The source string. * @return A JSONArray containing the structured data from the XML string. * @throws JSONException */ public static JSONArray toJSONArray(String string) throws JSONException { return toJSONArray(new XMLTokener(string)); } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONArray using the JsonML transform. Each XML tag is represented as * a JSONArray in which the first element is the tag name. If the tag has * attributes, then the second element will be JSONObject containing the * name/value pairs. If the tag contains children, then strings and * JSONArrays will represent the child content and tags. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param x An XMLTokener. * @return A JSONArray containing the structured data from the XML string. * @throws JSONException */ public static JSONArray toJSONArray(XMLTokener x) throws JSONException { return (JSONArray)parse(x, true, null); } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject using the JsonML transform. Each XML tag is represented as * a JSONObject with a "tagName" property. If the tag has attributes, then * the attributes will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param x An XMLTokener of the XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(XMLTokener x) throws JSONException { return (JSONObject)parse(x, false, null); } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject using the JsonML transform. Each XML tag is represented as * a JSONObject with a "tagName" property. If the tag has attributes, then * the attributes will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param string The XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { return toJSONObject(new XMLTokener(string)); } /** * Reverse the JSONML transformation, making an XML text from a JSONArray. * @param ja A JSONArray. * @return An XML string. * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { Object e; int i; JSONObject jo; String k; Iterator keys; int length; StringBuffer sb = new StringBuffer(); String tagName; String v; // Emit <tagName tagName = ja.getString(0); XML.noSpace(tagName); tagName = XML.escape(tagName); sb.append('<'); sb.append(tagName); e = ja.opt(1); if (e instanceof JSONObject) { i = 2; jo = (JSONObject)e; // Emit the attributes keys = jo.keys(); while (keys.hasNext()) { k = keys.next().toString(); XML.noSpace(k); v = jo.optString(k); if (v != null) { sb.append(' '); sb.append(XML.escape(k)); sb.append('='); sb.append('"'); sb.append(XML.escape(v)); sb.append('"'); } } } else { i = 1; } //Emit content in body length = ja.length(); if (i >= length) { sb.append('/'); sb.append('>'); } else { sb.append('>'); do { e = ja.get(i); i += 1; if (e != null) { if (e instanceof String) { sb.append(XML.escape(e.toString())); } else if (e instanceof JSONObject) { sb.append(toString((JSONObject)e)); } else if (e instanceof JSONArray) { sb.append(toString((JSONArray)e)); } } } while (i < length); sb.append('<'); sb.append('/'); sb.append(tagName); sb.append('>'); } return sb.toString(); } /** * Reverse the JSONML transformation, making an XML text from a JSONObject. * The JSONObject must contain a "tagName" property. If it has children, * then it must have a "childNodes" property containing an array of objects. * The other properties are attributes with string values. * @param jo A JSONObject. * @return An XML string. * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { StringBuffer sb = new StringBuffer(); Object e; int i; JSONArray ja; String k; Iterator keys; int len; String tagName; String v; //Emit <tagName tagName = jo.optString("tagName"); if (tagName == null) { return XML.escape(jo.toString()); } XML.noSpace(tagName); tagName = XML.escape(tagName); sb.append('<'); sb.append(tagName); //Emit the attributes keys = jo.keys(); while (keys.hasNext()) { k = keys.next().toString(); if (!k.equals("tagName") && !k.equals("childNodes")) { XML.noSpace(k); v = jo.optString(k); if (v != null) { sb.append(' '); sb.append(XML.escape(k)); sb.append('='); sb.append('"'); sb.append(XML.escape(v)); sb.append('"'); } } } //Emit content in body ja = jo.optJSONArray("childNodes"); if (ja == null) { sb.append('/'); sb.append('>'); } else { sb.append('>'); len = ja.length(); for (i = 0; i < len; i += 1) { e = ja.get(i); if (e != null) { if (e instanceof String) { sb.append(XML.escape(e.toString())); } else if (e instanceof JSONObject) { sb.append(toString((JSONObject)e)); } else if (e instanceof JSONArray) { sb.append(toString((JSONArray)e)); } } } sb.append('<'); sb.append('/'); sb.append(tagName); sb.append('>'); } return sb.toString(); } }
Java
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * This provides static methods to convert comma delimited text into a * JSONArray, and to covert a JSONArray into comma delimited text. Comma * delimited text is a very popular format for data interchange. It is * understood by most database, spreadsheet, and organizer programs. * <p> * Each row of text represents a row in a table or a data record. Each row * ends with a NEWLINE character. Each row contains one or more values. * Values are separated by commas. A value can contain any character except * for comma, unless is is wrapped in single quotes or double quotes. * <p> * The first row usually contains the names of the columns. * <p> * A comma delimited list can be converted into a JSONArray of JSONObjects. * The names for the elements in the JSONObjects can be taken from the names * in the first row. * @author JSON.org * @version 2008-09-18 */ public class CDL { /** * Get the next value. The value can be wrapped in quotes. The value can * be empty. * @param x A JSONTokener of the source text. * @return The value string, or null if empty. * @throws JSONException if the quoted string is badly formed. */ private static String getValue(JSONTokener x) throws JSONException { char c; do { c = x.next(); } while (c == ' ' || c == '\t'); switch (c) { case 0: return null; case '"': case '\'': return x.nextString(c); case ',': x.back(); return ""; default: x.back(); return x.nextTo(','); } } /** * Produce a JSONArray of strings from a row of comma delimited values. * @param x A JSONTokener of the source text. * @return A JSONArray of strings. * @throws JSONException */ public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { JSONArray ja = new JSONArray(); for (;;) { String value = getValue(x); if (value == null || (ja.length() == 0 && value.length() == 0)) { return null; } ja.put(value); for (;;) { char c = x.next(); if (c == ',') { break; } if (c != ' ') { if (c == '\n' || c == '\r' || c == 0) { return ja; } throw x.syntaxError("Bad character '" + c + "' (" + (int)c + ")."); } } } } /** * Produce a JSONObject from a row of comma delimited text, using a * parallel JSONArray of strings to provides the names of the elements. * @param names A JSONArray of names. This is commonly obtained from the * first row of a comma delimited text file using the rowToJSONArray * method. * @param x A JSONTokener of the source text. * @return A JSONObject combining the names and values. * @throws JSONException */ public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) throws JSONException { JSONArray ja = rowToJSONArray(x); return ja != null ? ja.toJSONObject(names) : null; } /** * Produce a JSONArray of JSONObjects from a comma delimited text string, * using the first row as a source of names. * @param string The comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException */ public static JSONArray toJSONArray(String string) throws JSONException { return toJSONArray(new JSONTokener(string)); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string, * using the first row as a source of names. * @param x The JSONTokener containing the comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException */ public static JSONArray toJSONArray(JSONTokener x) throws JSONException { return toJSONArray(rowToJSONArray(x), x); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string * using a supplied JSONArray as the source of element names. * @param names A JSONArray of strings. * @param string The comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException */ public static JSONArray toJSONArray(JSONArray names, String string) throws JSONException { return toJSONArray(names, new JSONTokener(string)); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string * using a supplied JSONArray as the source of element names. * @param names A JSONArray of strings. * @param x A JSONTokener of the source text. * @return A JSONArray of JSONObjects. * @throws JSONException */ public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException { if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); for (;;) { JSONObject jo = rowToJSONObject(names, x); if (jo == null) { break; } ja.put(jo); } if (ja.length() == 0) { return null; } return ja; } /** * Produce a comma delimited text row from a JSONArray. Values containing * the comma character will be quoted. * @param ja A JSONArray of strings. * @return A string ending in NEWLINE. */ public static String rowToString(JSONArray ja) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < ja.length(); i += 1) { if (i > 0) { sb.append(','); } Object o = ja.opt(i); if (o != null) { String s = o.toString(); if (s.indexOf(',') >= 0) { if (s.indexOf('"') >= 0) { sb.append('\''); sb.append(s); sb.append('\''); } else { sb.append('"'); sb.append(s); sb.append('"'); } } else { sb.append(s); } } } sb.append('\n'); return sb.toString(); } /** * Produce a comma delimited text from a JSONArray of JSONObjects. The * first row will be a list of names obtained by inspecting the first * JSONObject. * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { JSONObject jo = ja.optJSONObject(0); if (jo != null) { JSONArray names = jo.names(); if (names != null) { return rowToString(names) + toString(names, ja); } } return null; } /** * Produce a comma delimited text from a JSONArray of JSONObjects using * a provided list of names. The list of names is not included in the * output. * @param names A JSONArray of strings. * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ public static String toString(JSONArray names, JSONArray ja) throws JSONException { if (names == null || names.length() == 0) { return null; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < ja.length(); i += 1) { JSONObject jo = ja.optJSONObject(i); if (jo != null) { sb.append(rowToString(jo.toJSONArray(names))); } } return sb.toString(); } }
Java
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.util.Iterator; /** * Convert an HTTP header to a JSONObject and back. * @author JSON.org * @version 2008-09-18 */ public class HTTP { /** Carriage return/line feed. */ public static final String CRLF = "\r\n"; /** * Convert an HTTP header string into a JSONObject. It can be a request * header or a response header. A request header will contain * <pre>{ * Method: "POST" (for example), * "Request-URI": "/" (for example), * "HTTP-Version": "HTTP/1.1" (for example) * }</pre> * A response header will contain * <pre>{ * "HTTP-Version": "HTTP/1.1" (for example), * "Status-Code": "200" (for example), * "Reason-Phrase": "OK" (for example) * }</pre> * In addition, the other parameters in the header will be captured, using * the HTTP field names as JSON names, so that <pre> * Date: Sun, 26 May 2002 18:06:04 GMT * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s * Cache-Control: no-cache</pre> * become * <pre>{... * Date: "Sun, 26 May 2002 18:06:04 GMT", * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s", * "Cache-Control": "no-cache", * ...}</pre> * It does no further checking or conversion. It does not parse dates. * It does not do '%' transforms on URLs. * @param string An HTTP header string. * @return A JSONObject containing the elements and attributes * of the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject o = new JSONObject(); HTTPTokener x = new HTTPTokener(string); String t; t = x.nextToken(); if (t.toUpperCase().startsWith("HTTP")) { // Response o.put("HTTP-Version", t); o.put("Status-Code", x.nextToken()); o.put("Reason-Phrase", x.nextTo('\0')); x.next(); } else { // Request o.put("Method", t); o.put("Request-URI", x.nextToken()); o.put("HTTP-Version", x.nextToken()); } // Fields while (x.more()) { String name = x.nextTo(':'); x.next(':'); o.put(name, x.nextTo('\0')); x.next(); } return o; } /** * Convert a JSONObject into an HTTP header. A request header must contain * <pre>{ * Method: "POST" (for example), * "Request-URI": "/" (for example), * "HTTP-Version": "HTTP/1.1" (for example) * }</pre> * A response header must contain * <pre>{ * "HTTP-Version": "HTTP/1.1" (for example), * "Status-Code": "200" (for example), * "Reason-Phrase": "OK" (for example) * }</pre> * Any other members of the JSONObject will be output as HTTP fields. * The result will end with two CRLF pairs. * @param o A JSONObject * @return An HTTP header string. * @throws JSONException if the object does not contain enough * information. */ public static String toString(JSONObject o) throws JSONException { Iterator keys = o.keys(); String s; StringBuffer sb = new StringBuffer(); if (o.has("Status-Code") && o.has("Reason-Phrase")) { sb.append(o.getString("HTTP-Version")); sb.append(' '); sb.append(o.getString("Status-Code")); sb.append(' '); sb.append(o.getString("Reason-Phrase")); } else if (o.has("Method") && o.has("Request-URI")) { sb.append(o.getString("Method")); sb.append(' '); sb.append('"'); sb.append(o.getString("Request-URI")); sb.append('"'); sb.append(' '); sb.append(o.getString("HTTP-Version")); } else { throw new JSONException("Not enough material for an HTTP header."); } sb.append(CRLF); while (keys.hasNext()) { s = keys.next().toString(); if (!s.equals("HTTP-Version") && !s.equals("Status-Code") && !s.equals("Reason-Phrase") && !s.equals("Method") && !s.equals("Request-URI") && !o.isNull(s)) { sb.append(s); sb.append(": "); sb.append(o.getString(s)); sb.append(CRLF); } } sb.append(CRLF); return sb.toString(); } }
Java
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * Convert a web browser cookie specification to a JSONObject and back. * JSON and Cookies are both notations for name/value pairs. * @author JSON.org * @version 2008-09-18 */ public class Cookie { /** * Produce a copy of a string in which the characters '+', '%', '=', ';' * and control characters are replaced with "%hh". This is a gentle form * of URL encoding, attempting to cause as little distortion to the * string as possible. The characters '=' and ';' are meta characters in * cookies. By convention, they are escaped using the URL-encoding. This is * only a convention, not a standard. Often, cookies are expected to have * encoded values. We encode '=' and ';' because we must. We encode '%' and * '+' because they are meta characters in URL encoding. * @param string The source string. * @return The escaped result. */ public static String escape(String string) { char c; String s = string.trim(); StringBuffer sb = new StringBuffer(); int len = s.length(); for (int i = 0; i < len; i += 1) { c = s.charAt(i); if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { sb.append('%'); sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); sb.append(Character.forDigit((char)(c & 0x0f), 16)); } else { sb.append(c); } } return sb.toString(); } /** * Convert a cookie specification string into a JSONObject. The string * will contain a name value pair separated by '='. The name and the value * will be unescaped, possibly converting '+' and '%' sequences. The * cookie properties may follow, separated by ';', also represented as * name=value (except the secure property, which does not have a value). * The name will be stored under the key "name", and the value will be * stored under the key "value". This method does not do checking or * validation of the parameters. It only converts the cookie string into * a JSONObject. * @param string The cookie specification string. * @return A JSONObject containing "name", "value", and possibly other * members. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { String n; JSONObject o = new JSONObject(); Object v; JSONTokener x = new JSONTokener(string); o.put("name", x.nextTo('=')); x.next('='); o.put("value", x.nextTo(';')); x.next(); while (x.more()) { n = unescape(x.nextTo("=;")); if (x.next() != '=') { if (n.equals("secure")) { v = Boolean.TRUE; } else { throw x.syntaxError("Missing '=' in cookie parameter."); } } else { v = unescape(x.nextTo(';')); x.next(); } o.put(n, v); } return o; } /** * Convert a JSONObject into a cookie specification string. The JSONObject * must contain "name" and "value" members. * If the JSONObject contains "expires", "domain", "path", or "secure" * members, they will be appended to the cookie specification string. * All other members are ignored. * @param o A JSONObject * @return A cookie specification string * @throws JSONException */ public static String toString(JSONObject o) throws JSONException { StringBuffer sb = new StringBuffer(); sb.append(escape(o.getString("name"))); sb.append("="); sb.append(escape(o.getString("value"))); if (o.has("expires")) { sb.append(";expires="); sb.append(o.getString("expires")); } if (o.has("domain")) { sb.append(";domain="); sb.append(escape(o.getString("domain"))); } if (o.has("path")) { sb.append(";path="); sb.append(escape(o.getString("path"))); } if (o.optBoolean("secure")) { sb.append(";secure"); } return sb.toString(); } /** * Convert <code>%</code><i>hh</i> sequences to single characters, and * convert plus to space. * @param s A string that may contain * <code>+</code>&nbsp;<small>(plus)</small> and * <code>%</code><i>hh</i> sequences. * @return The unescaped string. */ public static String unescape(String s) { int len = s.length(); StringBuffer b = new StringBuffer(); for (int i = 0; i < len; ++i) { char c = s.charAt(i); if (c == '+') { c = ' '; } else if (c == '%' && i + 2 < len) { int d = JSONTokener.dehexchar(s.charAt(i + 1)); int e = JSONTokener.dehexchar(s.charAt(i + 2)); if (d >= 0 && e >= 0) { c = (char)(d * 16 + e); i += 2; } } b.append(c); } return b.toString(); } }
Java
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * The HTTPTokener extends the JSONTokener to provide additional methods * for the parsing of HTTP headers. * @author JSON.org * @version 2008-09-18 */ public class HTTPTokener extends JSONTokener { /** * Construct an XMLTokener from a string. * @param s A source string. */ public HTTPTokener(String s) { super(s); } /** * Get the next token or string. This is used in parsing HTTP headers. * @throws JSONException * @return A String. */ public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } } }
Java
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.io.IOException; import java.io.Writer; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeSet; /** * A JSONObject is an unordered collection of name/value pairs. Its * external form is a string wrapped in curly braces with colons between the * names and values, and commas between the values and names. The internal form * is an object having <code>get</code> and <code>opt</code> methods for * accessing the values by name, and <code>put</code> methods for adding or * replacing values by name. The values can be any of these types: * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, * <code>Number</code>, <code>String</code>, or the <code>JSONObject.NULL</code> * object. A JSONObject constructor can be used to convert an external form * JSON text into an internal form whose values can be retrieved with the * <code>get</code> and <code>opt</code> methods, or to convert values into a * JSON text using the <code>put</code> and <code>toString</code> methods. * A <code>get</code> method returns a value if one can be found, and throws an * exception if one cannot be found. An <code>opt</code> method returns a * default value instead of throwing an exception, and so is useful for * obtaining optional values. * <p> * The generic <code>get()</code> and <code>opt()</code> methods return an * object, which you can cast or query for type. There are also typed * <code>get</code> and <code>opt</code> methods that do type checking and type * coercion for you. * <p> * The <code>put</code> methods adds values to an object. For example, <pre> * myString = new JSONObject().put("JSON", "Hello, World!").toString();</pre> * produces the string <code>{"JSON": "Hello, World"}</code>. * <p> * The texts produced by the <code>toString</code> methods strictly conform to * the JSON syntax rules. * The constructors are more forgiving in the texts they will accept: * <ul> * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just * before the closing brace.</li> * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single * quote)</small>.</li> * <li>Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, * and if they do not contain any of these characters: * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers * and if they are not the reserved words <code>true</code>, * <code>false</code>, or <code>null</code>.</li> * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as * by <code>:</code>.</li> * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as * well as by <code>,</code> <small>(comma)</small>.</li> * <li>Numbers may have the <code>0-</code> <small>(octal)</small> or * <code>0x-</code> <small>(hex)</small> prefix.</li> * </ul> * @author JSON.org * @version 2008-09-18 */ public class JSONObject { /** * JSONObject.NULL is equivalent to the value that JavaScript calls null, * whilst Java's null is equivalent to the value that JavaScript calls * undefined. */ private static final class Null { /** * There is only intended to be a single instance of the NULL object, * so the clone method returns itself. * @return NULL. */ protected final Object clone() { return this; } /** * A Null object is equal to the null value and to itself. * @param object An object to test for nullness. * @return true if the object parameter is the JSONObject.NULL object * or null. */ public boolean equals(Object object) { return object == null || object == this; } /** * Get the "null" string value. * @return The string "null". */ public String toString() { return "null"; } } /** * The map where the JSONObject's properties are kept. */ private Map map; /** * It is sometimes more convenient and less ambiguous to have a * <code>NULL</code> object than to use Java's <code>null</code> value. * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>. * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>. */ public static final Object NULL = new Null(); /** * Construct an empty JSONObject. */ public JSONObject() { this.map = new HashMap(); } /** * Construct a JSONObject from a subset of another JSONObject. * An array of strings is used to identify the keys that should be copied. * Missing keys are ignored. * @param jo A JSONObject. * @param names An array of strings. * @exception JSONException If a value is a non-finite number or if a name is duplicated. */ public JSONObject(JSONObject jo, String[] names) throws JSONException { this(); for (int i = 0; i < names.length; i += 1) { putOnce(names[i], jo.opt(names[i])); } } /** * Construct a JSONObject from a JSONTokener. * @param x A JSONTokener object containing the source string. * @throws JSONException If there is a syntax error in the source string * or a duplicated key. */ public JSONObject(JSONTokener x) throws JSONException { this(); char c; String key; if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } for (;;) { c = x.nextClean(); switch (c) { case 0: throw x.syntaxError("A JSONObject text must end with '}'"); case '}': return; default: x.back(); key = x.nextValue().toString(); } /* * The key is followed by ':'. We will also tolerate '=' or '=>'. */ c = x.nextClean(); if (c == '=') { if (x.next() != '>') { x.back(); } } else if (c != ':') { throw x.syntaxError("Expected a ':' after a key"); } putOnce(key, x.nextValue()); /* * Pairs are separated by ','. We will also tolerate ';'. */ switch (x.nextClean()) { case ';': case ',': if (x.nextClean() == '}') { return; } x.back(); break; case '}': return; default: throw x.syntaxError("Expected a ',' or '}'"); } } } /** * Construct a JSONObject from a Map. * * @param map A map object that can be used to initialize the contents of * the JSONObject. */ public JSONObject(Map map) { this.map = (map == null) ? new HashMap() : map; } /** * Construct a JSONObject from a Map. * * Note: Use this constructor when the map contains <key,bean>. * * @param map - A map with Key-Bean data. * @param includeSuperClass - Tell whether to include the super class properties. */ public JSONObject(Map map, boolean includeSuperClass) { this.map = new HashMap(); if (map != null){ for (Iterator i = map.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry)i.next(); this.map.put(e.getKey(), new JSONObject(e.getValue(), includeSuperClass)); } } } /** * Construct a JSONObject from an Object using bean getters. * It reflects on all of the public methods of the object. * For each of the methods with no parameters and a name starting * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter, * the method is invoked, and a key and the value returned from the getter method * are put into the new JSONObject. * * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. If the second remaining * character is not upper case, then the first * character is converted to lower case. * * For example, if an object has a method named <code>"getName"</code>, and * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>, * then the JSONObject will contain <code>"name": "Larry Fine"</code>. * * @param bean An object that has getter methods that should be used * to make a JSONObject. */ public JSONObject(Object bean) { this(); populateInternalMap(bean, false); } /** * Construct JSONObject from the given bean. This will also create JSONObject * for all internal object (List, Map, Inner Objects) of the provided bean. * * -- See Documentation of JSONObject(Object bean) also. * * @param bean An object that has getter methods that should be used * to make a JSONObject. * @param includeSuperClass - Tell whether to include the super class properties. */ public JSONObject(Object bean, boolean includeSuperClass) { this(); populateInternalMap(bean, includeSuperClass); } private void populateInternalMap(Object bean, boolean includeSuperClass){ Class klass = bean.getClass(); //If klass.getSuperClass is System class then includeSuperClass = false; if (klass.getClassLoader() == null) { includeSuperClass = false; } Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods(); for (int i = 0; i < methods.length; i += 1) { try { Method method = methods[i]; String name = method.getName(); String key = ""; if (name.startsWith("get")) { key = name.substring(3); } else if (name.startsWith("is")) { key = name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } Object result = method.invoke(bean, (Object[])null); if (result == null){ map.put(key, NULL); }else if (result.getClass().isArray()) { map.put(key, new JSONArray(result,includeSuperClass)); }else if (result instanceof Collection) { //List or Set map.put(key, new JSONArray((Collection)result,includeSuperClass)); }else if (result instanceof Map) { map.put(key, new JSONObject((Map)result,includeSuperClass)); }else if (isStandardProperty(result.getClass())) { //Primitives, String and Wrapper map.put(key, result); }else{ if (result.getClass().getPackage().getName().startsWith("java") || result.getClass().getClassLoader() == null) { map.put(key, result.toString()); } else { //User defined Objects map.put(key, new JSONObject(result,includeSuperClass)); } } } } catch (Exception e) { throw new RuntimeException(e); } } } private boolean isStandardProperty(Class clazz) { return clazz.isPrimitive() || clazz.isAssignableFrom(Byte.class) || clazz.isAssignableFrom(Short.class) || clazz.isAssignableFrom(Integer.class) || clazz.isAssignableFrom(Long.class) || clazz.isAssignableFrom(Float.class) || clazz.isAssignableFrom(Double.class) || clazz.isAssignableFrom(Character.class) || clazz.isAssignableFrom(String.class) || clazz.isAssignableFrom(Boolean.class); } /** * Construct a JSONObject from an Object, using reflection to find the * public members. The resulting JSONObject's keys will be the strings * from the names array, and the values will be the field values associated * with those keys in the object. If a key is not found or not visible, * then it will not be copied into the new JSONObject. * @param object An object that has fields that should be used to make a * JSONObject. * @param names An array of strings, the names of the fields to be obtained * from the object. */ public JSONObject(Object object, String names[]) { this(); Class c = object.getClass(); for (int i = 0; i < names.length; i += 1) { String name = names[i]; try { putOpt(name, c.getField(name).get(object)); } catch (Exception e) { /* forget about it */ } } } /** * Construct a JSONObject from a source JSON text string. * This is the most commonly used JSONObject constructor. * @param source A string beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @exception JSONException If there is a syntax error in the source * string or a duplicated key. */ public JSONObject(String source) throws JSONException { this(new JSONTokener(source)); } /** * Accumulate values under a key. It is similar to the put method except * that if there is already an object stored under the key then a * JSONArray is stored under the key to hold all of the accumulated values. * If there is already a JSONArray, then the new value is appended to it. * In contrast, the put method replaces the previous value. * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number * or if the key is null. */ public JSONObject accumulate(String key, Object value) throws JSONException { testValidity(value); Object o = opt(key); if (o == null) { put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); } else if (o instanceof JSONArray) { ((JSONArray)o).put(value); } else { put(key, new JSONArray().put(o).put(value)); } return this; } /** * Append values to the array under a key. If the key does not exist in the * JSONObject, then the key is put in the JSONObject with its value being a * JSONArray containing the value parameter. If the key was already * associated with a JSONArray, then the value parameter is appended to it. * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the key is null or if the current value * associated with the key is not a JSONArray. */ public JSONObject append(String key, Object value) throws JSONException { testValidity(value); Object o = opt(key); if (o == null) { put(key, new JSONArray().put(value)); } else if (o instanceof JSONArray) { put(key, ((JSONArray)o).put(value)); } else { throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); } return this; } /** * Produce a string from a double. The string "null" will be returned if * the number is not finite. * @param d A double. * @return A String. */ static public String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String s = Double.toString(d); if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { while (s.endsWith("0")) { s = s.substring(0, s.length() - 1); } if (s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } return s; } /** * Get the value object associated with a key. * * @param key A key string. * @return The object associated with the key. * @throws JSONException if the key is not found. */ public Object get(String key) throws JSONException { Object o = opt(key); if (o == null) { throw new JSONException("JSONObject[" + quote(key) + "] not found."); } return o; } /** * Get the boolean value associated with a key. * * @param key A key string. * @return The truth. * @throws JSONException * if the value is not a Boolean or the String "true" or "false". */ public boolean getBoolean(String key) throws JSONException { Object o = get(key); if (o.equals(Boolean.FALSE) || (o instanceof String && ((String)o).equalsIgnoreCase("false"))) { return false; } else if (o.equals(Boolean.TRUE) || (o instanceof String && ((String)o).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); } /** * Get the double value associated with a key. * @param key A key string. * @return The numeric value. * @throws JSONException if the key is not found or * if the value is not a Number object and cannot be converted to a number. */ public double getDouble(String key) throws JSONException { Object o = get(key); try { return o instanceof Number ? ((Number)o).doubleValue() : Double.valueOf((String)o).doubleValue(); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } } /** * Get the int value associated with a key. If the number value is too * large for an int, it will be clipped. * * @param key A key string. * @return The integer value. * @throws JSONException if the key is not found or if the value cannot * be converted to an integer. */ public int getInt(String key) throws JSONException { Object o = get(key); return o instanceof Number ? ((Number)o).intValue() : (int)getDouble(key); } /** * Get the JSONArray value associated with a key. * * @param key A key string. * @return A JSONArray which is the value. * @throws JSONException if the key is not found or * if the value is not a JSONArray. */ public JSONArray getJSONArray(String key) throws JSONException { Object o = get(key); if (o instanceof JSONArray) { return (JSONArray)o; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); } /** * Get the JSONObject value associated with a key. * * @param key A key string. * @return A JSONObject which is the value. * @throws JSONException if the key is not found or * if the value is not a JSONObject. */ public JSONObject getJSONObject(String key) throws JSONException { Object o = get(key); if (o instanceof JSONObject) { return (JSONObject)o; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); } /** * Get the long value associated with a key. If the number value is too * long for a long, it will be clipped. * * @param key A key string. * @return The long value. * @throws JSONException if the key is not found or if the value cannot * be converted to a long. */ public long getLong(String key) throws JSONException { Object o = get(key); return o instanceof Number ? ((Number)o).longValue() : (long)getDouble(key); } /** * Get an array of field names from a JSONObject. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(JSONObject jo) { int length = jo.length(); if (length == 0) { return null; } Iterator i = jo.keys(); String[] names = new String[length]; int j = 0; while (i.hasNext()) { names[j] = (String)i.next(); j += 1; } return names; } /** * Get an array of field names from an Object. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(Object object) { if (object == null) { return null; } Class klass = object.getClass(); Field[] fields = klass.getFields(); int length = fields.length; if (length == 0) { return null; } String[] names = new String[length]; for (int i = 0; i < length; i += 1) { names[i] = fields[i].getName(); } return names; } /** * Get the string associated with a key. * * @param key A key string. * @return A string which is the value. * @throws JSONException if the key is not found. */ public String getString(String key) throws JSONException { return get(key).toString(); } /** * Determine if the JSONObject contains a specific key. * @param key A key string. * @return true if the key exists in the JSONObject. */ public boolean has(String key) { return this.map.containsKey(key); } /** * Determine if the value associated with the key is null or if there is * no value. * @param key A key string. * @return true if there is no value associated with the key or if * the value is the JSONObject.NULL object. */ public boolean isNull(String key) { return JSONObject.NULL.equals(opt(key)); } /** * Get an enumeration of the keys of the JSONObject. * * @return An iterator of the keys. */ public Iterator keys() { return this.map.keySet().iterator(); } /** * Get the number of keys stored in the JSONObject. * * @return The number of keys in the JSONObject. */ public int length() { return this.map.size(); } /** * Produce a JSONArray containing the names of the elements of this * JSONObject. * @return A JSONArray containing the key strings, or null if the JSONObject * is empty. */ public JSONArray names() { JSONArray ja = new JSONArray(); Iterator keys = keys(); while (keys.hasNext()) { ja.put(keys.next()); } return ja.length() == 0 ? null : ja; } /** * Produce a string from a Number. * @param n A Number * @return A String. * @throws JSONException If n is a non-finite number. */ static public String numberToString(Number n) throws JSONException { if (n == null) { throw new JSONException("Null pointer"); } testValidity(n); // Shave off trailing zeros and decimal point, if possible. String s = n.toString(); if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { while (s.endsWith("0")) { s = s.substring(0, s.length() - 1); } if (s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } return s; } /** * Get an optional value associated with a key. * @param key A key string. * @return An object which is the value, or null if there is no value. */ public Object opt(String key) { return key == null ? null : this.map.get(key); } /** * Get an optional boolean associated with a key. * It returns false if there is no such key, or if the value is not * Boolean.TRUE or the String "true". * * @param key A key string. * @return The truth. */ public boolean optBoolean(String key) { return optBoolean(key, false); } /** * Get an optional boolean associated with a key. * It returns the defaultValue if there is no such key, or if it is not * a Boolean or the String "true" or "false" (case insensitive). * * @param key A key string. * @param defaultValue The default. * @return The truth. */ public boolean optBoolean(String key, boolean defaultValue) { try { return getBoolean(key); } catch (Exception e) { return defaultValue; } } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONArray which is produced from a Collection. * @param key A key string. * @param value A Collection value. * @return this. * @throws JSONException */ public JSONObject put(String key, Collection value) throws JSONException { put(key, new JSONArray(value)); return this; } /** * Get an optional double associated with a key, * or NaN if there is no such key or if its value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A string which is the key. * @return An object which is the value. */ public double optDouble(String key) { return optDouble(key, Double.NaN); } /** * Get an optional double associated with a key, or the * defaultValue if there is no such key or if its value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public double optDouble(String key, double defaultValue) { try { Object o = opt(key); return o instanceof Number ? ((Number)o).doubleValue() : new Double((String)o).doubleValue(); } catch (Exception e) { return defaultValue; } } /** * Get an optional int value associated with a key, * or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @return An object which is the value. */ public int optInt(String key) { return optInt(key, 0); } /** * Get an optional int value associated with a key, * or the default if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public int optInt(String key, int defaultValue) { try { return getInt(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional JSONArray associated with a key. * It returns null if there is no such key, or if its value is not a * JSONArray. * * @param key A key string. * @return A JSONArray which is the value. */ public JSONArray optJSONArray(String key) { Object o = opt(key); return o instanceof JSONArray ? (JSONArray)o : null; } /** * Get an optional JSONObject associated with a key. * It returns null if there is no such key, or if its value is not a * JSONObject. * * @param key A key string. * @return A JSONObject which is the value. */ public JSONObject optJSONObject(String key) { Object o = opt(key); return o instanceof JSONObject ? (JSONObject)o : null; } /** * Get an optional long value associated with a key, * or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @return An object which is the value. */ public long optLong(String key) { return optLong(key, 0); } /** * Get an optional long value associated with a key, * or the default if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public long optLong(String key, long defaultValue) { try { return getLong(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional string associated with a key. * It returns an empty string if there is no such key. If the value is not * a string and is not null, then it is coverted to a string. * * @param key A key string. * @return A string which is the value. */ public String optString(String key) { return optString(key, ""); } /** * Get an optional string associated with a key. * It returns the defaultValue if there is no such key. * * @param key A key string. * @param defaultValue The default. * @return A string which is the value. */ public String optString(String key, String defaultValue) { Object o = opt(key); return o != null ? o.toString() : defaultValue; } /** * Put a key/boolean pair in the JSONObject. * * @param key A key string. * @param value A boolean which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, boolean value) throws JSONException { put(key, value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a key/double pair in the JSONObject. * * @param key A key string. * @param value A double which is the value. * @return this. * @throws JSONException If the key is null or if the number is invalid. */ public JSONObject put(String key, double value) throws JSONException { put(key, new Double(value)); return this; } /** * Put a key/int pair in the JSONObject. * * @param key A key string. * @param value An int which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, int value) throws JSONException { put(key, new Integer(value)); return this; } /** * Put a key/long pair in the JSONObject. * * @param key A key string. * @param value A long which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, long value) throws JSONException { put(key, new Long(value)); return this; } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONObject which is produced from a Map. * @param key A key string. * @param value A Map value. * @return this. * @throws JSONException */ public JSONObject put(String key, Map value) throws JSONException { put(key, new JSONObject(value)); return this; } /** * Put a key/value pair in the JSONObject. If the value is null, * then the key will be removed from the JSONObject if it is present. * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is non-finite number * or if the key is null. */ public JSONObject put(String key, Object value) throws JSONException { if (key == null) { throw new JSONException("Null key."); } if (value != null) { testValidity(value); this.map.put(key, value); } else { remove(key); } return this; } /** * Put a key/value pair in the JSONObject, but only if the key and the * value are both non-null, and only if there is not already a member * with that name. * @param key * @param value * @return his. * @throws JSONException if the key is a duplicate */ public JSONObject putOnce(String key, Object value) throws JSONException { if (key != null && value != null) { if (opt(key) != null) { throw new JSONException("Duplicate key \"" + key + "\""); } put(key, value); } return this; } /** * Put a key/value pair in the JSONObject, but only if the * key and the value are both non-null. * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is a non-finite number. */ public JSONObject putOpt(String key, Object value) throws JSONException { if (key != null && value != null) { put(key, value); } return this; } /** * Produce a string in double quotes with backslash sequences in all the * right places. A backslash will be inserted within </, allowing JSON * text to be delivered in HTML. In JSON text, a string cannot contain a * control character or an unescaped quote or backslash. * @param string A String * @return A String correctly formatted for insertion in a JSON text. */ public static String quote(String string) { if (string == null || string.length() == 0) { return "\"\""; } char b; char c = 0; int i; int len = string.length(); StringBuffer sb = new StringBuffer(len + 4); String t; sb.append('"'); for (i = 0; i < len; i += 1) { b = c; c = string.charAt(i); switch (c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; case '/': if (b == '<') { sb.append('\\'); } sb.append(c); break; case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { t = "000" + Integer.toHexString(c); sb.append("\\u" + t.substring(t.length() - 4)); } else { sb.append(c); } } } sb.append('"'); return sb.toString(); } /** * Remove a name and its value, if present. * @param key The name to be removed. * @return The value that was associated with the name, * or null if there was no value. */ public Object remove(String key) { return this.map.remove(key); } /** * Get an enumeration of the keys of the JSONObject. * The keys will be sorted alphabetically. * * @return An iterator of the keys. */ public Iterator sortedKeys() { return new TreeSet(this.map.keySet()).iterator(); } /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. * @param s A String. * @return A simple JSON value. */ static public Object stringToValue(String s) { if (s.equals("")) { return s; } if (s.equalsIgnoreCase("true")) { return Boolean.TRUE; } if (s.equalsIgnoreCase("false")) { return Boolean.FALSE; } if (s.equalsIgnoreCase("null")) { return JSONObject.NULL; } /* * If it might be a number, try converting it. We support the 0- and 0x- * conventions. If a number cannot be produced, then the value will just * be a string. Note that the 0-, 0x-, plus, and implied string * conventions are non-standard. A JSON parser is free to accept * non-JSON forms as long as it accepts all correct JSON forms. */ char b = s.charAt(0); if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { if (b == '0') { if (s.length() > 2 && (s.charAt(1) == 'x' || s.charAt(1) == 'X')) { try { return new Integer(Integer.parseInt(s.substring(2), 16)); } catch (Exception e) { /* Ignore the error */ } } else { try { return new Integer(Integer.parseInt(s, 8)); } catch (Exception e) { /* Ignore the error */ } } } try { return new Integer(s); } catch (Exception e) { try { return new Long(s); } catch (Exception f) { try { return new Double(s); } catch (Exception g) { /* Ignore the error */ } } } } return s; } /** * Throw an exception if the object is an NaN or infinite number. * @param o The object to test. * @throws JSONException If o is a non-finite number. */ static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } } /** * Produce a JSONArray containing the values of the members of this * JSONObject. * @param names A JSONArray containing a list of key strings. This * determines the sequence of the values in the result. * @return A JSONArray of values. * @throws JSONException If any of the values are non-finite numbers. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); for (int i = 0; i < names.length(); i += 1) { ja.put(this.opt(names.getString(i))); } return ja; } /** * Make a JSON text of this JSONObject. For compactness, no whitespace * is added. If this would not result in a syntactically correct JSON text, * then null will be returned instead. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. */ public String toString() { try { Iterator keys = keys(); StringBuffer sb = new StringBuffer("{"); while (keys.hasNext()) { if (sb.length() > 1) { sb.append(','); } Object o = keys.next(); sb.append(quote(o.toString())); sb.append(':'); sb.append(valueToString(this.map.get(o))); } sb.append('}'); return sb.toString(); } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONObject. * <p> * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, portable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ public String toString(int indentFactor) throws JSONException { return toString(indentFactor, 0); } /** * Make a prettyprinted JSON text of this JSONObject. * <p> * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ String toString(int indentFactor, int indent) throws JSONException { int j; int n = length(); if (n == 0) { return "{}"; } Iterator keys = sortedKeys(); StringBuffer sb = new StringBuffer("{"); int newindent = indent + indentFactor; Object o; if (n == 1) { o = keys.next(); sb.append(quote(o.toString())); sb.append(": "); sb.append(valueToString(this.map.get(o), indentFactor, indent)); } else { while (keys.hasNext()) { o = keys.next(); if (sb.length() > 1) { sb.append(",\n"); } else { sb.append('\n'); } for (j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(quote(o.toString())); sb.append(": "); sb.append(valueToString(this.map.get(o), indentFactor, newindent)); } if (sb.length() > 1) { sb.append('\n'); for (j = 0; j < indent; j += 1) { sb.append(' '); } } } sb.append('}'); return sb.toString(); } /** * Make a JSON text of an Object value. If the object has an * value.toJSONString() method, then that method will be used to produce * the JSON text. The method is required to produce a strictly * conforming text. If the object does not contain a toJSONString * method (which is the most common case), then a text will be * produced by other means. If the value is an array or Collection, * then a JSONArray will be made from it and its toJSONString method * will be called. If the value is a MAP, then a JSONObject will be made * from it and its toJSONString method will be called. Otherwise, the * value's toString method will be called, and the result will be quoted. * * <p> * Warning: This method assumes that the data structure is acyclical. * @param value The value to be serialized. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the value is or contains an invalid number. */ static String valueToString(Object value) throws JSONException { if (value == null || value.equals(null)) { return "null"; } if (value instanceof JSONString) { Object o; try { o = ((JSONString)value).toJSONString(); } catch (Exception e) { throw new JSONException(e); } if (o instanceof String) { return (String)o; } throw new JSONException("Bad value from toJSONString: " + o); } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { return value.toString(); } if (value instanceof Map) { return new JSONObject((Map)value).toString(); } if (value instanceof Collection) { return new JSONArray((Collection)value).toString(); } if (value.getClass().isArray()) { return new JSONArray(value).toString(); } return quote(value.toString()); } /** * Make a prettyprinted JSON text of an object value. * <p> * Warning: This method assumes that the data structure is acyclical. * @param value The value to be serialized. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ static String valueToString(Object value, int indentFactor, int indent) throws JSONException { if (value == null || value.equals(null)) { return "null"; } try { if (value instanceof JSONString) { Object o = ((JSONString)value).toJSONString(); if (o instanceof String) { return (String)o; } } } catch (Exception e) { /* forget about it */ } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean) { return value.toString(); } if (value instanceof JSONObject) { return ((JSONObject)value).toString(indentFactor, indent); } if (value instanceof JSONArray) { return ((JSONArray)value).toString(indentFactor, indent); } if (value instanceof Map) { return new JSONObject((Map)value).toString(indentFactor, indent); } if (value instanceof Collection) { return new JSONArray((Collection)value).toString(indentFactor, indent); } if (value.getClass().isArray()) { return new JSONArray(value).toString(indentFactor, indent); } return quote(value.toString()); } /** * Write the contents of the JSONObject as JSON text to a writer. * For compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean b = false; Iterator keys = keys(); writer.write('{'); while (keys.hasNext()) { if (b) { writer.write(','); } Object k = keys.next(); writer.write(quote(k.toString())); writer.write(':'); Object v = this.map.get(k); if (v instanceof JSONObject) { ((JSONObject)v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray)v).write(writer); } else { writer.write(valueToString(v)); } b = true; } writer.write('}'); return writer; } catch (IOException e) { throw new JSONException(e); } } }
Java
package org.json; /* Copyright (c) 2006 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.io.StringWriter; /** * JSONStringer provides a quick and convenient way of producing JSON text. * The texts produced strictly conform to JSON syntax rules. No whitespace is * added, so the results are ready for transmission or storage. Each instance of * JSONStringer can produce one JSON text. * <p> * A JSONStringer instance provides a <code>value</code> method for appending * values to the * text, and a <code>key</code> * method for adding keys before values in objects. There are <code>array</code> * and <code>endArray</code> methods that make and bound array values, and * <code>object</code> and <code>endObject</code> methods which make and bound * object values. All of these methods return the JSONWriter instance, * permitting cascade style. For example, <pre> * myString = new JSONStringer() * .object() * .key("JSON") * .value("Hello, World!") * .endObject() * .toString();</pre> which produces the string <pre> * {"JSON":"Hello, World!"}</pre> * <p> * The first method called must be <code>array</code> or <code>object</code>. * There are no methods for adding commas or colons. JSONStringer adds them for * you. Objects and arrays can be nested up to 20 levels deep. * <p> * This can sometimes be easier than using a JSONObject to build a string. * @author JSON.org * @version 2008-09-18 */ public class JSONStringer extends JSONWriter { /** * Make a fresh JSONStringer. It can be used to build one JSON text. */ public JSONStringer() { super(new StringWriter()); } /** * Return the JSON text. This method is used to obtain the product of the * JSONStringer instance. It will return <code>null</code> if there was a * problem in the construction of the JSON text (such as the calls to * <code>array</code> were not properly balanced with calls to * <code>endArray</code>). * @return The JSON text. */ public String toString() { return this.mode == 'd' ? this.writer.toString() : null; } }
Java
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * The XMLTokener extends the JSONTokener to provide additional methods * for the parsing of XML texts. * @author JSON.org * @version 2008-09-18 */ public class XMLTokener extends JSONTokener { /** The table of entity values. It initially contains Character values for * amp, apos, gt, lt, quot. */ public static final java.util.HashMap entity; static { entity = new java.util.HashMap(8); entity.put("amp", XML.AMP); entity.put("apos", XML.APOS); entity.put("gt", XML.GT); entity.put("lt", XML.LT); entity.put("quot", XML.QUOT); } /** * Construct an XMLTokener from a string. * @param s A source string. */ public XMLTokener(String s) { super(s); } /** * Get the text in the CDATA block. * @return The string up to the <code>]]&gt;</code>. * @throws JSONException If the <code>]]&gt;</code> is not found. */ public String nextCDATA() throws JSONException { char c; int i; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); if (c == 0) { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { sb.setLength(i); return sb.toString(); } } } /** * Get the next XML outer token, trimming whitespace. There are two kinds * of tokens: the '<' character which begins a markup tag, and the content * text between markup tags. * * @return A string, or a '<' Character, or null if there is no more * source text. * @throws JSONException */ public Object nextContent() throws JSONException { char c; StringBuffer sb; do { c = next(); } while (Character.isWhitespace(c)); if (c == 0) { return null; } if (c == '<') { return XML.LT; } sb = new StringBuffer(); for (;;) { if (c == '<' || c == 0) { back(); return sb.toString().trim(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } c = next(); } } /** * Return the next entity. These entities are translated to Characters: * <code>&amp; &apos; &gt; &lt; &quot;</code>. * @param a An ampersand character. * @return A Character or an entity String if the entity is not recognized. * @throws JSONException If missing ';' in XML entity. */ public Object nextEntity(char a) throws JSONException { StringBuffer sb = new StringBuffer(); for (;;) { char c = next(); if (Character.isLetterOrDigit(c) || c == '#') { sb.append(Character.toLowerCase(c)); } else if (c == ';') { break; } else { throw syntaxError("Missing ';' in XML entity: &" + sb); } } String s = sb.toString(); Object e = entity.get(s); return e != null ? e : a + s + ";"; } /** * Returns the next XML meta token. This is used for skipping over <!...> * and <?...?> structures. * @return Syntax characters (<code>< > / = ! ?</code>) are returned as * Character, and strings and names are returned as Boolean. We don't care * what the values actually are. * @throws JSONException If a string is not properly closed or if the XML * is badly structured. */ public Object nextMeta() throws JSONException { char c; char q; do { c = next(); } while (Character.isWhitespace(c)); switch (c) { case 0: throw syntaxError("Misshaped meta tag"); case '<': return XML.LT; case '>': return XML.GT; case '/': return XML.SLASH; case '=': return XML.EQ; case '!': return XML.BANG; case '?': return XML.QUEST; case '"': case '\'': q = c; for (;;) { c = next(); if (c == 0) { throw syntaxError("Unterminated string"); } if (c == q) { return Boolean.TRUE; } } default: for (;;) { c = next(); if (Character.isWhitespace(c)) { return Boolean.TRUE; } switch (c) { case 0: case '<': case '>': case '/': case '=': case '!': case '?': case '"': case '\'': back(); return Boolean.TRUE; } } } } /** * Get the next XML Token. These tokens are found inside of angle * brackets. It may be one of these characters: <code>/ > = ! ?</code> or it * may be a string wrapped in single quotes or double quotes, or it may be a * name. * @return a String or a Character. * @throws JSONException If the XML is not well formed. */ public Object nextToken() throws JSONException { char c; char q; StringBuffer sb; do { c = next(); } while (Character.isWhitespace(c)); switch (c) { case 0: throw syntaxError("Misshaped element"); case '<': throw syntaxError("Misplaced '<'"); case '>': return XML.GT; case '/': return XML.SLASH; case '=': return XML.EQ; case '!': return XML.BANG; case '?': return XML.QUEST; // Quoted string case '"': case '\'': q = c; sb = new StringBuffer(); for (;;) { c = next(); if (c == 0) { throw syntaxError("Unterminated string"); } if (c == q) { return sb.toString(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } } default: // Name sb = new StringBuffer(); for (;;) { sb.append(c); c = next(); if (Character.isWhitespace(c)) { return sb.toString(); } switch (c) { case 0: return sb.toString(); case '>': case '/': case '=': case '!': case '?': case '[': case ']': back(); return sb.toString(); case '<': case '"': case '\'': throw syntaxError("Bad character in a name"); } } } } /** * Skip characters until past the requested string. * If it is not found, we are left at the end of the source with a result of false. * @param to A string to skip past. * @throws JSONException */ public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int n = to.length(); char[] circle = new char[n]; /* * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ for (i = 0; i < n; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* * We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* * Compare the circle buffer with the to string. */ for (i = 0; i < n; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= n) { j -= n; } } /* * If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* * Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= n) { offset -= n; } } } }
Java
package org.json; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * A JSONTokener takes a source string and extracts characters and tokens from * it. It is used by the JSONObject and JSONArray constructors to parse * JSON source strings. * @author JSON.org * @version 2008-09-18 */ public class JSONTokener { private int index; private Reader reader; private char lastChar; private boolean useLastChar; /** * Construct a JSONTokener from a string. * * @param reader A reader. */ public JSONTokener(Reader reader) { this.reader = reader.markSupported() ? reader : new BufferedReader(reader); this.useLastChar = false; this.index = 0; } /** * Construct a JSONTokener from a string. * * @param s A source string. */ public JSONTokener(String s) { this(new StringReader(s)); } /** * Back up one character. This provides a sort of lookahead capability, * so that you can test for a digit or letter before attempting to parse * the next number or identifier. */ public void back() throws JSONException { if (useLastChar || index <= 0) { throw new JSONException("Stepping back two steps is not supported"); } index -= 1; useLastChar = true; } /** * Get the hex value of a character (base16). * @param c A character between '0' and '9' or between 'A' and 'F' or * between 'a' and 'f'. * @return An int between 0 and 15, or -1 if c was not a hex digit. */ public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; } /** * Determine if the source string still contains characters that next() * can consume. * @return true if not yet at the end of the source. */ public boolean more() throws JSONException { char nextChar = next(); if (nextChar == 0) { return false; } back(); return true; } /** * Get the next character in the source string. * * @return The next character, or 0 if past the end of the source string. */ public char next() throws JSONException { if (this.useLastChar) { this.useLastChar = false; if (this.lastChar != 0) { this.index += 1; } return this.lastChar; } int c; try { c = this.reader.read(); } catch (IOException exc) { throw new JSONException(exc); } if (c <= 0) { // End of stream this.lastChar = 0; return 0; } this.index += 1; this.lastChar = (char) c; return this.lastChar; } /** * Consume the next character, and check that it matches a specified * character. * @param c The character to match. * @return The character. * @throws JSONException if the character does not match. */ public char next(char c) throws JSONException { char n = next(); if (n != c) { throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); } return n; } /** * Get the next n characters. * * @param n The number of characters to take. * @return A string of n characters. * @throws JSONException * Substring bounds error if there are not * n characters remaining in the source string. */ public String next(int n) throws JSONException { if (n == 0) { return ""; } char[] buffer = new char[n]; int pos = 0; if (this.useLastChar) { this.useLastChar = false; buffer[0] = this.lastChar; pos = 1; } try { int len; while ((pos < n) && ((len = reader.read(buffer, pos, n - pos)) != -1)) { pos += len; } } catch (IOException exc) { throw new JSONException(exc); } this.index += pos; if (pos < n) { throw syntaxError("Substring bounds error"); } this.lastChar = buffer[n - 1]; return new String(buffer); } /** * Get the next char in the string, skipping whitespace. * @throws JSONException * @return A character, or 0 if there are no more characters. */ public char nextClean() throws JSONException { for (;;) { char c = next(); if (c == 0 || c > ' ') { return c; } } } /** * Return the characters up to the next close quote character. * Backslash processing is done. The formal JSON format does not * allow strings in single quotes, but an implementation is allowed to * accept them. * @param quote The quoting character, either * <code>"</code>&nbsp;<small>(double quote)</small> or * <code>'</code>&nbsp;<small>(single quote)</small>. * @return A String. * @throws JSONException Unterminated string. */ public String nextString(char quote) throws JSONException { char c; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); switch (c) { case 0: case '\n': case '\r': throw syntaxError("Unterminated string"); case '\\': c = next(); switch (c) { case 'b': sb.append('\b'); break; case 't': sb.append('\t'); break; case 'n': sb.append('\n'); break; case 'f': sb.append('\f'); break; case 'r': sb.append('\r'); break; case 'u': sb.append((char)Integer.parseInt(next(4), 16)); break; case 'x' : sb.append((char) Integer.parseInt(next(2), 16)); break; default: sb.append(c); } break; default: if (c == quote) { return sb.toString(); } sb.append(c); } } } /** * Get the text up but not including the specified character or the * end of line, whichever comes first. * @param d A delimiter character. * @return A string. */ public String nextTo(char d) throws JSONException { StringBuffer sb = new StringBuffer(); for (;;) { char c = next(); if (c == d || c == 0 || c == '\n' || c == '\r') { if (c != 0) { back(); } return sb.toString().trim(); } sb.append(c); } } /** * Get the text up but not including one of the specified delimiter * characters or the end of line, whichever comes first. * @param delimiters A set of delimiter characters. * @return A string, trimmed. */ public String nextTo(String delimiters) throws JSONException { char c; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { if (c != 0) { back(); } return sb.toString().trim(); } sb.append(c); } } /** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. * @throws JSONException If syntax error. * * @return An object. */ public Object nextValue() throws JSONException { char c = nextClean(); String s; switch (c) { case '"': case '\'': return nextString(c); case '{': back(); return new JSONObject(this); case '[': case '(': back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = next(); } back(); s = sb.toString().trim(); if (s.equals("")) { throw syntaxError("Missing value"); } return JSONObject.stringToValue(s); } /** * Skip characters until the next character is the requested character. * If the requested character is not found, no characters are skipped. * @param to A character to skip to. * @return The requested character, or zero if the requested character * is not found. */ public char skipTo(char to) throws JSONException { char c; try { int startIndex = this.index; reader.mark(Integer.MAX_VALUE); do { c = next(); if (c == 0) { reader.reset(); this.index = startIndex; return c; } } while (c != to); } catch (IOException exc) { throw new JSONException(exc); } back(); return c; } /** * Make a JSONException to signal a syntax error. * * @param message The error message. * @return A JSONException object, suitable for throwing */ public JSONException syntaxError(String message) { return new JSONException(message + toString()); } /** * Make a printable string of this JSONTokener. * * @return " at character [this.index]" */ public String toString() { return " at character " + index; } }
Java
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.util.Iterator; /** * Convert a web browser cookie list string to a JSONObject and back. * @author JSON.org * @version 2008-09-18 */ public class CookieList { /** * Convert a cookie list into a JSONObject. A cookie list is a sequence * of name/value pairs. The names are separated from the values by '='. * The pairs are separated by ';'. The names and the values * will be unescaped, possibly converting '+' and '%' sequences. * * To add a cookie to a cooklist, * cookielistJSONObject.put(cookieJSONObject.getString("name"), * cookieJSONObject.getString("value")); * @param string A cookie list string * @return A JSONObject * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject o = new JSONObject(); JSONTokener x = new JSONTokener(string); while (x.more()) { String name = Cookie.unescape(x.nextTo('=')); x.next('='); o.put(name, Cookie.unescape(x.nextTo(';'))); x.next(); } return o; } /** * Convert a JSONObject into a cookie list. A cookie list is a sequence * of name/value pairs. The names are separated from the values by '='. * The pairs are separated by ';'. The characters '%', '+', '=', and ';' * in the names and values are replaced by "%hh". * @param o A JSONObject * @return A cookie list string * @throws JSONException */ public static String toString(JSONObject o) throws JSONException { boolean b = false; Iterator keys = o.keys(); String s; StringBuffer sb = new StringBuffer(); while (keys.hasNext()) { s = keys.next().toString(); if (!o.isNull(s)) { if (b) { sb.append(';'); } sb.append(Cookie.escape(s)); sb.append("="); sb.append(Cookie.escape(o.getString(s))); b = true; } } return sb.toString(); } }
Java
package org.json; /** * The <code>JSONString</code> interface allows a <code>toJSONString()</code> * method so that a class can change the behavior of * <code>JSONObject.toString()</code>, <code>JSONArray.toString()</code>, * and <code>JSONWriter.value(</code>Object<code>)</code>. The * <code>toJSONString</code> method will be used instead of the default behavior * of using the Object's <code>toString()</code> method and quoting the result. */ public interface JSONString { /** * The <code>toJSONString</code> method allows a class to produce its own JSON * serialization. * * @return A strictly syntactically correct JSON text. */ public String toJSONString(); }
Java
package org.json; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.io.StringWriter; /** * Test class. This file is not formally a member of the org.json library. * It is just a casual test tool. */ public class Test { /** * Entry point. * @param args */ public static void main(String args[]) { Iterator it; JSONArray a; JSONObject j; JSONStringer jj; String s; /** * Obj is a typical class that implements JSONString. It also * provides some beanie methods that can be used to * construct a JSONObject. It also demonstrates constructing * a JSONObject with an array of names. */ class Obj implements JSONString { public String aString; public double aNumber; public boolean aBoolean; public Obj(String string, double n, boolean b) { this.aString = string; this.aNumber = n; this.aBoolean = b; } public double getNumber() { return this.aNumber; } public String getString() { return this.aString; } public boolean isBoolean() { return this.aBoolean; } public String getBENT() { return "All uppercase key"; } public String getX() { return "x"; } public String toJSONString() { return "{" + JSONObject.quote(this.aString) + ":" + JSONObject.doubleToString(this.aNumber) + "}"; } public String toString() { return this.getString() + " " + this.getNumber() + " " + this.isBoolean() + "." + this.getBENT() + " " + this.getX(); } } Obj obj = new Obj("A beany object", 42, true); try { j = XML.toJSONObject("<![CDATA[This is a collection of test patterns and examples for org.json.]]> Ignore the stuff past the end. "); System.out.println(j.toString()); s = "{ \"list of lists\" : [ [1, 2, 3], [4, 5, 6], ] }"; j = new JSONObject(s); System.out.println(j.toString(4)); System.out.println(XML.toString(j)); s = "<recipe name=\"bread\" prep_time=\"5 mins\" cook_time=\"3 hours\"> <title>Basic bread</title> <ingredient amount=\"8\" unit=\"dL\">Flour</ingredient> <ingredient amount=\"10\" unit=\"grams\">Yeast</ingredient> <ingredient amount=\"4\" unit=\"dL\" state=\"warm\">Water</ingredient> <ingredient amount=\"1\" unit=\"teaspoon\">Salt</ingredient> <instructions> <step>Mix all ingredients together.</step> <step>Knead thoroughly.</step> <step>Cover with a cloth, and leave for one hour in warm room.</step> <step>Knead again.</step> <step>Place in a bread baking tin.</step> <step>Cover with a cloth, and leave for one hour in warm room.</step> <step>Bake in the oven at 180(degrees)C for 30 minutes.</step> </instructions> </recipe> "; j = XML.toJSONObject(s); System.out.println(j.toString(4)); System.out.println(); j = JSONML.toJSONObject(s); System.out.println(j.toString()); System.out.println(JSONML.toString(j)); System.out.println(); a = JSONML.toJSONArray(s); System.out.println(a.toString(4)); System.out.println(JSONML.toString(a)); System.out.println(); s = "<div id=\"demo\" class=\"JSONML\"><p>JSONML is a transformation between <b>JSON</b> and <b>XML</b> that preserves ordering of document features.</p><p>JSONML can work with JSON arrays or JSON objects.</p><p>Three<br/>little<br/>words</p></div>"; j = JSONML.toJSONObject(s); System.out.println(j.toString(4)); System.out.println(JSONML.toString(j)); System.out.println(); a = JSONML.toJSONArray(s); System.out.println(a.toString(4)); System.out.println(JSONML.toString(a)); System.out.println(); s = "<person created=\"2006-11-11T19:23\" modified=\"2006-12-31T23:59\">\n <firstName>Robert</firstName>\n <lastName>Smith</lastName>\n <address type=\"home\">\n <street>12345 Sixth Ave</street>\n <city>Anytown</city>\n <state>CA</state>\n <postalCode>98765-4321</postalCode>\n </address>\n </person>"; j = XML.toJSONObject(s); System.out.println(j.toString(4)); j = new JSONObject(obj); System.out.println(j.toString()); s = "{ \"entity\": { \"imageURL\": \"\", \"name\": \"IXXXXXXXXXXXXX\", \"id\": 12336, \"ratingCount\": null, \"averageRating\": null } }"; j = new JSONObject(s); System.out.println(j.toString(2)); jj = new JSONStringer(); s = jj .object() .key("single") .value("MARIE HAA'S") .key("Johnny") .value("MARIE HAA\\'S") .key("foo") .value("bar") .key("baz") .array() .object() .key("quux") .value("Thanks, Josh!") .endObject() .endArray() .key("obj keys") .value(JSONObject.getNames(obj)) .endObject() .toString(); System.out.println(s); System.out.println(new JSONStringer() .object() .key("a") .array() .array() .array() .value("b") .endArray() .endArray() .endArray() .endObject() .toString()); jj = new JSONStringer(); jj.array(); jj.value(1); jj.array(); jj.value(null); jj.array(); jj.object(); jj.key("empty-array").array().endArray(); jj.key("answer").value(42); jj.key("null").value(null); jj.key("false").value(false); jj.key("true").value(true); jj.key("big").value(123456789e+88); jj.key("small").value(123456789e-88); jj.key("empty-object").object().endObject(); jj.key("long"); jj.value(9223372036854775807L); jj.endObject(); jj.value("two"); jj.endArray(); jj.value(true); jj.endArray(); jj.value(98.6); jj.value(-100.0); jj.object(); jj.endObject(); jj.object(); jj.key("one"); jj.value(1.00); jj.endObject(); jj.value(obj); jj.endArray(); System.out.println(jj.toString()); System.out.println(new JSONArray(jj.toString()).toString(4)); int ar[] = {1, 2, 3}; JSONArray ja = new JSONArray(ar); System.out.println(ja.toString()); String sa[] = {"aString", "aNumber", "aBoolean"}; j = new JSONObject(obj, sa); j.put("Testing JSONString interface", obj); System.out.println(j.toString(4)); j = new JSONObject("{slashes: '///', closetag: '</script>', backslash:'\\\\', ei: {quotes: '\"\\''},eo: {a: '\"quoted\"', b:\"don't\"}, quotes: [\"'\", '\"']}"); System.out.println(j.toString(2)); System.out.println(XML.toString(j)); System.out.println(""); j = new JSONObject( "{foo: [true, false,9876543210, 0.0, 1.00000001, 1.000000000001, 1.00000000000000001," + " .00000000000000001, 2.00, 0.1, 2e100, -32,[],{}, \"string\"], " + " to : null, op : 'Good'," + "ten:10} postfix comment"); j.put("String", "98.6"); j.put("JSONObject", new JSONObject()); j.put("JSONArray", new JSONArray()); j.put("int", 57); j.put("double", 123456789012345678901234567890.); j.put("true", true); j.put("false", false); j.put("null", JSONObject.NULL); j.put("bool", "true"); j.put("zero", -0.0); j.put("\\u2028", "\u2028"); j.put("\\u2029", "\u2029"); a = j.getJSONArray("foo"); a.put(666); a.put(2001.99); a.put("so \"fine\"."); a.put("so <fine>."); a.put(true); a.put(false); a.put(new JSONArray()); a.put(new JSONObject()); j.put("keys", JSONObject.getNames(j)); System.out.println(j.toString(4)); System.out.println(XML.toString(j)); System.out.println("String: " + j.getDouble("String")); System.out.println(" bool: " + j.getBoolean("bool")); System.out.println(" to: " + j.getString("to")); System.out.println(" true: " + j.getString("true")); System.out.println(" foo: " + j.getJSONArray("foo")); System.out.println(" op: " + j.getString("op")); System.out.println(" ten: " + j.getInt("ten")); System.out.println(" oops: " + j.optBoolean("oops")); s = "<xml one = 1 two=' \"2\" '><five></five>First \u0009&lt;content&gt;<five></five> This is \"content\". <three> 3 </three>JSON does not preserve the sequencing of elements and contents.<three> III </three> <three> T H R E E</three><four/>Content text is an implied structure in XML. <six content=\"6\"/>JSON does not have implied structure:<seven>7</seven>everything is explicit.<![CDATA[CDATA blocks<are><supported>!]]></xml>"; j = XML.toJSONObject(s); System.out.println(j.toString(2)); System.out.println(XML.toString(j)); System.out.println(""); ja = JSONML.toJSONArray(s); System.out.println(ja.toString(4)); System.out.println(JSONML.toString(ja)); System.out.println(""); s = "<xml do='0'>uno<a re='1' mi='2'>dos<b fa='3'/>tres<c>true</c>quatro</a>cinqo<d>seis<e/></d></xml>"; ja = JSONML.toJSONArray(s); System.out.println(ja.toString(4)); System.out.println(JSONML.toString(ja)); System.out.println(""); s = "<mapping><empty/> <class name = \"Customer\"> <field name = \"ID\" type = \"string\"> <bind-xml name=\"ID\" node=\"attribute\"/> </field> <field name = \"FirstName\" type = \"FirstName\"/> <field name = \"MI\" type = \"MI\"/> <field name = \"LastName\" type = \"LastName\"/> </class> <class name = \"FirstName\"> <field name = \"text\"> <bind-xml name = \"text\" node = \"text\"/> </field> </class> <class name = \"MI\"> <field name = \"text\"> <bind-xml name = \"text\" node = \"text\"/> </field> </class> <class name = \"LastName\"> <field name = \"text\"> <bind-xml name = \"text\" node = \"text\"/> </field> </class></mapping>"; j = XML.toJSONObject(s); System.out.println(j.toString(2)); System.out.println(XML.toString(j)); System.out.println(""); ja = JSONML.toJSONArray(s); System.out.println(ja.toString(4)); System.out.println(JSONML.toString(ja)); System.out.println(""); j = XML.toJSONObject("<?xml version=\"1.0\" ?><Book Author=\"Anonymous\"><Title>Sample Book</Title><Chapter id=\"1\">This is chapter 1. It is not very long or interesting.</Chapter><Chapter id=\"2\">This is chapter 2. Although it is longer than chapter 1, it is not any more interesting.</Chapter></Book>"); System.out.println(j.toString(2)); System.out.println(XML.toString(j)); System.out.println(""); j = XML.toJSONObject("<!DOCTYPE bCard 'http://www.cs.caltech.edu/~adam/schemas/bCard'><bCard><?xml default bCard firstname = '' lastname = '' company = '' email = '' homepage = ''?><bCard firstname = 'Rohit' lastname = 'Khare' company = 'MCI' email = 'khare@mci.net' homepage = 'http://pest.w3.org/'/><bCard firstname = 'Adam' lastname = 'Rifkin' company = 'Caltech Infospheres Project' email = 'adam@cs.caltech.edu' homepage = 'http://www.cs.caltech.edu/~adam/'/></bCard>"); System.out.println(j.toString(2)); System.out.println(XML.toString(j)); System.out.println(""); j = XML.toJSONObject("<?xml version=\"1.0\"?><customer> <firstName> <text>Fred</text> </firstName> <ID>fbs0001</ID> <lastName> <text>Scerbo</text> </lastName> <MI> <text>B</text> </MI></customer>"); System.out.println(j.toString(2)); System.out.println(XML.toString(j)); System.out.println(""); j = XML.toJSONObject("<!ENTITY tp-address PUBLIC '-//ABC University::Special Collections Library//TEXT (titlepage: name and address)//EN' 'tpspcoll.sgm'><list type='simple'><head>Repository Address </head><item>Special Collections Library</item><item>ABC University</item><item>Main Library, 40 Circle Drive</item><item>Ourtown, Pennsylvania</item><item>17654 USA</item></list>"); System.out.println(j.toString()); System.out.println(XML.toString(j)); System.out.println(""); j = XML.toJSONObject("<test intertag status=ok><empty/>deluxe<blip sweet=true>&amp;&quot;toot&quot;&toot;&#x41;</blip><x>eks</x><w>bonus</w><w>bonus2</w></test>"); System.out.println(j.toString(2)); System.out.println(XML.toString(j)); System.out.println(""); j = HTTP.toJSONObject("GET / HTTP/1.0\nAccept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*\nAccept-Language: en-us\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90; T312461; Q312461)\nHost: www.nokko.com\nConnection: keep-alive\nAccept-encoding: gzip, deflate\n"); System.out.println(j.toString(2)); System.out.println(HTTP.toString(j)); System.out.println(""); j = HTTP.toJSONObject("HTTP/1.1 200 Oki Doki\nDate: Sun, 26 May 2002 17:38:52 GMT\nServer: Apache/1.3.23 (Unix) mod_perl/1.26\nKeep-Alive: timeout=15, max=100\nConnection: Keep-Alive\nTransfer-Encoding: chunked\nContent-Type: text/html\n"); System.out.println(j.toString(2)); System.out.println(HTTP.toString(j)); System.out.println(""); j = new JSONObject("{nix: null, nux: false, null: 'null', 'Request-URI': '/', Method: 'GET', 'HTTP-Version': 'HTTP/1.0'}"); System.out.println(j.toString(2)); System.out.println("isNull: " + j.isNull("nix")); System.out.println(" has: " + j.has("nix")); System.out.println(XML.toString(j)); System.out.println(HTTP.toString(j)); System.out.println(""); j = XML.toJSONObject("<?xml version='1.0' encoding='UTF-8'?>"+"\n\n"+"<SOAP-ENV:Envelope"+ " xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\""+ " xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\""+ " xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\">"+ "<SOAP-ENV:Body><ns1:doGoogleSearch"+ " xmlns:ns1=\"urn:GoogleSearch\""+ " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"+ "<key xsi:type=\"xsd:string\">GOOGLEKEY</key> <q"+ " xsi:type=\"xsd:string\">'+search+'</q> <start"+ " xsi:type=\"xsd:int\">0</start> <maxResults"+ " xsi:type=\"xsd:int\">10</maxResults> <filter"+ " xsi:type=\"xsd:boolean\">true</filter> <restrict"+ " xsi:type=\"xsd:string\"></restrict> <safeSearch"+ " xsi:type=\"xsd:boolean\">false</safeSearch> <lr"+ " xsi:type=\"xsd:string\"></lr> <ie"+ " xsi:type=\"xsd:string\">latin1</ie> <oe"+ " xsi:type=\"xsd:string\">latin1</oe>"+ "</ns1:doGoogleSearch>"+ "</SOAP-ENV:Body></SOAP-ENV:Envelope>"); System.out.println(j.toString(2)); System.out.println(XML.toString(j)); System.out.println(""); j = new JSONObject("{Envelope: {Body: {\"ns1:doGoogleSearch\": {oe: \"latin1\", filter: true, q: \"'+search+'\", key: \"GOOGLEKEY\", maxResults: 10, \"SOAP-ENV:encodingStyle\": \"http://schemas.xmlsoap.org/soap/encoding/\", start: 0, ie: \"latin1\", safeSearch:false, \"xmlns:ns1\": \"urn:GoogleSearch\"}}}}"); System.out.println(j.toString(2)); System.out.println(XML.toString(j)); System.out.println(""); j = CookieList.toJSONObject(" f%oo = b+l=ah ; o;n%40e = t.wo "); System.out.println(j.toString(2)); System.out.println(CookieList.toString(j)); System.out.println(""); j = Cookie.toJSONObject("f%oo=blah; secure ;expires = April 24, 2002"); System.out.println(j.toString(2)); System.out.println(Cookie.toString(j)); System.out.println(""); j = new JSONObject("{script: 'It is not allowed in HTML to send a close script tag in a string<script>because it confuses browsers</script>so we insert a backslash before the /'}"); System.out.println(j.toString()); System.out.println(""); JSONTokener jt = new JSONTokener("{op:'test', to:'session', pre:1}{op:'test', to:'session', pre:2}"); j = new JSONObject(jt); System.out.println(j.toString()); System.out.println("pre: " + j.optInt("pre")); int i = jt.skipTo('{'); System.out.println(i); j = new JSONObject(jt); System.out.println(j.toString()); System.out.println(""); a = CDL.toJSONArray("No quotes, 'Single Quotes', \"Double Quotes\"\n1,'2',\"3\"\n,'It is \"good,\"', \"It works.\"\n\n"); System.out.println(CDL.toString(a)); System.out.println(""); System.out.println(a.toString(4)); System.out.println(""); a = new JSONArray(" [\"<escape>\", next is an implied null , , ok,] "); System.out.println(a.toString()); System.out.println(""); System.out.println(XML.toString(a)); System.out.println(""); j = new JSONObject("{ fun => with non-standard forms ; forgiving => This package can be used to parse formats that are similar to but not stricting conforming to JSON; why=To make it easier to migrate existing data to JSON,one = [[1.00]]; uno=[[{1=>1}]];'+':+6e66 ;pluses=+++;empty = '' , 'double':0.666,true: TRUE, false: FALSE, null=NULL;[true] = [[!,@;*]]; string=> o. k. ; \r oct=0666; hex=0x666; dec=666; o=0999; noh=0x0x}"); System.out.println(j.toString(4)); System.out.println(""); if (j.getBoolean("true") && !j.getBoolean("false")) { System.out.println("It's all good"); } System.out.println(""); j = new JSONObject(j, new String[]{"dec", "oct", "hex", "missing"}); System.out.println(j.toString(4)); System.out.println(""); System.out.println(new JSONStringer().array().value(a).value(j).endArray()); j = new JSONObject("{string: \"98.6\", long: 2147483648, int: 2147483647, longer: 9223372036854775807, double: 9223372036854775808}"); System.out.println(j.toString(4)); System.out.println("\ngetInt"); System.out.println("int " + j.getInt("int")); System.out.println("long " + j.getInt("long")); System.out.println("longer " + j.getInt("longer")); System.out.println("double " + j.getInt("double")); System.out.println("string " + j.getInt("string")); System.out.println("\ngetLong"); System.out.println("int " + j.getLong("int")); System.out.println("long " + j.getLong("long")); System.out.println("longer " + j.getLong("longer")); System.out.println("double " + j.getLong("double")); System.out.println("string " + j.getLong("string")); System.out.println("\ngetDouble"); System.out.println("int " + j.getDouble("int")); System.out.println("long " + j.getDouble("long")); System.out.println("longer " + j.getDouble("longer")); System.out.println("double " + j.getDouble("double")); System.out.println("string " + j.getDouble("string")); j.put("good sized", 9223372036854775807L); System.out.println(j.toString(4)); a = new JSONArray("[2147483647, 2147483648, 9223372036854775807, 9223372036854775808]"); System.out.println(a.toString(4)); System.out.println("\nKeys: "); it = j.keys(); while (it.hasNext()) { s = (String)it.next(); System.out.println(s + ": " + j.getString(s)); } System.out.println("\naccumulate: "); j = new JSONObject(); j.accumulate("stooge", "Curly"); j.accumulate("stooge", "Larry"); j.accumulate("stooge", "Moe"); a = j.getJSONArray("stooge"); a.put(5, "Shemp"); System.out.println(j.toString(4)); System.out.println("\nwrite:"); System.out.println(j.write(new StringWriter())); s = "<xml empty><a></a><a>1</a><a>22</a><a>333</a></xml>"; j = XML.toJSONObject(s); System.out.println(j.toString(4)); System.out.println(XML.toString(j)); s = "<book><chapter>Content of the first chapter</chapter><chapter>Content of the second chapter <chapter>Content of the first subchapter</chapter> <chapter>Content of the second subchapter</chapter></chapter><chapter>Third Chapter</chapter></book>"; j = XML.toJSONObject(s); System.out.println(j.toString(4)); System.out.println(XML.toString(j)); a = JSONML.toJSONArray(s); System.out.println(a.toString(4)); System.out.println(JSONML.toString(a)); Collection c = null; Map m = null; j = new JSONObject(m); a = new JSONArray(c); j.append("stooge", "Joe DeRita"); j.append("stooge", "Shemp"); j.accumulate("stooges", "Curly"); j.accumulate("stooges", "Larry"); j.accumulate("stooges", "Moe"); j.accumulate("stoogearray", j.get("stooges")); j.put("map", m); j.put("collection", c); j.put("array", a); a.put(m); a.put(c); System.out.println(j.toString(4)); s = "{plist=Apple; AnimalSmells = { pig = piggish; lamb = lambish; worm = wormy; }; AnimalSounds = { pig = oink; lamb = baa; worm = baa; Lisa = \"Why is the worm talking like a lamb?\" } ; AnimalColors = { pig = pink; lamb = black; worm = pink; } } "; j = new JSONObject(s); System.out.println(j.toString(4)); s = " (\"San Francisco\", \"New York\", \"Seoul\", \"London\", \"Seattle\", \"Shanghai\")"; a = new JSONArray(s); System.out.println(a.toString()); s = "<a ichi='1' ni='2'><b>The content of b</b> and <c san='3'>The content of c</c><d>do</d><e></e><d>re</d><f/><d>mi</d></a>"; j = XML.toJSONObject(s); System.out.println(j.toString(2)); System.out.println(XML.toString(j)); System.out.println(""); ja = JSONML.toJSONArray(s); System.out.println(ja.toString(4)); System.out.println(JSONML.toString(ja)); System.out.println(""); System.out.println("\nTesting Exceptions: "); System.out.print("Exception: "); try { a = new JSONArray(); a.put(Double.NEGATIVE_INFINITY); a.put(Double.NaN); System.out.println(a.toString()); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { System.out.println(j.getDouble("stooge")); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { System.out.println(j.getDouble("howard")); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { System.out.println(j.put(null, "howard")); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { System.out.println(a.getDouble(0)); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { System.out.println(a.get(-1)); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { System.out.println(a.put(Double.NaN)); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { j = XML.toJSONObject("<a><b> "); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { j = XML.toJSONObject("<a></b> "); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { j = XML.toJSONObject("<a></a "); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { ja = new JSONArray(new Object()); System.out.println(ja.toString()); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { s = "[)"; a = new JSONArray(s); System.out.println(a.toString()); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { s = "<xml"; ja = JSONML.toJSONArray(s); System.out.println(ja.toString(4)); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { s = "<right></wrong>"; ja = JSONML.toJSONArray(s); System.out.println(ja.toString(4)); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { s = "{\"koda\": true, \"koda\": true}"; j = new JSONObject(s); System.out.println(j.toString(4)); } catch (Exception e) { System.out.println(e); } System.out.print("Exception: "); try { jj = new JSONStringer(); s = jj .object() .key("bosanda") .value("MARIE HAA'S") .key("bosanda") .value("MARIE HAA\\'S") .endObject() .toString(); System.out.println(j.toString(4)); } catch (Exception e) { System.out.println(e); } } catch (Exception e) { System.out.println(e.toString()); } } }
Java
package org.json; import java.io.IOException; import java.io.Writer; /* Copyright (c) 2006 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * JSONWriter provides a quick and convenient way of producing JSON text. * The texts produced strictly conform to JSON syntax rules. No whitespace is * added, so the results are ready for transmission or storage. Each instance of * JSONWriter can produce one JSON text. * <p> * A JSONWriter instance provides a <code>value</code> method for appending * values to the * text, and a <code>key</code> * method for adding keys before values in objects. There are <code>array</code> * and <code>endArray</code> methods that make and bound array values, and * <code>object</code> and <code>endObject</code> methods which make and bound * object values. All of these methods return the JSONWriter instance, * permitting a cascade style. For example, <pre> * new JSONWriter(myWriter) * .object() * .key("JSON") * .value("Hello, World!") * .endObject();</pre> which writes <pre> * {"JSON":"Hello, World!"}</pre> * <p> * The first method called must be <code>array</code> or <code>object</code>. * There are no methods for adding commas or colons. JSONWriter adds them for * you. Objects and arrays can be nested up to 20 levels deep. * <p> * This can sometimes be easier than using a JSONObject to build a string. * @author JSON.org * @version 2008-09-18 */ public class JSONWriter { private static final int maxdepth = 20; /** * The comma flag determines if a comma should be output before the next * value. */ private boolean comma; /** * The current mode. Values: * 'a' (array), * 'd' (done), * 'i' (initial), * 'k' (key), * 'o' (object). */ protected char mode; /** * The object/array stack. */ private JSONObject stack[]; /** * The stack top index. A value of 0 indicates that the stack is empty. */ private int top; /** * The writer that will receive the output. */ protected Writer writer; /** * Make a fresh JSONWriter. It can be used to build one JSON text. */ public JSONWriter(Writer w) { this.comma = false; this.mode = 'i'; this.stack = new JSONObject[maxdepth]; this.top = 0; this.writer = w; } /** * Append a value. * @param s A string value. * @return this * @throws JSONException If the value is out of sequence. */ private JSONWriter append(String s) throws JSONException { if (s == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(s); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); } /** * Begin appending a new array. All values until the balancing * <code>endArray</code> will be appended to this array. The * <code>endArray</code> method must be called to mark the array's end. * @return this * @throws JSONException If the nesting is too deep, or if the object is * started in the wrong place (for example as a key or after the end of the * outermost array or object). */ public JSONWriter array() throws JSONException { if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { this.push(null); this.append("["); this.comma = false; return this; } throw new JSONException("Misplaced array."); } /** * End something. * @param m Mode * @param c Closing character * @return this * @throws JSONException If unbalanced. */ private JSONWriter end(char m, char c) throws JSONException { if (this.mode != m) { throw new JSONException(m == 'o' ? "Misplaced endObject." : "Misplaced endArray."); } this.pop(m); try { this.writer.write(c); } catch (IOException e) { throw new JSONException(e); } this.comma = true; return this; } /** * End an array. This method most be called to balance calls to * <code>array</code>. * @return this * @throws JSONException If incorrectly nested. */ public JSONWriter endArray() throws JSONException { return this.end('a', ']'); } /** * End an object. This method most be called to balance calls to * <code>object</code>. * @return this * @throws JSONException If incorrectly nested. */ public JSONWriter endObject() throws JSONException { return this.end('k', '}'); } /** * Append a key. The key will be associated with the next value. In an * object, every value must be preceded by a key. * @param s A key string. * @return this * @throws JSONException If the key is out of place. For example, keys * do not belong in arrays or if the key is null. */ public JSONWriter key(String s) throws JSONException { if (s == null) { throw new JSONException("Null key."); } if (this.mode == 'k') { try { if (this.comma) { this.writer.write(','); } stack[top - 1].putOnce(s, Boolean.TRUE); this.writer.write(JSONObject.quote(s)); this.writer.write(':'); this.comma = false; this.mode = 'o'; return this; } catch (IOException e) { throw new JSONException(e); } } throw new JSONException("Misplaced key."); } /** * Begin appending a new object. All keys and values until the balancing * <code>endObject</code> will be appended to this object. The * <code>endObject</code> method must be called to mark the object's end. * @return this * @throws JSONException If the nesting is too deep, or if the object is * started in the wrong place (for example as a key or after the end of the * outermost array or object). */ public JSONWriter object() throws JSONException { if (this.mode == 'i') { this.mode = 'o'; } if (this.mode == 'o' || this.mode == 'a') { this.append("{"); this.push(new JSONObject()); this.comma = false; return this; } throw new JSONException("Misplaced object."); } /** * Pop an array or object scope. * @param c The scope to close. * @throws JSONException If nesting is wrong. */ private void pop(char c) throws JSONException { if (this.top <= 0) { throw new JSONException("Nesting error."); } char m = this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != c) { throw new JSONException("Nesting error."); } this.top -= 1; this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; } /** * Push an array or object scope. * @param c The scope to open. * @throws JSONException If nesting is too deep. */ private void push(JSONObject jo) throws JSONException { if (this.top >= maxdepth) { throw new JSONException("Nesting too deep."); } this.stack[this.top] = jo; this.mode = jo == null ? 'a' : 'k'; this.top += 1; } /** * Append either the value <code>true</code> or the value * <code>false</code>. * @param b A boolean. * @return this * @throws JSONException */ public JSONWriter value(boolean b) throws JSONException { return this.append(b ? "true" : "false"); } /** * Append a double value. * @param d A double. * @return this * @throws JSONException If the number is not finite. */ public JSONWriter value(double d) throws JSONException { return this.value(new Double(d)); } /** * Append a long value. * @param l A long. * @return this * @throws JSONException */ public JSONWriter value(long l) throws JSONException { return this.append(Long.toString(l)); } /** * Append an object value. * @param o The object to append. It can be null, or a Boolean, Number, * String, JSONObject, or JSONArray, or an object with a toJSONString() * method. * @return this * @throws JSONException If the value is out of sequence. */ public JSONWriter value(Object o) throws JSONException { return this.append(JSONObject.valueToString(o)); } }
Java
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.io.IOException; import java.io.Writer; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * A JSONArray is an ordered sequence of values. Its external text form is a * string wrapped in square brackets with commas separating the values. The * internal form is an object having <code>get</code> and <code>opt</code> * methods for accessing the values by index, and <code>put</code> methods for * adding or replacing values. The values can be any of these types: * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, * <code>Number</code>, <code>String</code>, or the * <code>JSONObject.NULL object</code>. * <p> * The constructor can convert a JSON text into a Java object. The * <code>toString</code> method converts to JSON text. * <p> * A <code>get</code> method returns a value if one can be found, and throws an * exception if one cannot be found. An <code>opt</code> method returns a * default value instead of throwing an exception, and so is useful for * obtaining optional values. * <p> * The generic <code>get()</code> and <code>opt()</code> methods return an * object which you can cast or query for type. There are also typed * <code>get</code> and <code>opt</code> methods that do type checking and type * coercion for you. * <p> * The texts produced by the <code>toString</code> methods strictly conform to * JSON syntax rules. The constructors are more forgiving in the texts they will * accept: * <ul> * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just * before the closing bracket.</li> * <li>The <code>null</code> value will be inserted when there * is <code>,</code>&nbsp;<small>(comma)</small> elision.</li> * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single * quote)</small>.</li> * <li>Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, * and if they do not contain any of these characters: * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers * and if they are not the reserved words <code>true</code>, * <code>false</code>, or <code>null</code>.</li> * <li>Values can be separated by <code>;</code> <small>(semicolon)</small> as * well as by <code>,</code> <small>(comma)</small>.</li> * <li>Numbers may have the <code>0-</code> <small>(octal)</small> or * <code>0x-</code> <small>(hex)</small> prefix.</li> * </ul> * @author JSON.org * @version 2008-09-18 */ public class JSONArray { /** * The arrayList where the JSONArray's properties are kept. */ private ArrayList myArrayList; /** * Construct an empty JSONArray. */ public JSONArray() { this.myArrayList = new ArrayList(); } /** * Construct a JSONArray from a JSONTokener. * @param x A JSONTokener * @throws JSONException If there is a syntax error. */ public JSONArray(JSONTokener x) throws JSONException { this(); char c = x.nextClean(); char q; if (c == '[') { q = ']'; } else if (c == '(') { q = ')'; } else { throw x.syntaxError("A JSONArray text must start with '['"); } if (x.nextClean() == ']') { return; } x.back(); for (;;) { if (x.nextClean() == ',') { x.back(); this.myArrayList.add(null); } else { x.back(); this.myArrayList.add(x.nextValue()); } c = x.nextClean(); switch (c) { case ';': case ',': if (x.nextClean() == ']') { return; } x.back(); break; case ']': case ')': if (q != c) { throw x.syntaxError("Expected a '" + new Character(q) + "'"); } return; default: throw x.syntaxError("Expected a ',' or ']'"); } } } /** * Construct a JSONArray from a source JSON text. * @param source A string that begins with * <code>[</code>&nbsp;<small>(left bracket)</small> * and ends with <code>]</code>&nbsp;<small>(right bracket)</small>. * @throws JSONException If there is a syntax error. */ public JSONArray(String source) throws JSONException { this(new JSONTokener(source)); } /** * Construct a JSONArray from a Collection. * @param collection A Collection. */ public JSONArray(Collection collection) { this.myArrayList = (collection == null) ? new ArrayList() : new ArrayList(collection); } /** * Construct a JSONArray from a collection of beans. * The collection should have Java Beans. * * @throws JSONException If not an array. */ public JSONArray(Collection collection,boolean includeSuperClass) { this.myArrayList = new ArrayList(); if(collection != null) { for (Iterator iter = collection.iterator(); iter.hasNext();) { this.myArrayList.add(new JSONObject(iter.next(),includeSuperClass)); } } } /** * Construct a JSONArray from an array * @throws JSONException If not an array. */ public JSONArray(Object array) throws JSONException { this(); if (array.getClass().isArray()) { int length = Array.getLength(array); for (int i = 0; i < length; i += 1) { this.put(Array.get(array, i)); } } else { throw new JSONException("JSONArray initial value should be a string or collection or array."); } } /** * Construct a JSONArray from an array with a bean. * The array should have Java Beans. * * @throws JSONException If not an array. */ public JSONArray(Object array,boolean includeSuperClass) throws JSONException { this(); if (array.getClass().isArray()) { int length = Array.getLength(array); for (int i = 0; i < length; i += 1) { this.put(new JSONObject(Array.get(array, i),includeSuperClass)); } } else { throw new JSONException("JSONArray initial value should be a string or collection or array."); } } /** * Get the object value associated with an index. * @param index * The index must be between 0 and length() - 1. * @return An object value. * @throws JSONException If there is no value for the index. */ public Object get(int index) throws JSONException { Object o = opt(index); if (o == null) { throw new JSONException("JSONArray[" + index + "] not found."); } return o; } /** * Get the boolean value associated with an index. * The string values "true" and "false" are converted to boolean. * * @param index The index must be between 0 and length() - 1. * @return The truth. * @throws JSONException If there is no value for the index or if the * value is not convertable to boolean. */ public boolean getBoolean(int index) throws JSONException { Object o = get(index); if (o.equals(Boolean.FALSE) || (o instanceof String && ((String)o).equalsIgnoreCase("false"))) { return false; } else if (o.equals(Boolean.TRUE) || (o instanceof String && ((String)o).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a Boolean."); } /** * Get the double value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot * be converted to a number. */ public double getDouble(int index) throws JSONException { Object o = get(index); try { return o instanceof Number ? ((Number)o).doubleValue() : Double.valueOf((String)o).doubleValue(); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the int value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot * be converted to a number. * if the value cannot be converted to a number. */ public int getInt(int index) throws JSONException { Object o = get(index); return o instanceof Number ? ((Number)o).intValue() : (int)getDouble(index); } /** * Get the JSONArray associated with an index. * @param index The index must be between 0 and length() - 1. * @return A JSONArray value. * @throws JSONException If there is no value for the index. or if the * value is not a JSONArray */ public JSONArray getJSONArray(int index) throws JSONException { Object o = get(index); if (o instanceof JSONArray) { return (JSONArray)o; } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); } /** * Get the JSONObject associated with an index. * @param index subscript * @return A JSONObject value. * @throws JSONException If there is no value for the index or if the * value is not a JSONObject */ public JSONObject getJSONObject(int index) throws JSONException { Object o = get(index); if (o instanceof JSONObject) { return (JSONObject)o; } throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); } /** * Get the long value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot * be converted to a number. */ public long getLong(int index) throws JSONException { Object o = get(index); return o instanceof Number ? ((Number)o).longValue() : (long)getDouble(index); } /** * Get the string associated with an index. * @param index The index must be between 0 and length() - 1. * @return A string value. * @throws JSONException If there is no value for the index. */ public String getString(int index) throws JSONException { return get(index).toString(); } /** * Determine if the value is null. * @param index The index must be between 0 and length() - 1. * @return true if the value at the index is null, or if there is no value. */ public boolean isNull(int index) { return JSONObject.NULL.equals(opt(index)); } /** * Make a string from the contents of this JSONArray. The * <code>separator</code> string is inserted between each element. * Warning: This method assumes that the data structure is acyclical. * @param separator A string that will be inserted between the elements. * @return a string. * @throws JSONException If the array contains an invalid number. */ public String join(String separator) throws JSONException { int len = length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < len; i += 1) { if (i > 0) { sb.append(separator); } sb.append(JSONObject.valueToString(this.myArrayList.get(i))); } return sb.toString(); } /** * Get the number of elements in the JSONArray, included nulls. * * @return The length (or size). */ public int length() { return this.myArrayList.size(); } /** * Get the optional object value associated with an index. * @param index The index must be between 0 and length() - 1. * @return An object value, or null if there is no * object at that index. */ public Object opt(int index) { return (index < 0 || index >= length()) ? null : this.myArrayList.get(index); } /** * Get the optional boolean value associated with an index. * It returns false if there is no value at that index, * or if the value is not Boolean.TRUE or the String "true". * * @param index The index must be between 0 and length() - 1. * @return The truth. */ public boolean optBoolean(int index) { return optBoolean(index, false); } /** * Get the optional boolean value associated with an index. * It returns the defaultValue if there is no value at that index or if * it is not a Boolean or the String "true" or "false" (case insensitive). * * @param index The index must be between 0 and length() - 1. * @param defaultValue A boolean default. * @return The truth. */ public boolean optBoolean(int index, boolean defaultValue) { try { return getBoolean(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional double value associated with an index. * NaN is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public double optDouble(int index) { return optDouble(index, Double.NaN); } /** * Get the optional double value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index subscript * @param defaultValue The default value. * @return The value. */ public double optDouble(int index, double defaultValue) { try { return getDouble(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional int value associated with an index. * Zero is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public int optInt(int index) { return optInt(index, 0); } /** * Get the optional int value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. * @return The value. */ public int optInt(int index, int defaultValue) { try { return getInt(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional JSONArray associated with an index. * @param index subscript * @return A JSONArray value, or null if the index has no value, * or if the value is not a JSONArray. */ public JSONArray optJSONArray(int index) { Object o = opt(index); return o instanceof JSONArray ? (JSONArray)o : null; } /** * Get the optional JSONObject associated with an index. * Null is returned if the key is not found, or null if the index has * no value, or if the value is not a JSONObject. * * @param index The index must be between 0 and length() - 1. * @return A JSONObject value. */ public JSONObject optJSONObject(int index) { Object o = opt(index); return o instanceof JSONObject ? (JSONObject)o : null; } /** * Get the optional long value associated with an index. * Zero is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public long optLong(int index) { return optLong(index, 0); } /** * Get the optional long value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. * @return The value. */ public long optLong(int index, long defaultValue) { try { return getLong(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional string value associated with an index. It returns an * empty string if there is no value at that index. If the value * is not a string and is not null, then it is coverted to a string. * * @param index The index must be between 0 and length() - 1. * @return A String value. */ public String optString(int index) { return optString(index, ""); } /** * Get the optional string associated with an index. * The defaultValue is returned if the key is not found. * * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. * @return A String value. */ public String optString(int index, String defaultValue) { Object o = opt(index); return o != null ? o.toString() : defaultValue; } /** * Append a boolean value. This increases the array's length by one. * * @param value A boolean value. * @return this. */ public JSONArray put(boolean value) { put(value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONArray which is produced from a Collection. * @param value A Collection value. * @return this. */ public JSONArray put(Collection value) { put(new JSONArray(value)); return this; } /** * Append a double value. This increases the array's length by one. * * @param value A double value. * @throws JSONException if the value is not finite. * @return this. */ public JSONArray put(double value) throws JSONException { Double d = new Double(value); JSONObject.testValidity(d); put(d); return this; } /** * Append an int value. This increases the array's length by one. * * @param value An int value. * @return this. */ public JSONArray put(int value) { put(new Integer(value)); return this; } /** * Append an long value. This increases the array's length by one. * * @param value A long value. * @return this. */ public JSONArray put(long value) { put(new Long(value)); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONObject which is produced from a Map. * @param value A Map value. * @return this. */ public JSONArray put(Map value) { put(new JSONObject(value)); return this; } /** * Append an object value. This increases the array's length by one. * @param value An object value. The value should be a * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * @return this. */ public JSONArray put(Object value) { this.myArrayList.add(value); return this; } /** * Put or replace a boolean value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * @param index The subscript. * @param value A boolean value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray put(int index, boolean value) throws JSONException { put(index, value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONArray which is produced from a Collection. * @param index The subscript. * @param value A Collection value. * @return this. * @throws JSONException If the index is negative or if the value is * not finite. */ public JSONArray put(int index, Collection value) throws JSONException { put(index, new JSONArray(value)); return this; } /** * Put or replace a double value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad * it out. * @param index The subscript. * @param value A double value. * @return this. * @throws JSONException If the index is negative or if the value is * not finite. */ public JSONArray put(int index, double value) throws JSONException { put(index, new Double(value)); return this; } /** * Put or replace an int value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad * it out. * @param index The subscript. * @param value An int value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray put(int index, int value) throws JSONException { put(index, new Integer(value)); return this; } /** * Put or replace a long value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad * it out. * @param index The subscript. * @param value A long value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray put(int index, long value) throws JSONException { put(index, new Long(value)); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONObject which is produced from a Map. * @param index The subscript. * @param value The Map value. * @return this. * @throws JSONException If the index is negative or if the the value is * an invalid number. */ public JSONArray put(int index, Map value) throws JSONException { put(index, new JSONObject(value)); return this; } /** * Put or replace an object value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * @param index The subscript. * @param value The value to put into the array. The value should be a * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * @return this. * @throws JSONException If the index is negative or if the the value is * an invalid number. */ public JSONArray put(int index, Object value) throws JSONException { JSONObject.testValidity(value); if (index < 0) { throw new JSONException("JSONArray[" + index + "] not found."); } if (index < length()) { this.myArrayList.set(index, value); } else { while (index != length()) { put(JSONObject.NULL); } put(value); } return this; } /** * Produce a JSONObject by combining a JSONArray of names with the values * of this JSONArray. * @param names A JSONArray containing a list of key strings. These will be * paired with the values. * @return A JSONObject, or null if there are no names or if this JSONArray * has no values. * @throws JSONException If any of the names are null. */ public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; } /** * Make a JSON text of this JSONArray. For compactness, no * unnecessary whitespace is added. If it is not possible to produce a * syntactically correct JSON text then null will be returned instead. This * could occur if the array contains an invalid number. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, transmittable * representation of the array. */ public String toString() { try { return '[' + join(",") + ']'; } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONArray. * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>[</code>&nbsp;<small>(left bracket)</small> and ending * with <code>]</code>&nbsp;<small>(right bracket)</small>. * @throws JSONException */ public String toString(int indentFactor) throws JSONException { return toString(indentFactor, 0); } /** * Make a prettyprinted JSON text of this JSONArray. * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indention of the top level. * @return a printable, displayable, transmittable * representation of the array. * @throws JSONException */ String toString(int indentFactor, int indent) throws JSONException { int len = length(); if (len == 0) { return "[]"; } int i; StringBuffer sb = new StringBuffer("["); if (len == 1) { sb.append(JSONObject.valueToString(this.myArrayList.get(0), indentFactor, indent)); } else { int newindent = indent + indentFactor; sb.append('\n'); for (i = 0; i < len; i += 1) { if (i > 0) { sb.append(",\n"); } for (int j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(JSONObject.valueToString(this.myArrayList.get(i), indentFactor, newindent)); } sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } } sb.append(']'); return sb.toString(); } /** * Write the contents of the JSONArray as JSON text to a writer. * For compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean b = false; int len = length(); writer.write('['); for (int i = 0; i < len; i += 1) { if (b) { writer.write(','); } Object v = this.myArrayList.get(i); if (v instanceof JSONObject) { ((JSONObject)v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray)v).write(writer); } else { writer.write(JSONObject.valueToString(v)); } b = true; } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } } }
Java
package edu.uci.ics.xmlrpc.webserver; import java.net.InetAddress; import org.apache.xmlrpc.common.TypeConverterFactoryImpl; import org.apache.xmlrpc.server.PropertyHandlerMapping; import org.apache.xmlrpc.server.XmlRpcServer; import org.apache.xmlrpc.server.XmlRpcServerConfigImpl; import org.apache.xmlrpc.webserver.ServletWebServer; import org.apache.xmlrpc.webserver.XmlRpcServlet; public class ServletServer { private static final int port = 8081; public static void main(String[] args) throws Exception { XmlRpcServlet servlet = new Calculator(); System.out.println("Starting server..."); ServletWebServer webServer = new ServletWebServer(servlet, port); webServer.start(); System.out.println("Server started"); } }
Java
package edu.uci.ics.xmlrpc.webserver; import org.apache.xmlrpc.webserver.XmlRpcServlet; public class Calculator extends XmlRpcServlet { public int add(int i1, int i2) { return i1 + i2; } public int subtract(int i1, int i2) { return i1 - i2; } }
Java
package client; import java.io.*; import java.net.*; public class Client { public static void main(String[] args) throws IOException { String host = "169.234.14.7"; // String host = "169.234.15.29"; int port = 4444; String username = ""; String destination = ""; Socket kkSocket = null; PrintWriter out = null; BufferedReader in = null; try { kkSocket = new Socket(host, port); kkSocket.setKeepAlive(true); out = new PrintWriter(kkSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: " + host); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: " + host); System.exit(1); } System.out.println("Connected to host " + host + " on port " + port); // print out the server address InetAddress i = InetAddress.getLocalHost(); System.out.println("Your computer name: " + i.getHostName()); System.out.println("Your computer IP: " + i.getHostAddress()); System.out.println(); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String fromServer = ""; String fromUser = ""; // set the user's name System.out.print("What is your name? "); username = stdIn.readLine(); out.println("SETNAME:" + username); // set the user's destination System.out.print("Who are you chatting with? "); destination = stdIn.readLine(); System.out.println("Type \"Bye\" to quit"); while(!fromUser.equals("Bye")) { System.out.print(username + ": "); fromUser = stdIn.readLine(); String message = "<message>"; if (fromUser.equals("addb")) { message += "<type>AddBuddy</type>"; message += "<users>"; message += "<from><username>" + username + "</username></from>"; message += "<to><username>" + destination + "</username></to>"; message += "</users>"; message += "</message>"; } else { // send a Chat message // String message = "<message>"; message += "<type>Chat</type>"; message += "<users>"; message += "<from><username>" + username + "</username></from>"; message += "<to><username>" + destination + "</username></to>"; message += "</users>"; message += "<timestamp>right now</timestamp>"; message += "<text>" + fromUser + "</text>"; message += "</message>"; } // pipe the message out to the socket out.println(message); fromServer = in.readLine(); // read a line from the server if(fromServer != null) { System.out.println(fromServer); } } System.out.println("Messaging socket terminated"); out.close(); in.close(); stdIn.close(); kkSocket.close(); } }
Java
package parser; public class ChatMessage { private String type; private String from; private String to; private long timestamp; private String text; public ChatMessage(String type, String from, String to, long timestamp, String text) { this.type = type; this.from = from; this.to = to; this.timestamp = System.currentTimeMillis(); this.text = text; } public ChatMessage(String type, String from, String to, String timestamp, String text) { this.type = type; this.from = from; this.to = to; this.timestamp = System.currentTimeMillis(); this.text = text; } public void setType(String type) {this.type = type;} public void setFrom(String from) {this.from = from;} public void setTo(String to) {this.to = to;} public void setTimestamp() {this.timestamp = System.currentTimeMillis(); } public void setText(String text) {this.text = text;} public String getType() {return type;} public String getFrom() {return from;} public String getTo() {return to;} public long getTimestamp() {return timestamp;} public String getText() {return text;} public void printMessage() { System.out.println("Message (from: " + from + ") (to: " + to + ")"); System.out.println("Sent at: " + timestamp); System.out.println("Text: " + text); System.out.println(); } }
Java
package parser; public class ReturnStatusMessage { private String type; private String username; private int status; public ReturnStatusMessage(String type, String username, int status) { this.type = type; this.username = username; this.status = status; } public void setType(String type) {this.type = type;} public void setUsername(String username) {this.username = username;} public void setStatus(int status) {this.status = status;} public String getType() {return type;} public String getUsername() {return username;} public int getStatus() {return status;} public void printMessage() { System.out.println("Message (username: " + username + ") (status: " + status + ")"); // System.out.println("Sent at: " + timestamp); // System.out.println("Text: " + text); // System.out.println("User: " + username + " updated his/her status : " + from + " Added Buddy - " + to); System.out.println(); } }
Java
package parser; public class RemoveBuddyMessage { private String type; private String from; private String to; public RemoveBuddyMessage(String type, String from, String to) { this.type = type; this.from = from; this.to = to; } public void setType(String type) {this.type = type;} public void setFrom(String from) {this.from = from;} public void setTo(String to) {this.to = to;} public String getType() {return type;} public String getFrom() {return from;} public String getTo() {return to;} public void printMessage() { System.out.println("Message (from: " + from + ") (to: " + to + ")"); // System.out.println("Sent at: " + timestamp); // System.out.println("Text: " + text); System.out.println("Text: " + from + " Added Buddy - " + to); System.out.println(); } }
Java
package parser; public class AddBuddyMessage { private String type; private String from; private String to; public AddBuddyMessage(String type, String from, String to) { this.type = type; this.from = from; this.to = to; } public void setType(String type) {this.type = type;} public void setFrom(String from) {this.from = from;} public void setTo(String to) {this.to = to;} public String getType() {return type;} public String getFrom() {return from;} public String getTo() {return to;} public void printMessage() { System.out.println("Message (from: " + from + ") (to: " + to + ")"); // System.out.println("Sent at: " + timestamp); // System.out.println("Text: " + text); System.out.println("Text: " + from + " Added Buddy - " + to); System.out.println(); } }
Java
package parser; import messages.Message; public class GetBuddyListMessage extends Message { private String type; private String username; public GetBuddyListMessage() {} public GetBuddyListMessage(String type, String username) { super("ReturnStatus"); this.type = type; this.username = username; } public void setType(String type) {this.type = type;} public void setUsername(String username) {this.username = username;} public String getType() {return type;} public String getUsername() {return username;} public void printMessage() { System.out.println("Message (username: " + username + ") (BuddyList requested)"); // System.out.println("Sent at: " + timestamp); // System.out.println("Text: " + text); // System.out.println("User: " + username + " updated his/her status : " + from + " Added Buddy - " + to); System.out.println(); } // return an XML-formatted version of the message public String toXML() { String message = "<message>"; message += "<type>GetBuddyList</type>"; message += "<username>" + username + "</username>"; message += "</message>"; return message; } }
Java
package parser; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class MessageParser { public MessageParser() {} public ChatMessage getChatMessage(Element docEle) { // get the "from" tag NodeList users = docEle.getElementsByTagName("from"); Element userFrom = (Element)users.item(0); // get the "to" tag NodeList users2 = docEle.getElementsByTagName("to"); Element userTo = (Element)users2.item(0); // get the "username" tag values from the "from" and "to" tags String from = getTextValue(userFrom,"username"); String to = getTextValue(userTo,"username"); // get the "timestamp" tag value String timestamp = getTextValue(docEle, "timestamp"); // get the "text" tag value String text = getTextValue(docEle, "text"); // construct a ChatMessage and return it ChatMessage chatMessage = new ChatMessage("Chat",from,to,timestamp,text); return chatMessage; } public AddBuddyMessage getAddBuddyMessage(Element docEle) { // get the "from" tag NodeList user = docEle.getElementsByTagName("from"); Element userFrom = (Element)user.item(0); // get the "to" tag NodeList user2 = docEle.getElementsByTagName("to"); Element userTo = (Element)user2.item(0); // get the "username" tag values from the "from" and "to" tags String from = getTextValue(userFrom,"username"); String to = getTextValue(userTo,"username"); // get the "text" tag value // String text = getTextValue(docEle, "text"); // construct a AddBuddyMessage and return it AddBuddyMessage adMessage = new AddBuddyMessage("AddBuddy",from,to); return adMessage; } public RemoveBuddyMessage getRemoveBuddyMessage(Element docEle) { // get the "from" tag NodeList user = docEle.getElementsByTagName("from"); Element userFrom = (Element)user.item(0); // get the "to" tag NodeList user2 = docEle.getElementsByTagName("to"); Element userTo = (Element)user2.item(0); // get the "username" tag values from the "from" and "to" tags String from = getTextValue(userFrom,"username"); String to = getTextValue(userTo,"username"); // get the "text" tag value // String text = getTextValue(docEle, "text"); // construct a AddBuddyMessage and return it RemoveBuddyMessage rmMessage = new RemoveBuddyMessage("RemoveBuddy",from,to); return rmMessage; } public ReturnStatusMessage getReturnStatusMessage(Element docEle) { // get the "from" tag NodeList userTag = docEle.getElementsByTagName("username"); Element user = (Element)userTag.item(0); // get the "to" tag NodeList statusTag = docEle.getElementsByTagName("status"); Element status = (Element)statusTag.item(0); // get the "username" tag values from the "from" and "to" tags String userstr = getTextValue(user,"username"); String statusstr = getTextValue(status,"status"); // get the "text" tag value // String text = getTextValue(docEle, "text"); // construct a AddBuddyMessage and return it ReturnStatusMessage rsMessage = new ReturnStatusMessage("ReturnStatus", userstr, Integer.parseInt(statusstr)); return rsMessage; } /** * I take a xml element and the tag name, look for the tag and get * the text content * i.e for <employee><name>John</name></employee> xml snippet if * the Element points to employee node and tagName is name I will return John * @param ele * @param tagName * @return */ public String getTextValue(Element ele, String tagName) { String textVal = null; NodeList nl = ele.getElementsByTagName(tagName); if(nl != null && nl.getLength() > 0) { Element el = (Element)nl.item(0); textVal = el.getFirstChild().getNodeValue(); } return textVal; } /** * Calls getTextValue and returns a int value * @param ele * @param tagName * @return */ public int getIntValue(Element ele, String tagName) { //in production application you would catch the exception return Integer.parseInt(getTextValue(ele,tagName)); } }
Java
package server; import java.net.*; import java.io.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import DBComm.DBComm; import parser.AddBuddyMessage; import parser.ChatMessage; import parser.MessageParser; import parser.RemoveBuddyMessage; import parser.ReturnStatusMessage; //import Server.DBComm; public class ServerThread extends Thread { private Socket socket = null; private String username = "Client"; PrintWriter out; BufferedReader in; MessageParser messageParser = new MessageParser(); // XML message parser DBComm dbc = new DBComm(); public ServerThread(Socket socket) { super("ServerThread"); this.socket = socket; } private void setUserName(String username) {this.username = username;} public String getUserName() {return username;} public void run() { try { out = new PrintWriter(socket.getOutputStream(), true); // server socket output in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // client socket input String outputLine = ""; String inputLine = ""; while((inputLine = in.readLine()) != null) // read lines in from the client input { System.out.println(username + " sent a message"); // check input if(inputLine.equals("Bye")) { System.out.println("Client connection terminated"); socket.close(); break; } else if(inputLine.startsWith("SETNAME:")) { // set the name inputLine = inputLine.replace("SETNAME:", ""); System.out.println("\"" + username + "\" has changed his name to \"" + inputLine + "\""); setUserName(inputLine); } else if(inputLine.startsWith("<message>") && inputLine.endsWith("</message>")) { // parse out the message parseMessage(inputLine); System.out.println(inputLine); } else { // process input and create an output response outputLine = inputLine; // echo back what the client sent out.println("Server: " + outputLine); // send the output back through the output socket } } out.close(); in.close(); //socket.close(); } catch(SocketException e) { // often thrown when the Client is stopped without typing the "Bye" command System.out.println("Client (" + username + ") connection lost: SocketException - " + e.getMessage()); } catch (Exception e) { e.printStackTrace(); } } private void parseMessage(String inputLine) { Document dom; //get the factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { //Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); //parse using builder to get DOM representation of the XML String dom = db.parse(new InputSource(new StringReader(inputLine))); // parse the document parseDocument(dom); }catch(ParserConfigurationException pce) { pce.printStackTrace(); }catch(SAXException se) { se.printStackTrace(); }catch(IOException ioe) { ioe.printStackTrace(); } } private void parseDocument(Document dom) { //get the root element Element docEle = dom.getDocumentElement(); // get the "type" tag to figure out the type of message String type = messageParser.getTextValue(docEle, "type"); if(type.equals("Chat")) // Chat message { ChatMessage c = messageParser.getChatMessage(docEle); // send the message directly to the recipient sendMessageDirectlyTo(c.getFrom(), c.getTo(), c.getText()); dbc.addMessage(c.getFrom(), c.getText(), c.getTo()); } else if(type.equals("AddBuddy")) // Chat message { AddBuddyMessage abm = messageParser.getAddBuddyMessage(docEle); // send the message directly to the recipient sendMessageDirectlyTo(abm.getFrom(), abm.getTo(), "Text: " + abm.getFrom() + " Added Buddy - " + abm.getTo()); dbc.addBuddy(abm.getFrom(), abm.getTo(), "Buddies"); } else if(type.equals("RemoveBuddy")) // Chat message { RemoveBuddyMessage rbm = messageParser.getRemoveBuddyMessage(docEle); // send the message directly to the recipient sendMessageDirectlyTo(rbm.getFrom(), rbm.getTo(), "Text: " + rbm.getFrom() + " Removed Buddy - " + rbm.getTo()); dbc.removeBuddy(rbm.getFrom(), rbm.getTo(), "Buddies"); } else if(type.equals("UpdateStatus")) // Chat message { ReturnStatusMessage rsm = messageParser.getReturnStatusMessage(docEle); // send the message directly to the recipient // sendMessageDirectlyTo(rsm.getFrom(), rsm.getTo(), "Text: " + rsm.getFrom() + " Removed Buddy - " + rsm.getTo()); dbc.updateStatus(rsm.getUsername(), rsm.getStatus()); } } // send a message directly through this thread's socket to the connected client public void sendMessage(String userFrom, String message) { try { out.println(userFrom + ": " + message); } catch(Exception e) { System.out.println("Exception in sendMessage: " + e.getClass().getSimpleName() + " - " + e.getMessage()); } } // send a message from a given user (ServerThread) directly to a given user (ServerThread) public void sendMessageDirectlyTo(String userFrom, String userTo, String message) { // get a count of currently active threads in this ThreadGroup and create // an empty array of the same size as the count int activeThreads = this.getThreadGroup().activeCount(); Thread[] threadList = new Thread[activeThreads]; // copy all currently active threads in this ThreadGroup into the array this.getThreadGroup().enumerate(threadList); ServerThread theClient = this; // get the current client by default for(Thread t : threadList) // look through the threads to find ServerThread classes { if(t instanceof ServerThread) // make sure we're looking at the clients (ServerThread classes) { ServerThread s = (ServerThread)t; if(s.getUserName().equals(userTo)) { // found the desired recipient theClient = s; break; } } } if(theClient != null) { // pipe the message out to the client socket theClient.sendMessage(userFrom, message); } } }
Java
package server; import java.net.*; import java.io.*; public class Server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; boolean listening = true; int port = 4444; try { serverSocket = new ServerSocket(port); // print out the server address InetAddress i = InetAddress.getLocalHost(); System.out.println("Server host name: " + i.getHostName()); System.out.println("Server host IP: " + i.getHostAddress()); System.out.println("Listening for connections on port " + port); } catch (IOException e) { System.err.println("Could not listen on port " + port); System.exit(-1); } while (listening) // listen for connections { // accept a new connection Socket s = serverSocket.accept(); s.setKeepAlive(true); ServerThread clientConnection = new ServerThread(s); clientConnection.start(); //new ServerThread(serverSocket.accept()).start(); System.out.println("Connection accepted"); } System.out.println("Server socket closed"); serverSocket.close(); } }
Java
// ChatterServer // Receives XML-RPC messages sent by Client on the client side // and sends XML-RPC messages to ChatterClient on the client side package edu.uci.ics.xmlrpc.webserver; import java.net.URL; import java.util.HashMap; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory; import org.apache.xmlrpc.webserver.XmlRpcServlet; public class ChatterServer extends XmlRpcServlet { /** * */ private static final long serialVersionUID = 1L; private final int clientPort = 8080; // ordinarily there would be a database here instead, but fuck it for testing purposes HashMap<String,ChatUser> userMap = new HashMap<String,ChatUser>(); public ChatterServer() { userMap.put("Dan", new ChatUser("Dan", "169.234.3.86")); userMap.put("Chad", new ChatUser("Chad", "169.234.3.249")); userMap.put("Matt", new ChatUser("Matt", "169.234.14.7")); userMap.put("Alex", new ChatUser("Alex", "169.234.12.54")); userMap.put("Josh", new ChatUser("Josh", "169.234.15.214")); userMap.put("Scott", new ChatUser("Scott", "169.234.10.154")); userMap.put("Client6", new ChatUser("Client6", "127.0.0.1")); } // echo a given message public String echoMessage(String message) { return message; } // MESSAGE RE-ROUTING TO DIFFERENT USERS IS DONE HERE public String sendMessageTo(String userFrom, String userTo, String message) throws Exception { // send an XML-RPC message to the client's XML-RPC server (ChatterClient) // get the user out of the HashMap ChatUser userToConfig = userMap.get(userTo); // figure out the client address based upon the client's configuration String server = "http://" + userToConfig.getIPAddress() + ":" + clientPort + "/xmlrpc"; // create configuration XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); config.setServerURL(new URL(server)); config.setEnabledForExtensions(true); config.setConnectionTimeout(60 * 1000); config.setReplyTimeout(60 * 1000); XmlRpcClient client = new XmlRpcClient(); // use Commons HttpClient as transport client.setTransportFactory( new XmlRpcCommonsTransportFactory(client)); // set configuration client.setConfig(config); System.out.println("Received message from " + userFrom + ": " + message); // make the a regular call Object[] params = new Object[] { new String(userFrom), new String(message) }; client.execute("ChatterClient.receiveMessageFrom", params); System.out.println("Re-routed to " + userTo + ": " + message); return "true"; } } class ChatUser { private String username; private String ipAddress; public ChatUser(String username, String ipAddress) { this.username = username; this.ipAddress = ipAddress; } public String getUsername() {return username;} public String getIPAddress() {return ipAddress;} }
Java
package edu.uci.ics.xmlrpc.webserver; import org.apache.xmlrpc.server.PropertyHandlerMapping; import org.apache.xmlrpc.server.XmlRpcServer; import org.apache.xmlrpc.webserver.ServletWebServer; import org.apache.xmlrpc.webserver.XmlRpcServlet; public class ChatterServletServer { private static final int port = 8080; // can't run a Client and Server on same port public static void main(String[] args) throws Exception { XmlRpcServlet servlet = new ChatterServer(); System.out.println("Starting server (SERVER)..."); ServletWebServer webServer = new ServletWebServer(servlet, port); XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer(); /* You may also provide the handler classes directly, * like this: * phm.addHandler("Calculator", * org.apache.xmlrpc.demo.Calculator.class); * phm.addHandler(org.apache.xmlrpc.demo.proxy.Adder.class.getName(), * org.apache.xmlrpc.demo.proxy.AdderImpl.class); */ PropertyHandlerMapping phm = new PropertyHandlerMapping(); phm.addHandler("ChatterServer", edu.uci.ics.xmlrpc.webserver.ChatterServer.class); xmlRpcServer.setHandlerMapping(phm); webServer.start(); System.out.println("Server started (SERVER)"); } }
Java
// CommServerThread.java by Communications Team // March 9, 2009 // Thread for the Server Socket (one thread per connected client) package comm; public class CommServerThread { }
Java
// CommServerSocket.java by Communications Team // March 9, 2009 // Server socket pool that the Comm libraries will connect to package comm; public class CommServerSocket { }
Java
// ChatterClient // Receives XML-RPC messages from ChatterServer on the server package edu.uci.ics.xmlrpc; import org.apache.xmlrpc.webserver.XmlRpcServlet; public class ChatterClient extends XmlRpcServlet { /** * */ private static final long serialVersionUID = 1L; // receive a message after it has been re-routed through the Server public String receiveMessageFrom(String userFrom, String message) { System.out.println("MESSAGE RECEIVED"); System.out.println("From: " + userFrom); System.out.println("Text: " + message); System.out.println(); return "true"; } }
Java
package edu.uci.ics.xmlrpc; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory; public class ClientConsole{ // both of these are the "teambananas2" server //static String server = "http://teambananas2.ics.uci.edu:80/xmlrpc"; //static String server = "http://128.195.30.164:988/xmlrpc"; //static String server = "http://169.234.14.7:8080/xmlrpc"; //Matt //static String server = "http://169.234.12.54:8080/xmlrpc"; //Alex static String server = "http://169.234.3.86:8080/xmlrpc"; //Dan public static void main(String args[]) { String userFrom = ""; String userTo = ""; String message = ""; // open up standard input BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { while(!userFrom.equals("EXIT")) { // prompt the user to enter their name System.out.println(); System.out.print("FROM: "); userFrom = br.readLine(); if(userFrom.equals("EXIT")) break; System.out.print("TO: "); userTo = br.readLine(); System.out.print("MESSAGE: "); message = br.readLine(); send(userFrom, userTo, message); } } catch(Exception e) { e.printStackTrace(); } System.out.println("Messaging client terminated"); } // send a message to the Server for re-routing to another ChatterClient public static void send(String userFrom, String userTo, String message) throws Exception { //String userFrom = "Client1"; // user the message originates from //String userTo = "Client2"; // user the message is destined for //String message = "I am a message"; // whatever message you would like // create configuration XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); config.setServerURL(new URL(server)); config.setEnabledForExtensions(true); config.setConnectionTimeout(60 * 1000); config.setReplyTimeout(60 * 1000); XmlRpcClient client = new XmlRpcClient(); // use Commons HttpClient as transport client.setTransportFactory( new XmlRpcCommonsTransportFactory(client)); // set configuration client.setConfig(config); // make the a regular call Object[] params = new Object[] { new String(userFrom), new String(userTo), new String(message) }; client.execute("ChatterServer.sendMessageTo", params); System.out.println("Sent from " + userFrom + " to " + userTo + ": " + message); //System.out.println(config.getUserAgent()); } }
Java
package edu.uci.ics.xmlrpc; import org.apache.xmlrpc.server.PropertyHandlerMapping; import org.apache.xmlrpc.server.XmlRpcServer; import org.apache.xmlrpc.webserver.ServletWebServer; import org.apache.xmlrpc.webserver.XmlRpcServlet; public class ChatterServletServer { private static final int port = 8081; public static void main(String[] args) throws Exception { XmlRpcServlet servlet = new ChatterClient(); System.out.println("Starting server (CLIENT)..."); ServletWebServer webServer = new ServletWebServer(servlet, port); XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer(); /* You may also provide the handler classes directly, * like this: * phm.addHandler("Calculator", * org.apache.xmlrpc.demo.Calculator.class); * phm.addHandler(org.apache.xmlrpc.demo.proxy.Adder.class.getName(), * org.apache.xmlrpc.demo.proxy.AdderImpl.class); */ PropertyHandlerMapping phm = new PropertyHandlerMapping(); phm.addHandler("ChatterClient", edu.uci.ics.xmlrpc.ChatterClient.class); xmlRpcServer.setHandlerMapping(phm); webServer.start(); System.out.println("Server started (CLIENT)"); } }
Java
public class Main { public static void main(String[] args) { ClientServerFrame frame = new ClientServerFrame(); frame.setVisible(true); } }
Java
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.Scanner; public class Connector implements Runnable { private String name; private String address; private int port; private Thread connectorThread; private Socket socket; private ArrayList<ConnectorListener> listeners; private byte[] image; private String description; private int fileSize; private PrintWriter socketOut; private Scanner socketIn; public Connector(String name, String address, int port, byte[] image, int fileSize, String description) { this.name = name; this.address = address; this.port = port; this.image = image; this.fileSize = fileSize; this.description = description; connectorThread = new Thread(this); listeners = new ArrayList<ConnectorListener>(); } public void addConnectorListener(ConnectorListener listener) { listeners.add(listener); } public void removeConnectorListener(ConnectorListener listener) { listeners.remove(listener); } public void run() { String serverAddress = null; try { // the following is a protocol between client and server System.out.println("Description is " + description); socket = new Socket(address, port); Scanner socketIn = new Scanner(socket.getInputStream()); socketOut = new PrintWriter(socket.getOutputStream(), true); serverAddress = socket.getInetAddress().toString(); fireConnectorSucceeded(serverAddress, "blah"); socketOut.println("I45PFP_HELLO"); String line = socketIn.nextLine(); if (!line.startsWith("GOAHEAD")) { throw new ProtocolException("GOAHEAD expected"); } socketOut.println("IMAGE " + fileSize + " " + description); line = socketIn.next(); if (line.startsWith("ACCEPT")) { int offset = 0; while (offset < fileSize) { int chunkSize = 1024; if (fileSize - offset < chunkSize) { chunkSize = fileSize - offset; } socket.getOutputStream().write(image, offset, chunkSize); offset += chunkSize; System.out.println(offset + " bytes written."); } socket.getOutputStream().flush(); firePictureSent(); } if (line.startsWith("REJECT")) { fireRejected(); } line = socketIn.next(); if (!line.startsWith("GOODBYE")) { throw new ProtocolException("GOODBYE expected"); } fireCompleted(); //close(); } catch (Exception e) { fireConnectorFailed(serverAddress, e); } finally { //close(); } } public void start() { connectorThread.start(); } public void close() { try { if (socket != null) { socket.close(); } } catch (IOException e) { } } // The follow methods allow the Connector class to communicate with the GUI Frame. public void fireConnectorSucceeded(String serverAddress, String serverName) { for (ConnectorListener listener : listeners) { listener.connectorSucceeded(serverAddress, serverName); } } public void fireConnectorFailed(String serverAddress, Exception reason) { for (ConnectorListener listener : listeners) { listener.connectorFailed(serverAddress, reason); } } public void firePictureSent() { for (ConnectorListener listener : listeners) { listener.pictureSent(); } } public void fireRejected() { for (ConnectorListener listener : listeners) { listener.rejected(); } } public void fireCompleted() { for (ConnectorListener listener : listeners) { listener.completedClient(); } } public void sendText(String text) { try { socketOut.println("chat " + text); } catch(Exception e) { } } }
Java
public interface AcceptorListener { void acceptorSucceeded(String clientAddress, String clientName); void acceptorFailed(String clientAddress, Exception reason); void pictureAccepted(byte[] bytes, String description); void pictureQuery(); void completedServer(); void getText(String line); }
Java
public class ProtocolException extends Exception { public ProtocolException(String message) { super(message); } }
Java
import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; public class ClientServerFrame extends JFrame implements ConnectorListener, AcceptorListener { private JTextField nameField; private JTextField addressField; private JTextField portField; private JTextField listenPortField; private JTextField descriptionField; private JTextField chatField; private JButton connectButton; private JButton pictureButton; private JButton listenButton; private JButton sendTextButton; private DefaultListModel statusListModel; private File selectedFile; private String fileName; private JLabel drawPicture; private JMenuBar menuBar; private JMenu menu; private JMenuItem clientMenuItem; private JMenuItem serverMenuItem; private JMenuItem uploadImageMenuItem; private JMenuItem closeMenuItem; private JMenuItem acceptImageMenuItem; private JMenuItem rejectImageMenuItem; private JMenuItem previewImageMenuItem; private JMenuItem previewAcceptedImageMenuItem; private GridBagLayout layout; private byte[] fileBytes; private int fileLength; private Connector connector; private Acceptor acceptor; public ClientServerFrame() { setSize(100, 250); setTitle("Picture Client & Server Program"); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); buildUI(); connector = null; acceptor = null; } private void buildUI() { BoxLayout box = new BoxLayout(getContentPane(), BoxLayout.X_AXIS ); getContentPane().setLayout(box); // The follow code is used to construct the menu bar with its // various commands. menu = new JMenu("Select Options"); menu.setMnemonic(KeyEvent.VK_A); menuBar = new JMenuBar(); menuBar.add(menu); clientMenuItem = new JMenuItem("I am a client."); serverMenuItem = new JMenuItem("I am a server."); uploadImageMenuItem = new JMenuItem("Upload image."); closeMenuItem = new JMenuItem("Close application."); acceptImageMenuItem = new JMenuItem("Accept image."); rejectImageMenuItem = new JMenuItem("Reject image."); previewImageMenuItem = new JMenuItem("Preview uploaded image."); previewAcceptedImageMenuItem = new JMenuItem("Preview accepted image."); menu.add(clientMenuItem); menu.add(serverMenuItem); menu.addSeparator(); menu.add(uploadImageMenuItem); menu.add(previewImageMenuItem); menu.addSeparator(); menu.add(acceptImageMenuItem); menu.add(rejectImageMenuItem); menu.add(previewAcceptedImageMenuItem); menu.addSeparator(); menu.add(closeMenuItem); uploadImageMenuItem.setEnabled(false); acceptImageMenuItem.setEnabled(false); rejectImageMenuItem.setEnabled(false); previewImageMenuItem.setEnabled(false); previewAcceptedImageMenuItem.setEnabled(false); // Various action listeners for menu items. clientMenuItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { clientMenuItem.setEnabled(false); serverMenuItem.setEnabled(true); uploadImageMenuItem.setEnabled(true); previewAcceptedImageMenuItem.setEnabled(false); buildClient(); } } ); serverMenuItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { serverMenuItem.setEnabled(false); clientMenuItem.setEnabled(true); uploadImageMenuItem.setEnabled(false); previewImageMenuItem.setEnabled(false); buildServer(); } } ); uploadImageMenuItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { sendPicture(uploadImageMenuItem); } } ); acceptImageMenuItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { acceptor.acceptImage(); listenButton.setEnabled(true); acceptImageMenuItem.setEnabled(false); rejectImageMenuItem.setEnabled(false); } } ); rejectImageMenuItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { acceptor.rejectImage(); acceptImageMenuItem.setEnabled(false); rejectImageMenuItem.setEnabled(false); statusListModel.addElement("- Image has been rejected!"); listenButton.setEnabled(true); } } ); previewImageMenuItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { drawPicture2(fileBytes); } } ); previewAcceptedImageMenuItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { drawPicture2(fileBytes); } } ); closeMenuItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } } ); /* layout.setConstraints( menuBar, new GridBagConstraints( 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); */ getContentPane().add(menuBar); // If user chooses to be a client this method is run. } public void buildClient() { layout = new GridBagLayout(); setSize(600, 700); getContentPane().removeAll(); getContentPane().setLayout(layout); repaint(); setTitle("--- [ Client Frame ] ---"); layout.setConstraints( menuBar, new GridBagConstraints( 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(menuBar); JLabel nameLabel = new JLabel("Client Name: "); layout.setConstraints( nameLabel, new GridBagConstraints( 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(nameLabel); nameField = new JTextField(); layout.setConstraints( nameField, new GridBagConstraints( 1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(nameField); JLabel addressLabel = new JLabel("IP Address:"); layout.setConstraints( addressLabel, new GridBagConstraints( 0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(addressLabel); addressField = new JTextField(); layout.setConstraints( addressField, new GridBagConstraints( 1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(addressField); JLabel portLabel = new JLabel("Port: "); layout.setConstraints( portLabel, new GridBagConstraints( 0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(portLabel); portField = new JTextField(); layout.setConstraints( portField, new GridBagConstraints( 1, 3, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(portField); JLabel descriptionLabel = new JLabel("Description of Image: "); layout.setConstraints( descriptionLabel, new GridBagConstraints( 0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(descriptionLabel); descriptionField = new JTextField(); layout.setConstraints( descriptionField, new GridBagConstraints( 1, 4, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(descriptionField); descriptionField.setEnabled(true); connectButton = new JButton("Connect & Send Picture to Server"); connectButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { connect(); } }); layout.setConstraints( connectButton, new GridBagConstraints( 0, 6, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(connectButton); connectButton.setEnabled(true); JLabel statusLabel = new JLabel("Status"); layout.setConstraints( statusLabel, new GridBagConstraints( 0, 7, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(statusLabel); statusListModel = new DefaultListModel(); JList statusList = new JList(statusListModel); JScrollPane statusScroller = new JScrollPane(statusList); layout.setConstraints( statusScroller, new GridBagConstraints( 0, 8, 2, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(statusScroller); statusListModel.addElement("- Please use the 'Select Options' Menu"); statusListModel.addElement(" in order to upload an image before connecting."); repaint(); setVisible(true); JLabel chatLabel = new JLabel("Enter chat message"); layout.setConstraints( chatLabel, new GridBagConstraints( 0, 9, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); getContentPane().add(chatLabel); chatField = new JTextField(); layout.setConstraints( chatField, new GridBagConstraints( 1, 9, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(chatField); sendTextButton = new JButton("Send Text Message"); sendTextButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { sendText(); } }); layout.setConstraints( sendTextButton, new GridBagConstraints( 0, 10, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(sendTextButton); } // If the user chooses to be a server, this method is run. public void buildServer() { layout = new GridBagLayout(); setSize(500, 700); getContentPane().removeAll(); getContentPane().setLayout(layout); repaint(); setTitle("--- [ Server Frame ] ---"); layout.setConstraints( menuBar, new GridBagConstraints( 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(menuBar); JLabel nameLabel = new JLabel("Server Name: "); layout.setConstraints( nameLabel, new GridBagConstraints( 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(nameLabel); nameField = new JTextField(); layout.setConstraints( nameField, new GridBagConstraints( 1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(nameField); JLabel listenPortLabel = new JLabel("Listen Port:"); layout.setConstraints( listenPortLabel, new GridBagConstraints( 0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(listenPortLabel); listenPortField = new JTextField(); layout.setConstraints( listenPortField, new GridBagConstraints( 1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(listenPortField); listenButton = new JButton("Listen"); listenButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { listen(); } }); layout.setConstraints( listenButton, new GridBagConstraints( 1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(listenButton); JLabel statusLabel = new JLabel("Status"); layout.setConstraints( statusLabel, new GridBagConstraints( 0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(statusLabel); statusListModel = new DefaultListModel(); JList statusList = new JList(statusListModel); JScrollPane statusScroller = new JScrollPane(statusList); layout.setConstraints( statusScroller, new GridBagConstraints( 0, 5, 2, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(10, 10, 10, 10), 0, 0)); getContentPane().add(statusScroller); setVisible(true); } private void connect() { String name = nameField.getText().trim(); if (name.length() == 0) { JOptionPane.showMessageDialog( this, "Please specify a name", "Validation Error", JOptionPane.ERROR_MESSAGE); return; } String address = addressField.getText().trim(); if (address.length() == 0) { JOptionPane.showMessageDialog( this, "Please specify an address", "Validation Error", JOptionPane.ERROR_MESSAGE); return; } int port; try { port = Integer.parseInt(portField.getText()); } catch (NumberFormatException e) { JOptionPane.showMessageDialog( this, "Please specify a number for the port between 0 and 65535", "Validation Error", JOptionPane.ERROR_MESSAGE); return; } if (port < 0 || port > 65535) { JOptionPane.showMessageDialog( this, "Please specify a number for the port between 0 and 65535", "Validation Error", JOptionPane.ERROR_MESSAGE); return; } String description = descriptionField.getText(); if (description.length() == 0) { JOptionPane.showMessageDialog( this, "Please write a description to be sent with the image.", "Validation Error", JOptionPane.ERROR_MESSAGE); return; } connectButton.setEnabled(false); statusListModel.addElement("- Connecting to " + address + " on port " + port); connector = new Connector(name, address, port, fileBytes, fileLength, description); connector.addConnectorListener(this); connector.start(); } public void listen() { String name = nameField.getText().trim(); if (name.length() == 0) { JOptionPane.showMessageDialog( this, "Please specify a name.", "Validation Error", JOptionPane.ERROR_MESSAGE); return; } int listenPort; try { listenPort = Integer.parseInt(listenPortField.getText()); } catch (NumberFormatException e) { JOptionPane.showMessageDialog( this, "Please specify the port as a number between 0 and 65535", "Validation Error", JOptionPane.ERROR_MESSAGE); return; } if (listenPort < 0 || listenPort > 65535) { JOptionPane.showMessageDialog( this, "Please specify the port as a number between 0 and 65535", "Validation Error", JOptionPane.ERROR_MESSAGE); return; } listenButton.setEnabled(false); statusListModel.addElement("- Waiting for connection."); acceptor = new Acceptor(name, listenPort); acceptor.addAcceptorListener(this); acceptor.start(); } public void sendPicture(JButton buttonPressed) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "JPG & GIF & PNG Images", "jpg", "gif", "png"); chooser.setFileFilter(filter); chooser.showOpenDialog(buttonPressed); selectedFile = chooser.getSelectedFile(); fileName = chooser.getSelectedFile().getPath(); try { drawPicture(); } catch (IOException e) { e.printStackTrace(); } } public void sendPicture(JMenuItem buttonPressed) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "JPG & GIF & PNG Images", "jpg", "gif", "png"); chooser.setFileFilter(filter); chooser.showOpenDialog(buttonPressed); selectedFile = chooser.getSelectedFile(); fileName = chooser.getSelectedFile().getPath(); try { drawPicture(); } catch (IOException e) { e.printStackTrace(); } } public void drawPicture() throws IOException { fileLength = (int) selectedFile.length(); System.out.println(selectedFile.getName()); fileBytes = new byte[fileLength]; FileInputStream input = new FileInputStream(selectedFile); int offset = 0; while (offset < fileLength) { int chunkSize = 65536; if (fileLength - offset < chunkSize) { chunkSize = fileLength - offset; } offset += input.read(fileBytes, offset, chunkSize); } input.close(); connectButton.setEnabled(true); previewImageMenuItem.setEnabled(true); descriptionField.setEnabled(true); statusListModel.addElement("- Picture entitled: " + "'" + selectedFile.getName() + "'" + " (" + fileLength + " bytes" + ") " + "has been succesfully uploaded."); } public void drawPicture2(byte[] fileBytes) { ImageIcon picture = new ImageIcon(fileBytes); int picHeight = picture.getIconHeight(); int picWidth = picture.getIconWidth(); PictureFrame pictureFrame = new PictureFrame(fileBytes, picWidth, picHeight); pictureFrame.setVisible(true); } public void connectorSucceeded( final String serverAddress, final String serverName) { EventQueue.invokeLater( new Runnable() { public void run() { statusListModel.addElement( "- You are now connected to " + "Server Address: " + serverAddress); } }); } public void connectorFailed( final String serverAddress, final Exception reason) { EventQueue.invokeLater( new Runnable() { public void run() { connectButton.setEnabled(true); statusListModel.addElement("- Unable to establish a connection!"); if (serverAddress != null) { statusListModel.addElement( "While connected to " + serverAddress); } statusListModel.addElement("- " + reason.getClass().getName()); statusListModel.addElement("- " + reason.getMessage()); } }); } public void disposeClient() { if (connector != null) { connector.removeConnectorListener(this); } super.dispose(); } public void disposeServer() { if (acceptor != null) { acceptor.removeAcceptorListener(this); //acceptor.close(); } super.dispose(); } public void acceptorSucceeded( final String clientAddress, final String clientName) { EventQueue.invokeLater( new Runnable() { public void run() { statusListModel.addElement( "- Connection accepted. You are now connected to Client Address: " + clientAddress); } }); } public void acceptorFailed(final String address, final Exception reason) { EventQueue.invokeLater( new Runnable() { public void run() { listenButton.setEnabled(true); statusListModel.addElement("- Connection unaccepted!"); if (address != null) { statusListModel.addElement( "While connected to " + address); } statusListModel.addElement("- " + reason.getClass().getName()); statusListModel.addElement("- " + reason.getMessage()); } }); } public void pictureAccepted(final byte[] bytes, final String description) { EventQueue.invokeLater( new Runnable() { public void run() { fileBytes = bytes; previewAcceptedImageMenuItem.setEnabled(true); statusListModel.addElement("- You have received the image succesfully!"); statusListModel.addElement("- Description of image: " + description); } }); } public void pictureSent() { EventQueue.invokeLater( new Runnable() { public void run() { connectButton.setEnabled(true); statusListModel.addElement("- " + selectedFile.getName() + " has been sent!"); } }); } public void pictureQuery() { EventQueue.invokeLater( new Runnable() { public void run() { acceptImageMenuItem.setEnabled(true); rejectImageMenuItem.setEnabled(true); statusListModel.addElement("- Would you like to accept or reject the image proposed?"); } }); } public void rejected() { EventQueue.invokeLater( new Runnable() { public void run() { acceptImageMenuItem.setEnabled(true); rejectImageMenuItem.setEnabled(true); connectButton.setEnabled(true); statusListModel.addElement("- Server has rejected your request!"); } }); } public void completedServer() { EventQueue.invokeLater( new Runnable() { public void run() { statusListModel.addElement("- Connection complete. Connection closed."); } }); } public void completedClient() { EventQueue.invokeLater( new Runnable() { public void run() { statusListModel.addElement("- Connection complete. Connection closed."); } }); } public void sendText() { String text = chatField.getText().toString(); connector.sendText(text); } public void getText(final String line) { EventQueue.invokeLater( new Runnable() { public void run() { statusListModel.addElement("Received: " + line); } }); } }
Java
import javax.swing.*; public class PictureFrame extends JFrame { public JLabel pictureLabel; public JScrollPane scroll; public int height; public int width; public ImageIcon image; public byte[] filebytes; public PictureFrame(byte[] filebytes, int width, int height) { this.filebytes = filebytes; image = new ImageIcon(filebytes); this.height = height; this.width = width; setSize(width, height); setTitle("--- [ Picture Frame! ] ---"); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setVisible(true); buildUI(); } public void buildUI() { pictureLabel = new JLabel(image); getContentPane().add(pictureLabel); scroll = new JScrollPane(pictureLabel); getContentPane().add(scroll); setVisible(true); } }
Java
import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Scanner; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; // An Acceptor object represents a task that can be executed in a separate // thread, so it implements the Runnable interface. Threads begin by calling // the run() method on some object that implements Runnable; they continue // executing until the run() method returns (or terminates with an exception). public class Acceptor extends JFrame implements Runnable { private String name; private String description; private int listenPort; private Thread acceptorThread; private ArrayList<AcceptorListener> listeners; private ServerSocket serverSocket; private Socket socket; private JLabel drawPicture; public byte[] fileBytes; public Scanner socketIn; public PrintWriter socketOut; public int imageSize; public String clientAddress; public Acceptor(String name, int listenPort) { this.name = name; this.listenPort = listenPort; listeners = new ArrayList<AcceptorListener>(); // We create the acceptor thread here but do not start it yet. This // allows the GUI (or whoever) to register itself as a listener before // we start waiting for a connection. acceptorThread = new Thread(this); // Once we accept our conversation, either or both of these will be // non-null; initially, though, there are no sockets. description = ""; serverSocket = null; socket = null; } public void addAcceptorListener(AcceptorListener listener) { listeners.add(listener); } public void removeAcceptorListener(AcceptorListener listener) { listeners.remove(listener); } public void start() { acceptorThread.start(); } public void run() { clientAddress = null; try { // The following is the protocol between client and server. serverSocket = new ServerSocket(listenPort); socket = serverSocket.accept(); socketIn = new Scanner(socket.getInputStream()); socketOut = new PrintWriter(socket.getOutputStream(), true); clientAddress = socket.getInetAddress().toString(); fireAcceptorSucceeded(clientAddress, "blah"); String line = socketIn.nextLine(); if (!line.startsWith("I45PFP_HELLO")) { throw new ProtocolException("I45PFP_HELLO expected"); } socketOut.println("GOAHEAD"); line = socketIn.nextLine(); Scanner scanLine = new Scanner(line); if (!line.startsWith("IMAGE")) { throw new ProtocolException("IMAGE expected"); } String imageWord = scanLine.next(); imageSize = scanLine.nextInt(); description = scanLine.nextLine(); firePictureQuery(); } catch (Exception e) { fireAcceptorFailed(clientAddress, e); } } public void close() { if (socket != null) { try { socket.close(); } catch (IOException e) { } } if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { } } } public void acceptImage() { try { socketOut.println("ACCEPT"); fileBytes = new byte[imageSize]; System.out.println("Image Size is " + imageSize); int offset = 0; while (offset < imageSize) { int chunkSize = Math.min(imageSize - offset, 1024); offset += socket.getInputStream().read(fileBytes, offset, chunkSize); System.out.println(offset + " bytes read"); } firePictureAcceptor(fileBytes, description); } catch (Exception e) { fireAcceptorFailed(clientAddress, e); } finally { socketOut.println("GOODBYE"); //close(); ChatDevice chat = new ChatDevice(socket, listeners.get(0)); chat.start(); fireCompleted(); } } public void rejectImage() { try { socketOut.println("REJECT"); } catch (Exception e) { fireAcceptorFailed(clientAddress, e); } finally { socketOut.println("GOODBYE"); //close(); fireCompleted(); } } // the following allows the acceptor class to interact with the GUI frame public void fireAcceptorSucceeded(String clientAddress, String clientName) { for (AcceptorListener listener : listeners) { listener.acceptorSucceeded(clientAddress, clientName); } } public void fireAcceptorFailed(String clientAddress, Exception reason) { for (AcceptorListener listener : listeners) { listener.acceptorFailed(clientAddress, reason); } } public void firePictureAcceptor(byte[] bytes, String description) { for (AcceptorListener listener : listeners) { listener.pictureAccepted(bytes, description); } } public void firePictureQuery() { for (AcceptorListener listener : listeners) { listener.pictureQuery(); } } public void fireCompleted() { for (AcceptorListener listener : listeners) { listener.completedServer(); } } public void fireChat(String text) { for (AcceptorListener listener : listeners) { listener.getText(text); } } }
Java
public interface ConnectorListener { void connectorSucceeded(String serverAddress, String serverName); void connectorFailed(String serverAddress, Exception reason); void pictureSent(); void rejected(); void completedClient(); }
Java
import java.net.Socket; import java.util.Scanner; import javax.swing.JFrame; public class ChatDevice implements Runnable { Socket socket; Thread chatDevice; AcceptorListener gui; public ChatDevice(Socket socket, AcceptorListener gui) { this.socket = socket; chatDevice = new Thread(this); this.gui = gui; } public void start() { chatDevice.start(); } public void run() { try { Scanner socketIn = new Scanner(socket.getInputStream()); while (true) { String line = socketIn.next(); if (line.startsWith("chat")) { line = socketIn.nextLine(); gui.getText(line); } } } catch(Exception e) { } } }
Java
package edu.uci.ics.xmlrpc; import java.net.MalformedURLException; import java.net.URL; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory; import org.apache.xmlrpc.client.util.ClientFactory; public class Client { public static void main(String[] args) throws Exception { // create configuration String server = "http://localhost:8081/xmlrpc"; XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); config.setServerURL(new URL(server)); config.setEnabledForExtensions(true); config.setConnectionTimeout(60 * 1000); config.setReplyTimeout(60 * 1000); XmlRpcClient client = new XmlRpcClient(); // use Commons HttpClient as transport client.setTransportFactory( new XmlRpcCommonsTransportFactory(client)); // set configuration client.setConfig(config); // make the a regular call Object[] params = new Object[] { new Integer(2), new Integer(3) }; Integer result = (Integer) client.execute("Calculator.add", params); System.out.println("2 + 3 = " + result); } }
Java
package DBComm; // ReturnCodes.java // A class consisting of static return codes and nothing else // ex: return ReturnCodes.SUCCESS public class ReturnCodes { // general / server response code(s) public static int SERVER_ERROR = 0; public static int SUCCESS = 1; // specific login response code(s) public static int BAD_PASSWORD = 2; public static int INVALID_LOGIN = 3; // specific buddy list response code(s) public static int BUDDY_DOES_NOT_EXIST = 4; public static int FAILED_TO_ADD_BUDDY = 5; public static int FAILED_TO_DELETE_BUDDY = 6; // specific duplication response code(s) public static int EVENT_EXISTS_ALREADY = 7; }
Java
package DBComm; import java.util.ArrayList; //Dan Morgan public class Configuration { private ArrayList<String> _configuration; //index 0 = _clientID; //index 1 = _tabFill; //index 2 =_tabStroke; //index 3 = _windowFill; //index 4 = _windowStroke; //index 5 = _chatWindowColor; //index 6 = _textColor; //Constructor public Configuration(){ _configuration = new ArrayList<String>(7); //inserting dummy values because java is dumb for(int i = 0; i < 7; i++){ _configuration.add(null); } } //Provide a field to update and the update value public void updateConfiguration(int index, String update){ if(index >= 0 && index <= 6){ _configuration.set(index, update); } else{ System.err.println("Invalid input, please try again."); } } //if you want to get a specific configuration value, specify that field /* * Commenting this out for now as I figure you can just get the configuration array list and specify the index you want, it'd be faster. public String getConfigurationSetting(String field){ if(field.equals("clientID")){ return _configuration.get(0); } else if(field.equals("tabFill")){ return _configuration.get(1); } else if(field.equals("tabStroke")){ return _configuration.get(2); } else if(field.equals("windowFill")){ return _configuration.get(3); } else if(field.equals("windowStroke")){ return _configuration.get(4); } else if(field.equals("chatWindowColor")){ return _configuration.get(5); } else if(field.equals("textColor")){ return _configuration.get(6); } else{ System.err.println("Invalid input, please try again."); return field; } } */ public ArrayList<String> getConfiguration(){ return _configuration; } }
Java
package DBComm; //Hold Stats regarding IMing activity // //Scott J. Ditch public class Stats { private int messages; private int aveLength; private int fileShares; private int statusChanges; private int users; private int buddies; private int currentMessages; private long startTime; public Stats() { System.out.println("Building Stats"); startTime = System.currentTimeMillis(); } public void addMessage(int length) { messages++; currentMessages++; aveLength = ((messages * aveLength) + length)/ messages; } public void fileShared() { fileShares++; } public void changedStatus() { statusChanges++; } public void adduser() { users++; } public void moreBuddies() { buddies++; } public void removedBuddy() { buddies--; } //Give the time the program has been running in milliseconds. private long getTimeRunning() { return ((System.currentTimeMillis()) - startTime); } // //RETURN METHODS // // // public int getMessgaes() // { // return messages; // } // // public int getAverageLength() // { // return aveLength; // } // // public int getFilesShared() // { // return fileShares; // } // // public int getStatusChanges() // { // return statusChanges; // } public void printStats() { System.out.println("\n Stats: \n"); System.out.println(" The amount of messages sent: " + messages); System.out.println(" The average length of messages sent: " + aveLength); System.out.println(" The amount of files shared: " + fileShares); System.out.println(" The amount of status changes: " + statusChanges); System.out.println(" New users this session: " + users); System.out.println(" Buddies linked session: " + buddies); System.out.println(" Time the DBComm has been running (Milliseconds): " + getTimeRunning()); } }
Java
package DBComm; import java.sql.SQLException; import java.util.ArrayList; import messages.ChatMessage; // DBComm is the class responsible for reading and writing information to the database. An SQL implementation of a // database has been used for this project. A jdbc driver is also used and an additional library is needed to // establish this connection: mysql-connector-java-5.1.7-bin.jar. public class DBComm{ private java.sql.Connection con = null; private final String url = "jdbc:mysql://"; private final String serverName= "teambananas2.ics.uci.edu"; //Scott's Server IP: teambananas2.ics.uci.edu //Robert's IP 192.168.0.102 private final String portNumber = "987"; //MySQL: 987 (Robert), 3306 (Dan local). SQL Server 2008: 50479 private final String databaseName= "pIMp"; private final String userName = "pIMpAdmin"; //root private final String password = "ainteasy"; //Scott's root password: LopesSucksASS //pIMpAdmin: ainteasy private static Stats stats; //Hold the Statistics regarding IM activity to be reported to the admin //private final String selectMethod = "cursor"; // Constructor public DBComm(){ //Instantiate the database connection. //I think the max number of requests we can make to the MySQL server through one of these connections is 500 (at a time). //Or, we can make 500 max connections at a time. I know we can re-use connections; we don't have to make a new connection every time we want to do something //(and then close it afterward). This is easy for a small number of requests, but once we start scaling it up, I think we'll have to make multiple DBComm //objects, which will make multiple connections. //TODO test how many connections we can make. try{ con = this.getConnection(); } catch(Exception e){ e.printStackTrace(); } stats = new Stats(); } private String getConnectionUrl(){ //MS SQL Server //return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";"; //MySQL return url+serverName+":"+portNumber+"/"+databaseName+"?"; } private java.sql.Connection getConnection(){ try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password); if(con!=null) System.out.println("Connection Successful!" + "\n"); }catch(Exception e){ e.printStackTrace(); System.err.println("Error Trace in getConnection() : " + e.getMessage()); } return con; } // Robert Jolly // Method responsible for adding a chat message into the database. Returns a value of 1 if successful. Otherwise // it will need to return a number corresponding to the error message provided. public int addMessage(String from, String message, String to){ java.sql.Statement st = null; int retVal = 0; //SERVER ERROR String insertChat = "INSERT INTO chatlist (`from`, `messages`, `to`, `type`,`offline`) " + "VALUES ('" + from + "', '" + message + "', '" + to + "', 0, 1);"; int i; System.out.println(insertChat); try { st = con.createStatement(); i = st.executeUpdate(insertChat); if (i == 1){ retVal = 1; //SUCCESS System.out.println("Message Added."); //FOR STATS - Scott stats.addMessage(message.length()); } else{ retVal = 3; //Most likely to or from doesn't exist, so just say invalid login } st.close(); st = null; } catch (SQLException e) { retVal = 0; //Should be a server error...most likely it would be con.creatStatement() that failed. System.err.println(e); } addWebEvent(to, 1); return retVal; } // Robert Jolly // Method responsible for adding a chat message into the database. Returns a value of 1 if successful. Otherwise // it will need to return a number corresponding to the error message provided. public int addClientMessage(String from, String message, String to){ java.sql.Statement st = null; int retVal = 0; String insertChat = "INSERT INTO chatlist (`from`, `messages`, `to`, `type`) " + "VALUES ('" + from + "', '" + message + "', '" + to + "',0);"; int i; System.out.println(insertChat); try { st = con.createStatement(); i = st.executeUpdate(insertChat); if (i == 1){ retVal = 1; System.out.println("Message Added."); //FOR STATS - Scott stats.addMessage(message.length()); } else retVal = 0; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } addWebEvent(to, 1); return retVal; } // Robert Jolly // Method responsible for returning an ArrayList of Chat Message Objects. Each message is stored as one row in the // database table 'chatlog'. public ArrayList<ChatMessage> getMessage(String recipient){ ChatMessage chat = new ChatMessage(); ArrayList<ChatMessage> messages = new ArrayList<ChatMessage>(); java.sql.Statement st = null; java.sql.ResultSet rs = null; String getChat = "SELECT * FROM chatlist WHERE `to`='"+ recipient + "' AND type = 0;"; String updateChat = "UPDATE chatlist set type = 1 where chatlist.to = '" + recipient + "';"; try { st = con.createStatement(); rs = st.executeQuery(getChat); while (rs.next()){ System.out.println("from: " + rs.getString("from")); chat = new ChatMessage(rs.getString("from"), rs.getString("to"), rs.getString("messages")); messages.add(chat); } st = con.createStatement(); int i = st.executeUpdate(updateChat); if(i == 1){ //update successful } rs.close(); rs = null; st.close(); st = null; } catch (SQLException e) { System.err.println(e); } return messages; } // Robert Jolly // Method responsible for returning an ArrayList of Chat Message Objects. Each message is stored as one row in the // database table 'chatlog'. public ArrayList<ChatMessage> getClientMessage(String recipient){ ChatMessage chat = new ChatMessage(); ArrayList<ChatMessage> messages = new ArrayList<ChatMessage>(); java.sql.Statement st = null; java.sql.ResultSet rs = null; String getChat = "SELECT * FROM chatlist WHERE `to`='"+ recipient + "' AND type = 0; AND offline = 0"; String updateChat = "UPDATE chatlist set type = 1 where chatlist.to = '" + recipient + "';"; try { st = con.createStatement(); rs = st.executeQuery(getChat); while (rs.next()){ System.out.println("from: " + rs.getString("from")); chat = new ChatMessage(rs.getString("from"), rs.getString("to"), rs.getString("messages")); messages.add(chat); } st = con.createStatement(); int i = st.executeUpdate(updateChat); if(i == 1){ //update successful } rs.close(); rs = null; st.close(); st = null; } catch (SQLException e) { System.err.println(e); } return messages; } //Dan Morgan //This method updates the status, an integer, of the specified client. public int updateStatus(String clientid, int status){ int retVal = 0; //server error java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectClient = "SELECT * FROM client where clientid = '" + clientid + "';"; String updateStatus = "UPDATE client set status = '" + status + "' WHERE clientid = '" + clientid + "';"; try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectClient); //check if the clientid exists before updating the status if(rs.next()){ //if they exist, we can try to update their status try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. int i = st.executeUpdate(updateStatus); if(i == 1){ retVal = 1;//updateStatus successful System.out.println("updateStatus successful." + "\n"); //FOR STATS - SCOTT stats.changedStatus(); } } catch(Exception e) { System.err.println("updateStatus failed." + "\n"); System.err.println(e + "\n"); retVal = 0; //Server error...we found the client but the executeUpdate failed } } retVal = 3; //invalid login rs.close(); rs = null; st.close(); st = null; } else{ retVal = 0; //Server error...con.creatStatement most likely failed. System.out.println("Error: No active Connection" + "\n"); } }catch(Exception e){ retVal = 0; //server error, con not created System.err.println(e + "\n"); } this.updateBuddies(clientid); //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method gets the status, as an integer, of the specified client. //If this method returns -1, an error occured public int getStatus(String clientid){ int retVal = -1; //server error java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectStatus = "SELECT status FROM client where clientid = '" + clientid + "';"; try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectStatus); //rs.next() will return true if the client exists if(rs.next()){ //if it's true, we found the clientid, and can extract their status retVal = new Integer(rs.getString(1)).intValue(); } else{ System.err.println("That clientID does not exist. Please try another"); retVal = 3; //invalid login } rs.close(); rs = null; st.close(); st = null; }else{ retVal = 0; //server error System.err.println("Error: No active Connection" + "\n"); } }catch(Exception e){ System.err.println(e + "\n"); retVal = 0; //server error } return retVal; } //Robert Jolly // This will add a webevent to the database table. public int addWebEvent(String clientID, int type){ java.sql.Statement st = null; String insertEvent = "INSERT INTO event(ClientID, Type) " + "VALUES('" + clientID + "', " + type + ");"; String update1 = "UPDATE event SET Type=1 WHERE ClientID = '" + clientID + "';"; String update2 = "UPDATE event SET Type=2 WHERE ClientID = '" + clientID + "';"; String update3 = "UPDATE event SET Type=3 WHERE ClientID = '" + clientID + "';"; int retVal = 0; //Server Error try{ if(con!=null){ int checker = getWebEvent(clientID); System.out.println(checker); if (checker == 1 && type == 1){ st = con.createStatement(); st.executeUpdate(update1); retVal = 1; } else if (checker == 2 && type == 1){ st = con.createStatement(); st.executeUpdate(update3); retVal = 1; } else if (checker == 3 && type == 1){ st = con.createStatement(); st.executeUpdate(update3); retVal = 1; } else if (checker == 2 && type == 3){ st = con.createStatement(); st.executeUpdate(update2); retVal = 1; } else if (checker == 3 && type == 2){ st = con.createStatement(); st.executeUpdate(update3); retVal = 1; } else if (checker == 1 && type == 2){ st = con.createStatement(); st.executeUpdate(update3); retVal = 1; } else if (checker == 1 && type == 3){ System.out.println(update3); st = con.createStatement(); st.executeUpdate(update3); retVal = 1; } else if (checker == 3 && type == 3){ st = con.createStatement(); st.executeUpdate(update3); retVal = 1; } else st = con.createStatement(); st.executeUpdate(insertEvent); retVal = 1; //Currently 1 & add 1 //Currently 2 & add 1 make it a three //Currently 3 & add 1 make it a three //Current 2 & and add 2 stay a two //Currently 2 & add a three, becomes a three //Cureently 3 & add a two remains a three //Currently 1 & add a 2 it remains a three //Currently 1 and add a three it will become a three //Currently a three and want to add a three it will remain a three //if nothing then it will put in anything. } st.close(); st = null; } //if the event is already present, it will throw an exception catch(Exception e) { System.err.println("Your event is already present." + "\n"); System.err.println(e); retVal = 7; //Your event is already present } //return the error/success code to the caller so they can quickly parse what happened return retVal; } public int clearEvent(String clientID){ java.sql.Statement st = null; String deleteEvent = "DELETE FROM event WHERE ClientID='" + clientID + "';"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); retVal = st.executeUpdate(deleteEvent); } st.close(); st = null; } //if the event is already present, it will throw an exception catch(Exception e) { System.err.println("Event not found." + "\n"); System.err.println(e + "\n"); retVal = 7; //Your event is already present } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Chad Curtis // This will return a webevent from the database table. public int updateBuddies(String clientID){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectEvent = "SELECT clientID FROM Buddy b WHERE b.Buddy='" + clientID + "';"; System.out.println(selectEvent); int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectEvent); //iterate through the results and add them to the Events while(rs.next()){ //if it's true, we found the clientid, and can extract their status addWebEvent(rs.getString(1), 2); retVal = 1; } } rs.close(); rs = null; st.close(); st = null; } //if the event is already present, it will throw an exception catch(Exception e) { System.err.println("Your event is already present." + "\n"); System.err.println(e + "\n"); retVal = 7; //Your event is already present } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Robert Jolly // This will return a webevent from the database table. public int getWebEvent(String clientID){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectEvent = "SELECT type FROM event WHERE ClientID='" + clientID + "';"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectEvent); //rs.next() will return true if the client exists if(rs.next()){ //if it's true, we found the clientid, and can extract their status retVal = new Integer(rs.getString(1)).intValue(); } } rs.close(); rs = null; st.close(); st = null; } //if the event is already present, it will throw an exception catch(Exception e) { System.err.println("Your event is already present." + "\n"); System.err.println(e + "\n"); retVal = 7; //Your event is already present } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method will add a buddy to the buddy table. //ClientID is the person adding the buddy. //Buddy is...the buddy. //Group is their group in the buddy list (all buddies, friends, etc). public int addBuddy(String clientID, String buddy, String group){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectClient = "SELECT clientid FROM Client WHERE clientID = '" + clientID + "';"; String selectBuddy = "SELECT clientid FROM Client WHERE clientID = '" + buddy + "';"; String insertBuddy = "INSERT INTO buddy (clientid, buddy, usergroup) VALUES ('" + clientID + "','" + buddy + "','"+ group + "');"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectClient); //check if the original client exists //rs.next() will return true if the select statement found the client in the database, meaning he exists if(rs.next()){ //if he exists, now we check if the buddy we're adding exists rs = st.executeQuery(selectBuddy); if(rs.next()){ //if both exist, we can add the buddy try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. int i = st.executeUpdate(insertBuddy); if(i == 1){ retVal = 1;//addBuddy successful System.out.println("AddBuddy successful." + "\n"); //FOR STATS - Scott stats.moreBuddies(); } } //if the two are already buddies, it will throw an exception catch(Exception e) { //e.printStackTrace(); System.err.println("Your users are already buddies." + "\n"); System.err.println(e + "\n"); retVal = 5; //Your users are already buddies } } } else { retVal = 3;//Invalid ClientID } rs.close(); rs = null; st.close(); st = null; }else System.err.println("Error: No active Connection" + "\n"); }catch(Exception e){ e.printStackTrace(); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method will remove a buddy from the buddy table. //You must supply the ClientID (the person removing the buddy), the Buddy (the buddy to be removed), and the buddy's group (all buddies, friends, etc). //The reason is all three are primary keys in the database, so you must supply all three. public int removeBuddy(String clientID, String buddy, String group){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectBuddy = "SELECT ClientID, Buddy, UserGroup FROM Buddy WHERE ClientID = '" + clientID + "' AND Buddy = '" + buddy + "' AND UserGroup = '" + group + "';"; String deleteBuddy = "DELETE FROM buddy WHERE clientID = '" + clientID + "' AND buddy = '" + buddy + "' AND userGroup ='"+ group + "'"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectBuddy); //check and see if the buddy exists in the table //rs.next() will return true if the select statement found the buddy in the database, meaning he exists if(rs.next()){ //if they exist, we can try to delete the buddy try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. int i = st.executeUpdate(deleteBuddy); if(i == 1){ retVal = 1;//removeBuddy successful System.out.println("RemoveBuddy successful." + "\n"); } } catch(Exception e) { //e.printStackTrace(); System.err.println("Remove buddy failed." + "\n"); System.err.println(e + "\n"); retVal = 6; //TODO what is this error } } else { retVal = 3;//Invalid buddy, cannot delete because it doesn't exist } rs.close(); rs = null; st.close(); st = null; }else System.err.println("Error: No active Connection" + "\n"); }catch(Exception e){ //e.printStackTrace(); System.err.println(e + "\n"); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method will return a buddylist object, which is basically an arraylist of buddy strings. public BuddyList getBuddyList(String clientid){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectBuddys = "SELECT b.buddy, c.status FROM buddy b, client c WHERE b.clientid = '" + clientid + "' AND b.buddy = c.clientid;"; BuddyList buddyList = new BuddyList(); try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectBuddys); //iterate through the results and add them to the BuddyList while (rs.next()){ buddyList.addBuddy( new Buddy(rs.getString(1), Integer.parseInt(rs.getString(2)))); } rs.close(); rs = null; st.close(); st = null; }else System.out.println("Error: No active Connection" + "\n"); }catch(Exception e){ System.err.println(e + "\n"); } return buddyList; } // Robert Jolly public String getChatHistory(String clientID){ String history = ""; java.sql.ResultSet rs = null; java.sql.Statement st = null; String chatHistory = "SELECT ChatLog FROM chatlog WHERE ClientID = '" + clientID + "';"; try{ if (con!=null){ st = con.createStatement(); rs = st.executeQuery(chatHistory); history = rs.getString(1); } rs.close(); rs = null; st.close(); st = null; } catch(Exception e){ System.out.println("Unable to retrieve chat history."); System.err.println(e + "\n"); } return history; } public int verifyLogin(String loginID, String password){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectPassword = "SELECT password FROM Client WHERE clientID = '" + loginID + "' AND lockedout = 0;"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectPassword); //rs.next() will return true if the select statement found the client in the database, meaning he exists, and if the client is not locked out. if(rs.next()){ //if he exists, we check the password if(password.equals(rs.getString(1))){ retVal = 1;//Login successful } else{ retVal = 2;//Bad password } } else { retVal = 3;//Invalid ClientID, or the client is locked out. } rs.close(); rs = null; st.close(); st = null; }else System.err.println("Error: No active Connection" + "\n"); }catch(Exception e){ System.err.println(e + "\n"); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method will register a new user with the client. You must supply a clientID and a password. //adds a new user to the client table and sets default configurations in the configuration table //TODO for later would be allowing updating of email, status, and lockedout. public int registerUser(String clientID, String password){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectClient = "SELECT clientid FROM Client WHERE clientID = '" + clientID + "';"; //status and lockedout will default to 0 //email will default null //insert time timestamp when this method is called. long timestamp = System.currentTimeMillis(); String insertClient = "INSERT INTO Client (clientid, email, password, status, lockedout, timestamp) VALUES ('" + clientID + "',null,'"+ password + "',0,0,"+ timestamp + ");"; //the default configuration String insertConfiguration = "INSERT INTO configuration (clientid, tabfill, tabstroke, windowfill, windowstroke, chatwindowcolor, textcolor) VALUES" + " ('" + clientID + "','0x000000','0x000000','0x000000','0x000000','0x000000','0x000000');"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectClient); //check if the clientid already exists //rs.next() will return true if the select statement found the client in the database, meaning he exists //therefore, we want !rs.next() if(!rs.next()){ //if he doesn't exist, we can add him try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. //first we'll add the new client int i = st.executeUpdate(insertClient); if(i == 1){ System.out.println("RegisterUser successful."); //executeUpdate() returns an integer; a return of 1 means the insert was successful. //now we can set his initial configuration int j = st.executeUpdate(insertConfiguration); if(j == 1){ retVal = 1;//registerUser and setInitialConfig successful System.out.println("SetConfiguration successful."); System.out.println("New user and configuration successfully added." + "\n"); //FOR STATS - Scott stats.adduser(); } } } catch(Exception e) { System.err.println(e + "\n"); retVal = 0; //server error } } else { System.err.println("That ClientID already exists." + "\n"); retVal = 3;//Invalid ClientID } rs.close(); rs = null; st.close(); st = null; }else System.err.println("Error: No active Connection" + "\n"); }catch(Exception e){ System.err.println(e); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method will lock out a user from logging in to the chat system. //This should be called after 5 failed login attempts. The user will be unable to log in until unLockOutUser is called on their name. public int lockOutUser(String clientID){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectClient = "SELECT clientid FROM Client WHERE clientID = '" + clientID + "';"; String updateLockedOut = "UPDATE client set lockedout = 1 where clientid = '" + clientID + "';"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectClient); //check if the original client exists //rs.next() will return true if the select statement found the client in the database, meaning he exists if(rs.next()){ //if he exists, we can update his lockedout status try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. int i = st.executeUpdate(updateLockedOut); if(i == 1){ retVal = 1;//updateLockedOut successful System.out.println("lockOutUser successful." + "\n"); } } //MySQL doesn't seem to throw an error even if you give it an invalid clientid //It just says "Query OK, 0 rows affected" so I'm not expecting this to throw an error. catch(Exception e) { //e.printStackTrace(); System.err.println(e + "\n"); retVal = 0; //server error } } else { retVal = 3;//Invalid ClientID } rs.close(); rs = null; st.close(); st = null; }else System.err.println("Error: No active Connection" + "\n"); }catch(Exception e){ e.printStackTrace(); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //Removes the lock from the client's username so they can log in again. public int unLockOutUser(String clientID){ java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectClient = "SELECT clientid FROM Client WHERE clientID = '" + clientID + "';"; String updateLockedOut = "UPDATE client set lockedout = 0 where clientid = '" + clientID + "';"; int retVal = 0; //Server Error try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectClient); //check if the original client exists //rs.next() will return true if the select statement found the client in the database, meaning he exists if(rs.next()){ //if he exists, we can update his lockedout status try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. int i = st.executeUpdate(updateLockedOut); if(i == 1){ retVal = 1;//updateLockedOut successful System.out.println("unLockOutUser successful." + "\n"); } } //MySQL doesn't seem to throw an error even if you give it an invalid clientid //It just says "Query OK, 0 rows affected" so I'm not expecting this to throw an error. catch(Exception e) { //e.printStackTrace(); System.err.println(e + "\n"); retVal = 0; //server error } } else { retVal = 3;//Invalid ClientID } rs.close(); rs = null; st.close(); st = null; }else System.err.println("Error: No active Connection" + "\n"); }catch(Exception e){ System.err.println(e); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //This method sets a client's configuration, or preferences, which you can see listed below (the index references). These are for colors in the chat client. //You must supply a Configuration object, which is basically an arraylist of strings of the below preferences. public int updateConfiguration(String clientID, Configuration _config){ //index 0 = _clientID; //index 1 = _tabFill; //index 2 =_tabStroke; //index 3 = _windowFill; //index 4 = _windowStroke; //index 5 = _chatWindowColor; //index 6 = _textColor; ArrayList<String> configList = _config.getConfiguration(); int retVal = 0; //Server error java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectClientID = "SELECT clientid FROM client where clientid = '" + clientID + "';"; String updateConfiguration = "UPDATE configuration set tabfill = '" + configList.get(1) + "', tabstroke = '" + configList.get(2) + "', windowfill = '" + configList.get(3) + "', windowstroke = '" + configList.get(4) + "', chatwindowcolor = '" + configList.get(5) + "', textcolor = '" + configList.get(6) + "' WHERE clientid = '" + clientID + "';"; try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectClientID); //check if the clientid exists before inputing into configuration table if(rs.next()){ //if they exist, we can try to set their configuration try{ //executeUpdate() returns an integer; a return of 1 means the insert was successful. int i = st.executeUpdate(updateConfiguration); if(i == 1){ retVal = 1;//updateConfiguration successful System.out.println("updateConfiguration successful." + "\n"); } } catch(Exception e) { //e.printStackTrace(); System.err.println("updateConfiguration failed." + "\n"); System.err.println(e + "\n"); retVal = 0; //server error } } rs.close(); rs = null; st.close(); st = null; }else System.out.println("Error: No active Connection" + "\n"); }catch(Exception e){ System.err.println(e + "\n"); } //return the error/success code to the caller so they can quickly parse what happened return retVal; } //Dan Morgan //this will return a configuration object full of nulls if the clientID doesn't exist...maybe we should fix this. //This is because making a new configuration creates an arraylist with 7 nulls inserted, since specifying a size of the list //wasn't enough to say _configuration.set(index, string)...it threw index out of bounds errors. public Configuration getConfiguration(String clientID){ java.sql.ResultSet rs = null; java.sql.Statement st = null; Configuration _configuration = new Configuration(); String selectConfiguration = "SELECT * from configuration WHERE clientid = '" + clientID + "';"; try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectConfiguration); //this will return true if the clientid exists in the table if(rs.next()){ //if they exist, we can iterate their configuration //iterate through the results and add them to a configuration object System.out.println("Creating the config object..."); _configuration.updateConfiguration(0, clientID); for(int i = 2; i < 8; i++){ _configuration.updateConfiguration(i-1, rs.getString(i)); } System.out.println("Creation completed." + "\n"); } else if(!rs.next()){ System.err.println("That ClientID does not exist."); } rs.close(); rs = null; st.close(); st = null; }else System.out.println("Error: No active Connection" + "\n"); }catch(Exception e){ System.err.println(e + "\n"); } return _configuration; } //Outputs the stats regaurding the IM activity from the stats obj. -Scott public static void outStats() { stats.printStats(); } //Dan Morgan //This method doesn't serve any practical purposes, but is nice for debugging. public void selectAllFrom(String table){ java.sql.ResultSetMetaData rsmd = null; java.sql.ResultSet rs = null; java.sql.Statement st = null; String selectAllFromClient = "SELECT * FROM " + table; try{ if(con!=null){ st = con.createStatement(); rs = st.executeQuery(selectAllFromClient); rsmd = rs.getMetaData(); System.out.println("Table: " + rsmd.getTableName(1)); System.out.println("********************************"); //iterate through the results and print them while (rs.next()){ for (int i = 1; i <= rsmd.getColumnCount(); i++){ System.out.println(" " + rsmd.getColumnName(i)+ ": " + rs.getString(i)); } System.out.println(""); } System.out.println("********************************" + "\n"); rs.close(); rs = null; rsmd = null; st.close(); st = null; }else System.out.println("Error: No active Connection" + "\n"); }catch(Exception e){ //e.printStackTrace(); System.err.println(e + "\n"); } } public void closeConnection(){ try{ this.outStats(); if(con!=null) con.close(); System.out.println("The connection has been closed." + "\n"); con=null; }catch(Exception e){ //e.printStackTrace(); System.err.println(e + "\n"); } } public static void main(String[] args) throws Exception { System.out.println("Database connection initializing...."); DBComm myDBComm = new DBComm(); //myDBComm.selectAllFrom("client"); myDBComm.addBuddy("number1pimp", "realnumber1pimp", "Buddies"); myDBComm.addBuddy("realnumber1pimp", "number1pimp", "Homies"); //myDBComm.selectAllFrom("buddy"); //Testing correct ClientID and Password int i = myDBComm.verifyLogin("number1pimp", "bigpimpin"); System.out.println("Number should be 1: "+ i); //Testing incorrect Password int j = myDBComm.verifyLogin("number1pimp", "asdlgkjaslg"); System.out.println("Number should be 2: "+ j); //Testing incorrect ClientID int k = myDBComm.verifyLogin("number2pimp", "bigpimpin"); System.out.println("Number should be 3: "+ k + "\n"); myDBComm.removeBuddy("number1pimp", "realnumber1pimp", "Buddies"); //myDBComm.selectAllFrom("buddy"); myDBComm.registerUser("Dan2", "test2"); //myDBComm.selectAllFrom("client"); myDBComm.addMessage("Robert", "Hey Jordan", "Jordan"); myDBComm.getMessage("Robert"); myDBComm.addWebEvent("Dan1", 1); BuddyList newBuddyList = myDBComm.getBuddyList("jordan"); System.out.println("jordan's BuddyList:" + "\n"); for(Buddy b: newBuddyList.getBuddyList()){ System.out.println(b.toString()); } System.out.println(""); Configuration commConfigTestInput = new Configuration(); commConfigTestInput.updateConfiguration(0, "Dan1"); commConfigTestInput.updateConfiguration(1, "tabFillTest1"); commConfigTestInput.updateConfiguration(2, "tabStrokeTest1"); commConfigTestInput.updateConfiguration(3, "windowFillTest1"); commConfigTestInput.updateConfiguration(4, "windowStrokeTest1"); commConfigTestInput.updateConfiguration(5, "chatWindowColorTest1"); commConfigTestInput.updateConfiguration(6, "textColorTest1"); myDBComm.updateConfiguration("Dan1", commConfigTestInput); Configuration commConfigTestOutput = myDBComm.getConfiguration("Dan1"); System.out.println("Configuration Testing"); System.out.println("**********************************"); for(String s: commConfigTestOutput.getConfiguration()){ System.out.println(s); } System.out.println("**********************************"); System.out.println(""); System.out.println("getStatus Testing"); System.out.println("**********************************"); System.out.println("Dan1: " + myDBComm.getStatus("Dan1")); System.out.println("ditch: " + myDBComm.getStatus("ditch")); System.out.println("Josh: " + myDBComm.getStatus("Josh")); System.out.println("Jordan1: " + myDBComm.getStatus("Jordan1")); System.out.println("**********************************"); System.out.println(""); System.out.println("updateStatus Testing"); System.out.println("**********************************"); myDBComm.updateStatus("Dan1", 1); myDBComm.updateStatus("ditch", 2); myDBComm.updateStatus("Josh", 3); myDBComm.updateStatus("Jordan1", 4); System.out.println("**********************************"); //myDBComm.selectAllFrom("client"); System.out.println(""); System.out.println("lockOutUser Testing"); System.out.println("**********************************"); myDBComm.lockOutUser("Dan4"); //Testing locked out int l = myDBComm.verifyLogin("Dan4", "test4"); System.out.println("Number should be 3: "+ l + "\n"); System.out.println("**********************************"); System.out.println(""); System.out.println("unLockOutUser Testing"); System.out.println("**********************************"); myDBComm.unLockOutUser("Dan4"); //Testing un locked out int m = myDBComm.verifyLogin("Dan4", "test4"); System.out.println("Number should be 1: "+ m + "\n"); System.out.println("**********************************"); System.out.println(""); myDBComm.getWebEvent(""); System.out.println(myDBComm.getWebEvent("George Washington")); myDBComm.addWebEvent("pyrobug", 3); System.out.println(myDBComm.addWebEvent("George Washington", 2)); myDBComm.getMessage("Jordan"); System.out.println(myDBComm.getMessage("Jordan")); myDBComm.closeConnection(); myDBComm = null; //STATS outStats(); } }
Java