id
stringlengths
36
36
text
stringlengths
1
1.25M
fc071696-492f-4a40-acf2-b6f0b643442c
private void resetErrorStatus() { this.errcode = 0; this.errmsg = this.arrayErrorMap[errcode]; this.requestId = 0; }
5ee01d9d-b85b-4cf9-9dae-dac8c6596498
private JSONObject commonProcess(Map<String, String> paramOpt) { adjustOpt(paramOpt); ResponseCore ret = baseControl(paramOpt); if (ret == null) { throw new ChannelException("base control returned empty object", CHANNEL_SDK_SYS); } if (ret.isOK()) { try { JSONObject result = new JSONObject(ret.body); this.requestId = result.getInt("request_id"); return result; } catch (JSONException ex) { throw new ChannelException(ret.body, CHANNEL_SDK_HTTP_STATUS_OK_BUT_RESULT_ERROR); } } else { try { JSONObject result = new JSONObject(ret.body); this.requestId = result.getInt("request_id"); throw new ChannelException(result.getString("error_msg"), result.getInt("error_code")); } catch (JSONException ex) { throw new ChannelException("ret body:" + ret.body, CHANNEL_SDK_HTTP_STATUS_ERROR_AND_RESULT_ERROR); } } }
8cbb122d-207f-4736-be83-67635d0883b8
public Map<String, String> prepareArgs(String[] arrNeed, Map<String, String> tmpArgs) { Map<String, String> args; if (null == tmpArgs || tmpArgs.isEmpty()) { args = new HashMap<String, String>(); return args; } if (null != arrNeed && arrNeed.length > 0 && tmpArgs.isEmpty()) { String keys = "("; for (String key : arrNeed) { keys += key + ","; } keys += ")"; throw new ChannelException("invalid sdk params, params" + keys + "are needed",CHANNEL_SDK_PARAM); } if (null != arrNeed) { for (String key : arrNeed) { if (!tmpArgs.containsKey(key)) { throw new ChannelException("lack param (" + key + ")", CHANNEL_SDK_PARAM); } } } args = new HashMap<String, String>(tmpArgs); if (args.containsKey(CHANNEL_ID)) { String channelIDValue = (String)args.get(CHANNEL_ID); args.put(CHANNEL_ID, channelIDValue); // URLCodec codec = new URLCodec("utf8"); // String channelIDValue = (String)args.get(CHANNEL_ID); // try { // args.put(CHANNEL_ID, codec.encode(channelIDValue)); // } catch (EncoderException ex) { // throw new ChannelException("bad channel_id (" + channelIDValue + ")", CHANNEL_SDK_PARAM); // } } return args; }
b3f6bd03-b330-43ee-b6f5-a00d557f7e9d
private void adjustOpt(Map<String, String> opt) { if (null == opt || opt.isEmpty()) { throw new ChannelException("no params are set", CHANNEL_SDK_PARAM); } if (!opt.containsKey(TIMESTAMP)) { String timestamp = String.valueOf(System.currentTimeMillis()/1000); opt.put(TIMESTAMP, timestamp); } opt.put(HOST, DEFAULT_HOST); opt.put(API_KEY, apiKey); if (opt.containsKey(SECRET_KEY)) { opt.remove(SECRET_KEY); } }
825478a4-adbc-4e61-be92-cb6c974effd8
private ResponseCore baseControl(Map<String, String> opt) { StringBuilder content = new StringBuilder(); String resource = "channel"; if (opt.containsKey(CHANNEL_ID) && opt.get(CHANNEL_ID)!=null) { resource = opt.get(CHANNEL_ID); opt.remove(CHANNEL_ID); } String host = opt.get(HOST); opt.remove(HOST); String url = "http://" + host + "/rest/2.0/" + PRODUCT + "/"; url += resource; HttpMethod httpMethod = HttpMethod.HTTP_POST; String sign = genSign(httpMethod.toString(), url, opt); opt.put(SIGN, sign); Set<String> keys = opt.keySet(); for (String key : keys) { try { // try { //// key = new URLCodec("utf8").encode(key); //// String v = new URLCodec("utf8").encode(opt.get(key)); // content.append(key).append("=").append(opt.get(key)).append("&"); // } catch (EncoderException ex) { // Logger.getLogger(Channel.class.getName()).log(Level.SEVERE, null, ex); // } String v = URLEncoder.encode(opt.get(key), "utf8"); content.append(key).append("=").append(v).append("&"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(Channel.class.getName()).log(Level.SEVERE, null, ex); } } String postContent = content.toString(); postContent = postContent.substring(0, postContent.length()-1); logger.info("content = " + postContent); logger.info("url = " + url); RequestCore request = new RequestCore(url); Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/x-www-form-urlencoded"); headers.put("User-Agent", "Baidu Channel Service Javasdk Client"); Set<String> headerKeySet = headers.keySet(); for (String headerKey : headerKeySet) { String headerValue = headers.get(headerKey); request.addHeader(headerKey, headerValue); } request.setMethod(httpMethod); request.setBody(postContent); request.setConnectionOption(connOption); request.sendRequest(); return new ResponseCore(request.getResponseHeader(), request.getResponseBody(), request.getResponseCode()); }
d7855903-401f-4fe8-a662-992a0670bd01
private String genSign(String method, String url, Map<String, String> opt) { String gather = method + url; TreeMap<String, String> sortOpt = new TreeMap<String, String>(opt); NavigableSet<String> keySet = sortOpt.navigableKeySet(); Iterator<String> it = keySet.iterator(); while (it.hasNext()) { String key = it.next(); String value = sortOpt.get(key); gather += key + "=" + value; } gather += secretKey; logger.info("sign source content: " + gather); String encodedGather; try { // encodedGather = new URLCodec("utf8").encode(gather); encodedGather = URLEncoder.encode(gather, "utf8"); } catch (UnsupportedEncodingException ex) { throw new ChannelException("wrong params are seted: " + gather, CHANNEL_SDK_PARAM); } String sign = DigestUtils.md5Hex(encodedGather); return sign; }
9e339de3-e870-47c7-9033-ccabb663a765
public int errno() { return this.errcode; }
15f1bb83-c16d-4429-87b9-b18dd49589f1
public String errmsg() { return this.errmsg; }
36af4c53-7079-43b5-aba4-6cdcd0abbe96
public ResponseCore(Map<String, String> header, String body, int status) { this.header = header; this.body = body; this.status = status; }
20f261e2-d463-4662-9ffe-7ecd620be5d8
public boolean isOK(int... codes) { if (codes == null || codes.length == 0) { codes = new int[]{200, 201, 204, 206}; } boolean isOK = false; for (int code : codes) { if (status == code) { isOK = true; } } return isOK; }
1c73da4d-bf41-4d73-9356-c71b6027dc16
@Before public void setUp() { apiKey = "MFRUN68t8O33NZdDlUqHxi5Z"; secretKey = "UVUNcKzQvPwiI8mQVxxj3MsdGwTirzOf"; userId = "765522986755783217"; channelID = "3947047891437553579"; }
b2c62be2-0e96-4678-bb9d-90d8693c5a3c
@After public void finish() { // nothing }
2098fe11-a42e-4301-a8dd-e8d14a767500
@Test public void queryBindList() { Map<String, String> optional = new HashMap<String, String>(); optional.put(Channel.CHANNEL_ID, channelID); Channel channel = new Channel(); channel.initialize(apiKey, secretKey, null); JSONObject result = channel.queryBindList(userId, optional); if (channel.errcode ==0) { Assert.assertNotNull(result); } else { System.out.println("error_code: " + channel.errcode + "; error_msg: " + channel.errmsg); } }
c6e02b4e-7804-41aa-b887-d5d23d4c0bed
@Test public void pushMessage() { Map<String, String> optional = new HashMap<String, String>(); optional.put(Channel.USER_ID, userId); optional.put(Channel.MESSAGE_TYPE, String.valueOf(1)); Channel channel = new Channel(); channel.initialize(apiKey, secretKey, null); // int pushType = 3; String messages = "{ 'title': 'hello " + new Date() + "' , 'description': 'hello'}"; String messageKey = "msg_key"; JSONObject result = channel.pushMessage(pushType, messages, messageKey, optional); if (channel.errcode ==0) { Assert.assertNotNull(result); System.out.println(result); } else { System.out.println("error_code: " + channel.errcode + "; error_msg: " + channel.errmsg); } }
73fc5709-ee9c-4ee3-b210-04333c2318fa
public void updateOrders(Set<Order> orders);
9525f064-8086-4e9c-9061-34e2231fef45
public void statusUpdated(WASStatus oldStatus, WASStatus newStatus);
da6787cd-3cbb-491b-8257-f81bbed20edf
public WASClientRunner(InetSocketAddress address, WASClient wasClient) { this.address = address; this.wasClient = wasClient; try { docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException pce) { throw new IllegalStateException("Error while initialisation of XML Parser", pce); } wasDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); }
5edab67d-6d18-481d-8667-b94cbafe99d2
public void run() { //Error recovery loop while (!wasClient.isStop()) { try { // Operational loop while (!wasClient.isStop()) { try { initalizeSockets(); sendCommand(); readResponse(); Set<Order> orderCollection = parseResponse(); wasClient.fireOrderUpdate(orderCollection); if (!wasClient.isStop()) Thread.sleep(UPDATE_INTERVAL_MS); } catch (InterruptedException ex) { // Maybe we are terminated by WasClient, check in loop header } } } catch (ConnectException conEx){ wasClient.setState(WASStatus.DISCONNECTED); log.error("Can't connect to WAS! - Retry in 30sec",conEx); try { Thread.sleep(30000); } catch (InterruptedException e) { } } catch (IOException e) { log.error("IOException in WASClient!", e); wasClient.setState(WASStatus.ERROR); } finally { tearDownSockets(); } } wasClient.setState(WASStatus.STOPPED); }
4cd8d0fa-516f-46c1-8d7d-4ceccdbbf5bd
private void tearDownSockets() { try { if (w != null) w.close(); if (r != null) r.close(); if (sock != null) sock.close(); } catch (IOException e) { log.error("IOException during Socket tearDown - ignoreing", e); } finally { resetSocket(); } }
df12aac9-a17d-4c37-9421-437fc3765b47
private Set<Order> parseResponse() throws IOException { Document doc = loadDoc(response.getResponse()); Set<Order> orderSet = new HashSet<Order>(); NodeList orders = doc.getElementsByTagName("order"); // No orders if (orders.getLength() == 0) { return orderSet; } for (int i = 0; i < orders.getLength(); i++) { Node order = orders.item(i); orderSet.add(parseOrder(order)); } return orderSet; }
a52f83b7-84da-4be2-85ea-8000b6ba82e1
private Order parseOrder(Node node) { Order order = new Order(); //order.setKey(Long.parseLong(getTextNodeValue(node, "key").substring(2), 12)); //TODO: Fix numberformat exception! order.setOrigin(getTextNodeValue(node, "origin")); order.setReceived(parseWasDate(getTextNodeValue(node, "receive-tad"))); order.setOperationId(getTextNodeValue(node, "operation-id")); order.setAlarmlevel(Integer.parseInt(getTextNodeValue(node, "level"))); order.setName(getTextNodeValue(node, "name")); order.setCaller(getTextNodeValue(node, "caller")); order.setLocation(getTextNodeValue(node, "location")); order.setInfo(getTextNodeValue(node, "info")); order.setStatus(parseStatus(getTextNodeValue(node, "status"))); order.setWatchout(parseWasDate(getTextNodeValue(node, "watch-out-tad"))); order.setFinished(parseWasDate(getTextNodeValue(node, "finished-tad"))); order.setFireDepartments(parseFireDepartments(node)); return order; }
4e3bf408-ee04-40a2-b117-e7fbd4245077
private OrderStatus parseStatus(String status) { if (status.equalsIgnoreCase("AUSGERÜCKT")) { return OrderStatus.OUT; } if (status.equalsIgnoreCase("BEENDET")) {//TODO: Check if "BEENDET" is the right status!" return OrderStatus.END; } return OrderStatus.ALERT; }
9ee5d13b-0e5d-4f04-af87-f41eb4fcfb71
private List<String> parseFireDepartments(Node node) { Element element = (Element) node; List<String> fireDepartments = new ArrayList<String>(); NodeList destinations = element.getElementsByTagName("destination"); for (int i = 0; i < destinations.getLength(); i++) { Node destination = destinations.item(i); fireDepartments.add(destination.getTextContent() + " (" + destination.getAttributes().getNamedItem("id") + ")"); } return fireDepartments; }
387ddfed-7972-4b4f-8e2d-3472cf8f091a
private Date parseWasDate(String nodeValue) { try { return nodeValue == null || nodeValue.isEmpty() ? null : wasDateFormat.parse(nodeValue); } catch (ParseException e) { throw new IllegalStateException("Can't parse " + nodeValue + " to WAS Date!", e); } }
99387891-ec28-4f49-a187-65c2dda1fd71
private String getTextNodeValue(Node node, String key) { if (node.getNodeType() == 1) { Element nodeElement = (Element) node; NodeList nodeElementLst = nodeElement.getElementsByTagName(key); if (nodeElementLst.getLength() != 1) { throw new IllegalStateException("Can't read TextNode -> found " + nodeElementLst.getLength() + " Elements in with key " + key); } return nodeElementLst.item(0).getTextContent(); }else{ throw new IllegalStateException("Can't read TextNode! Parent node type="+node.getNodeType()); } }
b9818f9f-615c-4096-8e39-3cde8cd057da
private Document loadDoc(String response) throws IOException { InputSource inSource = new InputSource(new StringReader(response)); try { Document doc = docBuilder.parse(inSource); doc.normalize(); return doc; } catch (SAXException e) { throw new IOException("Error while reading XML!", e); } }
47e61bd6-032c-449a-8691-7934baf7336c
private void readResponse() throws IOException { String line; StringBuilder sb = new StringBuilder(); // Read till termination mark is found while ((line = r.readLine()) != null && !line.endsWith("</pdu>") && !line.equals("<pdu/>")) { sb.append(line); } // Add Termination Mark or fail if EOF before XML Termination if (line != null) { if (line.endsWith("</pdu>")) { sb.append("</pdu>"); } if (line.equals("<pdu/>")) { sb.append("<pdu/>"); } } else { throw new IOException("EOF before XML termination!\nAlready read:\n" + sb.toString()); } response=new WASResponse(sb.toString()); }
5a3d969b-97b4-4ac3-bb86-63475b697143
private void sendCommand() throws IOException { w.write("GET ALARMS\n"); w.flush(); }
9cbf2aa4-4621-4c0c-96d8-6c69dcbc5ba4
private void initalizeSockets() throws SocketException, IOException { if (sock == null || sock.isClosed()) { resetSocket(); wasClient.setState(WASStatus.DISCONNECTED); sock = new Socket(); sock.setSoTimeout(SOCKET_TIMEOUT_MS); } if (!sock.isConnected()) { sock.connect(address, SOCKET_TIMEOUT_MS); } if (sock.isConnected()) { if (w == null) w = new OutputStreamWriter(sock.getOutputStream()); if (r == null) r = new BufferedReader(new InputStreamReader(sock.getInputStream(), "ISO-8859-15")); } wasClient.setState(WASStatus.CONNECTED); }
3729f10b-da4e-4809-ba51-cd6303d6310d
private void resetSocket() { sock = null; w = null; r = null; }
507748b6-23eb-456e-8aed-03eafdae3a3a
public WASResponse getResponse() { return response; }
445b29f9-d4aa-4cb8-b568-2aa1bb0c68dd
public void setResponse(WASResponse response) { this.response = response; }
bf98c613-2111-4541-b495-de46d9c4f74e
public WASClient() { this("192.168.130.100", 47000); }
1a7ffab2-6aae-4dd2-b82e-3f5246560f20
public WASClient(String host, int port) { this(new InetSocketAddress(host, port)); }
a9a5d1e6-b750-4212-ae0a-d77aa0877fc8
public WASClient(InetSocketAddress address) { if (address == null) { throw new IllegalArgumentException("WAS Socket address was null!"); } this.address = address; if (log.isDebugEnabled()) { log.debug("New WASClient for endpoint: " + address.toString()); } }
36309719-33bb-4ac0-bbaa-ecd8e6729247
public void start() throws IllegalWasClientState { if (state == WASStatus.STOPPED) { stop=false; clientRunner = new WASClientRunner(address, this); clientThread = new Thread(clientRunner); clientThread.setName("wasClientThread"); clientThread.setDaemon(true); clientThread.start(); } else { throw new IllegalWasClientState("start", this.state); } }
fd20d500-0cba-4b5c-a6b4-23a853569a60
public void stop() { if (state != WASStatus.STOPPED && clientThread!=null && clientThread.isAlive()) { stop=true; clientThread.interrupt(); } }
56349f27-1812-48b0-a9c5-0d297a420610
public WASStatus getState() { return state; }
c7fe3d22-a970-4322-b519-b3ffaf45f3bf
void setState(WASStatus state) { if (this.state != state) { WASStatus oldState = this.state; this.state = state; if (log.isDebugEnabled()) log.debug("New state: " + state); fireStateUpdate(oldState, state); } }
74cf02df-9815-476b-a829-01a5577d3f91
public WASResponse getLastRAWData(){ if( clientRunner != null) { return clientRunner.getResponse(); } throw new IllegalStateException(); }
ff0f526f-f605-42e1-95a9-8d2c2330f0a1
boolean isStop(){ return stop; }
d3d6be63-cef7-4cdc-9db0-43381632e507
void fireStateUpdate(WASStatus oldState, WASStatus newState) { HashSet<WeakReference<WASStatusListener>> toRemove=new HashSet<WeakReference<WASStatusListener>>(); for (WeakReference<WASStatusListener> reference : statusListeners) { WASStatusListener listener= reference.get(); if(listener==null) toRemove.add(reference); else listener.statusUpdated(oldState, newState); } statusListeners.removeAll(toRemove); }
a1472fde-4b55-41e8-bcc8-c1a497109659
void fireOrderUpdate(Set<Order> orders) { HashSet<WeakReference<WASOrderListener>> toRemove = new HashSet<WeakReference<WASOrderListener>>(); for (WeakReference<WASOrderListener> reference : orderListeners) { WASOrderListener listener=reference.get(); if(listener==null) toRemove.add(reference); else listener.updateOrders(orders); } orderListeners.removeAll(toRemove); }
dc275e59-d310-4490-a7bb-a1c00a02fab2
public void addWasStatusListener(WASStatusListener listener){ statusListeners.add(new WeakReference<WASStatusListener>(listener)); }
329049cd-3ea7-4263-801d-c89e74c8227e
public void addWasOrderListener(WASOrderListener listener){ orderListeners.add(new WeakReference<WASOrderListener>(listener)); }
2ba1dda5-4799-42d0-9c10-dafba0631783
public IllegalWasClientState(String string, WASStatus state) { super("Illegal WAS Client state during " + string + ": " + state); }
01b5b2e9-2ecd-4107-a5e9-56a209c877d9
public WASResponse(){ }
d0eda672-deff-4af9-88f8-9342ee65b198
public WASResponse(String response){ this.response=response; this.timestamp=new Date(); }
0819605b-c77c-4aaa-9ddd-390b6af22c59
public String getResponse() { return response; }
b0df4630-23f8-426c-a6c8-76b537ca95c7
public void setResponse(String response) { this.response = response; }
c30625cc-6f24-493e-8a88-0edde7ce146a
public Date getTimestamp() { return timestamp; }
2f4d23ee-180a-4fa0-8f99-0eefb9d452ec
public void setTimestamp(Date timestamp) { this.timestamp = timestamp; }
0fd6856c-e4d7-45fb-bf4b-0c3e51b26895
public Order() { }
d7efb9bb-316e-4557-847f-a293bd031c42
public String getOrigin() { return origin; }
65016915-c401-41ad-ac8c-3707b11df190
public void setOrigin(String origin) { this.origin = origin; }
3f65ffc4-5b0a-4796-90eb-1be01a01eb5d
public Date getReceived() { return received; }
4959387b-fc42-4dda-9ded-c70b47d3f002
public void setReceived(Date received) { this.received = received; }
1102acbb-91ad-400f-ab75-25068c6be67d
public Date getWatchout() { return watchout; }
31698d3c-362f-45fb-ac51-bcc3ce907b1e
public void setWatchout(Date watchout) { this.watchout = watchout; }
f08dded7-c335-4cf0-9ad0-fcc94ac67e18
public String getOperationId() { return operationId; }
f93b756c-aa63-4021-9ca3-13d63b4e00ed
public void setOperationId(String operationId) { this.operationId = operationId; }
508a1374-4ab6-4504-afcf-f88daf97214b
public int getAlarmlevel() { return alarmlevel; }
58f7d08a-db00-4b39-bbc2-f7a94788c61d
public void setAlarmlevel(int alarmlevel) { this.alarmlevel = alarmlevel; }
d85453c4-3604-4543-b3fb-f664588b7d48
public String getName() { return name; }
b82d3b06-cafc-4ffd-afb1-f7e75d15d248
public void setName(String name) { this.name = name; }
7c379f70-b0a5-424b-a614-468546747588
public String getLocation() { return location; }
6184a8c0-1705-4db5-ac4d-f244b39c65f7
public void setLocation(String location) { this.location = location; }
f4ddd9f4-117d-4fc5-838b-7e5fef85bd24
public String getOperation() { return operation; }
8884f9a4-8eb3-40ee-b3a1-05861f46f1ab
public void setOperation(String operation) { this.operation = operation; }
83400324-1f91-4b4d-926c-bcaa99190172
public String getCaller() { return caller; }
b7c776bf-feef-4ffa-9f8c-6b86bca787f2
public void setCaller(String caller) { this.caller = caller; }
c2cbe910-6f0b-4edc-be9d-6660d6d3e07e
public String getInfo() { return info; }
ba20f170-0496-4c24-a73c-53b1defe599d
public void setInfo(String info) { this.info = info; }
51176224-2445-4770-9f15-1bf6891acdc1
public OrderStatus getStatus() { return status; }
f9cc6d82-3185-4c18-84bf-95d3e46b84d0
public void setStatus(OrderStatus status) { this.status = status; }
90a73786-9ab0-4798-88fe-c758a38391c4
public List<String> getFireDepartments() { return fireDepartments; }
ae73cde3-397c-452a-9f79-b2fc9d7f830b
public void setFireDepartments(List<String> fireDepartments) { this.fireDepartments = fireDepartments; }
4ee00600-249f-41e9-a66e-a5beb9d51304
public long getKey() { return key; }
62a84951-5922-465c-bc56-72f79012ab63
public void setKey(long key) { this.key = key; }
a132a547-1e8e-40b0-9306-43930b80e499
public Date getFinished() { return finished; }
549ed131-4285-4e30-a28a-a54894e68391
public void setFinished(Date finished) { this.finished = finished; }
82f01ea6-a74d-486d-88e4-08902e3b913e
public ViewData(String name) { this.name = name; context = new Context(); }
56ea6e77-a6fc-4067-ad5d-1948c89aee5e
public String getName() { return name; }
2381d584-f302-46a4-80ae-2a052bed35a4
public void setVariable(String name, ViewVariable variable) { context.setVariable(name, variable.getVariable()); if (variable.updateable()) { updateVariables.put(name, variable); } }
0be93f1a-ef03-4347-8649-1dc43354a158
public void setHost(String host) { context.setVariable("host", host); }
8aaa6ebd-7174-4f51-9a74-588c88f90744
public void update() { Iterator<Entry<String,ViewVariable>> it = updateVariables.entrySet().iterator(); Entry<String,ViewVariable> current; while (it.hasNext()) { current = it.next(); Object result = current.getValue().update(); context.setVariable(current.getKey(), result); } }
44813803-1ad7-42fb-ad24-b2d822824c7d
public Context getContext() { return context; }
fe46d52c-bba6-4b01-b453-2b7cb1281717
public MimeType guessContentTypeFromName(String name) { if (name.endsWith(".html") || name.endsWith(".htm")) { return new MimeType(false, MimeType.HTML_STR); } else if (name.endsWith(".txt") || name.endsWith(".java")) { return new MimeType(false, "text/plain"); } else if (name.endsWith(".gif")) { return new MimeType(true, "image/gif"); } else if (name.endsWith(".class")) { return new MimeType(true, "application/octet-stream"); } else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) { return new MimeType(true, "image/jpeg"); } else if (name.endsWith(".js")) { return new MimeType(false, "text/javascript; charset=UTF-8"); } else if (name.endsWith(".css")) { return new MimeType(false, "text/css"); } else if (name.endsWith(".png")) { return new MimeType(true, "image/png"); } else if (name.endsWith(".otf")) { //return new MimeType(true, "vnd.oasis.opendocument.formula-template"); // http://www.iana.org/assignments/media-types/application/vnd.oasis.opendocument.formula-template return new MimeType(true, "font/opentype"); // Chrome no winge with this. } else if (name.endsWith(".ico")) { return new MimeType(true, "image/vnd.microsoft.icon"); } else if (name.endsWith(".swf")) { return new MimeType(true, "application/x-shockwave-flash"); } else { return new MimeType(false, MimeType.HTML_STR); } }
6d922375-3bae-47ad-9d4d-30abc6d1b6ca
public URIPathMapper() { }
6cd93959-8fe8-45a4-a06a-e6498219e2d2
public void addMapping(String uri, ViewData template) { mappings.put(uri, template); log.info("Now serving: " + uri); }
5dd6bada-0734-4917-a726-2d851f3701f3
public ViewData getMapping(String uri) { return mappings.get(uri); }
cfbed3e3-f604-4a11-ad34-433b0d90a18c
public Set<String> getMappings() { return new TreeSet(mappings.keySet()); }
c40966a3-d4b1-4a64-9060-051834a0e10a
public boolean hasMapping(String uri) { return mappings.containsKey(uri); }
9a1cfe4b-230b-40ab-977d-1d305a564d44
public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler(new MiniThymeleafWebServer.MiniThymeleafWebServerExceptionHandler()); Integer port = null; if ((args.length > 0) && (args[0] != null)) { port = Integer.parseInt(args[0]); // http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt if (!((port.intValue() == 80) || (port.intValue() == 8080) || (port.intValue() >= 8084))) { log.info("Please use a valid port number, 80, 8080 or >= 8084. Using default."); port = null; } } us = MiniThymeleafWebServer.getInstance(port); }
82ee3428-b616-4db4-b4fa-90471ecf0c6b
private MiniThymeleafWebServer(Integer port) { if (port != null) { httpPort = port.intValue(); } createMappings(); createThymeleaf(); constructServer(); }
5615ca9a-d67a-4172-bb5a-21491cbb62e5
public static MiniThymeleafWebServer getInstance(Integer port) { if (MiniThymeleafWebServer.us == null) { us = new MiniThymeleafWebServer(port); } return us; }
e18a6822-543a-48c0-9b41-f2e85c41c0af
private void constructServer() { log.info("Mini Thymeleaf Web Server"); log.info("Port is: " + httpPort + " - to change append the port number after the '.jar', i.e. java -jar ./target/MiniThymeleafWebServer-1.0-SNAPSHOT.jar 80"); userdir = System.getProperty("user.dir") + System.getProperty("file.separator") + "web"; log.info("Served directory is: " + userdir); log.debug("MiniThymeleafWebServer:constructServer() - Class path is: " + System.getProperty("java.class.path")); createServer(); }
e91222a0-8162-44cf-a421-56e66a7d95ea
public static void destruct(int exitCode) { System.exit(exitCode); }
d5102abb-b2b2-4397-ad71-522048e21d93
@Override public void uncaughtException(Thread t, Throwable e) { log.info("Mini Thymeleaf Web Server Java VM Exception: " + e.getMessage() + " from " + t.getName()); log.info("Goodbye."); destruct(-1); }
b5802e50-d00e-4439-827f-6f9894083bcf
private void createServer() { InetSocketAddress address = new InetSocketAddress(httpPort); try { HttpServer theServer = HttpServer.create(address, 0); theServer.createContext("/", this); createThreads(theServer); // Try without to see the difference of not having multiple threads to serve the requests. theServer.start(); log.info("Accepting requests on " + httpPort); } catch (IOException ex) { log.error("MiniThymeleafWebServer:createServer()", ex); } }