id
stringlengths
36
36
text
stringlengths
1
1.25M
205d7435-996c-434f-a24e-f5b8dd6c4999
private void createThreads(HttpServer theServer) { int corePoolSize = 20; int maximumPoolSize = 40; long keepAliveTime = 10; TimeUnit unit = TimeUnit.SECONDS; int workQueueCapacity = 40; int threadPriority = Thread.NORM_PRIORITY; log.info("MiniWebServer:createThreads - Creating thread factory with a thread priority of: " + threadPriority); MiniThymeleafWebServerThreadFactory threadFactory = new MiniThymeleafWebServerThreadFactory(threadPriority); log.info("MiniWebServer:createThreads - Creating thread pool executor with:"); log.info("Core Pool Size : " + corePoolSize); log.info("Maximum Pool Size : " + maximumPoolSize); log.info("Keep Alive Time : " + keepAliveTime + " seconds."); log.info("Work Queue Capacity: " + workQueueCapacity); MiniThymeleafWebServerThreadPoolExecutor threadExecutor = new MiniThymeleafWebServerThreadPoolExecutor( corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueueCapacity, threadFactory); theServer.setExecutor(threadExecutor); }
095901e0-2bd8-4786-bf8e-7346c1043c7e
private void createThymeleaf() { resolver.setTemplateMode("XHTML"); //resolver.setPrefix(userdir); // For FileTemplateResolver resolver.setSuffix(".html"); engine.setTemplateResolver(resolver); // TODO: I've not worked out how to have a properties file for the message resolver when using Context and not IContext. org.thymeleaf.messageresolver.StandardMessageResolver messageResolver = new org.thymeleaf.messageresolver.StandardMessageResolver(); messageResolver.addDefaultMessage("minithymeleafwebserver.title", "Mini Thymeleaf Web Server"); messageResolver.addDefaultMessage("props.property", "Property"); messageResolver.addDefaultMessage("props.value", "Value"); messageResolver.addDefaultMessage("serve.uri", "Serving uniform resource identifiers"); engine.setMessageResolver(messageResolver); }
7a9c5dc7-44bd-44ba-95ca-23086ffc33fb
private void createMappings() { ViewData template = new ViewData("web/index"); // View data for the index view. // Create the update action for the 'nowdate' view variable. ViewVariableAction action = new ViewVariableAction() { @Override public Object performUpdate() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); } }; // Create the 'nowdate' variable. ViewVariable variable = new ViewVariable(action.performUpdate(), action); // Add the 'nowdate' variable to the list of variables for the index view. template.setVariable("nowdate", variable); // Create the 'startdate' view variable and add it to the list of variables for the index view. String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); variable = new ViewVariable(now, null); template.setVariable("startdate", variable); // Map the index view to it's URI's. mapper.addMapping("/", template); mapper.addMapping("/index.html", template); template = new ViewData("web/props"); Properties sysProperties = System.getProperties(); java.util.LinkedList<SysProp> sysProps = new java.util.LinkedList<>(); SysProp currentProp; Iterator<Entry<Object, Object>> it = sysProperties.entrySet().iterator(); Entry<Object, Object> current; while (it.hasNext()) { current = it.next(); currentProp = new SysProp(); currentProp.setName((String) current.getKey()); currentProp.setValue((String) current.getValue()); sysProps.add(currentProp); } variable = new ViewVariable(sysProps, null); template.setVariable("sysProps", variable); mapper.addMapping("/props.html", template); // Now all the mappings are done we can set the URI list on the index page. // Create the 'startdate' view variable and add it to the list of variables for the index view. variable = new ViewVariable(mapper.getMappings(), null); template = mapper.getMapping("/"); template.setVariable("uris", variable); }
8f7f259e-ef0c-411b-9a8f-b959999fe511
@Override public Object performUpdate() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); }
9653514e-52ca-44be-bb72-2554b60212f9
@Override public void handle(HttpExchange request) throws IOException { long handleTimeNS = System.nanoTime(); long handleTimeMS = System.currentTimeMillis(); processRequest(request); handleTimeNS = System.nanoTime() - handleTimeNS; handleTimeMS = System.currentTimeMillis() - handleTimeMS; log.info(request.getRequestURI().toString() + " took " + handleTimeNS + "ns or " + handleTimeMS + "ms."); }
21c5c3de-46b1-4054-b202-517f22e5ea5e
private void processRequest(HttpExchange request) { // TODO: Process specific URL's, GET and POST requests. Possibly using Servlet technology. URI dUrl = request.getRequestURI(); String rawPath = dUrl.getRawPath(); if (mapper.hasMapping(rawPath)) { ViewData mapping = mapper.getMapping(rawPath); sendTemplate(request, mapping); } else if (rawPath.length() > 1) { sendFile(request, rawPath); } else if (rawPath.charAt(0) == '/') { sendIndex(request); } else { // Bogus request... Headers responseHeaders = request.getResponseHeaders(); responseHeaders.set("Date", new Date().toString()); responseHeaders.set("Server", MTWS_TITLE); try { //responseHeaders.set("Content-type", MimeType.HTML.getType()); request.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0); //OutputStream os = request.getResponseBody(); //os.write(responseString.getBytes()); } catch (IOException ex) { log.info("MiniThymeleafWebServer:processRequest - Bad request."); log.trace("MiniThymeleafWebServer:processRequest - Bad request.", ex); } request.close(); } }
b10e3809-50be-4e87-bdbf-60590ca83fa2
private void sendIndex(HttpExchange request) { log.info("MiniThymeleafWebServer:sendIndex - " + request.getRequestURI().toString()); Headers responseHeaders = request.getResponseHeaders(); responseHeaders.set("Content-type", mimeTypeFactory.HTML.getType()); responseHeaders.set("Date", new Date().toString()); responseHeaders.set("Server", MTWS_TITLE); try { String contents = "<html><head><title>Mini Thymeleaf Web Server</title></head><body><h1>The content</h1></body></html>"; request.sendResponseHeaders(HttpURLConnection.HTTP_OK, contents.length()); try (OutputStream os = request.getResponseBody()) { os.write(contents.getBytes()); os.flush(); } request.close(); } catch (IOException ex) { log.error("sendIndex()", ex); } }
7519df6c-0ab8-4759-8578-0ca717d9c06f
private void sendTemplate(HttpExchange request, ViewData mapping) { log.info("MiniThymeleafWebServer:sendTemplate - " + request.getRequestURI().toString()); // Set the 'host' template variable if it has been set in the request headers. Headers requestHeaders = request.getRequestHeaders(); String host = ""; if (requestHeaders.containsKey("Host")) { List<String> values = request.getRequestHeaders().get("Host"); host = values.get(0); } mapping.setHost(host); Headers responseHeaders = request.getResponseHeaders(); responseHeaders.set("Content-type", mimeTypeFactory.HTML.getType()); responseHeaders.set("Date", new Date().toString()); responseHeaders.set("Server", MTWS_TITLE); try { String contents; try { mapping.update(); contents = engine.process(mapping.getName(), mapping.getContext()); request.sendResponseHeaders(HttpURLConnection.HTTP_OK, contents.length()); } catch (IOException ex) { log.error("MiniThymeleafWebServer:sendTemplate()", ex); contents = ex.getMessage(); request.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, contents.length()); } try (OutputStream os = request.getResponseBody()) { os.write(contents.getBytes()); os.flush(); } request.close(); } catch (IOException ex) { log.error("MiniThymeleafWebServer:sendTemplate()", ex); } }
3350a1c8-4032-4dc7-bd7a-6de842d2aeeb
private void sendFile(HttpExchange request, String file) { String fullname = userdir + file; log.info("MiniThymeleafWebServer:sendFile - " + request.getRequestURI().toString() + " - " + fullname); File theFile = new File(fullname); if (theFile.exists()) { MimeType theType = mimeTypeFactory.guessContentTypeFromName(file); byte[] fileContents = getFile(theFile); if (fileContents != null) { Headers responseHeaders = request.getResponseHeaders(); responseHeaders.set("Date", new Date().toString()); responseHeaders.set("Server", MTWS_TITLE); responseHeaders.set("Content-type", theType.getType()); if (theType.isBinary()) { try { // Info on http://elliotth.blogspot.com/2009/03/using-comsunnethttpserver.html responseHeaders.set("Content-Encoding", "gzip"); request.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); // Don't know how large the compressed file will be. try (GZIPOutputStream gos = new GZIPOutputStream(request.getResponseBody(), BUFFER_MAX)) { gos.write(fileContents); gos.finish(); gos.close(); } catch (Exception ex) { log.error("MiniThymeleafWebServer:sendFile - Binary file: " + file); log.error("MiniThymeleafWebServer:sendFile()", ex); } } catch (IOException ex) { log.error("MiniThymeleafWebServer:sendFile - Binary file: " + file); log.error("MiniThymeleafWebServer:sendFile()", ex); } } else { try { request.sendResponseHeaders(HttpURLConnection.HTTP_OK, fileContents.length); try (OutputStream os = request.getResponseBody()) { os.write(fileContents); os.flush(); os.close(); } catch (Exception ex) { log.error("MiniThymeleafWebServer:sendFile - Text file: " + file); log.error("MiniThymeleafWebServer:sendFile()", ex); } } catch (IOException ex) { log.error("MiniThymeleafWebServer:sendFile - Text file: " + file); log.error("MiniThymeleafWebServer:sendFile()", ex); } } request.close(); } else { // Code above has not got the file... try { // File has no content. request.sendResponseHeaders(HttpURLConnection.HTTP_NO_CONTENT, 0); request.close(); } catch (IOException ex) { log.error("MiniThymeleafWebServer:sendFile - Sending response headers for file: " + file); log.error("MiniThymeleafWebServer:sendFile()", ex); } log.warn("MiniThymeleafWebServer:sendFile - File '" + file + "' has no content."); } } else { // Code above has not got the file... try { // File does not exist. request.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, 0); request.close(); } catch (IOException ex) { log.error("MiniThymeleafWebServer:sendFile - Sending response headers for file: " + file); log.error("MiniThymeleafWebServer:sendFile()", ex); } log.info("File '" + file + "' not sent."); } }
249d293c-5821-4cb8-8894-c3fd0d5975b1
private byte[] getFile(File theFile) { byte[] buffer = null; FileInputStream fis = null; try { fis = new FileInputStream(theFile); FileChannel fc = fis.getChannel(); long len = theFile.length(); int byteReadCount = 0; ByteBuffer byteBuffer = ByteBuffer.allocate((int) len); int bytesRead = 0; while ((bytesRead != -1) && (byteReadCount < len)) { bytesRead = fc.read(byteBuffer); byteReadCount += bytesRead; // Cope with 0 return when have reached end of text file and cannot get -1 byte as buffer is full. } buffer = byteBuffer.array(); } catch (FileNotFoundException ex) { log.error("MiniThymeleafWebServer:getFile()", ex); } catch (IOException ex) { log.error("MiniThymeleafWebServer:getFile()", ex); } finally { if (fis != null) { try { fis.close(); } catch (IOException ex) { log.error("MiniThymeleafWebServer:getFile()", ex); } } } return buffer; }
a51208b9-524d-4af6-8e44-c514036518f7
public MiniThymeleafWebServerThreadFactory(int threadPriority) { this.threadPriority = threadPriority; }
0b3b39e1-8686-4db4-a659-a4e153f2750b
@Override public Thread newThread(Runnable r) { Thread theThread = new Thread(miniThymeleafWebServerThreadGroup, r, "MTWS HTTP Server Thread-" + ++threadCount); theThread.setPriority(threadPriority); return theThread; }
acecd3b6-d46d-42cd-afa0-bac2dd8b888d
public ThreadGroup getThreadGroup() { return miniThymeleafWebServerThreadGroup; }
90a5cb30-9b33-449b-996e-d62a9956b646
public Thread[] getThreads() { Thread[] theThreads = new Thread[miniThymeleafWebServerThreadGroup.activeCount()]; int threads = miniThymeleafWebServerThreadGroup.enumerate(theThreads); log.info("MiniThymeleafWebServerThreadFactory:getThreads - " + threads + " active threads returned."); return theThreads; }
9076bb5f-d2af-4534-b2e2-784c89af6c56
public void setThreadPriority(int threadPriority) { // TODO: Set thread priority of all existing threads too. this.threadPriority = threadPriority; }
9bd870f4-07c4-4a2b-95db-3c9adcf4ac2c
public MiniThymeleafWebServerThreadPoolExecutor( int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, int workQueueCapacity, ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, new MiniThymeleafWebServerBlockingQueue<Runnable>(workQueueCapacity), threadFactory); }
d5d11205-cc5a-47e8-a438-4f6db21f60e8
public MiniThymeleafWebServerBlockingQueue(int capacity) { super(capacity); }
8d1e2b4a-d6e0-4f8d-9b65-24a7aef6f170
public SysProp() { }
fe0a562d-4f3d-4c7d-9cf7-e68ee682b57b
public String getName() { return name; }
cfad4946-672d-4d73-b410-d122a3da1629
public void setName(String name) { this.name = name; }
4dbfbe2f-8dd9-414c-92d8-47d1cb318f74
public String getValue() { return value; }
042adb4d-6bc8-4ad8-af8f-b1f665d4c5ca
public void setValue(String value) { this.value = value; }
a37f0b39-a8e7-4055-94ff-b779a143b6d1
public MimeType(boolean isBinary, String type) { this.isBinary = isBinary; this.type = type; }
038c7a5f-2475-4c40-8773-72b15c15523e
public boolean isBinary() { return isBinary; }
1ea7ceec-c510-46bc-95aa-4aa08154c68a
public String getType() { return type; }
b68bb499-62ab-4969-9ed6-0e986d834c67
public Object performUpdate();
bc70cbb3-53c9-4afd-ba5b-d0eb448637a0
public ViewVariable(Object variable, ViewVariableAction action) { this.variable = variable; this.action = action; }
162b885b-b3ce-490e-9aef-79746df5dca8
public boolean updateable() { return (action != null); }
500c4a83-f9ec-4ca0-a204-c7087c72369f
public Object getVariable() { return variable; }
cf25df26-8fd1-455a-90cb-af5699d58a6b
public Object update() { Object retr = null; if (updateable()) { retr = action.performUpdate(); variable = retr; } return retr; }
e50e703d-9de9-4c12-bebf-02f7740f5d27
public HttpExchangeStub(String requestURI) throws URISyntaxException { this.requestURI = new URI(requestURI); }
bd40c4aa-e18d-4041-a37b-ca1919eb0052
@Override public void close() { System.out.println("HttpExchangeStub - close()"); if (responseBody != null) { try { responseBody.close(); } catch (IOException e) { e.printStackTrace(); } } }
f944e148-d4ae-4ee5-a82b-bfc83062663c
@Override public Object getAttribute(String arg0) { // TODO Auto-generated method stub return null; }
50559f25-8361-48e1-91d5-e46cf215ec68
@Override public HttpContext getHttpContext() { // TODO Auto-generated method stub return null; }
02eb40f5-96e5-4492-903f-15d876a2b024
@Override public InetSocketAddress getLocalAddress() { // TODO Auto-generated method stub return null; }
6d2af0a6-702a-4eae-a8b9-c6be692ec3ab
@Override public HttpPrincipal getPrincipal() { // TODO Auto-generated method stub return null; }
e58d8d02-ffdf-4a8c-83b9-8a52abff6520
@Override public String getProtocol() { // TODO Auto-generated method stub return null; }
42d30868-15eb-42a1-94fa-0a9ae65ad369
@Override public InetSocketAddress getRemoteAddress() { // TODO Auto-generated method stub return null; }
babc2b32-65a7-4653-96b3-23108ada3832
@Override public InputStream getRequestBody() { // TODO Auto-generated method stub return null; }
31df97ee-d35f-4536-bb25-3e5425440214
@Override public Headers getRequestHeaders() { if (requestHeaders == null) { requestHeaders = new Headers(); LinkedList<String> hostvars = new LinkedList<>(); hostvars.add("http://localhost"); requestHeaders.put("Host", hostvars); } return requestHeaders; }
0a84e560-4462-4592-81f7-ccaa41b2899f
@Override public String getRequestMethod() { // TODO Auto-generated method stub return null; }
9d6e6a21-5aa9-4325-bd6c-fb8784b81ef1
@Override public URI getRequestURI() { return requestURI; }
458c6ec7-f1a0-44b5-9795-254a9cf3acaf
@Override public OutputStream getResponseBody() { if (responseBody == null) { responseBody = new ByteArrayOutputStream(); } return responseBody; }
5eef9ed1-1f63-4283-8481-c0247498cceb
@Override public int getResponseCode() { // TODO Auto-generated method stub return 0; }
d3a2e5be-b23b-4cad-b21a-13233d603d5c
@Override public Headers getResponseHeaders() { if (responseHeaders == null) { responseHeaders = new Headers(); } return responseHeaders; }
4ec27197-bccb-4f72-b2f2-2fb0d79f1569
@Override public void sendResponseHeaders(int arg0, long arg1) throws IOException { // TODO Auto-generated method stub }
556074c3-47b1-4da2-ae8b-a77d6e69e35c
@Override public void setAttribute(String arg0, Object arg1) { // TODO Auto-generated method stub }
04cfd738-af72-4dbc-909e-5b91e4652327
@Override public void setStreams(InputStream arg0, OutputStream arg1) { // TODO Auto-generated method stub }
b837c0fd-89d8-4f15-8583-767814a168f0
public String responseHeadersToString() { String retr = "No headers"; if (responseHeaders != null) { Set<Map.Entry<String, List<String>>> entrySet = responseHeaders.entrySet(); Iterator<Map.Entry<String, List<String>>> its = entrySet.iterator(); Map.Entry<String, List<String>> currentEntry; if (its.hasNext()) { retr = ""; } while (its.hasNext()) { currentEntry = its.next(); String currentKey = currentEntry.getKey(); Iterator<String> itl = currentEntry.getValue().iterator(); while (itl.hasNext()) { retr += "Key: " + currentKey + " Value: " + itl.next() + "\n"; } } } return retr; }
5eca4fdf-dc99-429b-b2e1-1a427b218055
@Override public void setUp() { us = MiniThymeleafWebServer.getInstance(null); }
2fba9b6c-4d39-4c15-9504-ae7529baea5f
@Override public void tearDown() { us = null; }
c051f496-fa25-48ca-a5fa-6dbbbb96d1f9
public MiniThymeleafWebServerTest(String testName) { super(testName); }
c190f3c8-36c3-41f1-bac9-0606b1c76755
public static TestSuite suite() { TestSuite suite = new TestSuite(MiniThymeleafWebServerTest.class); //suite.addTest(new MiniThymeleafWebServerTest("testMiniThymeleafWebServer")); return suite; }
48c3c86f-3510-4db8-b65c-2b26975bad1f
public void testIndexRequest() { try { HttpExchangeStub exchange = new HttpExchangeStub("/"); try { us.handle(exchange); } catch (IOException e) { e.printStackTrace(); assertTrue(false); } boolean result = true; OutputStream response = exchange.getResponseBody(); String responseString = response.toString(); if (responseString.equalsIgnoreCase("The date now")) { // Failed to transform template. result = false; } System.out.println(responseString); String responseHeadersString = exchange.responseHeadersToString(); System.out.println(responseHeadersString); assertTrue(responseString + " - " + responseHeadersString, result); } catch (URISyntaxException e) { e.printStackTrace(); assertTrue(false); } }
bdd29387-9eaa-4a7a-9101-262ead3f272e
public void testMimeTypeFactory() { MimeTypeFactory mtf = new MimeTypeFactory(); MimeType mt = mtf.guessContentTypeFromName(".html"); assertTrue(mt.getType().equalsIgnoreCase("text/html")); }
b570f647-5a3b-4adb-80c9-89a990b0fa01
public void testViewData() { ViewData viewData = new ViewData("test"); ViewVariableAction vva = mock(ViewVariableAction.class); String vvat = "performUpdate"; when(vva.performUpdate()).thenReturn(vvat); ViewVariable vv = new ViewVariable(new Date(), vva); viewData.setVariable("thedate", vv); viewData.update(); boolean result = true; verify(vva).performUpdate(); if (((String)vv.getVariable()).equalsIgnoreCase(vvat) == false) { result = false; } assertTrue(result); }
76b4f5c3-59e1-4439-ae08-1827ef206eca
public void testURLPathMapper() { ViewData viewData = mock(ViewData.class); URIPathMapper upm = new URIPathMapper(); String uri = "/test"; upm.addMapping(uri, viewData); assertTrue(upm.hasMapping(uri)); assertTrue(upm.getMapping(uri).equals(viewData)); }
4c197853-7306-42ec-b56d-54db4d2aed97
public static void main( String[] args ) { System.out.println( "Hello World!" ); }
ac63c777-d632-439f-9a9d-1a1eeb1b0ca9
public static void main( String[] args ) { System.out.println( "Hello World!" ); Pattern regexPattern = Pattern.compile("\\S+\\.class$|\\S+\\.jar$|^web\\.xml$|^ibm-web-bnd\\.xml$"); Matcher[] matchers = new Matcher[3]; matchers[0] = regexPattern.matcher("a.class"); matchers[1] = regexPattern.matcher("web.xml"); matchers[2] = regexPattern.matcher("ibm-web-bnd.xml"); System.out.println("====================================="); for (Matcher matcher : matchers) { System.out.println(matcher.find()); System.out.println(matcher.matches()); System.out.println(matcher.group()); } }
14f8c3f3-b2cc-407d-bd5f-bfdb930866af
public static RuntimeException uncheckException(Throwable t) { return new RuntimeException(t); }
45383b34-a44b-476f-855b-bc02877d2f59
public static RuntimeException uncheckException(String msg, Throwable t) { return new RuntimeException(msg, t); }
c9eae86e-2b58-4871-84fd-f8187b4d1d30
public static int waitForProcess(Process p, int iteration, int delay) throws TimeoutException { for (int i = 0; i < iteration; i++) { try { Thread.sleep(delay); } catch (Exception e) { // ignore } try { return p.exitValue(); } catch (IllegalThreadStateException e) { // ignore } } // process timeout, destroy process and throw out exception p.destroy(); throw new TimeoutException("Process did not complete and had to be terminated"); }
de08f8ff-b870-4ce8-a4f4-7e2cc130fdce
public static String getStringFromStream(InputStream in) throws IOException { BufferedReader bufReader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line; try { while ((line = bufReader.readLine()) != null) { sb.append(line + MyStringUtils.LINE_SEPARATOR); } } finally { MyIOUtils.close(bufReader); } return sb.toString(); }
17581ed5-c3b0-4f06-b620-6480727c7211
public static void close(Closeable obj) { if (null != obj) { try { obj.close(); } catch (IOException e) { // do nothing } } }
43badbf7-0750-436c-ab89-493c5c982211
public boolean portAvailable(int port) { String[] commands = netstatCommand(port); ProcessBuilder pb = new ProcessBuilder(); pb.command(commands); InputStream inStream = null; try { Process process = pb.start(); MyProcessUtils.waitForProcess(process, 10, 500); inStream = process.getInputStream(); String netout = IOUtils.toString(inStream); return StringUtils.equals(StringUtils.EMPTY, netout) ? true : false; } catch (IOException e) { throw MyExceptionUtils.uncheckException(e); } catch (TimeoutException e) { throw MyExceptionUtils.uncheckException(e); } finally { IOUtils.closeQuietly(inStream); } }
d8c92a87-6f4c-4985-8ddb-bd49719d8ca6
public Set<Integer> notAvaiPorts() { String[] commands = new String[2]; commands[0] = "netstat"; commands[1] = "-an"; ProcessBuilder pb = new ProcessBuilder(); pb.command(commands); try { Process process = pb.start(); process.waitFor(); String netout = IOUtils.toString(process.getInputStream()); StringTokenizer rowst = new StringTokenizer(netout, MyStringUtils.LINE_SEPARATOR); rowst.nextElement(); rowst.nextElement(); Set<Integer> notAvaiPortSet = new HashSet<Integer>(); while (rowst.hasMoreElements()) { String row = (String) rowst.nextElement(); StringTokenizer wordst = new StringTokenizer(row); wordst.nextElement(); wordst.nextElement(); wordst.nextElement(); String addr = (String) wordst.nextElement(); if (addr.contains(COLON)) { String port = addr.substring(addr.lastIndexOf(COLON) + 1); notAvaiPortSet.add(Integer.valueOf(port)); } } return notAvaiPortSet; } catch (IOException e) { throw MyExceptionUtils.uncheckException(e); } catch (InterruptedException e) { throw MyExceptionUtils.uncheckException(e); } }
0cee0645-f1a3-424b-92cf-2bab29d64ec2
private static String[] netstatCommand(int port) { String os = System.getProperty("os.name").toLowerCase(); String[] commands; if (os.contains("windows")) { commands = new String[7]; commands[0] = "cmd"; commands[1] = "/c"; commands[2] = "netstat"; commands[3] = "-an"; commands[4] = "|"; commands[5] = "findstr"; commands[6] = String.valueOf(port); } else { commands = new String[3]; commands[0] = "/bin/sh"; commands[1] = "-c"; commands[2] = "netstat -an | grep " + String.valueOf(port); } return commands; }
f6d15edf-457d-4dff-b7c8-98354b8b6195
public static boolean portAvailable(int port) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); serverSocket.setReuseAddress(true); } catch(IOException e) { // do nothing return false; } finally { if (null != serverSocket && !serverSocket.isClosed()) { try { serverSocket.close(); } catch(IOException e) { // do nothing } } } Socket socket = null; try { socket = new Socket("localhost", port); } catch (UnknownHostException e) { // do nothing } catch(IOException e) { return true; } finally { if (null != socket && !socket.isClosed()) { try { socket.close(); } catch (IOException e) { // do nothing } } } return false; }
461a8e34-6201-4481-9813-2ffc4132200b
public static int findAvailablePort() { int port = 0; do { port = random.nextInt(10000) + 30000; } while(portAvailable(port)); try { Thread.sleep(200); } catch(Exception e) { // do nothing } return port; }
57b41013-e9c5-4a33-ab36-7b39e7af3799
public static int findAvailablePort2() { int port = 0; do { port = random.nextInt(10000) + 20000; } while(!portAvailable(port)); return port; }
9e1e0f9d-a6b8-4bd6-bfb2-9d8c3f4db03e
public static void main(String[] args) { int port = 0; for (int i=0; i < 10; ++i) { port = findAvailablePort2(); System.out.println(port + " port available:"); } System.out.println("Thread sleep over"); }
527587f4-965d-476b-a3b6-aee89749a49e
public List<Integer> getNetstat() { return netstat; }
765e9b0f-5a1f-496b-ab27-7e96e79e0352
public void callNetstat() { try { ByteArrayOutputStream netout = new ByteArrayOutputStream(); ByteArrayOutputStream neterr = new ByteArrayOutputStream(); String systemOS = System.getProperty("os.name"); String localaddr = ""; ArrayList<String> cmd = new ArrayList<String>(); if (systemOS.equals("z/OS")) { cmd.add("onetstat"); cmd.add("-a"); } else if (systemOS.equalsIgnoreCase("OS/400")) { cmd.add("qsh"); cmd.add("-c"); cmd.add("netstat"); } else { cmd.add("netstat"); cmd.add("-n"); cmd.add("-a"); } ProcessBuilder pb = new ProcessBuilder(cmd); Process p = pb.start(); MyReader out = new MyReader(p.getInputStream(), netout); MyReader err = new MyReader(p.getErrorStream(), neterr); out.start(); err.start(); p.waitFor(); out.join(); err.join(); String output = netout.toString(); if (output.trim().length() == 0) { throw new Exception("Did not receive any output from netstat"); } StringTokenizer stok = new StringTokenizer(output, "\r\n"); stok.nextElement(); stok.nextElement(); if (systemOS.equals("z/OS")) { stok.nextElement(); } while (stok.hasMoreElements()) { String s = (String) stok.nextElement(); if (systemOS.equals("z/OS")) { Pattern ptrn = Pattern .compile("\\s\\sLocal\\sSocket:.*?\\.\\.(\\d*).*"); Matcher m = ptrn.matcher(s); if (m.find()) { localaddr = m.group(1); try { int port = Integer.parseInt(localaddr); if (!this.netstat.contains(Integer.valueOf(port))) this.netstat.add(Integer.valueOf(port)); } catch (NumberFormatException e) { } } } else { StringTokenizer stok2 = new StringTokenizer(s); if (stok2.countTokens() > 1) { stok2.nextElement(); if (!System.getProperty("os.name").toLowerCase() .contains("windows")) { if (stok2.countTokens() > 2) { stok2.nextElement(); stok2.nextElement(); } } else { } localaddr = (String) stok2.nextElement(); if (localaddr.indexOf(":") != -1) localaddr = localaddr.substring(localaddr .lastIndexOf(":") + 1); else if (localaddr.lastIndexOf(".") != -1) { localaddr = localaddr.substring(localaddr .lastIndexOf(".") + 1); } try { int port = Integer.parseInt(localaddr); if (!this.netstat.contains(Integer .valueOf(port))) this.netstat.add(Integer.valueOf(port)); } catch (NumberFormatException e) { // do nothing } } } } } catch (Exception e) { throw MyExceptionUtils.uncheckException( "Error trying to parse netstat output", e); } }
bd70f3c7-ecef-4b88-8f3a-f80df9ff7617
public MyReader(InputStream in, OutputStream out) { this.out = out; this.in = in; }
c5fddcfe-29c0-418e-ab5b-b7d584f0578d
public void run() { PrintWriter writer = new PrintWriter(this.out, true); BufferedReader reader = new BufferedReader(new InputStreamReader( this.in)); try { String line = null; while ((line = reader.readLine()) != null) writer.println(line); } catch (Exception e) { } if (reader != null) try { reader.close(); } catch (IOException e) { } }
4999e61d-2bb1-4468-a504-138e645531a1
public AppTest( String testName ) { super( testName ); }
50c392f4-711d-4a98-9e3e-ce29f39034ee
public static Test suite() { return new TestSuite( AppTest.class ); }
e8a467a0-90bf-4e21-8deb-b3022a61e307
public void testApp() { assertTrue( true ); }
50bda5d8-3218-4c65-98f5-a5a57bc94912
@Test public void testStringSplit() { String str1 = "WEB-INF/classes"; String[] items = str1.split("/"); System.out.println("items length: " + items.length); System.out.println("items: " + Arrays.toString(items)); assertEquals(2, items.length); assertEquals("WEB-INF", items[0]); assertEquals("classes", items[1]); String str2 = "/WEB-INF/classes"; assertEquals(3, str2.split("/").length); }
a80b1f18-d0a1-45ef-a85f-653ed934abb6
@Test public void testPortSelector() { PortSelector portSel = new PortSelector(); portSel.callNetstat(); System.out.println(portSel.getNetstat()); }
e007b5d6-a073-4001-afe4-365f006b47c2
@Before public void setUp() { avaiPort = new NetstatAvailablePort(); }
3c8105d7-4ff4-4012-8bde-1cd7ecacb02f
public void t(){ boolean portAvailable = avaiPort.portAvailable(450); System.out.println(portAvailable); }
e37087b1-ba59-4555-9fed-30dbcc6753b4
@Test public void testPortAvailable() { Set<Integer> notAvaiPorts = avaiPort.notAvaiPorts(); int port; do { port = randomInt(30000, 40000); } while (notAvaiPorts.contains(port)); assertTrue(avaiPort.portAvailable(port)); }
051e0d84-2a03-4f78-9c13-64bbae18a623
@Test public void testPortNotAvailable() { Set<Integer> notAvaiPorts = avaiPort.notAvaiPorts(); assertFalse(avaiPort.portAvailable(notAvaiPorts.iterator().next())); }
38b0bd53-cb13-4c80-b457-9dcebdb9bb41
private int randomInt(int lowBound, int upperBound) { Random random = new Random(); return random.nextInt(upperBound - lowBound) + lowBound; }
ed5c3c55-117e-45be-95fd-fb053dc20cb2
public static RuntimeException uncheckException(String msg, Throwable e) { return new RuntimeException(msg, e); }
34b9ab06-a427-46a7-ba36-d7d14120cf21
public static RuntimeException uncheckException(Throwable cause) { return new RuntimeException(cause); }
58bd656c-2ab2-4930-a755-bc431924e8af
public static void unzipFromStream(InputStream inStream, String targetFolder) { ZipInputStream zipInputStream = null; FileOutputStream outputStream = null; try { System.out.println(new Date() + "Started unzip: " + targetFolder); // 1. Use ZipInputStream to parse the zip zipInputStream = new ZipInputStream(inStream); ZipEntry zipEntry = null; outputStream = null; // 2. Parse and unzip each zip entry from the zip input stream while ((zipEntry = zipInputStream.getNextEntry()) != null) { // 2.1 If the zip entry is folder, create the folder if (zipEntry.isDirectory()) { String name = zipEntry.getName(); name = name.substring(0, name.length() - 1); File file = new File(targetFolder + File.separator + name); file.mkdir(); } // 2.2 If the zip entry is file, unzip it to file else { File file = new File(targetFolder + File.separator + zipEntry.getName()); file.createNewFile(); outputStream = new FileOutputStream(file); // Get the size of next zip entry from the input stream int size = (int) zipEntry.getSize(); byte[] bytes = new byte[size]; int offset = 0; int chunk = 0; // Then read corresponding size bytes from the input stream, // and write it to file while (offset < size) { chunk = zipInputStream.read(bytes, offset, size - offset); if (chunk == -1) { break; } offset += chunk; } outputStream.write(bytes); } } outputStream.flush(); System.out.println(new Date() + "Completed unzip: " + targetFolder); } catch (java.io.IOException e) { e.printStackTrace(); } finally { try { zipInputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
827271d1-9104-4f2e-9fc0-50eb4f87e507
public static void main(String[] args) { FileInputStream fis = null; try { try { String srcPath = "d:/wjh/temp/wlp.zip"; fis = new FileInputStream(srcPath); doUnzip(fis); } finally { fis.close(); } } catch (FileNotFoundException e) { throw ExceptionUtils.uncheckException(e); } catch (IOException e) { throw ExceptionUtils.uncheckException(e); } }
f161e758-9e30-4970-abd8-9616e1501bee
private static void doUnzip(InputStream in) { // String eclipseHomeFolder = System.getProperty("user.dir"); String eclipseHomeFolder = "d:/wjh/temp"; // Unzip liberty only if the target wlp folder does not exist File folder = new File(eclipseHomeFolder + File.separator + "wlp"); if (!folder.exists()) { // Get the wlp.zip from plugin jar as resource stream // ClassLoader loader = Thread.currentThread().getContextClassLoader(); // InputStream in = loader.getResourceAsStream("libs" + File.separator // + "wlp.zip"); // Unzip wlp (Liberty) unzipFromStream(in, eclipseHomeFolder); setPermission(eclipseHomeFolder + File.separator + "wlp"); } }
022ea664-3619-48f9-956b-f57ad1ff1b50
private static void setPermission(String wlpPath) { String[] permissionFileName = new String[]{"server", "isadc", "productInfo", "securityUtility"}; for (String fileName : permissionFileName) { File executableFile = new File(wlpPath + File.separator + "bin" + File.separator + fileName); executableFile.setExecutable(true); } }
56cef2a3-d2d4-47df-9ef6-1355692eeb7d
public static void main(String[] args) { String str = "org.txxfu.lang.java.core"; //String subDir = str.replaceAll("\\.", "\\\\"); String subDir = str.replace(".", File.separator); System.out.println(subDir); }
3c0eade1-fe1f-4537-a088-026eaca69c50
public static void main(String[] args) { System.out.println("Hello World!"); System.out.println("Hello World!2"); System.out.println("Hello World!3"); }
a491bb00-d8c1-4041-9d67-5de4f640e7c1
public CreditsScreenState(int StateID) { super(); GameStateID = StateID; }
3f7ec341-2815-4e1d-81fb-b75b249469b4
@Override public int getID() { return GameStateID; }
424430e7-44e8-4cc5-87eb-c95fbc8de405
@Override public void init(GameContainer container, StateBasedGame game) throws SlickException { font = new AngelCodeFont("data/fonts/averia_30.fnt", "data/fonts/averia_30.png", true); background = ResourceManager.getInstance().getImage("bg_credits"); //check if image has to be scaled to fit completely if (background != null && ( background.getHeight() != container.getHeight() || background.getWidth() != container.getWidth() ) ) { background = background.getScaledCopy(container.getWidth(), container.getHeight()); } StringBuilder sb = new StringBuilder(); int lineCount = 0; try { String NL = System.getProperty("line.separator"); Scanner scanner = new Scanner(new FileInputStream("data/credits.txt"), "UTF-8"); try { while (scanner.hasNextLine()){ sb.append(scanner.nextLine() + NL); ++lineCount; } } finally{ scanner.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); sb = new StringBuilder(e.getLocalizedMessage()); lineCount = 1; } creditsPosY = container.getHeight(); creditText = sb.toString(); maxCreditY = lineCount * container.getGraphics().getFont().getLineHeight(); //font.getLineHeight() }
8d6a85b6-8b8a-4042-aa89-2be998bfbf1c
@Override public void enter(GameContainer container, StateBasedGame game) throws SlickException { super.enter(container, game); if (!container.isMusicOn()) { if (music != null) { music.stop(); } } else { music = ResourceManager.getInstance().getMusic("green_town"); if (music != null) { music.loop(); } } }
8f01cd07-ed2f-40c4-a1a4-c2a40287e73d
@Override public void leave(GameContainer container, StateBasedGame game) throws SlickException { super.leave(container, game); if (container.isMusicOn()) { if (music != null && music.playing()) music.stop(); } }
bcf3cc03-d30a-4481-963e-9810afaf6fbe
@Override public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException { //Draw credits g.setColor(Color.white); g.setFont(font); // credits (running from bottom to top of the screen) g.drawString(creditText, 32.0f, creditsPosY); // alpha-layered background image background.draw(0, 0); // info messages, what the user can do within this screen g.drawString(credits, (container.getWidth() / 2) - (font.getWidth(credits) / 2), font.getHeight(credits)); // fixed position for word "CREDITS" g.drawString(escToReturn, container.getWidth() - font.getWidth(escToReturn) , container.getHeight() - font.getLineHeight()); }
6521bd69-1e06-4dcf-99a3-3785d40005e8
@Override public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { if (container.getInput().isKeyPressed(Input.KEY_ESCAPE)) { game.enterState(SideScrollerGame.PLAY_STATEID, new FadeOutTransition(Color.white, 1000), new FadeInTransition(Color.black, 1000) ); } --creditsPosY; if (creditsPosY < 0 - maxCreditY) { creditsPosY = container.getHeight(); } }