answer
stringlengths
17
10.2M
package org.springframework.web.util; import java.io.File; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.BeanUtils; /** * Miscellaneous utilities for web applications. * Used by various framework classes. * @author Rod Johnson * @author Juergen Hoeller */ public abstract class WebUtils { /** * Web app root key parameter at the servlet context level * (i.e. web.xml): "webAppRootKey". */ public static final String WEB_APP_ROOT_KEY_PARAM = "webAppRootKey"; /** Default web app root key: "webapp.root" */ public static final String DEFAULT_WEB_APP_ROOT_KEY = "webapp.root"; /** * Standard Servlet spec context attribute that specifies a temporary * directory for the current web application, of type java.io.File */ public static final String TEMP_DIR_CONTEXT_ATTRIBUTE = "javax.servlet.context.tempdir"; /** * Standard servlet spec request attributes for include URI and paths. * <p>If included via a RequestDispatcher, the current resource will see the * original request. Its own URI and paths are exposed as request attributes. */ public static final String INCLUDE_URI_REQUEST_ATTRIBUTE = "javax.servlet.include.request_uri"; public static final String INCLUDE_CONTEXT_PATH_REQUEST_ATTRIBUTE = "javax.servlet.include.context_path"; public static final String INCLUDE_SERVLET_PATH_REQUEST_ATTRIBUTE = "javax.servlet.include.servlet_path"; /** Name suffixes in case of image buttons */ public static final String[] SUBMIT_IMAGE_SUFFIXES = {".x", ".y"}; public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException { String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM); String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY); String oldValue = System.getProperty(key); String root = servletContext.getRealPath("/"); if (root == null) { throw new IllegalStateException("Cannot set web app root system property when WAR file is not expanded"); } if (oldValue != null && !oldValue.equals(root)) { throw new IllegalStateException("Web app root system property already set to different value: '" + key + "' = [" + oldValue + "] - Choose unique webAppRootKey values in your web.xml files!"); } System.setProperty(key, root); servletContext.log("Set web app root system property: " + key + " = " + root); } /** * Return the temporary directory for the current web application, * as provided by the servlet container. * @param servletContext the servlet context of the web application * @return the File representing the temporary directory */ public static File getTempDir(ServletContext servletContext) { return (File) servletContext.getAttribute(TEMP_DIR_CONTEXT_ATTRIBUTE); } /** * Check the given request for a session attribute of the given name. * Returns null if there is no session or if the session has no such attribute. * Does not create a new session if none has existed before! * @param request current HTTP request * @param name the name of the session attribute * @return the value of the session attribute, or null if not found */ public static Object getSessionAttribute(HttpServletRequest request, String name) { HttpSession session = request.getSession(false); return (session != null ? session.getAttribute(name) : null); } /** * Set the session attribute with the given name to the given value. * Removes the session attribute if value is null, if a session existed at all. * Does not create a new session on remove if none has existed before! * @param request current HTTP request * @param name the name of the session attribute */ public static void setSessionAttribute(HttpServletRequest request, String name, Object value) { if (value != null) { request.getSession().setAttribute(name, value); } else { HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute(name); } } } /** * Get the specified session attribute, creating and setting a new attribute if * no existing found. The given class needs to have a public no-arg constructor. * Useful for on-demand state objects in a web tier, like shopping carts. * @param request current HTTP request * @param name the name of the session attribute * @param clazz the class to instantiate for a new attribute * @return the value of the session attribute, newly created if not found */ public static Object getOrCreateSessionAttribute(HttpServletRequest request, String name, Class clazz) { Object sessionObject = getSessionAttribute(request, name); if (sessionObject == null) { sessionObject = BeanUtils.instantiateClass(clazz); request.getSession(true).setAttribute(name, sessionObject); } return sessionObject; } /** * Retrieve the first cookie with the given name. Note that multiple * cookies can have the same name but different paths or domains. * @param name cookie name * @return the first cookie with the given name, or null if none is found */ public static Cookie getCookie(HttpServletRequest request, String name) { Cookie cookies[] = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (name.equals(cookies[i].getName())) return cookies[i]; } } return null; } /** * Return the URL of the root of the current application. * @param request current HTTP request */ public static String getUrlToApplication(HttpServletRequest request) { return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; } /** * Return the correct request URI for the given request. * <p>Regards include request URL if called within a RequestDispatcher include. * <p>The URI that the web container resolves <i>should</i> be correct, but some * containers like JBoss/Jetty incorrectly include ";" strings like ";jsessionid" * in the URI. This method cuts off such incorrect appendices. * @param request current HTTP request * @return the correct request URI */ public static String getRequestUri(HttpServletRequest request) { String uri = (String) request.getAttribute(INCLUDE_URI_REQUEST_ATTRIBUTE); if (uri == null) { uri = request.getRequestURI(); } int semicolonIndex = uri.indexOf(';'); return (semicolonIndex != -1 ? uri.substring(0, semicolonIndex) : uri); } /** * Return the path within the web application for the given request. * <p>Regards include request URL if called within a RequestDispatcher include. * @param request current HTTP request * @return the path within the web application */ public static String getPathWithinApplication(HttpServletRequest request) { String contextPath = (String) request.getAttribute(INCLUDE_CONTEXT_PATH_REQUEST_ATTRIBUTE); if (contextPath == null) { contextPath = request.getContextPath(); } return getRequestUri(request).substring(contextPath.length()); } * <p>E.g.: servlet mapping = "/*.test"; request URI = "/a.test" -> "". * @param request current HTTP request * @return the path within the servlet mapping, or "" */ public static String getPathWithinServletMapping(HttpServletRequest request) { String servletPath = (String) request.getAttribute(INCLUDE_SERVLET_PATH_REQUEST_ATTRIBUTE); if (servletPath == null) { servletPath = request.getServletPath(); } return getPathWithinApplication(request).substring(servletPath.length()); } /** * Return the mapping lookup path for the given request, within the current * servlet mapping if applicable, else within the web application. * <p>Regards include request URL if called within a RequestDispatcher include. * @param request current HTTP request * @param alwaysUseFullPath if the full path within the context * should be used in any case * @return the lookup path * @see #getPathWithinApplication * @see #getPathWithinServletMapping */ public static String getLookupPathForRequest(HttpServletRequest request, boolean alwaysUseFullPath) { // always use full path within current servlet context? if (alwaysUseFullPath) { return WebUtils.getPathWithinApplication(request); } // else use path within current servlet mapping if applicable String rest = WebUtils.getPathWithinServletMapping(request); if (!"".equals(rest)) return rest; else return WebUtils.getPathWithinApplication(request); } /** * Given a servlet path string, determine the directory within the WAR * this belongs to, ending with a /. For example, /cat/dog/test.html would be * returned as /cat/dog/. /test.html would be returned as / */ public static String getDirectoryForServletPath(String servletPath) { // Arg will be of form /dog/cat.jsp. We want to see /dog/ if (servletPath == null || servletPath.indexOf("/") == -1) return "/"; String left = servletPath.substring(0, servletPath.lastIndexOf("/") + 1); return left; } /** * Convenience method to return a map from un-prefixed property names * to values. E.g. with a prefix of price, price_1, price_2 produce * a properties object with mappings for 1, 2 to the same values. * Maps single values to String and multiple values to String array. * @param request HTTP request in which to look for parameters * @param base beginning of parameter name * (if this is null or the empty string, all parameters will match) * @return map containing request parameters <b>without the prefix</b>, * containing either a String or a String[] as values */ public static Map getParametersStartingWith(ServletRequest request, String base) { Enumeration enum = request.getParameterNames(); Map params = new HashMap(); if (base == null) { base = ""; } while (enum != null && enum.hasMoreElements()) { String paramName = (String) enum.nextElement(); if (base == null || "".equals(base) || paramName.startsWith(base)) { String unprefixed = paramName.substring(base.length()); String[] values = request.getParameterValues(paramName); if (values == null) { // do nothing, no values found at all } else if (values.length > 1) { params.put(unprefixed, values); } else { params.put(unprefixed, values[0]); } } } return params; } /** * Checks if a specific input type="submit" parameter was sent in the request, * either via a button (directly with name) or via an image (name + ".x" or * name + ".y"). * @param request current HTTP request * @param name name of the parameter * @return if the parameter was sent * @see #SUBMIT_IMAGE_SUFFIXES */ public static boolean hasSubmitParameter(ServletRequest request, String name) { if (request.getParameter(name) != null) { return true; } for (int i = 0; i < SUBMIT_IMAGE_SUFFIXES.length; i++) { String suffix = SUBMIT_IMAGE_SUFFIXES[i]; if (request.getParameter(name + suffix) != null) { return true; } } return false; } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in th future. package org.usfirst.frc3946.UltimateAscent; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.JoystickButton; import org.usfirst.frc3946.UltimateAscent.commands.*; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ public class OI { //// CREATING BUTTONS // One type of button is a joystick button which is any button on a joystick. // You create one by telling it which joystick it's on and which button // number it is. // Joystick stick = new Joystick(port); // Button button = new JoystickButton(stick, buttonNumber); // Another type of button you can create is a DigitalIOButton, which is // a button or switch hooked up to the cypress module. These are useful if // you want to build a customized operator interface. // Button button = new DigitalIOButton(1); // There are a few additional built in buttons you can use. Additionally, // by subclassing Button you can create custom triggers and bind those to // commands the same as any other Button. //// TRIGGERING COMMANDS WITH BUTTONS // Once you have a button, it's trivial to bind it to a button in one of // three ways: // Start the command when the button is pressed and let it run the command // until it is finished as determined by it's isFinished method. // button.whenPressed(new ExampleCommand()); // Run the command while the button is being held down and interrupt it once // the button is released. // button.whileHeld(new ExampleCommand()); // Start the command when the button is released and let it run the command // until it is finished as determined by it's isFinished method. // button.whenReleased(new ExampleCommand()); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public JoystickButton rightTrigger; public Joystick rightStick; public Joystick leftStick; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public XboxJoystick xbox; public OI() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS leftStick = new Joystick(2); rightStick = new Joystick(1); rightTrigger = new JoystickButton(rightStick, 1); rightTrigger.whileHeld(new PlaceHolder()); // SmartDashboard Buttons SmartDashboard.putData("Autonomous Command", new AutonomousCommand()); SmartDashboard.putData("TankDrive", new TankDrive()); SmartDashboard.putData("PlaceHolder", new PlaceHolder()); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS xbox = new XboxJoystick(3); } // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS public Joystick getrightStick() { return rightStick; } public Joystick getleftStick() { return leftStick; } public XboxJoystick getxbox() { return xbox; } // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS }
package com.karateca.jstoolbox.joiner; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import java.io.File; /** * @author Andres Dominguez. */ public class JoinerActionTest extends LightCodeInsightFixtureTestCase { @Override protected String getTestDataPath() { return new File("testData").getPath(); } public void testJoin() { myFixture.configureByFiles("multiLineStringBefore.js"); myFixture.performEditorAction("com.karateca.jstoolbox.joiner.JoinerAction"); myFixture.checkResultByFile("multiLineStringBefore.js", "multiLineStringAfter.js", false); } }
package edu.umich.intnw; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.InetSocketAddress; import edu.umich.intnw.MultiSocket; import android.test.InstrumentationTestCase; public class SmokeTest extends InstrumentationTestCase { private static final String TEST_MSG = "testing, testing, testing"; private static final int CHUNK_SIZE = 40; private MultiSocket socket; public void setUp() throws IOException { socket = new MultiSocket(); socket.connect(new InetSocketAddress("141.212.110.132", 4242)); } public void tearDown() throws IOException { socket.close(); } public void testConnection() throws IOException { final byte[] msg = padWithNul(TEST_MSG, CHUNK_SIZE); OutputStream out = socket.getOutputStream(); out.write(msg); byte[] response = new byte[64]; InputStream in = socket.getInputStream(); int rc = in.read(response); assertEquals(msg.length, rc); String expected = new String(msg); String actual = new String(response, 0, rc); assertEquals(expected, actual); } private byte[] padWithNul(String string, int size) { assert(string.length() < size); byte[] buf = new byte[size]; for (int i = 0; i < size; ++i) { if (i < string.length()) { buf[i] = (byte) string.charAt(i); } else { buf[i] = 0; } } return buf; } public void testReaderWriter() throws IOException { // second newline will be overwritten with a NUL in the response String msg = "01234567890123456789012345678901234567\n\n"; assertEquals(CHUNK_SIZE, msg.length()); OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream()); writer.write(msg); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String actual = reader.readLine(); // trims off the newline assertEquals(msg.trim(), actual); } }
package org.jcouchdb.db; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.any; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.jcouchdb.document.Attachment; import org.jcouchdb.document.BaseDocument; import org.jcouchdb.document.DesignDocument; import org.jcouchdb.document.Document; import org.jcouchdb.document.DocumentInfo; import org.jcouchdb.document.ValueAndDocumentRow; import org.jcouchdb.document.ValueRow; import org.jcouchdb.document.View; import org.jcouchdb.document.ViewAndDocumentsResult; import org.jcouchdb.document.ViewResult; import org.jcouchdb.exception.DataAccessException; import org.jcouchdb.exception.DocumentValidationException; import org.jcouchdb.exception.NotFoundException; import org.jcouchdb.exception.UpdateConflictException; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runners.JUnit4; import org.slf4j.LoggerFactory; import org.svenson.JSON; import org.svenson.JSONParser; /** * Runs tests against a real couchdb database running on localhost * * @author fforw at gmx dot de */ public class LocalDatabaseTestCase { private JSON jsonGenerator = new JSON(); public final static String ADMIN_USER = "username"; public final static String ADMIN_PASSWORD = "password"; public final static String COUCHDB_HOST = "localhost"; public final static int COUCHDB_PORT = Server.DEFAULT_PORT; private static final String TESTDB_NAME = "jcouchdb_test"; private static final String MY_FOO_DOC_ID = "myFoo/DocId"; private static final String BY_VALUE_FUNCTION = "function(doc) { if (doc.type == 'foo') { emit(doc.value,doc); } }"; private static final String BY_VALUE_TO_NULL_FUNCTION = "function(doc) { if (doc.type == 'foo') { emit(doc.value,null); } }"; private static final String COMPLEX_KEY_FUNCTION = "function(doc) { if (doc.type == 'foo') { emit([1,{\"value\":doc.value}],doc); } }"; private static org.slf4j.Logger log = LoggerFactory.getLogger(LocalDatabaseTestCase.class); public static Database createDatabaseForTest() { Server server = createServer(); List<String> databases = server.listDatabases(); log.debug("databases = " + databases); if (!databases.contains(TESTDB_NAME)) { server.createDatabase(TESTDB_NAME); } return new Database(server,TESTDB_NAME); } @Test public void testInRightOrder() throws IOException { recreateTestDatabase(); createTestDocuments(); thatMapDocumentsWork(); thatCreateNamedDocWorks(); thatUpdateDocWorks(); thatUpdateConflictWorks(); testGetAll(); testCreateDesignDocument(); queryDocuments(); queryViewAndDocuments(); queryDocumentsWithComplexKey(); thatGetDocumentWorks(); thatAdHocViewsWork(); thatNonDocumentFetchingWorks(); thatBulkCreationWorks(); thatBulkCreationWithIdsWorks(); thatUpdateConflictsWork(); thatDeleteWorks(); thatDeleteFailsIfWrong(); thatAttachmentHandlingWorks(); thatViewKeyQueryingFromAllDocsWorks(); thatViewKeyQueryingFromAllDocsWorks2(); thatViewKeyQueryingWorks(); thatViewAndDocumentQueryingWorks(); testPureBaseDocumentAccess(); testAttachmentStreaming(); testValidation(); thatBulkDeletionWorks(); testThatStatsWorks(); thatShowsWorks(); thatViewsWorks(); thatDesignDocumentDeletionWorks(); thatFindDocumentWorks(); } public void recreateTestDatabase() { try { Server server = createServer(); List<String> databases = server.listDatabases(); log.debug("databases = " + databases); if (databases.contains(TESTDB_NAME)) { server.deleteDatabase(TESTDB_NAME); } server.createDatabase(TESTDB_NAME); } catch (RuntimeException e) { log.error("", e); } } public void createTestDocuments() { Database db = createDatabaseForTest(); FooDocument foo = new FooDocument("bar!"); assertThat(foo.getId(), is(nullValue())); assertThat(foo.getRevision(), is(nullValue())); db.createDocument(foo); assertThat(foo.getId(), is(notNullValue())); assertThat(foo.getRevision(), is(notNullValue())); foo = new FooDocument("baz!"); foo.setProperty("baz2", "Some test value"); db.createDocument(foo); log.debug(" } public void thatMapDocumentsWork() { Database db = createDatabaseForTest(); Map<String,String> doc = new HashMap<String, String>(); doc.put("foo", "value for the foo attribute"); doc.put("bar", "value for the bar attribute"); db.createDocument(doc); final String id = doc.get("_id"); assertThat(id, is(notNullValue())); assertThat(doc.get("_rev"), is(notNullValue())); doc = db.getDocument(Map.class, id); assertThat(doc.get("foo"), is("value for the foo attribute")); assertThat(doc.get("bar"), is("value for the bar attribute")); } public void thatCreateNamedDocWorks() { FooDocument doc = new FooDocument("qux"); doc.setId(MY_FOO_DOC_ID); Database db = createDatabaseForTest(); db.createDocument(doc); assertThat(doc.getId(), is(MY_FOO_DOC_ID)); assertThat(doc.getRevision(), is(notNullValue())); } public void thatUpdateDocWorks() { Database db = createDatabaseForTest(); FooDocument doc = db.getDocument(FooDocument.class, MY_FOO_DOC_ID); assertThat(doc.getValue(), is("qux")); doc.setValue("qux!"); db.updateDocument(doc); doc = db.getDocument(FooDocument.class, MY_FOO_DOC_ID); assertThat(doc.getValue(), is("qux!")); } public void thatUpdateConflictWorks() { boolean conflict; try { FooDocument doc = new FooDocument("qux"); doc.setId(MY_FOO_DOC_ID); createDatabaseForTest().createDocument(doc); conflict = false; } catch(UpdateConflictException e) { conflict = true; } assertThat(conflict, is(true)); } public void testGetAll() { Database db = createDatabaseForTest(); ViewResult<Map> result = db.listDocuments(null,null); List<ValueRow<Map>> rows = result.getRows(); String json = jsonGenerator.forValue(rows); System.out.println("rows = " + json); assertThat(rows.size(), is(4)); } // removed in 0.11 // public void testGetAllBySeq() // Database db = createDatabaseForTest(); // ViewResult<Map> result = db.listDocumentsByUpdateSequence(null,null); // List<ValueRow<Map>> rows = result.getRows(); // assertThat(rows.size(), is(4)); // assertThat(rows.get(0).getKey().toString(), is("1")); // assertThat(rows.get(1).getKey().toString(), is("2")); // assertThat(rows.get(2).getKey().toString(), is("3")); // assertThat(rows.get(3).getKey().toString(), is("5")); // this one was updated once // String json = jsonGenerator.forValue(rows); // log.debug("rows = " + json); public void testCreateDesignDocument() { Database db = createDatabaseForTest(); DesignDocument designDocument = new DesignDocument("foo"); designDocument.addView("byValue", new View(BY_VALUE_FUNCTION)); designDocument.addView("complex", new View(COMPLEX_KEY_FUNCTION)); log.debug("DESIGN DOC = " + jsonGenerator.dumpObjectFormatted(designDocument)); db.createDocument(designDocument); DesignDocument doc = db.getDesignDocument("foo"); log.debug(jsonGenerator.dumpObjectFormatted(doc)); assertThat(doc, is(notNullValue())); assertThat(doc.getId(), is(DesignDocument.PREFIX + "foo")); assertThat(doc.getViews().get("byValue").getMap(), is(BY_VALUE_FUNCTION)); assertThat(doc.getProperty("id"), is(nullValue())); } public void queryDocuments() { Database db = createDatabaseForTest(); ViewResult<FooDocument> result = db.queryView("foo/byValue", FooDocument.class, null, null); assertThat(result.getRows().size(), is(3)); FooDocument doc = result.getRows().get(0).getValue(); assertThat(doc, is(notNullValue())); assertThat(doc.getValue(), is("bar!")); doc = result.getRows().get(1).getValue(); assertThat(doc, is(notNullValue())); assertThat(doc.getValue(), is("baz!")); doc = result.getRows().get(2).getValue(); assertThat(doc, is(notNullValue())); assertThat(doc.getId(), is(MY_FOO_DOC_ID)); assertThat(doc.getValue(), is("qux!")); } public void queryViewAndDocuments() { Database db = createDatabaseForTest(); ViewAndDocumentsResult<Object,FooDocument> result = db.queryViewAndDocuments("foo/byValue", Object.class, FooDocument.class, null, null); assertThat(result.getRows().size(), is(3)); FooDocument doc = result.getRows().get(0).getDocument(); assertThat(doc, is(notNullValue())); assertThat(doc.getValue(), is("bar!")); doc = result.getRows().get(1).getDocument(); assertThat(doc, is(notNullValue())); assertThat(doc.getValue(), is("baz!")); doc = result.getRows().get(2).getDocument(); assertThat(doc, is(notNullValue())); assertThat(doc.getId(), is(MY_FOO_DOC_ID)); assertThat(doc.getValue(), is("qux!")); } public void queryDocumentsWithComplexKey() { Database db = createDatabaseForTest(); ViewResult<FooDocument> result = db.queryView("foo/complex", FooDocument.class, null, null); assertThat(result.getRows().size(), is(3)); ValueRow<FooDocument> row = result.getRows().get(0); assertThat(jsonGenerator.forValue(row.getKey()), is("[1,{\"value\":\"bar!\"}]")); } public void thatGetDocumentWorks() { Database db = createDatabaseForTest(); FooDocument doc = db.getDocument(FooDocument.class, MY_FOO_DOC_ID); assertThat(doc.getId(), is(MY_FOO_DOC_ID)); assertThat(doc.getRevision(), is(notNullValue())); assertThat(doc.getValue(), is("qux!")); log.debug(jsonGenerator.dumpObjectFormatted(doc)); } public void thatAdHocViewsWork() { Database db = createDatabaseForTest(); ViewResult<FooDocument> result = db.queryAdHocView(FooDocument.class, "{ \"map\" : \"function(doc) { if (doc.baz2 == 'Some test value') emit(null,doc); } \" }", null, null); assertThat(result.getRows().size(), is(1)); FooDocument doc = result.getRows().get(0).getValue(); assertThat((String)doc.getProperty("baz2"), is("Some test value")); } public void thatNonDocumentFetchingWorks() { Database db = createDatabaseForTest(); NotADocument doc = db.getDocument(NotADocument.class, MY_FOO_DOC_ID); assertThat(doc.getId(), is(MY_FOO_DOC_ID)); assertThat(doc.getRevision(), is(notNullValue())); assertThat((String)doc.getProperty("value"), is("qux!")); log.debug(jsonGenerator.dumpObjectFormatted(doc)); doc.setProperty("value", "changed"); db.updateDocument(doc); NotADocument doc2 = db.getDocument(NotADocument.class, MY_FOO_DOC_ID); assertThat((String)doc2.getProperty("value"), is("changed")); } public void thatBulkCreationWorks() { Database db = createDatabaseForTest(); List<Document> docs = new ArrayList<Document>(); docs.add(new FooDocument("doc-1")); docs.add(new FooDocument("doc-2")); docs.add(new FooDocument("doc-3")); List<DocumentInfo> infos = db.bulkCreateDocuments(docs); assertThat(infos.size(), is(3)); } public void thatBulkCreationWithIdsWorks() { Database db = createDatabaseForTest(); List<Document> docs = new ArrayList<Document>(); FooDocument fooDocument = new FooDocument("doc-2"); fooDocument.setId("second-foo-with-id"); docs.add(new FooDocument("doc-1")); docs.add(fooDocument); FooDocument fd2 = new FooDocument("doc-3"); fd2.setId(MY_FOO_DOC_ID); docs.add(fd2); List<DocumentInfo> infos = db.bulkCreateDocuments(docs); assertThat(infos.size(), is(3)); assertThat(infos.get(0).getId().length(), is(greaterThan(0))); assertThat(infos.get(1).getId(), is("second-foo-with-id")); // conflict results in error and reason being set assertThat(infos.get(2).getError().length(), is(greaterThan(0))); assertThat(infos.get(2).getReason().length(), is(greaterThan(0))); } public void thatUpdateConflictsWork() { boolean conflict; try { FooDocument foo = new FooDocument("value foo"); FooDocument foo2 = new FooDocument("value foo2"); foo.setId("update_conflict"); foo2.setId("update_conflict"); Database db = createDatabaseForTest(); db.createDocument(foo); db.createDocument(foo2); conflict = false; } catch(UpdateConflictException e) { conflict = true; } assertThat(conflict, is(true)); } public void thatDeleteWorks() { FooDocument foo = new FooDocument("a document"); Database db = createDatabaseForTest(); db.createDocument(foo); assertThat(foo.getId(), is ( notNullValue())); FooDocument foo2 = db.getDocument(FooDocument.class, foo.getId()); assertThat(foo.getValue(), is(foo2.getValue())); db.delete(foo); try { db.getDocument(FooDocument.class, foo.getId()); throw new IllegalStateException("document shouldn't be there anymore"); } catch(NotFoundException nfe) { // yay! } } public void thatDeleteFailsIfWrong() { boolean error; try { Database db = createDatabaseForTest(); db.delete("fakeid", "fakrev"); error = false; } catch(DataAccessException e) { error = true; } assertThat(error,is(true)); } private int valueCount(ViewResult<FooDocument> viewResult, String value) { int cnt = 0; for (ValueRow<FooDocument> row : viewResult.getRows()) { if (row.getValue().getValue().equals(value)) { cnt++; } } return cnt; } public void thatAttachmentHandlingWorks() throws UnsupportedEncodingException { final String attachmentContent = "The quick brown fox jumps over the lazy dog."; FooDocument fooDocument = new FooDocument("foo with attachment"); fooDocument.addAttachment("test", new Attachment("text/plain", attachmentContent.getBytes())); Database db = createDatabaseForTest(); db.createDocument(fooDocument); String id = fooDocument.getId(); // re-read document fooDocument = db.getDocument(FooDocument.class, id); Attachment attachment = fooDocument.getAttachments().get("test"); assertThat(attachment, is(notNullValue())); assertThat(attachment.isStub(), is(true)); assertThat(attachment.getContentType(), is("text/plain")); assertThat(attachment.getLength(), is(44l)); // re-save the document to test that we can save with 'stubs' fooDocument.setProperty("ping", "pong"); db.createOrUpdateDocument(fooDocument); String content = new String(db.getAttachment(id, "test")); assertThat(content, is(attachmentContent)); String newRev = db.updateAttachment(fooDocument.getId(), fooDocument.getRevision(), "test", "text/plain", (attachmentContent+"!!").getBytes()); assertThat(newRev, is(notNullValue())); assertThat(newRev.length(), is(greaterThan(0))); content = new String(db.getAttachment(id, "test")); assertThat(content, is(attachmentContent+"!!")); newRev = db.deleteAttachment(fooDocument.getId(), newRev, "test"); assertThat(newRev, is(notNullValue())); assertThat(newRev.length(), is(greaterThan(0))); try { content = new String(db.getAttachment(id, "test")); throw new IllegalStateException("attachment should be gone by now"); } catch(NotFoundException e) { // yay! } newRev = db.createAttachment(fooDocument.getId(), newRev, "test", "text/plain", "TEST".getBytes()); assertThat(newRev, is(notNullValue())); assertThat(newRev.length(), is(greaterThan(0))); content = new String(db.getAttachment(id, "test")); assertThat(content, is("TEST")); } public void thatViewKeyQueryingFromAllDocsWorks() { Database db = createDatabaseForTest(); ViewResult<Map> result = db.queryByKeys(Map.class, Arrays.asList(MY_FOO_DOC_ID,"second-foo-with-id"), null, null); assertThat(result.getRows().size(), is(2)); assertThat(result.getRows().get(0).getId(), is(MY_FOO_DOC_ID)); assertThat(result.getRows().get(1).getId(), is("second-foo-with-id")); } public void thatViewKeyQueryingFromAllDocsWorks2() { Database db = createDatabaseForTest(); ViewResult<Map> result = db.queryByKeys(Map.class, Arrays.asList(MY_FOO_DOC_ID,"second-foo-with-id"), null, null); assertThat(result.getRows().size(), is(2)); assertThat(result.getRows().get(0).getId(), is(MY_FOO_DOC_ID)); assertThat(result.getRows().get(1).getId(), is("second-foo-with-id")); } public void thatViewKeyQueryingWorks() { Database db = createDatabaseForTest(); ViewResult<FooDocument> result = db.queryViewByKeys("foo/byValue", FooDocument.class, Arrays.asList("doc-1","doc-2"), null, null); assertThat(result.getRows().size(), is(4)); assertThat( valueCount(result,"doc-1"), is(2)); assertThat( valueCount(result,"doc-2"), is(2)); } public void thatViewAndDocumentQueryingWorks() { Database db = createDatabaseForTest(); ViewAndDocumentsResult<Object,FooDocument> result = db.queryViewAndDocumentsByKeys("foo/byValue", Object.class, FooDocument.class, Arrays.asList("doc-1"), null, null); List<ValueAndDocumentRow<Object, FooDocument>> rows = result.getRows(); assertThat(rows.size(), is(2)); ValueAndDocumentRow<Object, FooDocument> row = rows.get(0); assertThat(row.getDocument(), is(notNullValue())); assertThat(row.getDocument().getValue(), is("doc-1")); row = rows.get(1); assertThat(row.getDocument(), is(notNullValue())); assertThat(row.getDocument().getValue(), is("doc-1")); } public void testPureBaseDocumentAccess() { Database db = createDatabaseForTest(); BaseDocument newdoc = new BaseDocument(); final String value = "baz403872349"; newdoc.setProperty("foo",value); // same as JSON: { foo: "baz..." } assertThat(newdoc.getId(), is(nullValue())); assertThat(newdoc.getRevision(), is(nullValue())); db.createDocument(newdoc); // auto-generated id given by the database assertThat(newdoc.getId().length(), is(greaterThan(0))); assertThat(newdoc.getRevision().length(), is(greaterThan(0))); BaseDocument doc = db.getDocument(BaseDocument.class, newdoc.getId()); assertThat((String)doc.getProperty("foo"), is(value)); } public void testAttachmentStreaming() throws IOException { Database db = createDatabaseForTest(); final String docId = "attachmentStreamingDoc"; final String content = "Streaming test."; final String content2 = "Streaming test 2."; byte[] data = content.getBytes(); String revision = db.createAttachment(docId, null, "test.txt", "text/plain", new ByteArrayInputStream(data), data.length); assertThat(revision.length(), is(greaterThan(0))); Response resp = db.getAttachmentResponse(docId, "test.txt"); InputStream is = resp.getInputStream(); assertThat(new String(IOUtils.toByteArray(is)), is(content)); resp.destroy(); byte[] data2 = content2.getBytes(); revision = db.updateAttachment(docId, revision, "test.txt", "text/plain", new ByteArrayInputStream(data2), data2.length); resp = db.getAttachmentResponse(docId, "test.txt"); is = resp.getInputStream(); assertThat(new String(IOUtils.toByteArray(is)), is(content2)); resp.destroy(); } public void testValidation() { String fn = "function(newDoc, oldDoc, userCtx){\n" + " if (newDoc.validationTestField && newDoc.validationTestField !== '123') {\n" + " throw({'forbidden':'not 123'});\n" + " }\n" + "}"; DesignDocument designDoc = new DesignDocument("validate_test"); designDoc.setValidateOnDocUpdate(fn); Database db = createDatabaseForTest(); assertThat(designDoc.getRevision(), is(nullValue())); db.createDocument(designDoc); assertThat(designDoc.getRevision(), is(notNullValue())); BaseDocument doc = new BaseDocument(); doc.setProperty("validationTestField", "123"); assertThat(doc.getRevision(), is(nullValue())); db.createDocument(doc); assertThat(doc.getRevision(), is(notNullValue())); doc.setProperty("validationTestField", "invalid"); DocumentValidationException e = null; try { db.updateDocument(doc); } catch(DocumentValidationException e2) { e = e2; } assertThat(e, is(notNullValue())); assertThat(e.getReason(), is("not 123")); assertThat(e.getError(), is("forbidden")); } @Ignore public void thatHandlingHugeAttachmentsWorks() { Database db = createDatabaseForTest(); BaseDocument doc = new BaseDocument(); db.createDocument(doc); long length = (long)(Runtime.getRuntime().maxMemory() * 1.1); InputStream is = new SizedInputStreamMock((byte)'A', length); db.createAttachment(doc.getId(), doc.getRevision(), "hugeAttachment.txt", "text/plain", is, length); doc = db.getDocument(BaseDocument.class, doc.getId()); Map<String, Attachment> attachments = doc.getAttachments(); assertThat(attachments.size(), is(1)); Attachment attachment = attachments.get("hugeAttachment.txt"); assertThat(attachment, is(notNullValue())); assertThat(attachment.getLength(), is(length)); assertThat(attachment.getContentType(), is("text/plain")); assertThat(attachment.isStub(), is(true)); } public void thatBulkDeletionWorks() { Database db = createDatabaseForTest(); String[] ids = new String[] { "doc-1", "doc-2", "doc-3" }; List<Document> docs = new ArrayList<Document>(); for (String id : ids) { Document d = new FooDocument("value-" + id); d.setId(id); docs.add(d); } List<DocumentInfo> infos = db.bulkCreateDocuments(docs); assertThat(infos.size(), is(3)); docs.clear(); for (String docid : ids) { docs.add(db.getDocument(FooDocument.class, docid)); } infos = db.bulkDeleteDocuments(docs); assertThat(infos.size(), is(3)); for (String docid : ids) { try { db.getDocument(FooDocument.class, docid); assertThat("NotFoundException expected", true, is(false)); } catch (NotFoundException nfe) { // expected } } } public void testThatStatsWorks() { Database db = createDatabaseForTest(); { Map<String,Map<String,Object>> stats = db.getServer().getStats(null); assertThat(stats.size(), is(greaterThan(1))); assertThat(stats.get("couchdb"), is(any(Map.class))); } { Map<String,Map<String,Object>> stats = db.getServer().getStats("/couchdb/request_time"); assertThat(stats.size(), is(1)); assertThat(stats.get("couchdb").size(), is(1)); assertThat((Map)stats.get("couchdb").get("request_time"), is(any(Map.class))); } } public void thatShowsWorks() { DesignDocument doc = new DesignDocument("showDoc"); doc.addShowFunction("foo", "function(doc,req) { return {body: '[' + doc.value + ']'}; }"); Database db = createDatabaseForTest(); db.createDocument(doc); String content = db.queryShow("showDoc/foo", MY_FOO_DOC_ID, null).getContentAsString(); assertThat(content, is("[changed]")); } public void thatViewsWorks() throws FileNotFoundException, IOException { Database db = createDatabaseForTest(); DesignDocument doc = null; try { doc = db.getDesignDocument("listDoc"); } catch(NotFoundException e) { } if (doc == null) { doc = new DesignDocument("listDoc"); } doc.addView("foos-by-value", new View(BY_VALUE_TO_NULL_FUNCTION)); doc.addListFunction("foo", "function(head, req){\n" + " var row;\n" + " send('{\"head\": ' + toJSON(head) + ',\"rows\":[' );\n" + " var first = true;" + " while(row = getRow()) {\n" + " send((first?'':',') + toJSON(row));\n" + " first = false;" + " }\n" + " send(']}');" + "}"); db.createOrUpdateDocument(doc); Response response = null; try { response = db.queryList("listDoc/foo", "foos-by-value", new Options().key("changed")); JSONParser parser = new JSONParser(); parser.addTypeHint(".rows[]", ValueRow.class); response.setParser(parser); String s = response.getContentAsString(); System.out.println(s); Map m = parser.parse(Map.class, s); Map head = (Map)m.get("head"); assertThat(head, is(notNullValue())); assertThat((Long)head.get("total_rows"), is(10L)); assertThat((Long)head.get("offset"), is(2L)); List<ValueRow<String>> rows = (List<ValueRow<String>>) m.get("rows"); assertThat(rows.size(), is(1)); ValueRow<String> row = rows.get(0); assertThat(row.getId(),is(MY_FOO_DOC_ID)); assertThat((String)row.getKey(),is("changed")); } finally { if (response != null) { response.destroy(); } } response = null; try { response = db.queryList("listDoc/foo", "foos-by-value", new Options().key("changed")); JSONParser parser = new JSONParser(); parser.addTypeHint(".rows[]", ValueRow.class); response.setParser(parser); String s = response.getContentAsString(); System.out.println(s); Map m = parser.parse(Map.class, s); Map head = (Map)m.get("head"); assertThat(head, is(notNullValue())); assertThat((Long)head.get("total_rows"), is(10L)); assertThat((Long)head.get("offset"), is(2L)); List<ValueRow<String>> rows = (List<ValueRow<String>>) m.get("rows"); assertThat(rows.size(), is(1)); ValueRow<String> row = rows.get(0); assertThat(row.getId(),is(MY_FOO_DOC_ID)); assertThat((String)row.getKey(),is("changed")); } finally { if (response != null) { response.destroy(); } } } public static void deleteDocIfExists(Database db, String docId) { try { BaseDocument doc = db.getDocument(BaseDocument.class, docId); db.delete(doc); } catch(NotFoundException e) { // ignore } } public static void assertNotExist(Database db, String docId) { try { BaseDocument doc = db.getDocument(BaseDocument.class, docId); Assert.fail(docId + " should not exists, but does exist"); } catch(NotFoundException e) { // ignore } } public void thatDesignDocumentDeletionWorks() { Database db = createDatabaseForTest(); DesignDocument doc = db.getDesignDocument("foo"); assertThat(doc,is(notNullValue())); db.delete(doc); try { doc = db.getDesignDocument("foo"); Assert.fail("design doc should be deleted."); } catch(NotFoundException e) { } } public void thatFindDocumentWorks() { BaseDocument doc = new BaseDocument(); String value = "X0Z:@S-3Poj.+q&STXgO"; doc.setProperty("prop", value); Database db = createDatabaseForTest(); db.createDocument(doc); BaseDocument doc2 = db.findDocument(BaseDocument.class, doc.getId(), null); assertThat((String)doc2.getProperty("prop"), is(value)); BaseDocument doc3 = db.findDocument(BaseDocument.class, "noExistingId", null); assertThat(doc3,is(nullValue())); } public static Database createRandomNamedDB(String prefix) { Server server = createServer(); String name = prefix + server.getUUIDs(1).get(0); server.createDatabase(name); return new Database(server, name); } private static ServerImpl createServer() { ServerImpl server = new ServerImpl(LocalDatabaseTestCase.COUCHDB_HOST, LocalDatabaseTestCase.COUCHDB_PORT); Credentials credentials = new UsernamePasswordCredentials(ADMIN_USER, ADMIN_PASSWORD); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME); server.setCredentials(authScope, credentials); return server; } public static Database recreateDB(String name) { Server server = createServer(); if (server.listDatabases().contains(name)) { server.deleteDatabase(name); } server.createDatabase(name); return new Database(server, name); } }
package com.vimeo.networking.utils; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.internal.bind.util.ISO8601Utils; import com.vimeo.networking.logging.ClientLogger; import java.lang.reflect.Type; import java.text.ParseException; import java.text.ParsePosition; import java.util.Date; /** * A wrapper class that serializes and deserializes dates * using the {@link ISO8601Utils} class that catches errors * and reports them to the client application, allowing * them to decide if they should crash or not. If we just * rely on the default adapter used by Gson, we are unable * to absorb date parsing errors or log them correctly. * Additionally, the default adapter was not serializing the * dates correctly. */ @SuppressWarnings("WeakerAccess") public final class ISO8601Wrapper { private ISO8601Wrapper() { } public static JsonSerializer<Date> getDateSerializer() { return new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive(ISO8601Utils.format(src)); } }; } public static JsonDeserializer<Date> getDateDeserializer() { return new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return json == null ? null : ISO8601Utils.parse(json.getAsString(), new ParsePosition(0)); } catch (ParseException e) { ClientLogger.e("Incorrectly formatted date sent from server: " + json.getAsString(), e); return null; } } }; } }
package it.unimi.dsi.fastutil.objects; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Comparator; import java.util.Random; import org.junit.Test; @SuppressWarnings("boxing") public class ObjectArraysTest { public static Integer[] identity( final int n ) { final Integer[] perm = new Integer[ n ]; for( int i = perm.length; i-- != 0; ) perm[ i ] = i; return perm; } @Test public void testMergeSort() { Integer[] a = { 2, 1, 5, 2, 1, 0, 9, 1, 4, 2, 4, 6, 8, 9, 10, 12, 1, 7 }, b = a.clone(), sorted = a.clone(); Arrays.sort( sorted ); ObjectArrays.mergeSort( b ); assertArrayEquals( sorted, b ); ObjectArrays.mergeSort( b ); assertArrayEquals( sorted, b ); final Integer[] d = a.clone(); ObjectArrays.mergeSort( d, new Comparator<Integer>() { @Override public int compare( Integer k1, Integer k2 ) { return k1.compareTo( k2 ); } }); assertArrayEquals( sorted, d ); ObjectArrays.mergeSort( d, new Comparator<Integer>() { @Override public int compare( Integer k1, Integer k2 ) { return k1.compareTo( k2 ); } }); assertArrayEquals( sorted, d ); } @Test public void testMergeSortSmallSupport() { Integer[] a = { 2, 1, 5, 2, 1, 0, 9, 1, 4, 2, 4, 6, 8, 9, 10, 12, 1, 7 }; for( int to = 1; to < a.length; to++ ) for( int from = 0; from <= to; from++ ) { final Integer[] support = new Integer[ to ]; System.arraycopy( a, 0, support, 0, to ); ObjectArrays.mergeSort( a, from, to, support ); if ( from < to ) for( int i = to - 1; i-- != from; ) assertTrue( a[ i ] <= a[ i + 1 ] ); } } @Test public void testQuickSort() { Integer[] a = { 2, 1, 5, 2, 1, 0, 9, 1, 4, 2, 4, 6, 8, 9, 10, 12, 1, 7 }, b = a.clone(), sorted = a.clone(); Arrays.sort( sorted ); Arrays.sort( b ); assertArrayEquals( sorted, b ); Arrays.sort( b ); assertArrayEquals( sorted, b ); final Integer[] d = a.clone(); ObjectArrays.quickSort( d, new Comparator<Integer>() { @Override public int compare( Integer k1, Integer k2 ) { return k1.compareTo( k2 ); } }); assertArrayEquals( sorted, d ); ObjectArrays.quickSort( d, new Comparator<Integer>() { @Override public int compare( Integer k1, Integer k2 ) { return k1.compareTo( k2 ); } }); assertArrayEquals( sorted, d ); } @Test public void testParallelQuickSort() { Integer[] a = { 2, 1, 5, 2, 1, 0, 9, 1, 4, 2, 4, 6, 8, 9, 10, 12, 1, 7 }, b = a.clone(), sorted = a.clone(); Arrays.sort( sorted ); Arrays.sort( b ); assertArrayEquals( sorted, b ); Arrays.sort( b ); assertArrayEquals( sorted, b ); final Integer[] d = a.clone(); ObjectArrays.parallelQuickSort( d, 0, d.length ); assertArrayEquals( sorted, d ); } @Test public void testLargeParallelQuickSortWithComparator() { Object [] a = new Object[8192+1]; // PARALLEL_QUICKSORT_NO_FORK for (int i = 0; i < a.length; i++) { a[i] = new Object(); } ObjectArrays.parallelQuickSort(a, new Comparator<Object>(){ @Override public int compare(Object o1, Object o2) { return Integer.compare(System.identityHashCode(o1), System.identityHashCode(o2)); }}); } @Test public void testSmallParallelQuickSortWithComparator() { Object [] a = new Object[8]; for (int i = 0; i < a.length; i++) { a[i] = new Object(); } ObjectArrays.parallelQuickSort(a, new Comparator<Object>(){ @Override public int compare(Object o1, Object o2) { return Integer.compare(System.identityHashCode(o1), System.identityHashCode(o2)); }}); } @Test public void testQuickSort1() { Integer[] t = { 2, 1, 0, 4 }; ObjectArrays.quickSort( t ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] <= t[ i + 1 ] ); t = new Integer[] { 2, -1, 0, -4 }; ObjectArrays.quickSort( t ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] <= t[ i + 1 ] ); t = ObjectArrays.shuffle( identity( 100 ), new Random( 0 ) ); ObjectArrays.quickSort( t ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] <= t[ i + 1 ] ); t = new Integer[ 100 ]; Random random = new Random( 0 ); for( int i = t.length; i-- != 0; ) t[ i ] = random.nextInt(); ObjectArrays.quickSort( t ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] <= t[ i + 1 ] ); t = new Integer[ 100000 ]; random = new Random( 0 ); for( int i = t.length; i-- != 0; ) t[ i ] = random.nextInt(); ObjectArrays.quickSort( t ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] <= t[ i + 1 ] ); for( int i = 100; i-- != 10; ) t[ i ] = random.nextInt(); ObjectArrays.quickSort( t, 10, 100 ); for( int i = 99; i-- != 10; ) assertTrue( t[ i ] <= t[ i + 1 ] ); t = new Integer[ 10000000 ]; random = new Random( 0 ); for( int i = t.length; i-- != 0; ) t[ i ] = random.nextInt(); ObjectArrays.quickSort( t ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] <= t[ i + 1 ] ); } private final static Comparator<Integer> OPPOSITE_COMPARATOR = new Comparator<Integer>() { @Override public int compare( Integer o1, Integer o2 ) { return o2.compareTo( o1 ); }}; @Test public void testQuickSort1Comp() { Integer[] t = { 2, 1, 0, 4 }; ObjectArrays.quickSort( t, OPPOSITE_COMPARATOR ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] >= t[ i + 1 ] ); t = new Integer[] { 2, -1, 0, -4 }; ObjectArrays.quickSort( t, OPPOSITE_COMPARATOR ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] >= t[ i + 1 ] ); t = ObjectArrays.shuffle( identity( 100 ), new Random( 0 ) ); ObjectArrays.quickSort( t, OPPOSITE_COMPARATOR ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] >= t[ i + 1 ] ); t = new Integer[ 100 ]; Random random = new Random( 0 ); for( int i = t.length; i-- != 0; ) t[ i ] = random.nextInt(); ObjectArrays.quickSort( t, OPPOSITE_COMPARATOR ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] >= t[ i + 1 ] ); t = new Integer[ 100000 ]; random = new Random( 0 ); for( int i = t.length; i-- != 0; ) t[ i ] = random.nextInt(); ObjectArrays.quickSort( t, OPPOSITE_COMPARATOR ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] >= t[ i + 1 ] ); for( int i = 100; i-- != 10; ) t[ i ] = random.nextInt(); ObjectArrays.quickSort( t, 10, 100, OPPOSITE_COMPARATOR ); for( int i = 99; i-- != 10; ) assertTrue( t[ i ] >= t[ i + 1 ] ); t = new Integer[ 10000000 ]; random = new Random( 0 ); for( int i = t.length; i-- != 0; ) t[ i ] = random.nextInt(); ObjectArrays.quickSort( t, OPPOSITE_COMPARATOR ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] >= t[ i + 1 ] ); } @Test public void testParallelQuickSort1() { Integer[] t = { 2, 1, 0, 4 }; ObjectArrays.parallelQuickSort( t ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] <= t[ i + 1 ] ); t = new Integer[] { 2, -1, 0, -4 }; ObjectArrays.parallelQuickSort( t ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] <= t[ i + 1 ] ); t = ObjectArrays.shuffle( identity( 100 ), new Random( 0 ) ); ObjectArrays.parallelQuickSort( t ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] <= t[ i + 1 ] ); t = new Integer[ 100 ]; Random random = new Random( 0 ); for( int i = t.length; i-- != 0; ) t[ i ] = random.nextInt(); ObjectArrays.parallelQuickSort( t ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] <= t[ i + 1 ] ); t = new Integer[ 100000 ]; random = new Random( 0 ); for( int i = t.length; i-- != 0; ) t[ i ] = random.nextInt(); ObjectArrays.parallelQuickSort( t ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] <= t[ i + 1 ] ); for( int i = 100; i-- != 10; ) t[ i ] = random.nextInt(); ObjectArrays.parallelQuickSort( t, 10, 100 ); for( int i = 99; i-- != 10; ) assertTrue( t[ i ] <= t[ i + 1 ] ); t = new Integer[ 10000000 ]; random = new Random( 0 ); for( int i = t.length; i-- != 0; ) t[ i ] = random.nextInt(); ObjectArrays.parallelQuickSort( t ); for( int i = t.length - 1; i-- != 0; ) assertTrue( t[ i ] <= t[ i + 1 ] ); } @Test public void testQuickSort2() { Integer[][] d = new Integer[ 2 ][]; d[ 0 ] = new Integer[ 10 ]; for( int i = d[ 0 ].length; i-- != 0; ) d[ 0 ][ i ] = 3 - i % 3; d[ 1 ] = ObjectArrays.shuffle( identity( 10 ), new Random( 0 ) ); ObjectArrays.quickSort( d[ 0 ], d[ 1 ] ); for( int i = d[ 0 ].length - 1; i-- != 0; ) assertTrue( Integer.toString( i ) + ": <" + d[ 0 ][ i ] + ", " + d[ 1 ][ i ] + ">, <" + d[ 0 ][ i + 1 ] + ", " + d[ 1 ][ i + 1 ] + ">", d[ 0 ][ i ] < d[ 0 ][ i + 1 ] || d[ 0 ][ i ].equals( d[ 0 ][ i + 1 ] ) && d[ 1 ][ i ] <= d[ 1 ][ i + 1 ] ); d[ 0 ] = new Integer[ 100000 ]; for( int i = d[ 0 ].length; i-- != 0; ) d[ 0 ][ i ] = 100 - i % 100; d[ 1 ] = ObjectArrays.shuffle( identity( 100000 ), new Random( 6 ) ); ObjectArrays.quickSort( d[ 0 ], d[ 1 ] ); for( int i = d[ 0 ].length - 1; i-- != 0; ) assertTrue( Integer.toString( i ) + ": <" + d[ 0 ][ i ] + ", " + d[ 1 ][ i ] + ">, <" + d[ 0 ][ i + 1 ] + ", " + d[ 1 ][ i + 1 ] + ">", d[ 0 ][ i ] < d[ 0 ][ i + 1 ] || d[ 0 ][ i ].equals( d[ 0 ][ i + 1 ] ) && d[ 1 ][ i ] <= d[ 1 ][ i + 1 ] ); d[ 0 ] = new Integer[ 10 ]; for( int i = d[ 0 ].length; i-- != 0; ) d[ 0 ][ i ] = i % 3 - 2; Random random = new Random( 0 ); d[ 1 ] = new Integer[ d[ 0 ].length ]; for( int i = d[ 1 ].length; i-- != 0; ) d[ 1 ][ i ] = random.nextInt(); ObjectArrays.quickSort( d[ 0 ], d[ 1 ] ); for( int i = d[ 0 ].length - 1; i-- != 0; ) assertTrue( Integer.toString( i ) + ": <" + d[ 0 ][ i ] + ", " + d[ 1 ][ i ] + ">, <" + d[ 0 ][ i + 1 ] + ", " + d[ 1 ][ i + 1 ] + ">", d[ 0 ][ i ] < d[ 0 ][ i + 1 ] || d[ 0 ][ i ].equals( d[ 0 ][ i + 1 ] ) && d[ 1 ][ i ] <= d[ 1 ][ i + 1 ] ); d[ 0 ] = new Integer[ 100000 ]; random = new Random( 0 ); for( int i = d[ 0 ].length; i-- != 0; ) d[ 0 ][ i ] = random.nextInt(); d[ 1 ] = new Integer[ d[ 0 ].length ]; for( int i = d[ 1 ].length; i-- != 0; ) d[ 1 ][ i ] = random.nextInt(); ObjectArrays.quickSort( d[ 0 ], d[ 1 ] ); for( int i = d[ 0 ].length - 1; i-- != 0; ) assertTrue( Integer.toString( i ) + ": <" + d[ 0 ][ i ] + ", " + d[ 1 ][ i ] + ">, <" + d[ 0 ][ i + 1 ] + ", " + d[ 1 ][ i + 1 ] + ">", d[ 0 ][ i ] < d[ 0 ][ i + 1 ] || d[ 0 ][ i ].equals( d[ 0 ][ i + 1 ] ) && d[ 1 ][ i ] <= d[ 1 ][ i + 1 ] ); for( int i = 100; i-- != 10; ) d[ 0 ][ i ] = random.nextInt(); for( int i = 100; i-- != 10; ) d[ 1 ][ i ] = random.nextInt(); ObjectArrays.quickSort( d[ 0 ], d[ 1 ], 10, 100 ); for( int i = 99; i-- != 10; ) assertTrue( Integer.toString( i ) + ": <" + d[ 0 ][ i ] + ", " + d[ 1 ][ i ] + ">, <" + d[ 0 ][ i + 1 ] + ", " + d[ 1 ][ i + 1 ] + ">", d[ 0 ][ i ] < d[ 0 ][ i + 1 ] || d[ 0 ][ i ].equals( d[ 0 ][ i + 1 ] ) && d[ 1 ][ i ] <= d[ 1 ][ i + 1 ] ); d[ 0 ] = new Integer[ 10000000 ]; random = new Random( 0 ); for( int i = d[ 0 ].length; i-- != 0; ) d[ 0 ][ i ] = random.nextInt(); d[ 1 ] = new Integer[ d[ 0 ].length ]; for( int i = d[ 1 ].length; i-- != 0; ) d[ 1 ][ i ] = random.nextInt(); ObjectArrays.quickSort( d[ 0 ], d[ 1 ] ); for( int i = d[ 0 ].length - 1; i-- != 0; ) assertTrue( Integer.toString( i ) + ": <" + d[ 0 ][ i ] + ", " + d[ 1 ][ i ] + ">, <" + d[ 0 ][ i + 1 ] + ", " + d[ 1 ][ i + 1 ] + ">", d[ 0 ][ i ] < d[ 0 ][ i + 1 ] || d[ 0 ][ i ].equals( d[ 0 ][ i + 1 ] ) && d[ 1 ][ i ] <= d[ 1 ][ i + 1 ] ); } @Test public void testParallelQuickSort2() { Integer[][] d = new Integer[ 2 ][]; d[ 0 ] = new Integer[ 10 ]; for( int i = d[ 0 ].length; i-- != 0; ) d[ 0 ][ i ] = 3 - i % 3; d[ 1 ] = ObjectArrays.shuffle( identity( 10 ), new Random( 0 ) ); ObjectArrays.parallelQuickSort( d[ 0 ], d[ 1 ] ); for( int i = d[ 0 ].length - 1; i-- != 0; ) assertTrue( Integer.toString( i ) + ": <" + d[ 0 ][ i ] + ", " + d[ 1 ][ i ] + ">, <" + d[ 0 ][ i + 1 ] + ", " + d[ 1 ][ i + 1 ] + ">", d[ 0 ][ i ] < d[ 0 ][ i + 1 ] || d[ 0 ][ i ].equals( d[ 0 ][ i + 1 ] ) && d[ 1 ][ i ] <= d[ 1 ][ i + 1 ] ); d[ 0 ] = new Integer[ 100000 ]; for( int i = d[ 0 ].length; i-- != 0; ) d[ 0 ][ i ] = 100 - i % 100; d[ 1 ] = ObjectArrays.shuffle( identity( 100000 ), new Random( 6 ) ); ObjectArrays.parallelQuickSort( d[ 0 ], d[ 1 ] ); for( int i = d[ 0 ].length - 1; i-- != 0; ) assertTrue( Integer.toString( i ) + ": <" + d[ 0 ][ i ] + ", " + d[ 1 ][ i ] + ">, <" + d[ 0 ][ i + 1 ] + ", " + d[ 1 ][ i + 1 ] + ">", d[ 0 ][ i ] < d[ 0 ][ i + 1 ] || d[ 0 ][ i ].equals( d[ 0 ][ i + 1 ] ) && d[ 1 ][ i ] <= d[ 1 ][ i + 1 ] ); d[ 0 ] = new Integer[ 10 ]; for( int i = d[ 0 ].length; i-- != 0; ) d[ 0 ][ i ] = i % 3 - 2; Random random = new Random( 0 ); d[ 1 ] = new Integer[ d[ 0 ].length ]; for( int i = d[ 1 ].length; i-- != 0; ) d[ 1 ][ i ] = random.nextInt(); ObjectArrays.parallelQuickSort( d[ 0 ], d[ 1 ] ); for( int i = d[ 0 ].length - 1; i-- != 0; ) assertTrue( Integer.toString( i ) + ": <" + d[ 0 ][ i ] + ", " + d[ 1 ][ i ] + ">, <" + d[ 0 ][ i + 1 ] + ", " + d[ 1 ][ i + 1 ] + ">", d[ 0 ][ i ] < d[ 0 ][ i + 1 ] || d[ 0 ][ i ].equals( d[ 0 ][ i + 1 ] ) && d[ 1 ][ i ] <= d[ 1 ][ i + 1 ] ); d[ 0 ] = new Integer[ 100000 ]; random = new Random( 0 ); for( int i = d[ 0 ].length; i-- != 0; ) d[ 0 ][ i ] = random.nextInt(); d[ 1 ] = new Integer[ d[ 0 ].length ]; for( int i = d[ 1 ].length; i-- != 0; ) d[ 1 ][ i ] = random.nextInt(); ObjectArrays.parallelQuickSort( d[ 0 ], d[ 1 ] ); for( int i = d[ 0 ].length - 1; i-- != 0; ) assertTrue( Integer.toString( i ) + ": <" + d[ 0 ][ i ] + ", " + d[ 1 ][ i ] + ">, <" + d[ 0 ][ i + 1 ] + ", " + d[ 1 ][ i + 1 ] + ">", d[ 0 ][ i ] < d[ 0 ][ i + 1 ] || d[ 0 ][ i ].equals( d[ 0 ][ i + 1 ] ) && d[ 1 ][ i ] <= d[ 1 ][ i + 1 ] ); for( int i = 100; i-- != 10; ) d[ 0 ][ i ] = random.nextInt(); for( int i = 100; i-- != 10; ) d[ 1 ][ i ] = random.nextInt(); ObjectArrays.parallelQuickSort( d[ 0 ], d[ 1 ], 10, 100 ); for( int i = 99; i-- != 10; ) assertTrue( Integer.toString( i ) + ": <" + d[ 0 ][ i ] + ", " + d[ 1 ][ i ] + ">, <" + d[ 0 ][ i + 1 ] + ", " + d[ 1 ][ i + 1 ] + ">", d[ 0 ][ i ] < d[ 0 ][ i + 1 ] || d[ 0 ][ i ].equals( d[ 0 ][ i + 1 ] ) && d[ 1 ][ i ] <= d[ 1 ][ i + 1 ] ); d[ 0 ] = new Integer[ 10000000 ]; random = new Random( 0 ); for( int i = d[ 0 ].length; i-- != 0; ) d[ 0 ][ i ] = random.nextInt(); d[ 1 ] = new Integer[ d[ 0 ].length ]; for( int i = d[ 1 ].length; i-- != 0; ) d[ 1 ][ i ] = random.nextInt(); ObjectArrays.parallelQuickSort( d[ 0 ], d[ 1 ] ); for( int i = d[ 0 ].length - 1; i-- != 0; ) assertTrue( Integer.toString( i ) + ": <" + d[ 0 ][ i ] + ", " + d[ 1 ][ i ] + ">, <" + d[ 0 ][ i + 1 ] + ", " + d[ 1 ][ i + 1 ] + ">", d[ 0 ][ i ] < d[ 0 ][ i + 1 ] || d[ 0 ][ i ].equals( d[ 0 ][ i + 1 ] ) && d[ 1 ][ i ] <= d[ 1 ][ i + 1 ] ); } @Test public void testShuffle() { Integer[] a = new Integer[ 100 ]; for( int i = a.length; i-- != 0; ) a[ i ] = i; ObjectArrays.shuffle( a, new Random() ); boolean[] b = new boolean[ a.length ]; for( int i = a.length; i assertFalse( b[ a[ i ] ] ); b[ a[ i ] ] = true; } } @Test public void testShuffleFragment() { Integer[] a = new Integer[ 100 ]; for( int i = a.length; i-- != 0; ) a[ i ] = -1; for( int i = 10; i < 30; i++ ) a[ i ] = i - 10; ObjectArrays.shuffle( a, 10, 30, new Random() ); boolean[] b = new boolean[ 20 ]; for( int i = 20; i assertFalse( b[ a[ i + 10 ] ] ); b[ a[ i + 10 ] ] = true; } } @Test public void testBinarySearchLargeKey() { final Integer[] a = { 1, 2, 3 }; ObjectArrays.binarySearch( a, 4 ); } @Test public void testReverse() { assertArrayEquals( new Integer[] { 0, 1, 2, 3 }, ObjectArrays.reverse( new Integer[] { 3, 2, 1, 0 } ) ); assertArrayEquals( new Integer[] { 0, 1, 2, 3, 4 }, ObjectArrays.reverse( new Integer[] { 4, 3, 2, 1, 0 } ) ); assertArrayEquals( new Integer[] { 4, 1, 2, 3, 0 }, ObjectArrays.reverse( new Integer[] { 4, 3, 2, 1, 0 }, 1, 4 ) ); assertArrayEquals( new Integer[] { 4, 2, 3, 1, 0 }, ObjectArrays.reverse( new Integer[] { 4, 3, 2, 1, 0 }, 1, 3 ) ); assertArrayEquals( new Integer[] { 0, 1, 2, 3, 4 }, ObjectArrays.reverse( new Integer[] { 0, 1, 2, 3, 4 }, 1, 2 ) ); } @Test public void testStabilize() { int[] perm; Integer[] val; perm = new int[] { 0, 1, 2, 3 }; val = new Integer[] { 0, 0, 0, 0 }; ObjectArrays.stabilize( perm, val ); assertArrayEquals( new int[] { 0, 1, 2, 3 }, perm ); perm = new int[] { 3, 1, 2, 0 }; val = new Integer[] { 0, 0, 0, 0 }; ObjectArrays.stabilize( perm, val ); assertArrayEquals( new int[] { 0, 1, 2, 3 }, perm ); perm = new int[] { 3, 2, 1, 0 }; val = new Integer[] { 0, 1, 1, 2 }; ObjectArrays.stabilize( perm, val ); assertArrayEquals( new int[] { 3, 1, 2, 0 }, perm ); perm = new int[] { 3, 2, 1, 0 }; val = new Integer[] { 0, 0, 1, 1 }; ObjectArrays.stabilize( perm, val ); assertArrayEquals( new int[] { 2, 3, 0, 1 }, perm ); perm = new int[] { 4, 3, 2, 1, 0 }; val = new Integer[] { 1, 1, 0, 0, 0 }; ObjectArrays.stabilize( perm, val, 1, 3 ); assertArrayEquals( new int[] { 4, 2, 3, 1, 0 }, perm ); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package kg.apc.jmeter.vizualizers; import java.util.Calendar; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author apc */ public class DateTimeRendererTest { public DateTimeRendererTest() { } /** * * @throws Exception */ @BeforeClass public static void setUpClass() throws Exception { } /** * * @throws Exception */ @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of setValue method, of class DateTimeRenderer. */ @Test public void testSetValue() { System.out.println("setValue"); DateTimeRenderer instance = new DateTimeRenderer("HH:mm:ss"); Calendar test = Calendar.getInstance(); test.set(Calendar.HOUR_OF_DAY, 3); test.set(Calendar.MINUTE, 16); test.set(Calendar.SECOND, 40); test.set(Calendar.MILLISECOND, 0); instance.setValue(null); assertEquals("", instance.getText()); instance.setValue(test.getTimeInMillis()); String text = instance.getText(); assertEquals("03:16:40", text); } @Test public void testConstructors() { DateTimeRenderer i1=new DateTimeRenderer(); DateTimeRenderer i2=new DateTimeRenderer("HH"); } }
package org.nutz.aop.javassist; import java.lang.reflect.Method; import java.util.Arrays; import org.junit.Test; import org.nutz.aop.Aop; import org.nutz.aop.ClassAgent; import org.nutz.aop.javassist.lstn.MethodCounter; import org.nutz.aop.javassist.lstn.RhinocerosListener; import org.nutz.aop.javassist.meta.Vegetarians; import org.nutz.aop.javassist.meta.Vegetarian.BEH; import org.nutz.aop.javassist.meta.Buffalo; import org.nutz.aop.javassist.meta.Moose; import org.nutz.aop.javassist.meta.Rhinoceros; import org.nutz.aop.javassist.meta.Hippo; import org.nutz.aop.javassist.meta.Vegetarian; import static org.junit.Assert.*; import static java.lang.reflect.Modifier.*; import org.nutz.json.Json; import org.nutz.lang.Mirror; public class JavassistClassAgentTest { @Test public void test_duplicate_class_exception() throws Exception { int[] cc = new int[4]; ClassAgent ca = getNewClassAgent(); ca.addListener(Aop.matcher(".*"), new MethodCounter(cc)); ClassAgent ca2 = getNewClassAgent(); ca2.addListener(Aop.matcher(".*"), new MethodCounter(cc)); Class<? extends Moose> c = ca.define(Moose.class); Moose m = c.newInstance(); m.doSomething(BEH.run); assertEquals("[2, 2, 0, 0]", Json.toJson(cc)); Class<? extends Moose> c2 = ca2.define(Moose.class); assertEquals(c,c2); m = c.newInstance(); m.doSomething(BEH.run); assertEquals("[4, 4, 0, 0]", Json.toJson(cc)); } @Test public void test_return_array_method() { int[] cc = new int[4]; Arrays.fill(cc, 0); ClassAgent aca = getNewClassAgent(); aca.addListener(Aop.matcher("returnArrayMethod"), new MethodCounter(cc)); Class<? extends Buffalo> c = aca.define(Buffalo.class);// RA.class; Buffalo r = Mirror.me(c).born(); String[] ss = r.returnArrayMethod(); assertEquals("[1, 1, 0, 0]", Json.toJson(cc)); assertEquals(3, ss.length); } @Test public void test_basice_matcher() throws Exception { Method method = Vegetarian.class.getDeclaredMethod("doSomething", BEH.class); assertTrue(Aop.matcher().match(method)); assertTrue(Aop.matcher(PUBLIC).match(method)); assertFalse(Aop.matcher(PROTECTED).match(method)); assertFalse(Aop.matcher(TRANSIENT).match(method)); assertFalse(Aop.matcher(PRIVATE).match(method)); method = Vegetarian.class.getDeclaredMethod("run", int.class); assertTrue(Aop.matcher().match(method)); assertFalse(Aop.matcher(PUBLIC).match(method)); assertTrue(Aop.matcher(PROTECTED).match(method)); assertFalse(Aop.matcher(TRANSIENT).match(method)); assertFalse(Aop.matcher(PRIVATE).match(method)); method = Vegetarian.class.getDeclaredMethod("defaultMethod"); assertTrue(Aop.matcher().match(method)); assertFalse(Aop.matcher(PUBLIC).match(method)); assertFalse(Aop.matcher(PROTECTED).match(method)); assertTrue(Aop.matcher(TRANSIENT).match(method)); assertFalse(Aop.matcher(PRIVATE).match(method)); method = Vegetarian.class.getDeclaredMethod("privateMethod"); assertTrue(Aop.matcher().match(method)); assertFalse(Aop.matcher(PUBLIC).match(method)); assertFalse(Aop.matcher(PROTECTED).match(method)); assertFalse(Aop.matcher(TRANSIENT).match(method)); assertTrue(Aop.matcher(PRIVATE).match(method)); } @Test public void test_basice_matcher_by_name() throws Exception { Method method = Vegetarian.class.getDeclaredMethod("doSomething", BEH.class); assertTrue(Aop.matcher("doSomething").match(method)); } @Test public void test_basice_listener() { int[] cc = new int[4]; int[] crun = new int[4]; Arrays.fill(cc, 0); Arrays.fill(crun, 0); ClassAgent aca = getNewClassAgent(); aca.addListener(Aop.matcher(".*"), new MethodCounter(cc)); aca.addListener(Aop.matcher("run"), new MethodCounter(crun)); aca.addListener(Aop.matcher("doSomething"), new RhinocerosListener()); Class<? extends Rhinoceros> c = aca.define(Rhinoceros.class);// RA.class; Rhinoceros r = Mirror.me(c).born(); r.doSomething(BEH.run); r.doSomething(BEH.fight); try { r.doSomething(BEH.lecture); fail(); } catch (Throwable e) {} try { r.doSomething(BEH.fly); fail(); } catch (Throwable e) {} assertEquals("[5, 3, 1, 1]", Json.toJson(cc)); assertEquals("[1, 1, 0, 0]", Json.toJson(crun)); } @Test public void test_basice_matcher_by_mod() { int[] cpub = new int[4]; int[] cpro = new int[4]; Arrays.fill(cpub, 0); Arrays.fill(cpro, 0); ClassAgent aca = getNewClassAgent(); aca.addListener(Aop.matcher(PUBLIC), new MethodCounter(cpub)); aca.addListener(Aop.matcher(PROTECTED), new MethodCounter(cpro)); Class<? extends Hippo> c = aca.define(Hippo.class);// RA.class; Hippo r = Mirror.me(c).born(); Vegetarians.run(r, 78); r.doSomething(BEH.run); try { r.doSomething(BEH.lecture); fail(); } catch (Throwable e) {} try { r.doSomething(BEH.fly); fail(); } catch (Throwable e) {} assertEquals("[3, 1, 1, 1]", Json.toJson(cpub)); assertEquals("[2, 2, 0, 0]", Json.toJson(cpro)); } public ClassAgent getNewClassAgent(){ return new JavassistClassAgent(); } }
package org.sagebionetworks.bridge.cache; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.sagebionetworks.bridge.cache.ViewCache.ViewCacheKey; import org.sagebionetworks.bridge.dynamodb.DynamoStudy; import org.sagebionetworks.bridge.exceptions.BridgeServiceException; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.models.studies.Study; import com.google.common.base.Supplier; import com.google.common.collect.Maps; public class ViewCacheTest { private BridgeObjectMapper mapper; private Study study; @Before public void before() { mapper = BridgeObjectMapper.get(); study = new DynamoStudy(); study.setIdentifier("testStudy"); study.setName("Test Study"); } @Test public void nothingWasCached() throws Exception { ViewCache cache = new ViewCache(); ViewCacheKey cacheKey = cache.getCacheKey(Study.class, study.getIdentifier()); CacheProvider provider = mock(CacheProvider.class); when(provider.getString(cacheKey.getKey())).thenReturn(null); cache.setCacheProvider(provider); String json = cache.getView(cacheKey, new Supplier<Study>() { @Override public Study get() { Study study = new DynamoStudy(); study.setName("Test Study 2"); return study; } }); Study foundStudy = DynamoStudy.fromJson(mapper.readTree(json)); assertEquals("Test Study 2", foundStudy.getName()); } @Test public void nothingWasCachedAndThereIsAnException() { ViewCache cache = new ViewCache(); ViewCacheKey cacheKey = cache.getCacheKey(Study.class, study.getIdentifier()); CacheProvider provider = mock(CacheProvider.class); when(provider.getString(cacheKey.getKey())).thenReturn(null); cache.setCacheProvider(provider); // It doesn't get wrapped or transformed or anything try { cache.getView(cacheKey, new Supplier<Study>() { @Override public Study get() { throw new BridgeServiceException("There has been a problem retrieving the study"); } }); fail("This should have thrown an exception"); } catch(BridgeServiceException e) { assertEquals("There has been a problem retrieving the study", e.getMessage()); } } @Test public void somethingIsCached() throws Exception { String originalStudyJson = mapper.writeValueAsString(study); ViewCache cache = new ViewCache(); ViewCacheKey cacheKey = cache.getCacheKey(Study.class, study.getIdentifier()); CacheProvider provider = mock(CacheProvider.class); when(provider.getString(cacheKey.getKey())).thenReturn(originalStudyJson); cache.setCacheProvider(provider); String json = cache.getView(cacheKey, new Supplier<Study>() { @Override public Study get() { fail("This should not be called"); return null; } }); Study foundStudy = DynamoStudy.fromJson(mapper.readTree(json)); assertEquals("Test Study", foundStudy.getName()); } @Test public void removeFromCacheWorks() throws Exception { final String originalStudyJson = mapper.writeValueAsString(study); ViewCache cache = new ViewCache(); final ViewCacheKey cacheKey = cache.getCacheKey(Study.class, study.getIdentifier()); cache.setCacheProvider(getSimpleCacheProvider(cacheKey.getKey(), originalStudyJson)); cache.removeView(cacheKey); String json = cache.getView(cacheKey, new Supplier<Study>() { @Override public Study get() { Study study = new DynamoStudy(); study.setName("Test Study 2"); return study; } }); Study foundStudy = DynamoStudy.fromJson(mapper.readTree(json)); assertEquals("Test Study 2", foundStudy.getName()); } @Test public void getCacheKeyWorks() { ViewCache cache = new ViewCache(); ViewCacheKey cacheKey = cache.getCacheKey(Study.class, "mostRandom", "leastRandom"); assertEquals("mostRandom:leastRandom:org.sagebionetworks.bridge.models.studies.Study:view", cacheKey.getKey()); } private CacheProvider getSimpleCacheProvider(final String cacheKey, final String originalStudyJson) { return new CacheProvider() { private Map<String,String> map = Maps.newHashMap(); { map.put(cacheKey, originalStudyJson); } public String getString(String cacheKey) { return map.get(cacheKey); } public void setString(String cacheKey, String value, int ttlSeconds) { map.put(cacheKey, value); } public void removeString(String cacheKey) { map.remove(cacheKey); } }; } }
package org.springframework.binding.form; import java.util.Date; import javax.swing.JTextField; import junit.framework.TestCase; import org.springframework.binding.form.support.CompoundFormModel; import org.springframework.binding.value.ValueModel; import org.springframework.binding.value.support.BufferedValueModel; import org.springframework.binding.value.support.ValueHolder; import org.springframework.context.ApplicationContext; import org.springframework.context.support.StaticApplicationContext; import org.springframework.richclient.application.Application; import org.springframework.richclient.application.ApplicationServices; import org.springframework.richclient.application.DefaultPropertyEditorRegistry; import org.springframework.richclient.application.config.BeanFactoryApplicationAdvisor; import org.springframework.richclient.forms.SwingFormModel; import org.springframework.util.ToStringBuilder; /** * * @author HP */ public class FormModelTest extends TestCase { static { Application application = new Application(new ApplicationServices(), new BeanFactoryApplicationAdvisor()); Application.services().setPropertyEditorRegistry( new DefaultPropertyEditorRegistry()); Application.services().setApplicationContext(new StaticApplicationContext()); } public static class Employee { private String name; private Employee supervisor; private Address address = new Address(); private int age; private Date hireDate; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getHireDate() { return hireDate; } public void setHireDate(Date hireDate) { this.hireDate = hireDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Employee getSupervisor() { return supervisor; } public void setSupervisor(Employee supervisor) { this.supervisor = supervisor; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String toString() { return new ToStringBuilder(this).appendProperties().toString(); } } public static class Address { private String streetAddress1; private String streetAddress2; private String city; private String state; private String zipCode; private Country country; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getStreetAddress1() { return streetAddress1; } public void setStreetAddress1(String streetAddress1) { this.streetAddress1 = streetAddress1; } public String getStreetAddress2() { return streetAddress2; } public void setStreetAddress2(String streetAddress2) { this.streetAddress2 = streetAddress2; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public String toString() { return new ToStringBuilder(this).appendProperties().toString(); } } private static class Country { private String name; private String description; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public FormModelTest() { super(); } public void testValueHolder() { ValueHolder v = new ValueHolder(); assertTrue(v.getValue() == null); Object object = new Object(); v.setValue(object); assertTrue(v.getValue() == object); } public void testBufferedValueModelCommit() { ValueHolder v = new ValueHolder("Keith"); assertTrue(v.getValue().equals("Keith")); BufferedValueModel buf = new BufferedValueModel(v); buf.setValue("Keri"); assertTrue(v.getValue().equals("Keith")); buf.commit(); assertTrue(v.getValue().equals("Keri")); } public void testCompoundFormModel() { CompoundFormModel formModel = new CompoundFormModel(new Employee()); ConfigurableFormModel supervisorModel = formModel.createChild( "supervisorPage", "supervisor"); SwingFormModel supervisorPage = new SwingFormModel(supervisorModel); JTextField field = (JTextField)supervisorPage .createBoundControl("name"); assertTrue(field.getText().equals("")); field.setText("Don"); ValueModel name = supervisorPage.getValueModel("name"); assertTrue(name.getValue().equals("Don")); supervisorPage.setEnabled(true); supervisorPage.commit(); Employee emp = (Employee)formModel.getFormObject(); assertTrue(emp.getSupervisor().getName().equals("Don")); } public void testNestedCompoundFormModel() { CompoundFormModel formModel = new CompoundFormModel(new Employee()); NestingFormModel address = formModel.createCompoundChild("AddressForm", "address"); SwingFormModel countryPage = new SwingFormModel(address.createChild( "CountryForm", "country")); JTextField field = (JTextField)countryPage.createBoundControl("name"); assertTrue(field.getText().equals("")); field.setText("USA"); ValueModel name = countryPage.getValueModel("name"); assertTrue(name.getValue().equals("USA")); countryPage.setEnabled(true); countryPage.commit(); address.commit(); Employee emp = (Employee)formModel.getFormObject(); assertTrue(emp.getAddress().getCountry().getName().equals("USA")); } public void testPageFormModel() { SwingFormModel employeePage = SwingFormModel .createFormModel(new Employee()); JTextField field = (JTextField)employeePage .createBoundControl("address.streetAddress1"); field.setText("12345 Some Lane"); employeePage.commit(); Employee emp = (Employee)employeePage.getFormObject(); assertTrue(emp.getAddress().getStreetAddress1().equals( "12345 Some Lane")); } // this fails right now - we can't exactly instantiate supervisor employee // abitrarily by default on all employees - stack overflow! public void testOptionalPageFormModel() { fail("this fails right now - we can't exactly instantiate supervisor employee abitrarily by default on all employees - stack overflow!"); SwingFormModel employeePage = SwingFormModel .createFormModel(new Employee()); JTextField field = (JTextField)employeePage .createBoundControl("supervisor.name"); field.setText("Don"); employeePage.commit(); Employee emp = (Employee)employeePage.getFormObject(); assertTrue(emp.getSupervisor().getName().equals("Don")); } }
package us.codecraft.webmagic.selector; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * Selector in regex.<br> * * @author code4crafter@gmail.com <br> * @since 0.1.0 */ public class RegexSelector implements Selector { private String regexStr; private Pattern regex; private int group = 1; public RegexSelector(String regexStr, int group) { if (StringUtils.isBlank(regexStr)) { throw new IllegalArgumentException("regex must not be empty"); } // Check bracket for regex group. Add default group 1 if there is no group. // Only check if there exists the valid left parenthesis, leave regexp validation for Pattern. if ( ! hasGroup(regexStr) ){ regexStr = "(" + regexStr + ")"; } this.regexStr = regexStr; try { regex = Pattern.compile(regexStr, Pattern.DOTALL | Pattern.CASE_INSENSITIVE); } catch (PatternSyntaxException e) { throw new IllegalArgumentException("invalid regex", e); } this.group = group; } public RegexSelector(String regexStr) { this(regexStr, 1); } private boolean hasGroup(String regexStr) { int x = StringUtils.countMatches(regexStr, "(") - StringUtils.countMatches(regexStr, "\\("); int a = StringUtils.countMatches(regexStr, "(?:") - StringUtils.countMatches(regexStr, "\\(?:"); int b = StringUtils.countMatches(regexStr, "(?=") - StringUtils.countMatches(regexStr, "\\(?="); int c = StringUtils.countMatches(regexStr, "(?<") - StringUtils.countMatches(regexStr, "\\(?<"); int d = StringUtils.countMatches(regexStr, "(?!") - StringUtils.countMatches(regexStr, "\\(?!"); int e = StringUtils.countMatches(regexStr, "(?#") - StringUtils.countMatches(regexStr, "\\(?#"); if (x == (a + b + c + d + e)) { return false; } return true; } @Override public String select(String text) { return selectGroup(text).get(group); } @Override public List<String> selectList(String text) { List<String> strings = new ArrayList<String>(); List<RegexResult> results = selectGroupList(text); for (RegexResult result : results) { strings.add(result.get(group)); } return strings; } public RegexResult selectGroup(String text) { Matcher matcher = regex.matcher(text); if (matcher.find()) { String[] groups = new String[matcher.groupCount() + 1]; for (int i = 0; i < groups.length; i++) { groups[i] = matcher.group(i); } return new RegexResult(groups); } return RegexResult.EMPTY_RESULT; } public List<RegexResult> selectGroupList(String text) { Matcher matcher = regex.matcher(text); List<RegexResult> resultList = new ArrayList<RegexResult>(); while (matcher.find()) { String[] groups = new String[matcher.groupCount() + 1]; for (int i = 0; i < groups.length; i++) { groups[i] = matcher.group(i); } resultList.add(new RegexResult(groups)); } return resultList; } @Override public String toString() { return regexStr; } }
package com.wegas.core.ejb; import static com.wegas.core.ejb.AbstractEJBTest.gameModel; import static com.wegas.core.ejb.AbstractEJBTest.gameModelFacade; import static com.wegas.core.ejb.AbstractEJBTest.lookupBy; import static com.wegas.core.ejb.AbstractEJBTest.player; import com.wegas.core.exception.internal.WegasNoResultException; import com.wegas.core.persistence.game.GameModel; import com.wegas.core.persistence.variable.DescriptorListI; import com.wegas.core.persistence.variable.ListDescriptor; import com.wegas.core.persistence.variable.ListInstance; import com.wegas.core.persistence.variable.VariableDescriptor; import com.wegas.core.persistence.variable.primitive.*; import com.wegas.core.persistence.variable.scope.GameModelScope; import java.util.Collection; import java.util.List; import javax.naming.NamingException; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Francois-Xavier Aeberhard (fx at red-agent.com) */ public class VariableDescriptorFacadeTest extends AbstractEJBTest { private static final Logger logger = LoggerFactory.getLogger(VariableDescriptorFacadeTest.class); @Test public void testDoubleReset() throws NamingException, WegasNoResultException { VariableDescriptorFacade vdf = lookupBy(VariableDescriptorFacade.class); // Test the descriptor NumberDescriptor desc1 = new NumberDescriptor("x"); desc1.setDefaultInstance(new NumberInstance(0)); vdf.create(gameModel.getId(), desc1); gameModelFacade.reset(gameModel.getId()); vdf.update(desc1.getId(), desc1); gameModelFacade.reset(gameModel.getId()); gameModelFacade.reset(gameModel.getId()); vdf.remove(desc1.getId()); } @Test public void testNumberDescriptor() throws NamingException, WegasNoResultException { final String VARIABLENAME = "test-variable"; final String VARIABLENAME2 = "test-variable2"; final double VAL1 = 0; final double VAL2 = 1; final double VAL3 = 2; VariableDescriptorFacade vdf = lookupBy(VariableDescriptorFacade.class); VariableInstanceFacade vif = lookupBy(VariableInstanceFacade.class); // Test the descriptor NumberDescriptor desc1 = new NumberDescriptor(VARIABLENAME); desc1.setDefaultInstance(new NumberInstance(VAL1)); NumberDescriptor desc2 = new NumberDescriptor(VARIABLENAME2); desc2.setDefaultInstance(new NumberInstance(VAL2)); this.testVariableDescriptor(desc1, desc2); // Check its value NumberInstance instance = (NumberInstance) vif.find(desc1.getId(), player); Assert.assertEquals(VAL2, instance.getValue(), 0.0001); // Edit the variable instance NumberInstance newNumberInstance = new NumberInstance(VAL3); newNumberInstance.setVersion(instance.getVersion()); vif.update(desc1.getId(), player.getId(), newNumberInstance); // Verify the new value instance = (NumberInstance) vif.find(desc1.getId(), player.getId()); Assert.assertEquals(VAL3, instance.getValue(), 0.0001); // Reset the game and test gameModelFacade.reset(gameModel.getId()); instance = (NumberInstance) vif.find(desc1.getId(), player); Assert.assertEquals(VAL2, instance.getValue(), 0.0001); vdf.remove(desc1.getId()); } @Test public void testStringDescriptor() throws NamingException, WegasNoResultException { final String VARIABLENAME = "test-variable"; final String VARIABLENAME2 = "test-variable2"; final String VALUE1 = "test-value"; final String VALUE2 = "test-value2"; final String VALUE3 = "test-value3"; VariableDescriptorFacade vdf = lookupBy(VariableDescriptorFacade.class); VariableInstanceFacade vif = lookupBy(VariableInstanceFacade.class); // Test the descriptor StringDescriptor stringDescriptor = new StringDescriptor(VARIABLENAME); stringDescriptor.setDefaultInstance(new StringInstance(VALUE1)); StringDescriptor stringDescriptor2 = new StringDescriptor(VARIABLENAME2); stringDescriptor2.setDefaultInstance(new StringInstance(VALUE2)); this.testVariableDescriptor(stringDescriptor, stringDescriptor2); // Check its value StringInstance instance = (StringInstance) vif.find(stringDescriptor.getId(), player); Assert.assertEquals(VALUE2, instance.getValue()); // Edit the variable instance StringInstance newStringInstance = new StringInstance(VALUE3); newStringInstance.setVersion(instance.getVersion()); vif.update(stringDescriptor.getId(), player.getId(), newStringInstance); // Verify the new value instance = (StringInstance) vif.find(stringDescriptor.getId(), player.getId()); Assert.assertEquals(VALUE3, instance.getValue()); // Reset the game and test gameModelFacade.reset(gameModel.getId()); instance = (StringInstance) vif.find(stringDescriptor.getId(), player); Assert.assertEquals(VALUE2, instance.getValue()); vdf.remove(stringDescriptor.getId()); } @Test public void testBooleanDescriptor() throws NamingException, WegasNoResultException { final String VARIABLENAME = "test-variable"; final String VARIABLENAME2 = "test-variable2"; VariableDescriptorFacade vdf = lookupBy(VariableDescriptorFacade.class); VariableInstanceFacade vif = lookupBy(VariableInstanceFacade.class); // Test the descriptor BooleanDescriptor booleanDescriptor = new BooleanDescriptor(VARIABLENAME); booleanDescriptor.setDefaultInstance(new BooleanInstance(true)); BooleanDescriptor booleanDescriptor2 = new BooleanDescriptor(VARIABLENAME2); booleanDescriptor2.setDefaultInstance(new BooleanInstance(false)); this.testVariableDescriptor(booleanDescriptor, booleanDescriptor2); // Check its value BooleanInstance instance = (BooleanInstance) vif.find(booleanDescriptor.getId(), player); Assert.assertEquals(false, instance.getValue()); // Edit the variable instance BooleanInstance newInstance = new BooleanInstance(true); newInstance.setVersion(instance.getVersion()); vif.update(booleanDescriptor.getId(), player.getId(), newInstance); // Verify the new value instance = (BooleanInstance) vif.find(booleanDescriptor.getId(), player.getId()); Assert.assertEquals(true, instance.getValue()); // Reset the game and test gameModelFacade.reset(gameModel.getId()); instance = (BooleanInstance) vif.find(booleanDescriptor.getId(), player); Assert.assertEquals(false, instance.getValue()); vdf.remove(booleanDescriptor.getId()); } @Test public void testGameModelScope() throws NamingException { final String VARIABLENAME = "test-variable"; VariableDescriptorFacade vdf = lookupBy(VariableDescriptorFacade.class); VariableInstanceFacade vif = lookupBy(VariableInstanceFacade.class); // Test the descriptor BooleanDescriptor desc = new BooleanDescriptor(VARIABLENAME); desc.setDefaultInstance(new BooleanInstance(true)); desc.setScope(new GameModelScope()); vdf.create(gameModel.getId(), desc); gameModelFacade.reset(gameModel.getId()); Assert.assertEquals(desc.getId(), vif.find(desc.getId(), player).getDescriptorId()); // Check its value BooleanInstance instance = (BooleanInstance) vif.find(desc.getId(), player); Assert.assertEquals(true, instance.getValue()); // Edit the variable instance //vif.update(desc.getId(), player.getId(), new BooleanInstance(true)); // Verify the new value //instance = (BooleanInstance) vif.find(desc.getId(), player.getId()); //Assert.assertEquals(true, instance.getValue()); // Reset the game and test // gameModelFacade.reset(gameModel.getId()); // instance = (BooleanInstance) vif.find(desc.getId(), player); // Assert.assertEquals(false, instance.getValue()); vdf.remove(desc.getId()); } public <T extends VariableDescriptor> T testVariableDescriptor(T descriptor1, T descriptor2) throws NamingException, WegasNoResultException { final String VARIABLENAME2 = "test-variable2"; VariableDescriptorFacade vdf = lookupBy(VariableDescriptorFacade.class); // Create the descriptor logger.info("" + descriptor1 + "*" + descriptor2); vdf.create(gameModel.getId(), descriptor1); gameModelFacade.reset(gameModel.getId()); // Edit this descriptor descriptor1 = (T) vdf.find(descriptor1.getId()); /* * update against up-to-date version */ descriptor2.setVersion(descriptor1.getVersion()); descriptor2.getDefaultInstance().setVersion(descriptor1.getDefaultInstance().getVersion()); vdf.update(descriptor1.getId(), descriptor2); // Edit this descriptor descriptor1 = (T) vdf.find(descriptor1.getId()); gameModelFacade.reset(gameModel.getId()); // Check edition T findByName = (T) vdf.find(gameModel, VARIABLENAME2); Assert.assertEquals(descriptor1.getId(), findByName.getId()); Assert.assertEquals(descriptor2.getName(), findByName.getName()); // Check the findByClass Function T findByClass = (T) vdf.findByClass(gameModel, descriptor1.getClass()).get(0); Assert.assertEquals(descriptor1.getId(), findByClass.getId()); // Check the findByGameModel function Collection<VariableDescriptor> findByRootGameModelId = vdf.findAll(gameModel.getId()); Assert.assertTrue(findByRootGameModelId.contains(descriptor1)); return descriptor1; } @Test public void testMove2P() throws NamingException, WegasNoResultException { final String VARIABLENAME = "test-variable"; final String VARIABLENAME2 = "test-variable2"; final double VAL1 = 0; final double VAL2 = 1; final double VAL3 = 2; VariableDescriptorFacade vdf = lookupBy(VariableDescriptorFacade.class); VariableInstanceFacade vif = lookupBy(VariableInstanceFacade.class); // Test the descriptor NumberDescriptor desc1 = new NumberDescriptor(VARIABLENAME); desc1.setDefaultInstance(new NumberInstance(VAL1)); NumberDescriptor desc2 = new NumberDescriptor(VARIABLENAME2); desc2.setDefaultInstance(new NumberInstance(VAL2)); this.testVariableDescriptor(desc1, desc2); // Check its value NumberInstance instance = (NumberInstance) vif.find(desc1.getId(), player); Assert.assertEquals(VAL2, instance.getValue(), 0.0001); // Edit the variable instance NumberInstance newInstance = new NumberInstance(VAL3); newInstance.setVersion(instance.getVersion()); vif.update(desc1.getId(), player.getId(), newInstance); // Verify the new value instance = (NumberInstance) vif.find(desc1.getId(), player.getId()); Assert.assertEquals(VAL3, instance.getValue(), 0.0001); // Reset the game and test gameModelFacade.reset(gameModel.getId()); instance = (NumberInstance) vif.find(desc1.getId(), player); Assert.assertEquals(VAL2, instance.getValue(), 0.0001); vdf.remove(desc1.getId()); } @Test public void testMove2() throws NamingException { final String VARIABLENAME = "test_variable"; final String VARIABLENAME2 = "test_variable2"; final String VARIABLENAME3 = "test_variable3"; final String SUBNAME1 = "test_variable4"; final String VALUE1 = "test_value"; VariableDescriptorFacade vdf = lookupBy(VariableDescriptorFacade.class); GameModel gm; // 1st case: move from root to root StringDescriptor vd1 = new StringDescriptor(VARIABLENAME); vd1.setDefaultInstance(new StringInstance(VALUE1)); vdf.create(gameModel.getId(), vd1); gm = gameModelFacade.find(gameModel.getId()); Assert.assertEquals(1, gm.getChildVariableDescriptors().size()); Assert.assertEquals(1, gm.getVariableDescriptors().size()); //gm = gameModelFacade.find(gameModel.getId()); StringDescriptor vd2 = new StringDescriptor(VARIABLENAME2); vd2.setDefaultInstance(new StringInstance(VALUE1)); vdf.create(gameModel.getId(), vd2); gm = gameModelFacade.find(gameModel.getId()); Assert.assertEquals(2, gm.getChildVariableDescriptors().size()); Assert.assertEquals(2, gm.getVariableDescriptors().size()); vdf.move(vd1.getId(), 1); // Move first item to second position List<VariableDescriptor> findByGameModelId = vdf.findByGameModelId(gameModel.getId());// Refresh Assert.assertEquals(VARIABLENAME, findByGameModelId.get(1).getName()); // 2nd case: from list to root ListDescriptor vd3 = new ListDescriptor(VARIABLENAME3); vd3.setDefaultInstance(new ListInstance()); vdf.create(gameModel.getId(), vd3); gm = gameModelFacade.find(gameModel.getId()); Assert.assertEquals(3, gm.getChildVariableDescriptors().size()); Assert.assertEquals(3, gm.getVariableDescriptors().size()); StringDescriptor sub1 = new StringDescriptor(SUBNAME1); sub1.setDefaultInstance(new StringInstance(VALUE1)); vdf.createChild(vd3.getId(), sub1); gm = gameModelFacade.find(gameModel.getId()); // The last one in not at root level: Assert.assertEquals(3, gm.getChildVariableDescriptors().size()); Assert.assertEquals(4, gm.getVariableDescriptors().size()); findByGameModelId = vdf.findByGameModelId(gameModel.getId()); // Refresh Assert.assertEquals(SUBNAME1, ((ListDescriptor) findByGameModelId.get(2)).item(0).getName()); vdf.move(sub1.getId(), 0); // Move at first position gm = gameModelFacade.find(gameModel.getId()); // now, it is: Assert.assertEquals(4, gm.getChildVariableDescriptors().size()); Assert.assertEquals(4, gm.getVariableDescriptors().size()); findByGameModelId = vdf.findByGameModelId(gameModel.getId()); // Refresh Assert.assertEquals(SUBNAME1, findByGameModelId.get(0).getName()); Assert.assertEquals(0, ((ListDescriptor) findByGameModelId.get(3)).size()); vdf.remove(vd1.getId()); gm = gameModelFacade.find(gameModel.getId()); Assert.assertEquals(3, gm.getVariableDescriptors().size()); Assert.assertEquals(3, gm.getChildVariableDescriptors().size()); vdf.remove(vd2.getId()); gm = gameModelFacade.find(gameModel.getId()); Assert.assertEquals(2, gm.getVariableDescriptors().size()); Assert.assertEquals(2, gm.getChildVariableDescriptors().size()); vdf.remove(vd3.getId()); gm = gameModelFacade.find(gameModel.getId()); Assert.assertEquals(1, gm.getVariableDescriptors().size()); Assert.assertEquals(1, gm.getChildVariableDescriptors().size()); vdf.remove(sub1.getId()); gm = gameModelFacade.find(gameModel.getId()); Assert.assertEquals(0, gm.getVariableDescriptors().size()); Assert.assertEquals(0, gm.getChildVariableDescriptors().size()); } @Test public void testMove3P() throws NamingException { final String VARIABLENAME1 = "test_variable"; final String VARIABLENAME2 = "test_variable2"; final String VARIABLENAME3 = "test_variable4"; final String LISTNAME1 = "test_variable3"; final String LISTNAME2 = "test_variable3dasdas"; final String VALUE1 = "test_value"; VariableDescriptorFacade vdf = lookupBy(VariableDescriptorFacade.class); GameModel gm; // 1st case: move from descriptor to descriptor ListDescriptor list1 = new ListDescriptor(LISTNAME1); list1.setDefaultInstance(new ListInstance()); vdf.create(gameModel.getId(), list1); gm = gameModelFacade.find(gameModel.getId()); Assert.assertEquals(1, gm.getVariableDescriptors().size()); Assert.assertEquals(1, gm.getChildVariableDescriptors().size()); StringDescriptor vd1 = new StringDescriptor(VARIABLENAME1); vd1.setDefaultInstance(new StringInstance(VALUE1)); vdf.createChild(list1.getId(), vd1); gm = gameModelFacade.find(gameModel.getId()); Assert.assertEquals(2, gm.getVariableDescriptors().size()); Assert.assertEquals(1, gm.getChildVariableDescriptors().size()); StringDescriptor vd2 = new StringDescriptor(VARIABLENAME2); vd2.setDefaultInstance(new StringInstance(VALUE1)); vdf.createChild(list1.getId(), vd2); List<VariableDescriptor> childrenDescriptors = vdf.findByGameModelId(gameModel.getId()); Assert.assertEquals(VARIABLENAME1, ((ListDescriptor) childrenDescriptors.get(0)).item(0).getName());// Check if item was successfully added gm = gameModelFacade.find(gameModel.getId()); Assert.assertEquals(3, gm.getVariableDescriptors().size()); Assert.assertEquals(1, gm.getChildVariableDescriptors().size()); vdf.move(vd1.getId(), list1.getId(), 1); // Move first item to second position childrenDescriptors = vdf.findByGameModelId(gameModel.getId()); // Refresh Assert.assertEquals(VARIABLENAME2, ((ListDescriptor) childrenDescriptors.get(0)).item(0).getName()); // 2nd case: from root to descriptor StringDescriptor vd3 = new StringDescriptor(VARIABLENAME3); vd3.setDefaultInstance(new StringInstance(VALUE1)); vdf.create(gameModel.getId(), vd3); vdf.move(vd3.getId(), list1.getId(), 0); // Move first item to index 0 childrenDescriptors = vdf.findByGameModelId(gameModel.getId()); // Refresh Assert.assertEquals(VARIABLENAME3, ((ListDescriptor) childrenDescriptors.get(0)).item(0).getName()); Assert.assertEquals(1, childrenDescriptors.size()); // 3rd case: from one descriptor to another ListDescriptor list2 = new ListDescriptor(LISTNAME2); list2.setDefaultInstance(new ListInstance()); vdf.create(gameModel.getId(), list2); vdf.move(vd3.getId(), list2.getId(), 0); // Move first item to index 0 childrenDescriptors = vdf.findByGameModelId(gameModel.getId()); // Refresh Assert.assertEquals(VARIABLENAME3, ((ListDescriptor) childrenDescriptors.get(1)).item(0).getName()); Assert.assertEquals(2, ((ListDescriptor) childrenDescriptors.get(0)).size()); vdf.remove(vd1.getId()); // Clean up vdf.remove(vd2.getId()); vdf.remove(vd3.getId()); vdf.remove(list1.getId()); vdf.remove(list2.getId()); } @Test public void testListDuplicate() throws NamingException, CloneNotSupportedException, WegasNoResultException { final String VARIABLENAME1 = "test_variable"; final String LISTNAME1 = "list1"; final String LISTNAME2 = "list2"; final String LISTNAME3 = "list3"; final String LISTNAME4 = "list4"; VariableDescriptorFacade vdf = lookupBy(VariableDescriptorFacade.class); ListDescriptor list1 = new ListDescriptor(LISTNAME1, new ListInstance());// Create a hierarchy of lists vdf.create(gameModel.getId(), list1); ListDescriptor list2 = new ListDescriptor(LISTNAME2, new ListInstance()); vdf.createChild(list1.getId(), list2); ListDescriptor list3 = new ListDescriptor(LISTNAME3, new ListInstance()); vdf.createChild(list1.getId(), list3); ListDescriptor list4 = new ListDescriptor(LISTNAME4, new ListInstance()); vdf.createChild(list3.getId(), list4); NumberDescriptor nb = new NumberDescriptor(VARIABLENAME1, new NumberInstance(10)); vdf.createChild(list4.getId(), nb); DescriptorListI duplicate = (DescriptorListI) vdf.duplicate(list1.getId()); // Duplicate a root variable Assert.assertEquals(10.0, ((NumberDescriptor) ((DescriptorListI) ((DescriptorListI) duplicate.item(1)).item(0)).item(0)).getInstance(player).getValue(), 0.0001); duplicate = (DescriptorListI) vdf.duplicate(list3.getId()); // Duplicate a sub child variable Assert.assertEquals(10.0, ((NumberDescriptor) ((DescriptorListI) duplicate.item(0)).item(0)).getInstance(player).getValue(), 0.0001); GameModel duplicateGm = gameModelFacade.duplicateWithDebugGame(gameModel.getId()); DescriptorListI find = (DescriptorListI) vdf.find(duplicateGm, LISTNAME1); Assert.assertEquals(10.0, ((NumberInstance) ((DescriptorListI) ((DescriptorListI) find.item(1)).item(0)).item(0).getScope().getVariableInstances().values().iterator().next()).getValue(), 0.0001); } }
package mms.Pluginsystem.Impl; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.ResourceBundle; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.binding.Bindings; import javafx.beans.property.DoubleProperty; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.MenuBar; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaView; import mms.Pluginsystem.PluginInterface; import mms.Pluginsystem.PluginManagerInterface; public class PluginManager implements Initializable, PluginManagerInterface { @FXML private StackPane stackPane; @FXML private MediaView mediaView; @FXML private MenuBar menuBar; private final List<PluginInterface> loadedPlugins = new ArrayList<>(); /** * Initializes the controller class. * * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { DoubleProperty width = mediaView.fitWidthProperty(); DoubleProperty height = mediaView.fitHeightProperty(); width.bind(Bindings.selectDouble(mediaView.sceneProperty(), "width")); height.bind(Bindings.selectDouble(mediaView.sceneProperty(), "height")); //Load plugins start(); PluginManager manager = this; //Will be called on program exit Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { manager.stop(); } }); } public void start() { File[] files = new File("Plugins").listFiles(); for (File f : files) { loadPlugin(f); } loadedPlugins.stream().forEach((pi) -> { pi.setPluginManager(this); pi.start(); }); } public void stop() { loadedPlugins.stream().forEach((pi) -> { pi.stop(); }); } public void loadPlugin(File file) { try { //Create the JAR-object JarFile jar = new JarFile(file); String entryName; Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { entryName = entries.nextElement().getName(); if (entryName.endsWith(".class")) { //Load class URLClassLoader loader = new URLClassLoader(new URL[]{file.toURI().toURL()}); //Delete .class and replace / with . String className = entryName.substring(0, entryName.length() - 6).replace('/', '.'); //Load class Class cl = loader.loadClass(className); loader.close(); //Check implemented interfaces (should implement our PluginInterface) if (PluginInterface.class.isAssignableFrom(cl)) { loadedPlugins.add((PluginInterface) cl.newInstance()); break; } } } jar.close(); } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { Logger.getLogger(PluginManager.class.getName()).log(Level.SEVERE, null, ex); } } / @Override public void addToGUI(Pane pane) { stackPane.getChildren().add(pane); } @Override public MenuBar getMenuBar() { return menuBar; } @Override public void setPlayer(MediaPlayer player) { mediaView.setMediaPlayer(player); } / }
package net.wigle.wigleandroid; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.SQLException; import android.graphics.Color; import android.location.Location; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import androidx.fragment.app.DialogFragment; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.text.ClipboardManager; import android.text.InputType; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.material.textfield.TextInputEditText; import com.google.gson.Gson; import net.wigle.wigleandroid.background.QueryThread; import net.wigle.wigleandroid.db.DatabaseHelper; import net.wigle.wigleandroid.model.ConcurrentLinkedHashMap; import net.wigle.wigleandroid.model.MccMncRecord; import net.wigle.wigleandroid.model.Network; import net.wigle.wigleandroid.model.NetworkType; import net.wigle.wigleandroid.model.OUI; import net.wigle.wigleandroid.ui.NetworkListUtil; @SuppressWarnings("deprecation") public class NetworkActivity extends AppCompatActivity implements DialogListener { private static final int MENU_RETURN = 11; private static final int MENU_COPY = 12; private static final int NON_CRYPTO_DIALOG = 130; private static final int MSG_OBS_UPDATE = 1; private static final int MSG_OBS_DONE = 2; private static final int DEFAULT_ZOOM = 18; private Network network; private MapView mapView; private int observations = 0; private boolean isDbResult = false; private final ConcurrentLinkedHashMap<LatLng, Integer> obsMap = new ConcurrentLinkedHashMap<>(512); // used for shutting extraneous activities down on an error public static NetworkActivity networkActivity; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { MainActivity.info("NET: onCreate"); super.onCreate(savedInstanceState); if (ListFragment.lameStatic.oui == null) { ListFragment.lameStatic.oui = new OUI(getAssets()); } final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } // set language MainActivity.setLocale( this ); setContentView(R.layout.network); networkActivity = this; final Intent intent = getIntent(); final String bssid = intent.getStringExtra( ListFragment.NETWORK_EXTRA_BSSID ); isDbResult = intent.getBooleanExtra(ListFragment.NETWORK_EXTRA_IS_DB_RESULT, false); MainActivity.info( "bssid: " + bssid + " isDbResult: " + isDbResult); final SimpleDateFormat format = NetworkListUtil.getConstructionTimeFormater(this); if (null != MainActivity.getNetworkCache()) { network = MainActivity.getNetworkCache().get(bssid); } TextView tv = findViewById( R.id.bssid ); tv.setText( bssid ); if ( network == null ) { MainActivity.info( "no network found in cache for bssid: " + bssid ); } else { // do gui work tv = findViewById( R.id.ssid ); tv.setText( network.getSsid() ); final String ouiString = network.getOui(ListFragment.lameStatic.oui); tv = findViewById( R.id.oui ); tv.setText( ouiString ); final int image = NetworkListUtil.getImage( network ); final ImageView ico = findViewById( R.id.wepicon ); ico.setImageResource( image ); final ImageView btico = findViewById(R.id.bticon); if (NetworkType.BT.equals(network.getType()) || NetworkType.BLE.equals(network.getType())) { btico.setVisibility(View.VISIBLE); Integer btImageId = NetworkListUtil.getBtImage(network); if (null == btImageId) { btico.setVisibility(View.GONE); } else { btico.setImageResource(btImageId); } } else { btico.setVisibility(View.GONE); } tv = findViewById( R.id.na_signal ); final int level = network.getLevel(); tv.setTextColor( NetworkListUtil.getSignalColor( level ) ); tv.setText( Integer.toString( level ) ); tv = findViewById( R.id.na_type ); tv.setText( network.getType().name() ); tv = findViewById( R.id.na_firsttime ); tv.setText( NetworkListUtil.getConstructionTime(format, network ) ); tv = findViewById( R.id.na_chan ); Integer chan = network.getChannel(); if ( NetworkType.WIFI.equals(network.getType()) ) { chan = chan != null ? chan : network.getFrequency(); tv.setText(" " + Integer.toString(chan) + " "); } else if ( NetworkType.CDMA.equals(network.getType()) || chan == null) { tv.setText( getString(R.string.na) ); } else { final String[] cellCapabilities = network.getCapabilities().split(";"); tv.setText(cellCapabilities[0]+" "+channelCodeTypeForNetworkType(network.getType())+" "+chan); } tv = findViewById( R.id.na_cap ); tv.setText( " " + network.getCapabilities().replace("][", "] [") ); if ( NetworkType.GSM.equals(network.getType()) || NetworkType.LTE.equals(network.getType()) || NetworkType.WCDMA.equals(network.getType())) { // cell net types with advanced data if ((bssid != null) && (bssid.length() > 5) && (bssid.indexOf('_') >= 5)) { final String operatorCode = bssid.substring(0, bssid.indexOf("_")); MccMncRecord rec = null; if (operatorCode.length() > 5 && operatorCode.length() < 7) { final String mnc = operatorCode.substring(3, operatorCode.length()); final String mcc = operatorCode.substring(0, 3); //DEBUG: MainActivity.info("\t\tmcc: "+mcc+"; mnc: "+mnc); try { rec = MainActivity.getStaticState().mxcDbHelper.networkRecordForMccMnc(mcc, mnc); } catch (SQLException sqex) { MainActivity.error("Unable to access Mxc Database: ",sqex); } if (rec != null) { View v = findViewById(R.id.cell_info); v.setVisibility(View.VISIBLE); tv = findViewById( R.id.na_cell_status ); tv.setText( " "+rec.getStatus() ); tv = findViewById( R.id.na_cell_brand ); tv.setText( " "+rec.getBrand()); tv = findViewById( R.id.na_cell_bands ); tv.setText( " "+rec.getBands()); if (rec.getNotes() != null && !rec.getNotes().isEmpty()) { v = findViewById(R.id.cell_notes_row); v.setVisibility(View.VISIBLE); tv = findViewById( R.id.na_cell_notes ); tv.setText( " "+rec.getNotes()); } } } } else { MainActivity.warn("unable to get operatorCode for "+bssid); } } setupMap( network, savedInstanceState ); // kick off the query now that we have our map setupQuery(); setupButtons( network ); } } @Override public void onDestroy() { MainActivity.info("NET: onDestroy"); networkActivity = null; if (mapView != null) { mapView.onDestroy(); } super.onDestroy(); } @Override public void onResume() { MainActivity.info("NET: onResume"); super.onResume(); if (mapView != null) { mapView.onResume(); } else { setupMap( network, null ); } } @Override public void onPause() { MainActivity.info("NET: onPause"); super.onPause(); if (mapView != null) { mapView.onPause(); } } @Override public void onSaveInstanceState(final Bundle outState) { MainActivity.info("NET: onSaveInstanceState"); super.onSaveInstanceState(outState); if (mapView != null) { try { mapView.onSaveInstanceState(outState); } catch (android.os.BadParcelableException bpe) { MainActivity.error("Exception saving NetworkActivity instance state: ",bpe); //this is really low-severity, since we can restore all state anyway } } } @Override public void onLowMemory() { MainActivity.info("NET: onLowMemory"); super.onLowMemory(); if (mapView != null) { mapView.onLowMemory(); } } @SuppressLint("HandlerLeak") private void setupQuery() { // what runs on the gui thread final Handler handler = new Handler() { @Override public void handleMessage( final Message msg ) { final TextView tv = findViewById( R.id.na_observe ); if ( msg.what == MSG_OBS_UPDATE ) { tv.setText( " " + Integer.toString( observations ) + "..."); } else if ( msg.what == MSG_OBS_DONE ) { tv.setText( " " + Integer.toString( observations ) ); // ALIBI: assumes all observations belong to one "cluster" w/ a single centroid. // we could check and perform multi-cluster here // (get arithmetic mean, std-dev, try to do sigma-based partitioning) // but that seems less likely w/ one individual's observations final LatLng estCentroid = computeBasicLocation(obsMap); final int zoomLevel = computeZoom(obsMap, estCentroid); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(final GoogleMap googleMap) { int count = 0; int maxDistMeters = 0; for (Map.Entry<LatLng, Integer> obs : obsMap.entrySet()) { final LatLng latLon = obs.getKey(); final int level = obs.getValue(); // default to initial position if (count == 0 && network.getLatLng() == null) { final CameraPosition cameraPosition = new CameraPosition.Builder() .target(latLon).zoom(DEFAULT_ZOOM).build(); googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } BitmapDescriptor obsIcon = NetworkListUtil.getSignalBitmap( getApplicationContext(), level); googleMap.addMarker(new MarkerOptions().icon(obsIcon) .position(latLon).zIndex(level)); count++; } // if we got a good centroid, display it and center on it if (null != estCentroid && estCentroid.latitude != 0d && estCentroid.longitude != 0d) { //TODO: improve zoom based on obs distances? final CameraPosition cameraPosition = new CameraPosition.Builder() .target(estCentroid).zoom(zoomLevel).build(); googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); googleMap.addMarker(new MarkerOptions().position(estCentroid)); } MainActivity.info("observation count: " + count); } }); } } }; final String sql = "SELECT level,lat,lon FROM " + DatabaseHelper.LOCATION_TABLE + " WHERE bssid = '" + network.getBssid() + "' ORDER BY _id DESC limit " + obsMap.maxSize(); final QueryThread.Request request = new QueryThread.Request( sql, new QueryThread.ResultHandler() { @Override public boolean handleRow( final Cursor cursor ) { observations++; obsMap.put( new LatLng( cursor.getFloat(1), cursor.getFloat(2) ), cursor.getInt(0) ); if ( ( observations % 10 ) == 0 ) { // change things on the gui thread handler.sendEmptyMessage( MSG_OBS_UPDATE ); } return true; } @Override public void complete() { handler.sendEmptyMessage( MSG_OBS_DONE ); } }); ListFragment.lameStatic.dbHelper.addToQueue( request ); } private final LatLng computeBasicLocation(ConcurrentLinkedHashMap<LatLng, Integer> obsMap) { double latSum = 0.0; double lonSum = 0.0; double weightSum = 0.0; for (Map.Entry<LatLng, Integer> obs : obsMap.entrySet()) { if (null != obs.getKey()) { float cleanSignal = cleanSignal((float) obs.getValue()); cleanSignal *= cleanSignal; latSum += (obs.getKey().latitude * cleanSignal); lonSum += (obs.getKey().longitude * cleanSignal); weightSum += cleanSignal; } } double trilateratedLatitude = 0; double trilateratedLongitude = 0; if (weightSum > 0) { trilateratedLatitude = latSum / weightSum; trilateratedLongitude = lonSum / weightSum; } return new LatLng(trilateratedLatitude, trilateratedLongitude); } private final int computeZoom(ConcurrentLinkedHashMap<LatLng, Integer> obsMap, final LatLng centroid) { float maxDist = 0f; for (Map.Entry<LatLng, Integer> obs : obsMap.entrySet()) { float[] res = new float[3]; Location.distanceBetween(centroid.latitude, centroid.longitude, obs.getKey().latitude, obs.getKey().longitude, res); if(res[0] > maxDist) { maxDist = res[0]; } } MainActivity.info("max dist: "+maxDist); if (maxDist < 135) { return 18; } else if (maxDist < 275) { return 17; } else if (maxDist < 550) { return 16; } else if (maxDist < 1100) { return 15; } else if (maxDist < 2250) { return 14; } else if (maxDist < 4500) { return 13; } else if (maxDist < 9000) { return 12; } else if (maxDist < 18000) { return 11; } else if (maxDist < 36000) { // ALiBI: cells can be this big. return 10; } else { return DEFAULT_ZOOM; } } /** * optimistic signal weighting * @param signal * @return */ public static float cleanSignal(Float signal) { float signalMemo = signal; if (signal == null || signal == 0f) { return 100f; } else if (signal >= -200 && signal < 0) { signalMemo += 200f; } else if (signal <= 0 || signal > 200) { signalMemo = 100f; } if (signalMemo < 1f) { signalMemo = 1f; } return signalMemo; } private void setupMap( final Network network, final Bundle savedInstanceState ) { mapView = new MapView( this ); try { mapView.onCreate(savedInstanceState); } catch (NullPointerException ex) { MainActivity.error("npe in mapView.onCreate: " + ex, ex); } MapsInitializer.initialize( this ); if ((network != null) && (network.getLatLng() != null)) { mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(final GoogleMap googleMap) { final CameraPosition cameraPosition = new CameraPosition.Builder() .target(network.getLatLng()).zoom(DEFAULT_ZOOM).build(); googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); googleMap.addCircle(new CircleOptions() .center(network.getLatLng()) .radius(5) .fillColor(Color.argb(128, 240, 240, 240)) .strokeColor(Color.argb(200, 255, 32, 32)) .strokeWidth(3f) .zIndex(100)); } }); } final RelativeLayout rlView = findViewById( R.id.netmap_rl ); rlView.addView( mapView ); } private void setupButtons( final Network network ) { final SharedPreferences prefs = getSharedPreferences(ListFragment.SHARED_PREFS, 0); final ArrayList<String> hideAddresses = addressListForPref(prefs, ListFragment.PREF_EXCLUDE_DISPLAY_ADDRS); final ArrayList<String> blockAddresses = addressListForPref(prefs, ListFragment.PREF_EXCLUDE_LOG_ADDRS); if ( ! NetworkType.WIFI.equals(network.getType()) ) { final View filterRowView = findViewById(R.id.filter_row); filterRowView.setVisibility(View.GONE); } else { final Button hideMacButton = findViewById( R.id.hide_mac_button ); final Button hideOuiButton = findViewById( R.id.hide_oui_button ); final Button disableLogMacButton = findViewById( R.id.disable_log_mac_button ); if ( (null == network.getBssid()) || (network.getBssid().length() < 17) || (hideAddresses.contains(network.getBssid().toUpperCase())) ) { hideMacButton.setEnabled(false); } if ( (null == network.getBssid()) || (network.getBssid().length() < 8) || (hideAddresses.contains(network.getBssid().toUpperCase().substring(0, 8)))) { hideOuiButton.setEnabled(false); } if ( (null == network.getBssid()) || (network.getBssid().length() < 17) || (blockAddresses.contains(network.getBssid().toUpperCase())) ) { disableLogMacButton.setEnabled(false); } hideMacButton.setOnClickListener( new OnClickListener() { @Override public void onClick( final View buttonView ) { // add a display-exclude row fot MAC MacFilterActivity.addEntry(hideAddresses, prefs, network.getBssid().replace(":",""), ListFragment.PREF_EXCLUDE_DISPLAY_ADDRS); hideMacButton.setEnabled(false); } }); hideOuiButton.setOnClickListener( new OnClickListener() { @Override public void onClick( final View buttonView ) { // add a display-exclude row fot OUI MacFilterActivity.addEntry(hideAddresses, prefs, network.getBssid().replace(":","").substring(0,6), ListFragment.PREF_EXCLUDE_DISPLAY_ADDRS); hideOuiButton.setEnabled(false); } }); disableLogMacButton.setOnClickListener( new OnClickListener() { @Override public void onClick( final View buttonView ) { // add a log-exclude row fot OUI MacFilterActivity.addEntry(blockAddresses, prefs, network.getBssid().replace(":",""), ListFragment.PREF_EXCLUDE_LOG_ADDRS); //TODO: should this also delete existing records? disableLogMacButton.setEnabled(false); } }); } } private ArrayList<String> addressListForPref(final SharedPreferences prefs, final String key) { Gson gson = new Gson(); String[] values = gson.fromJson(prefs.getString(key, "[]"), String[].class); return new ArrayList<String>(Arrays.asList(values)); } private int getExistingSsid( final String ssid ) { final WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); final String quotedSsid = "\"" + ssid + "\""; int netId = -2; for ( final WifiConfiguration config : wifiManager.getConfiguredNetworks() ) { MainActivity.info( "bssid: " + config.BSSID + " ssid: " + config.SSID + " status: " + config.status + " id: " + config.networkId + " preSharedKey: " + config.preSharedKey + " priority: " + config.priority + " wepTxKeyIndex: " + config.wepTxKeyIndex + " allowedAuthAlgorithms: " + config.allowedAuthAlgorithms + " allowedGroupCiphers: " + config.allowedGroupCiphers + " allowedKeyManagement: " + config.allowedKeyManagement + " allowedPairwiseCiphers: " + config.allowedPairwiseCiphers + " allowedProtocols: " + config.allowedProtocols + " hiddenSSID: " + config.hiddenSSID + " wepKeys: " + Arrays.toString( config.wepKeys ) ); if ( quotedSsid.equals( config.SSID ) ) { netId = config.networkId; break; } } return netId; } @Override public void handleDialog(final int dialogId) { switch(dialogId) { case NON_CRYPTO_DIALOG: connectToNetwork( null ); break; default: MainActivity.warn("Network unhandled dialogId: " + dialogId); } } private void connectToNetwork( final String password ) { final int preExistingNetId = getExistingSsid( network.getSsid() ); final WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService( Context.WIFI_SERVICE ); int netId = -2; if ( preExistingNetId < 0 ) { final WifiConfiguration newConfig = new WifiConfiguration(); newConfig.SSID = "\"" + network.getSsid() + "\""; newConfig.hiddenSSID = false; if ( password != null ) { if ( Network.CRYPTO_WEP == network.getCrypto() ) { newConfig.wepKeys = new String[]{ "\"" + password + "\"" }; } else { newConfig.preSharedKey = "\"" + password + "\""; } } netId = wifiManager.addNetwork( newConfig ); } if ( netId >= 0 ) { final boolean disableOthers = true; wifiManager.enableNetwork(netId, disableOthers); } } public static class CryptoDialog extends DialogFragment { public static CryptoDialog newInstance(final Network network) { final CryptoDialog frag = new CryptoDialog(); Bundle args = new Bundle(); args.putString("ssid", network.getSsid()); args.putString("capabilities", network.getCapabilities()); args.putString("level", Integer.toString(network.getLevel())); frag.setArguments(args); return frag; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final Dialog dialog = getDialog(); View view = inflater.inflate(R.layout.cryptodialog, container); dialog.setTitle(getArguments().getString("ssid")); TextView text = view.findViewById( R.id.security ); text.setText(getArguments().getString("capabilities")); text = view.findViewById( R.id.signal ); text.setText(getArguments().getString("level")); final Button ok = view.findViewById( R.id.ok_button ); final TextInputEditText password = view.findViewById( R.id.edit_password ); password.addTextChangedListener( new SettingsFragment.SetWatcher() { @Override public void onTextChanged( final String s ) { if ( s.length() > 0 ) { ok.setEnabled(true); } } }); final CheckBox showpass = view.findViewById( R.id.showpass ); showpass.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged( final CompoundButton buttonView, final boolean isChecked ) { if ( isChecked ) { password.setInputType( InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD ); password.setTransformationMethod( null ); } else { password.setInputType( InputType.TYPE_TEXT_VARIATION_PASSWORD ); password.setTransformationMethod( android.text.method.PasswordTransformationMethod.getInstance() ); } } }); ok.setOnClickListener( new OnClickListener() { @Override public void onClick( final View buttonView ) { try { final NetworkActivity networkActivity = (NetworkActivity) getActivity(); networkActivity.connectToNetwork( password.getText().toString() ); dialog.dismiss(); } catch ( Exception ex ) { // guess it wasn't there anyways MainActivity.info( "exception dismissing crypto dialog: " + ex ); } } } ); Button cancel = view.findViewById( R.id.cancel_button ); cancel.setOnClickListener( new OnClickListener() { @Override public void onClick( final View buttonView ) { try { dialog.dismiss(); } catch ( Exception ex ) { // guess it wasn't there anyways MainActivity.info( "exception dismissing crypto dialog: " + ex ); } } } ); return view; } } /* Creates the menu items */ @Override public boolean onCreateOptionsMenu( final Menu menu ) { MenuItem item = menu.add(0, MENU_COPY, 0, getString(R.string.menu_copy_network)); item.setIcon( android.R.drawable.ic_menu_save ); item = menu.add(0, MENU_RETURN, 0, getString(R.string.menu_return)); item.setIcon( android.R.drawable.ic_menu_revert ); return true; } /* Handles item selections */ @Override public boolean onOptionsItemSelected( final MenuItem item ) { switch ( item.getItemId() ) { case MENU_RETURN: // call over to finish finish(); return true; case MENU_COPY: // copy the netid if (network != null) { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(network.getBssid()); } return true; case android.R.id.home: // MainActivity.info("NETWORK: actionbar back"); if (isDbResult) { // don't go back to main activity finish(); return true; } } return false; } private static final String channelCodeTypeForNetworkType(NetworkType type) { switch (type) { case GSM: return "ARFCN" ; case LTE: return "EARFCN"; case WCDMA: return "UARFCN"; default: return null; } } }
package com.cryptoregistry.workbench; import java.util.List; import junit.framework.Assert; import org.junit.Test; public class ClassSearchUtilTest { @Test public void classSearchUtilTest() { @SuppressWarnings("rawtypes") List list = ClassSearchUtils.searchClassPath("template", ".properties"); Assert.assertEquals(6, list.size()); } }
//Java class that gets all of user's txt files. /* THIS IS HEAVILY COMMENTED SO YOU CAN UNDERSTAND AND HOPEFULLY DEBUG KEVIN */ import java.io.File; import java.io.IOException; import java.util.ArrayList; public class FileList { //used to store the different filenames private ArrayList<String> filePaths; //some common plaintext extensions protected final static String plaintextextensions = "html,java,py,css,js,lua,rkt,nlogo,pde,ps1,md"; public static void getfiles(File dir, ArrayList<String> stored) { try { File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { if(file.getPath().substring(file.getPath().lastIndexOf("/") + 1).indexOf(".") == -1) { //recursive, if file is a directory run the method on that directory getfiles(file, stored); } } else { //get substring of path after last "/", so just filename with extension String filename = file.getCanonicalPath().substring(file.getCanonicalPath().lastIndexOf("/") + 1); //checks if file is some form of txt file if (txtTrue(filename) && (filename.indexOf(".")!=-1)) { //store the file path to the arraylist stored.add(file.getCanonicalPath()); } } } } catch (IOException e) { e.printStackTrace(); } } public static boolean txtTrue(String file) { String extension = ""; int i = file.lastIndexOf('.'); if (i >= 0) { extension = file.substring(i + 1); } return plaintextextensions.toLowerCase().contains(extension.toLowerCase()); } public FileList() { filePaths = new ArrayList<String>(); //gets home directory of the user File homedir = new File(System.getProperty("user.home")); //stores files in directory getfiles(homedir, filePaths); } public static void main(String[] args) { FileList c9 = new FileList(); for (int i = 0 ; i < c9.filePaths.size() ; i++) { System.out.println(c9.filePaths.get(i)); } } }
package org.openoffice.xmerge.converter.palm; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; /** * <p>Class used only internally by <code>PdbEncoder</code> and * <code>PdbDecoder</code> to store, read and write a PDB header.</p> * * <p>Note that fields are intended to be accessible only at the * package level.</p> * * <p>Some of the fields are internally represented using a * larger type since Java does not have unsigned types. * Some are not since they are not relevant for now. * The <code>read</code> and <code>write</code> methods should * handle them properly.</p> * * @author Herbie Ong * @see PalmDB * @see Record */ final class PdbHeader { /** Name of the database. 32 bytes. */ byte[] pdbName = null; /** * Flags for the database. Palm UInt16. Unsignedness should be * irrelevant. */ short attribute = 0; /** Application-specific version for the database. Palm UInt16. */ int version = 0; /** Date created. Palm UInt32. */ long creationDate = 0; /** Date last modified. Palm UInt32. */ long modificationDate = 0; /** Date last backup. Palm UInt32. */ long lastBackupDate = 0; /** * Incremented every time a <code>Record</code> is * added, deleted or modified. Palm UInt32. */ long modificationNumber = 0; /** Optional field. Palm UInt32. Unsignedness should be irrelevant. */ int appInfoID = 0; /** Optional field. Palm UInt32. Unsignedness should be irrelevant. */ int sortInfoID = 0; /** Database type ID. Palm UInt32. Unsignedness should be irrelevant. */ int typeID = 0; /** Database creator ID. Palm UInt32. Unsignedness should be irrelevant. */ int creatorID = 0; int uniqueIDSeed = 0; /** See numRecords. 4 bytes. */ int nextRecordListID = 0; /** * Number of Records stored in the database header. * If all the <code>Record</code> entries cannot fit in the header, * then <code>nextRecordList</code> has the local ID of a * RecordList that contains the next set of <code>Record</code>. * Palm UInt16. */ int numRecords = 0; /** * Read in the data for the PDB header. Need to * preserve the unsigned value for some of the fields. * * @param di A <code>DataInput</code> object. * * @throws IOException If any I/O error occurs. */ public void read(DataInput in) throws IOException { pdbName = new byte[PalmDB.NAME_LENGTH]; in.readFully(pdbName); attribute = in.readShort(); version = in.readUnsignedShort(); creationDate = ((long) in.readInt()) & 0xffffffffL; modificationDate = ((long) in.readInt()) & 0xffffffffL; lastBackupDate = ((long) in.readInt()) & 0xffffffffL; modificationNumber = ((long) in.readInt()) & 0xffffffffL; appInfoID = in.readInt(); sortInfoID = in.readInt(); creatorID = in.readInt(); typeID = in.readInt(); uniqueIDSeed = in.readInt(); nextRecordListID = in.readInt(); numRecords = in.readUnsignedShort(); } /** * Write out PDB header data. * * @param out A <code>DataOutput</code> object. * * @throws IOException If any I/O error occurs. */ public void write(DataOutput out) throws IOException { out.write(pdbName); out.writeShort(attribute); out.writeShort(version); out.writeInt((int) creationDate); out.writeInt((int) modificationDate); out.writeInt((int) lastBackupDate); out.writeInt((int) modificationNumber); out.writeInt(appInfoID); out.writeInt(sortInfoID); out.writeInt(typeID); out.writeInt(creatorID); out.writeInt(uniqueIDSeed); out.writeInt(nextRecordListID); out.writeShort(numRecords); } }
package com.thoughtworks.xstream.core.util; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * ClassLoader that is composed of other classloaders. Each loader will be used to try to load the particular class, until * one of them succeeds. <b>Note:</b> The loaders will always be called in the REVERSE order they were added in. * * <p>The Composite class loader also has registered the classloader that loaded xstream.jar * and (if available) the thread's context classloader.</p> * * <h1>Example</h1> * <pre><code>CompositeClassLoader loader = new CompositeClassLoader(); * loader.add(MyClass.class.getClassLoader()); * loader.add(new AnotherClassLoader()); * &nbsp; * loader.loadClass("com.blah.ChickenPlucker"); * </code></pre> * * <p>The above code will attempt to load a class from the following classloaders (in order):</p> * * <ul> * <li>AnotherClassLoader (and all its parents)</li> * <li>The classloader for MyClas (and all its parents)</li> * <li>The thread's context classloader (and all its parents)</li> * <li>The classloader for XStream (and all its parents)</li> * </ul> * * <p>The added classloaders are kept with weak references to allow an application container to reload classes.</p> * * @author Joe Walnes * @author J&ouml;rg Schaible * @since 1.0.3 */ public class CompositeClassLoader extends ClassLoader { private final ReferenceQueue queue = new ReferenceQueue(); private final List classLoaders = new ArrayList(); public CompositeClassLoader() { addInternal(Object.class.getClassLoader()); // bootstrap loader. addInternal(getClass().getClassLoader()); // whichever classloader loaded this jar. } /** * Add a loader to the n * @param classLoader */ public synchronized void add(ClassLoader classLoader) { cleanup(); if (classLoader != null) { addInternal(classLoader); } } private void addInternal(ClassLoader classLoader) { WeakReference refClassLoader = null; for (Iterator iterator = classLoaders.iterator(); iterator.hasNext();) { WeakReference ref = (WeakReference) iterator.next(); ClassLoader cl = (ClassLoader)ref.get(); if (cl == null) { iterator.remove(); } else if (cl == classLoader) { iterator.remove(); refClassLoader = ref; } } classLoaders.add(0, refClassLoader != null ? refClassLoader : new WeakReference(classLoader, queue)); } public Class loadClass(String name) throws ClassNotFoundException { List copy = new ArrayList() { public boolean add(Object ref) { Object classLoader = ((WeakReference)ref).get(); if (classLoader != null) { return super.add(classLoader); } return false; } }; synchronized(this) { cleanup(); copy.addAll(classLoaders); } ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); for (Iterator iterator = copy.iterator(); iterator.hasNext();) { ClassLoader classLoader = (ClassLoader) iterator.next(); if (classLoader == contextClassLoader) { contextClassLoader = null; } try { return classLoader.loadClass(name); } catch (ClassNotFoundException notFound) { // ok.. try another one } } // One last try - the context class loader associated with the current thread. Often used in j2ee servers. // Note: The contextClassLoader cannot be added to the classLoaders list up front as the thread that constructs // XStream is potentially different to thread that uses it. if (contextClassLoader != null) { return contextClassLoader.loadClass(name); } else { throw new ClassNotFoundException(name); } } private void cleanup() { WeakReference ref; while ((ref = (WeakReference)queue.poll()) != null) { classLoaders.remove(ref); } } }
package AlphaTris; import java.util.Scanner; import java.util.function.Function; public class TrisInterface { static int depth; public static void main(String[] args) { System.out.println("Inserire 2 numeri, la dimensione della griglia e la lunghezza della serie"); int serie, size; Scanner in = new Scanner(System.in); size = in.nextInt(); serie = in.nextInt(); System.out.println("Tu sei X"); game(size, serie); } static void game(int size, int serie) { TrisState t = new TrisState(serie, size); System.out.println(t); Function<TrisState, TrisState> engine = getEngine(size, serie, t); Scanner in = new Scanner(System.in); int x,y; while (!t.isTerminal()) { System.out.println("Inserire 2 numeri, la riga e la colonna della casella da segnare"); x = in.nextInt(); y = in.nextInt(); t.state[x][y] = -1; TrisState.generated = 0; long time = System.currentTimeMillis(); t = engine.apply(t); time = System.currentTimeMillis()- time; System.out.println(); System.out.println("tempo elaborazione mossa: " + time + "ms"); System.out.println("profondità esplorazione: " + depth); System.out.println("nodi generati: " + TrisState.generated); System.out.println(); System.out.println(t); } if(t.eval() == 0) System.out.println("Pareggio!"); else if(t.eval() > 0) System.out.println("Hai perso :("); else if(t.eval() < 0) System.out.println("Hai Vinto :)"); } static Function<TrisState,TrisState> getEngine(int size, int serie, TrisState t) { int beam; if(size <= 10) { beam = 10; depth = 6; } else if(size > 10 && size < 25) { beam = 12; depth = 4; } else { beam = 20; depth = 2; } Engine ab = new Engine(); return (x -> ab.parallelNextState(x, depth)); } }
package ru.job4j.map; import java.util.*; public class User { String name; int children; Calendar birthday; public User(String name, int children, Calendar birthday) { this.name = name; this.children = children; this.birthday = birthday; } /*@Override public int hashCode() { return name.hashCode() + children + birthday.hashCode(); }*/ @Override public boolean equals(Object object) { if (this == object) return true; if (object == null) return false; if (this.getClass() != object.getClass()) return false; User another = (User) object; if (!birthday.equals(another.birthday) || children != another.children || !name.equals(another.name)) return false; return true; } }
package org.a5calls.android.a5calls.model; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; /** * Local database helper. I believe this is already "thread-safe" and such because SQLiteOpenHelper * handles all of that for us. As long as we just use one SQLiteOpenHelper from AppSingleton * we should be safe! */ public class DatabaseHelper extends SQLiteOpenHelper { private static final String TAG = "DatabaseHelper"; private static final int DATABASE_VERSION = 1; private static final String CALLS_TABLE_NAME = "UserCallsDatabase"; private static class CallsColumns { public static String TIMESTAMP = "timestamp"; public static String CONTACT_ID = "contactid"; public static String ISSUE_ID = "issueid"; public static String LOCATION = "location"; public static String RESULT = "result"; } private static final String CALLS_TABLE_CREATE = "CREATE TABLE " + CALLS_TABLE_NAME + " (" + CallsColumns.TIMESTAMP + " INTEGER, " + CallsColumns.CONTACT_ID + " STRING, " + CallsColumns.ISSUE_ID + " STRING, " + CallsColumns.LOCATION + " STRING, " + CallsColumns.RESULT + " STRING);"; public DatabaseHelper(Context context) { super(context, CALLS_TABLE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CALLS_TABLE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } /** * Adds a successful call to the user's local database * @param issueId * @param contactId * @param location * @param result */ public void addCall(String issueId, String contactId, String result, String location) { ContentValues values = new ContentValues(); values.put(CallsColumns.TIMESTAMP, System.currentTimeMillis()); values.put(CallsColumns.CONTACT_ID, contactId); values.put(CallsColumns.ISSUE_ID, issueId); values.put(CallsColumns.LOCATION, location); values.put(CallsColumns.RESULT, result); getWritableDatabase().insert(CALLS_TABLE_NAME, null, values); } /** * Gets the calls in the database for a particular issue. * @param issueId * @return A list of the contact IDs contacted for this issue. */ public List<String> getCallsForIssue(String issueId) { Cursor c = getReadableDatabase().rawQuery("SELECT " + CallsColumns.CONTACT_ID + " FROM " + CALLS_TABLE_NAME + " WHERE " + CallsColumns.ISSUE_ID + " = ? GROUP BY " + CallsColumns.CONTACT_ID, new String[] {issueId}); List<String> result = new ArrayList<>(); while (c.moveToNext()) { result.add(c.getString(0)); } c.close(); return result; } /** * Gets the calls in the database for a particular issue. * @param issueId * @param zip * @return A list of the contact IDs contacted for this issue. */ public List<String> getCallsForIssueAndZip(String issueId, String zip) { String query = "SELECT " + CallsColumns.CONTACT_ID + " FROM " + CALLS_TABLE_NAME + " WHERE " + CallsColumns.ISSUE_ID + " = ? AND " + CallsColumns.LOCATION + " = ? GROUP BY " + CallsColumns.CONTACT_ID; Cursor c = getReadableDatabase().rawQuery(query, new String[] {issueId, zip}); List<String> result = new ArrayList<>(); while (c.moveToNext()) { result.add(c.getString(0)); } c.close(); return result; } /** * Gets the calls in the database for a particular contact. * @param contactId * @return a list of the issues IDs that were called for a particular contact. */ public List<String> getCallsForContact(String contactId) { // TODO do we want to return issue IDs, or more detailed info about the call? What about // whether contact was made? // Probably need to make a "Call" class to store this in. return null; } /** * Whether a contact has been called for a particular issue. * @param issueId * @param contactId */ public boolean hasCalled(String issueId, String contactId) { Cursor c = getReadableDatabase().rawQuery("SELECT " + CallsColumns.TIMESTAMP + " FROM " + CALLS_TABLE_NAME + " WHERE " + CallsColumns.ISSUE_ID + " = ? AND " + CallsColumns.CONTACT_ID + " = ?", new String[] {issueId, contactId}); return c.getCount() > 0; } /** * Gets the total number of calls this user has made */ public int getCallsCount() { Cursor c = getReadableDatabase().rawQuery( "SELECT " + CallsColumns.TIMESTAMP + " FROM " + CALLS_TABLE_NAME, null); int count = c.getCount(); c.close(); return count; } }
package com.ormma.controller; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.util.DisplayMetrics; import android.util.Log; import android.view.Surface; import android.view.View; import android.view.WindowManager; import com.ormma.controller.util.OrmmaConfigurationBroadcastReceiver; import com.ormma.view.OrmmaView; /** * The Class OrmmaDisplayController. A ormma controller for handling display related operations */ public class OrmmaDisplayController extends OrmmaController { //tag for logging private static final String TAG = "OrmmaDisplayController"; private WindowManager mWindowManager; private boolean bMaxSizeSet = false; private int mMaxWidth = -1; private int mMaxHeight = -1; private OrmmaConfigurationBroadcastReceiver mBroadCastReceiver; private float mDensity; /** * Instantiates a new ormma display controller. * * @param adView the ad view * @param c the context */ public OrmmaDisplayController(OrmmaView adView, Context c) { super(adView, c); DisplayMetrics metrics = new DisplayMetrics(); mWindowManager = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); mWindowManager.getDefaultDisplay().getMetrics(metrics); mDensity = metrics.density; } /** * Resize the view. * * @param width the width * @param height the height */ public void resize(int width, int height) { if (((mMaxHeight > 0) && (height > mMaxHeight)) || ((mMaxWidth > 0) && (width > mMaxWidth))) { mOrmmaView.injectJavaScript("OrmmaAdController.fireError(\"Maximum size exceeded\", \"resize\")"); } else mOrmmaView.resize((int) (mDensity * width), (int) (mDensity * height)); } /** * Open a browser * * @param url the url * @param back show the back button * @param forward show the forward button * @param refresh show the refresh button */ public void open(String url, boolean back, boolean forward, boolean refresh) { mOrmmaView.open(url, back, forward, refresh); } public void openMap(String url, boolean fullscreen) { mOrmmaView.openMap(url, fullscreen); } public void playAudio(String url, boolean autoPlay, boolean controls, boolean loop, boolean inline, String startStyle, String stopStyle) { mOrmmaView.playAudio(url, autoPlay, controls, loop, inline, startStyle, stopStyle); } public void playVideo(String url, boolean audioMuted, boolean autoPlay, boolean controls, boolean loop, int[] inline, String startStyle, String stopStyle) { mOrmmaView.playVideo(url, audioMuted, autoPlay, controls, loop, inline, startStyle, stopStyle); } /** * Expand the view * * @param dimensions the dimensions to expand to * @param URL the uRL * @param properties the properties for the expansion */ public void expand(String dimensions, String URL, String properties) { try { Dimensions d = (Dimensions) getFromJSON(new JSONObject(dimensions), Dimensions.class); d.width *= mDensity; d.height *= mDensity; d.x *= mDensity; d.y *= mDensity; if (d.height < 0) d.height = mOrmmaView.getHeight(); if (d.width < 0) d.width = mOrmmaView.getWidth(); int loc[] = new int[2]; mOrmmaView.getLocationInWindow(loc); if (d.x < 0) d.x = loc[0]; if (d.y < 0) { int topStuff = 0;// ((Activity)mContext).findViewById(Window.ID_ANDROID_CONTENT).getTop(); d.y = loc[1] - topStuff; } mOrmmaView.expand(d, URL, (Properties) getFromJSON(new JSONObject(properties), Properties.class)); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NullPointerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Close the view */ public void close() { mOrmmaView.close(); } /** * Hide the view */ public void hide() { mOrmmaView.hide(); } /** * Show the view */ public void show() { mOrmmaView.show(); } /** * Checks if is visible. * * @return true, if is visible */ public boolean isVisible() { return (mOrmmaView.getVisibility() == View.VISIBLE); } /** * Dimensions. * * @return the string */ public String dimensions() { return "{ \"top\" :" + (int) (mOrmmaView.getTop() / mDensity) + "," + "\"left\" :" + (int) (mOrmmaView.getLeft() / mDensity) + "," + "\"bottom\" :" + (int) (mOrmmaView.getBottom() / mDensity) + "," + "\"right\" :" + (int) (mOrmmaView.getRight() / mDensity) + "}"; } /** * Gets the orientation. * * @return the orientation */ public int getOrientation() { int orientation = mWindowManager.getDefaultDisplay().getOrientation(); int ret = -1; switch (orientation) { case Surface.ROTATION_0: ret = 0; break; case Surface.ROTATION_90: ret = 90; break; case Surface.ROTATION_180: ret = 180; break; case Surface.ROTATION_270: ret = 270; break; } return ret; } /** * Gets the screen size. * * @return the screen size */ public String getScreenSize() { DisplayMetrics metrics = new DisplayMetrics(); mWindowManager.getDefaultDisplay().getMetrics(metrics); return "{ width: " + (int) (metrics.widthPixels / metrics.density) + ", " + "height: " + (int) (metrics.heightPixels / metrics.density) + "}"; } /** * Gets the size. * * @return the size */ public String getSize() { return mOrmmaView.getSize(); } /** * Gets the max size. * * @return the max size */ public String getMaxSize() { if (bMaxSizeSet) return "{ width: " + mMaxWidth + ", " + "height: " + mMaxHeight + "}"; else return getScreenSize(); } /** * Sets the max size. * * @param w the w * @param h the h */ public void setMaxSize(int w, int h) { bMaxSizeSet = true; mMaxWidth = w; mMaxHeight = h; } // public void startOrientationListener() { // if (mOrientationListenerCount == 0) { // mBroadCastReceiver = new OrmmaConfigurationBroadcastReceiver(this); // mFilter = new IntentFilter(); // mFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED); // mOrientationListenerCount++; // mContext.registerReceiver(mBroadCastReceiver, mFilter); // public void stopOrientationListener() { // mOrientationListenerCount--; // if (mOrientationListenerCount == 0){ // mContext.unregisterReceiver(mBroadCastReceiver); // mBroadCastReceiver = null; // mFilter = null; /** * On orientation changed. * * @param orientation the orientation */ public void onOrientationChanged(int orientation) { mOrmmaView.injectJavaScript("Ormma.gotOrientationChange(" + orientation + ")"); } /** * Log html. * * @param html the html */ public void logHTML(String html) { Log.d(TAG, html); } /* (non-Javadoc) * @see com.ormma.controller.OrmmaController#stopAllListeners() */ @Override public void stopAllListeners() { try { mContext.unregisterReceiver(mBroadCastReceiver); } catch (Exception e) { } mBroadCastReceiver = null; } }
package org.a11y.brltty.android.settings; import org.a11y.brltty.android.*; import java.util.List; import android.os.Bundle; import android.content.Context; import android.preference.PreferenceActivity; public class SettingsActivity extends PreferenceActivity { private final static String LOG_TAG = SettingsActivity.class.getName(); @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.SETTINGS_SCREEN_MAIN); } @Override public void onBuildHeaders (List<Header> headers) { loadHeadersFromResource(R.xml.settings_headers, headers); } @Override protected boolean isValidFragment (String name) { return true; } public static void launch () { ApplicationUtilities.launch(SettingsActivity.class); } }
package com.support.android.designlibdemo; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.Activity; import android.app.LoaderManager.LoaderCallbacks; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import utils.LoginRequest; import utils.Password; import utils.RequestHandler; import utils.SecurityHandler; /** * A login screen that offers login via email/password. */ public class LoginUserActivity extends Activity implements LoaderCallbacks<Cursor> { /** * Keep track of the login task to ensure we can cancel it if requested. */ private UserLoginTask mAuthTask = null; // UI references. private AutoCompleteTextView userView; private EditText mPasswordView; private View mProgressView; private View mLoginFormView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_user); // Set up the login form. userView = (AutoCompleteTextView) findViewById(R.id.user); populateAutoComplete(); mPasswordView = (EditText) findViewById(R.id.password); mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.login || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } }); Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); mEmailSignInButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { attemptLogin(); } }); mLoginFormView = findViewById(R.id.login_form); mProgressView = findViewById(R.id.login_progress); } private void populateAutoComplete() { getLoaderManager().initLoader(0, null, this); } /** * Attempts to sign in or register the account specified by the login form. * If there are form errors (invalid email, missing fields, etc.), the * errors are presented and no actual login attempt is made. */ public void attemptLogin() { if (mAuthTask != null) { return; } // Reset errors. userView.setError(null); mPasswordView.setError(null); // Store values at the time of the login attempt. String user = userView.getText().toString(); String password = mPasswordView.getText().toString(); boolean cancel = false; View focusView = null; // Check for a valid password, if the user entered one. if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) { mPasswordView.setError(getString(R.string.error_invalid_password)); focusView = mPasswordView; cancel = true; } // Check for a valid email address. if (TextUtils.isEmpty(user)) { userView.setError(getString(R.string.error_field_required)); focusView = userView; cancel = true; } else if (!isUserValid(user)) { userView.setError(getString(R.string.error_invalid_user)); focusView = userView; cancel = true; } if (cancel) { // There was an error; don't attempt login and focus the first // form field with an error. focusView.requestFocus(); } else { // Show a progress spinner, and kick off a background task to // perform the user login attempt. showProgress(true); mAuthTask = new UserLoginTask(user, password); mAuthTask.execute((Void) null); } } private boolean isUserValid(String user) { //return ((user.length() >= 6 && user.length() <= 12) && user.matches("[a-zA-Z][0-9]+")); return ((user.length() >= 6 && user.length() <= 12)); } private boolean isPasswordValid(String password) { /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void showProgress(final boolean show) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); mLoginFormView.animate().setDuration(shortAnimTime).alpha( show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mProgressView.animate().setDuration(shortAnimTime).alpha( show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact. // Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, // ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // // Select only email addresses. // ContactsContract.Contacts.Data.MIMETYPE + // " = ?", new String[]{ContactsContract.CommonDataKinds.Email // .CONTENT_ITEM_TYPE}, // // Show primary email addresses first. Note that there won't be // // a primary email address if the user hasn't specified one. // ContactsContract.Contacts.Data.IS_PRIMARY + " DESC"); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { // List<String> users = new ArrayList<String>(); // cursor.moveToFirst(); // while (!cursor.isAfterLast()) { // users.add(cursor.getString(ProfileQuery.NAME)); // cursor.moveToNext(); //addEmailsToAutoComplete(users); } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { } // private interface ProfileQuery { // String[] PROJECTION = { // ContactsContract.CommonDataKinds.Nickname.NAME, // ContactsContract.CommonDataKinds.Nickname.IS_PRIMARY, // int NAME = 0; // int IS_PRIMARY = 1; // private void addEmailsToAutoComplete(List<String> usersCollection) { // //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list. // ArrayAdapter<String> adapter = // new ArrayAdapter<String>(LoginUserActivity.this, // android.R.layout.simple_dropdown_item_1line, usersCollection); // userView.setAdapter(adapter); /** * Represents an asynchronous login/registration task used to authenticate * the user. */ public class UserLoginTask extends AsyncTask<Void, Void, Boolean>{ private final String mUser; private final String mPassword; private boolean mStatus; private boolean userValid; private boolean passValid; UserLoginTask(String email, String password) { mUser = email; mPassword = password; mStatus = false; userValid = false; passValid = false; } @Override protected Boolean doInBackground(Void... params) { // TODO: attempt authentication against a network service. return true; // SecurityHandler securityHandler = new SecurityHandler(); // Password encryptedPassword= securityHandler.createPassword(mPassword.toString()); // LoginRequest loginRequest = new LoginRequest(getApplicationContext()); // String salt = loginRequest.getUserSalt(mUser); // if (!salt.isEmpty()){ // encryptedPassword.setSalt(salt); // mStatus = loginRequest.isValidUserPassword(mUser,encryptedPassword); // return mStatus; } @Override protected void onPostExecute(final Boolean success) { mAuthTask = null; showProgress(false); if (success) { Intent intent = new Intent(LoginUserActivity.this, MainActivity.class); startActivity(intent); finish(); } else { if (!userValid){ userView.setError(getString(R.string.error_incorrect_password)); userView.requestFocus(); } if (!passValid){ mPasswordView.setError(getString(R.string.error_incorrect_password)); mPasswordView.requestFocus(); } } } @Override protected void onCancelled() { mAuthTask = null; showProgress(false); } } }
// WinController.java package de.htwg.battleship.controller.impl; import de.htwg.battleship.controller.IWinLooseController; import de.htwg.battleship.model.IPlayer; import de.htwg.battleship.model.IShip; import de.htwg.battleship.observer.impl.Observable; /** * WinController checks if someone has won. * @author Moritz Sauter (SauterMoritz@gmx.de) * @version 1.00 * @since 2014-12-11 */ public class WinController extends Observable implements IWinLooseController { /** * Saves first Player. */ private final IPlayer player1; /** * Saves second Player. */ private final IPlayer player2; /** * Saves the Chain-of-Responsibility. * Checks if a Ship is destroyed. */ private final DestroyedController dc; /** * Public Constructor. * Initializes intern Chain-of-Responsibility. * @param player1 first Player * @param player2 second Player */ public WinController(final IPlayer player1, final IPlayer player2) { this.player1 = player1; this.player2 = player2; dc = new DestroyedTrueController(); } @Override public final IPlayer win() { if (playerDestroyed(player1)) { return player2; } if (playerDestroyed(player2)) { return player1; } return null; } /** * Private Utility-Method to check if a Player is fully Destroyed. * @param player which player should be checked * @return true if the Player is destroyed, false if not */ private boolean playerDestroyed(final IPlayer player) { IShip[] shipList = player.getOwnBoard().getShipList(); for (int i = 0; i < player.getOwnBoard().getShips(); i++) { if (!isDestroyed(shipList[i], player)) { return false; } } return true; } /** * Private Utility-Method to pass the responsibility to the chain. * The chain checks if a ship is destroyed. * @param ship which ship should be checked * @param player which player owns the ship * @return true if the ship is fully destroyed, false if not */ private boolean isDestroyed(final IShip ship, final IPlayer player) { return dc.responsibility(ship, player); } }
package net.acomputerdog.ircbot.main; import com.sorcix.sirc.main.IrcConnection; import com.sorcix.sirc.util.NickNameException; import net.acomputerdog.core.java.MemBuffer; import net.acomputerdog.core.java.Sleep; import net.acomputerdog.core.logger.CLogger; import net.acomputerdog.ircbot.command.Command; import net.acomputerdog.ircbot.config.Admins; import net.acomputerdog.ircbot.config.AutoJoinList; import net.acomputerdog.ircbot.config.Config; import net.acomputerdog.ircbot.irc.IrcListener; import net.acomputerdog.ircbot.logging.LogManager; import net.acomputerdog.ircbot.security.Auth; import net.acomputerdog.ircbot.security.BlackList; import net.acomputerdog.ircbot.security.NickServ; import net.acomputerdog.ircbot.security.StringCheck; public class IrcBot { public static final IrcBot instance = new IrcBot(); public static CLogger LOGGER; private final MemBuffer buffer = new MemBuffer(); private boolean isRunning = false; private boolean canRun = true; private String shutdownReason = null; private boolean properShutdown = false; private IrcListener handler; private IrcConnection connection; private NickServ nickServ; private Admins admins; private Auth auth; private StringCheck stringCheck; private BlackList blacklist; private AutoJoinList autoJoinList; private LogManager logManager; private IrcBot() { if (instance != null) { throw new IllegalStateException("Cannot create more than one IrcBot!"); } } public static void main(String[] args) { instance.start(); } private void start() { if (!isRunning) { isRunning = true; try { init(); while (canRun) { long methodStartTime = System.currentTimeMillis(); onTick(); Sleep.sync(methodStartTime, 1000 / Config.TPS); } end(0); } catch (Throwable t) { buffer.free(); LOGGER.logFatal("Uncaught exception in IrcBot loop!", t); end(-1); } } else { throw new IllegalArgumentException("Cannot start more than one IrcBot!"); } } private void init() { try { logManager = new LogManager(this); } catch (Exception e) { throw new RuntimeException("Unable to initialize log manager!", e); } Config.load(); LOGGER = logManager.getLogger(Config.BOT_USERNAME); buffer.allocate(Config.MEMORY_BUFFER_SIZE); LOGGER.logInfo(getVersionString() + " starting."); Runtime.getRuntime().addShutdownHook(new IrcShutdownHandler(this)); admins = new Admins(this); auth = new Auth(this); blacklist = new BlackList(this); stringCheck = new StringCheck(this); autoJoinList = new AutoJoinList(this); admins.load(); blacklist.load(); autoJoinList.load(); handler = new IrcListener(this); Command.init(this); LOGGER.logInfo("Loaded " + Command.getCommandNameMap().size() + " commands with " + Command.getCommandMap().size() + " aliases."); IrcConnection.ABOUT_ADDITIONAL += (" + " + getVersionString()); connection = new IrcConnection(Config.SERVER); if (Config.USE_LOGIN) { connection.setUsername(Config.BOT_USERNAME); } connection.setNick(Config.BOT_NICK); connection.addMessageListener(handler); connection.addServerListener(handler); connection.setUnknownListener(handler); connection.addMessageListener(nickServ = new NickServ(this)); connection.setMessageDelay(Config.MESSAGES_PER_SECOND); connection.setVersion(getVersionString()); try { LOGGER.logInfo("Connecting to " + Config.SERVER + "..."); connection.connect(); LOGGER.logInfo("Connected."); } catch (NickNameException e) { LOGGER.logFatal("Nickname " + Config.BOT_NICK + " is already in use!"); end(-2); } catch (Exception e) { LOGGER.logFatal("Unable to connect to IRC network!", e); end(-1); } if (Config.USE_LOGIN) { nickServ.send("GHOST " + Config.BOT_USERNAME + " " + Config.BOT_PASS); nickServ.send("IDENTIFY " + Config.BOT_PASS); } LOGGER.logInfo("Startup complete."); autoJoinList.joinChannels(); } private void onTick() { auth.tick(); } private void end(int code) { if (code == 0) { LOGGER.logInfo("Shutting down normally."); } else { LOGGER.logWarning("Shutting down unexpectedly with code " + code + "!"); } if (shutdownReason != null) { LOGGER.logInfo("Shutdown reason: " + shutdownReason); } try { if (connection != null) { connection.disconnect(shutdownReason == null ? "Bot shutting down." : shutdownReason); } blacklist.save(); autoJoinList.save(); admins.save(); Config.save(); IrcConnection.ABOUT_ADDITIONAL = ""; logManager.onShutdown(); properShutdown = true; } catch (Throwable ignored) {} System.exit(code); } public boolean isProperShutdown() { return properShutdown; } public void stop() { canRun = false; } public void stop(String reason) { shutdownReason = reason; stop(); } public IrcListener getHandler() { return handler; } public IrcConnection getConnection() { return connection; } public String getVersionString() { return "AcomputerBot v0.15"; } public boolean canRun() { return canRun; } public NickServ getNickServ() { return nickServ; } public Admins getAdmins() { return admins; } public Auth getAuth() { return auth; } public StringCheck getStringCheck() { return stringCheck; } public BlackList getBlacklist() { return blacklist; } public LogManager getLogManager() { return logManager; } }
package com.endovectors.uta.processing.vision; import org.opencv.core.*; import org.opencv.highgui.Highgui; import org.opencv.highgui.VideoCapture; import org.opencv.imgproc.*; import java.awt.image.BufferedImage; import java.util.*; import java.util.List; import com.endovectors.uta.processing.CheckersBoard; public class CaptureImage { //private final char COLOR_RED = 'r'; //private final char COLOR_GREEN = 'g'; private final char COLOR_BLUE = 'b'; private final char COLOR_ORANGE = 'o'; //private final char COLOR_YELLOW = 'y'; private final char COLOR_WHITE = 'w'; private final char COLOR_BLACK = 'l'; private Mat capturedFrame; // raw image private Mat processedFrame; // processed image private BufferedImage img; // image of board private byte board[]; // holds where pieces are private byte captured[]; // holds where captured pieces are; even is left side, odd is right /** * Constructor: creates 2 mat objects: * 1 for the raw image; * other for the processed image */ public CaptureImage() { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); capturedFrame = new Mat(); processedFrame = new Mat(); board = new byte[32]; captured = new byte[12]; } /** * Determines where captured pieces are * @param in Mat image of the board */ public void findCaptured(Mat in) { int vsegment = in.rows() / 8; // only accounts 8 playable int hsegment = in.cols() / 12; // 8 playable, 2 capture, 2 extra int offset; // offset for playable board int capSquares = 12; // number of capture squares int rowNum = 1; // starting row number for capture squares int rightdx = 48; int leftdx = 0; offset = hsegment; int count = 0; // keep track of captured squares // left: end user, right: system for (int i = 0; i < capSquares; i++) { // find where roi should be Point p1 = new Point(offset + count * hsegment, rowNum * vsegment); // top left point of rectangle (x,y) Point p2 = new Point(offset + (count + 1) * hsegment, (rowNum + 1) * vsegment); // bottom right point of rectangle (x,y) // create rectangle that is board square Rect bound = new Rect(p1, p2); char color; // frame only includes rectangle Mat roi = new Mat(in, bound); // get the color color = identifyColor(roi); switch(color) { case COLOR_BLUE: //Imgproc.rectangle(in, p1, p2, new Scalar(255, 0, 0), 3); Core.rectangle(in, p1, p2, new Scalar(255, 0, 0), 2); captured[i] = 1; break; case COLOR_ORANGE: //Imgproc.rectangle(in, p1, p2, new Scalar(0, 128, 255), 3); Core.rectangle(in, p1, p2, new Scalar(0, 128, 255), 2); captured[i] = 1; break; case COLOR_WHITE: //Imgproc.rectangle(in, p1, p2, new Scalar(255, 255, 255), 3); Core.rectangle(in, p1, p2, new Scalar(255, 255, 255), 2); captured[i] = 0; break; case COLOR_BLACK: //Imgproc.rectangle(in, p1, p2, new Scalar(0, 0, 0), 3); Core.rectangle(in, p1, p2, new Scalar(255, 255, 255), 2); captured[i] = 0; break; } count++; if (count == 1) { offset = hsegment * 10 - rightdx; } else if (count == 2) { count = 0; rightdx -= 6; leftdx += 6; offset = hsegment - leftdx; rowNum++; } } } /** * Processes the board image * @param in image captured of board * @param out processed image of board */ public void processFrame(Mat in, Mat out) { // multiple regions of interest int playSquares = 32; // number of playable game board squares // keep track of starting row square int parity = 0; // 0 is even, 1 is odd, tied to row number int count = 0; // row square int rowNum = 0; // row number, starting at 0 int vsegment = in.rows() / 8; // only accounts 8 playable int hsegment = in.cols() / 10; // 8 playable, 2 capture int hOffset = hsegment * 2; // offset for playable board int vOffset = vsegment + 40; // For angle of camera int dx = 80; int ddx = 0; hsegment -= 16; int dy = 20; vsegment -= 24; // Go through all playable squares for (int i = 0; i < playSquares; i++) { // change offset depending on the row if (parity == 0) // playable squares start on 2nd square from left { if (rowNum >= 5) dx -= 3; hOffset = hsegment * 2 + dx; } else // playable squares start on immediate left { if (rowNum >= 5) dx -= 3; hOffset = hsegment + dx; } if (rowNum == 4) if (count == 6) ddx = 10; if (rowNum == 5) { if (count == 0) ddx = -6; else if (count == 2) ddx = 6; else if (count == 4) ddx = 12; else if (count == 6) ddx = 20; } if (rowNum == 6) { if (count == 0) ddx = 0; else if (count == 2) ddx = 16; else if (count == 4) ddx = 32; else if (count == 6) ddx = 40; } if (rowNum == 7) { if (count == 0) ddx = 0; else if (count == 2) ddx = 24; else if (count == 4) ddx = 40; else ddx = 52; } // find where roi should be //System.out.println("" + vOffset); Point p1 = new Point(hOffset + count * hsegment + ddx, vOffset + rowNum * vsegment - dy); // top left point of rectangle (x,y) Point p2 = new Point(hOffset + (count + 1) * hsegment + ddx, vOffset + (rowNum + 1) * vsegment - dy); // bottom right point of rectangle (x,y) // create rectangle that is board square Rect bound = new Rect(p1, p2); char color; if (i == 0) { // frame only includes rectangle Mat roi = new Mat(in, bound); // get the color color = identifyColor(roi); // copy input image to output image in.copyTo(out); } else { // frame only includes rectangle Mat roi = new Mat(out, bound); // get the color color = identifyColor(roi); } // annotate the output image // scalar values as (blue, green, red) switch(color) { case COLOR_BLUE: //Imgproc.rectangle(out, p1, p2, new Scalar(255, 0, 0), 2); Core.rectangle(out, p1, p2, new Scalar(255, 0, 0), 2); board[i] = CheckersBoard.BLACK; // end user's piece break; case COLOR_ORANGE: //Imgproc.rectangle(out, p1, p2, new Scalar(0, 128, 255), 2); Core.rectangle(out, p1, p2, new Scalar(0, 128, 255), 2); board[i] = CheckersBoard.WHITE; // system's piece break; case COLOR_WHITE: //Imgproc.rectangle(out, p1, p2, new Scalar(255, 255, 255), 2); Core.rectangle(out, p1, p2, new Scalar(255, 255, 255), 2); board[i] = CheckersBoard.EMPTY; break; case COLOR_BLACK: // this is black //Imgproc.rectangle(out, p1, p2, new Scalar(0, 0, 0), 2); Core.rectangle(out, p1, p2, new Scalar(0, 0, 0), 2); // maybe add 8, 0 as line type and fractional bits board[i] = CheckersBoard.EMPTY; break; } count += 2; if (count == 8) { parity = ++parity % 2; // change odd or even count = 0; rowNum++; hsegment += 2; dx -= 10; dy += 10; vsegment += 3; } } } /** * Determines which pieces are kings * @param in Mat image of board */ public void determineKings(Mat in) { int playSquares = 32; Mat dst = new Mat(in.rows(), in.cols(), in.type()); in.copyTo(dst); Imgproc.cvtColor(dst, dst, Imgproc.COLOR_BGR2GRAY); // change to single color Mat canny = new Mat(); Imgproc.Canny(dst, canny, 10, 50); // make image a canny image that is only edges; 2,4 // lower threshold values find more edges List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Mat hierarchy = new Mat(); // holds nested contour information Imgproc.findContours(canny, contours, hierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE); // Imgproc.RETR_LIST, TREE //draw contour image Mat mask = new Mat(); mask = Mat.zeros(dst.size(), dst.type()); Imgproc.drawContours(mask, contours, -1, new Scalar(255,255,255), 1, 8, hierarchy, 2, new Point()); Highgui.imwrite("contours.jpg", mask); ArrayList occupied = new ArrayList<Integer>(); for (int i = 0; i < playSquares; i++) { if (board[i] != 0) occupied.add(i); } for (int i = 0; i < contours.size(); i++) // assuming only contours are checker pieces { // determine if it should be a king // use Rect r = Imgproc.boundingRect then find height of it by r.height // Get bounding rect of contour Rect bound = Imgproc.boundingRect(contours.get(i)); if (bound.height > in.rows() / 8) { //board[(int) occupied.get(0)]++; // make it a king //occupied.remove(0); } } // or apply to each region of interest /* // keep track of starting row square int parity = 0; // 0 is even, 1 is odd, tied to row number int count = 0; // row square int rowNum = 0; // row number, starting at 0 int vsegment = in.rows() / 8; // only accounts 8 playable int hsegment = in.cols() / 12; // 8 playable, 2 capture, 2 extra int offset = hsegment * 2; // offset for playable board // For angle of camera int dx = 48; hsegment -= 8; // Go through all playable squares for (int i = 0; i < playSquares; i++) { // change offset depending on the row if (parity == 0) // playable squares start on immediate left offset = hsegment * 3 + dx; else // playable squares start on 2nd square from left offset = hsegment * 2 + dx; // find where roi should be Point p1 = new Point(offset + count * hsegment, rowNum * vsegment); // top left point of rectangle (x,y) Point p2 = new Point(offset + (count + 1) * hsegment, (rowNum + 1) * vsegment); // bottom right point of rectangle (x,y) // create rectangle that is board square Rect bound = new Rect(p1, p2); // frame only includes rectangle Mat roi = new Mat(in, bound); Imgproc.cvtColor(roi, roi, Imgproc.COLOR_BGR2GRAY); // change to single color Mat canny = new Mat(); Imgproc.Canny(roi, canny, 2, 4); // make image a canny image that is only edges; 2,4 // lower threshold values find more edges List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Mat hierarchy = new Mat(); // holds nested contour information Imgproc.findContours(canny, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); // Imgproc.RETR_LIST, TREE // Get bounding rect of contour Rect rect = Imgproc.boundingRect(contours.get(0)); if (rect.height > in.rows() / 8) { board[i]++; // make it a king } count += 2; if (count == 8) { parity = ++parity % 2; // change odd or even count = 0; rowNum++; hsegment += 1; dx -= 6; } }*/ } /** * Identifies the color in the frame * @param in the Mat image in the region of interest * @return the color */ public char identifyColor(Mat in) { //Mat blue = new Mat(in.rows(), in.cols(), CvType.CV_8UC1); //Mat green = new Mat(in.rows(), in.cols(), CvType.CV_8UC1); //Mat red = new Mat(in.rows(), in.cols(), CvType.CV_8UC1); //split the channels of the image Mat blue = new Mat(); // default is CV_8UC3 Mat green = new Mat(); Mat red = new Mat(); List<Mat> channels = new ArrayList<Mat>(3); Core.split(in, channels); blue = channels.get(0); // makes all 3 CV_8UC1 green = channels.get(1); red = channels.get(2); //System.out.println(blue.toString()); // add the intensities Mat intensity = new Mat(in.rows(), in.cols(), CvType.CV_32F); //Mat mask = new Mat(); Core.add(blue, green, intensity);//, mask, CvType.CV_32F); Core.add(intensity, red, intensity);//, mask, CvType.CV_32F); // not sure if correct from here to ... Mat inten = new Mat(); Core.divide(intensity, Scalar.all(3.0), inten); //System.out.println(intensity.toString()); //Core.divide(3.0, intensity, inten); // if intensity = intensity / 3.0; means element-wise division // use intensity.muls(Mat m) // so make new Mat m of same size that has each element of 1/3 /* * or * About per-element division you can use Core.divide() Core.divide(A,Scalar.all(d), B); It's equivalent to B=A/d */ // find normalized values Mat bnorm = new Mat(); Mat gnorm = new Mat(); Mat rnorm = new Mat(); //blue.convertTo(blue, CvType.CV_32F); //green.convertTo(green, CvType.CV_32F); //red.convertTo(red, CvType.CV_32F); Core.divide(blue, inten, bnorm); Core.divide(green, inten, gnorm); Core.divide(red, inten, rnorm); // find average norm values Scalar val = new Scalar(0); val = Core.mean(bnorm); String value[] = val.toString().split(","); String s = value[0].substring(1); double bavg = Double.parseDouble(s); val = Core.mean(gnorm); String value1[] = val.toString().split(","); String s1 = value1[0].substring(1); double gavg = Double.parseDouble(s1); val = Core.mean(rnorm); String value2[] = val.toString().split(","); String s2 = value2[0].substring(1); double ravg = Double.parseDouble(s2); // ... here //original values /* // define the reference color values //double RED[] = {0.4, 0.5, 1.8}; //double GREEN[] = {1.0, 1.2, 1.0}; double BLUE[] = {1.75, 1.0, 0.5}; //double YELLOW[] = {0.82, 1.7, 1.7}; double ORANGE[] = {0.2, 1.0, 2.0}; double WHITE[] = {2.0, 1.7, 1.7}; //double BLACK[] = {0.0, 0.3, 0.3}; */ // define the reference color values //double RED[] = {0.4, 0.5, 1.8}; //double GREEN[] = {1.0, 1.2, 1.0}; double BLUE[] = {1.75, 1.0, 0.5}; //double YELLOW[] = {0.82, 1.7, 1.7}; double ORANGE[] = {0.2, 1.0, 2.0}; double WHITE[] = {2.0, 1.7, 1.7}; double BLACK[] = {0.0, 0.3, 0.3}; // compute the square error relative to the reference color values //double minError = 3.0; double minError = 2.2; double errorSqr; char bestFit = 'x'; // check BLUE fitness errorSqr = normSqr(BLUE[0], BLUE[1], BLUE[2], bavg, gavg, ravg); if(errorSqr < minError) { minError = errorSqr; bestFit = COLOR_BLUE; } // check ORANGE fitness errorSqr = normSqr(ORANGE[0], ORANGE[1], ORANGE[2], bavg, gavg, ravg); if(errorSqr < minError) { minError = errorSqr; bestFit = COLOR_ORANGE; } // check WHITE fitness errorSqr = normSqr(WHITE[0], WHITE[1], WHITE[2], bavg, gavg, ravg); if(errorSqr < minError) { minError = errorSqr; bestFit = COLOR_WHITE; } // check BLACK fitness errorSqr = normSqr(BLACK[0], BLACK[1], BLACK[2], bavg, gavg, ravg); if(errorSqr < minError) { minError = errorSqr; bestFit = COLOR_BLACK; } // return the best fit color label return bestFit; } /** * Computes the squared norm of two tuples * @param x1 x coordinate of first point * @param y1 y coordinate of first point * @param z1 z coordinate of first point * @param x2 x coordinate of second point * @param y2 y coordinate of second point * @param z2 z coordinate of second point * @return the squared norm of the two tuples */ public double normSqr(double x1, double y1, double z1, double x2, double y2, double z2) { return (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) + (z1 - z2)*(z1 - z2); } /** * Capture images and run color processing through here */ public void capture() { VideoCapture camera = new VideoCapture(); camera.set(12, -20); // change contrast, might not be necessary CaptureImage image = new CaptureImage(); camera.open(0); //Useless if(!camera.isOpened()) { System.out.println("Camera Error"); // Determine whether to use System.exit(0) or return } else { System.out.println("Camera OK"); } boolean success = camera.read(capturedFrame); if (success) { image.processFrame(capturedFrame, processedFrame); // processedFrame should be CV_8UC3 //image.findCaptured(processedFrame); image.determineKings(capturedFrame); int bufferSize = processedFrame.channels() * processedFrame.cols() * processedFrame.rows(); byte[] b = new byte[bufferSize]; processedFrame.get(0,0,b); // get all the pixels // This might need to be BufferedImage.TYPE_INT_ARGB img = new BufferedImage(processedFrame.cols(), processedFrame.rows(), BufferedImage.TYPE_INT_RGB); int width = (int)camera.get(Highgui.CV_CAP_PROP_FRAME_WIDTH); int height = (int)camera.get(Highgui.CV_CAP_PROP_FRAME_HEIGHT); //img.getRaster().setDataElements(0, 0, width, height, b); byte[] a = new byte[bufferSize]; System.arraycopy(b, 0, a, 0, bufferSize); Highgui.imwrite("camera.jpg",processedFrame); System.out.println("Success"); } else System.out.println("Unable to capture image"); camera.release(); } /** * @return BufferedImage of the processed image */ public BufferedImage getImage() { return this.img; } /** * @return state of board */ public byte[] getBoard() { return this.board; } public byte[] getCaptured() { return this.captured; } public static void main(String args[]) { CaptureImage im = new CaptureImage(); im.capture(); } }
package com.kylantraynor.civilizations.banners; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.block.banner.Pattern; import org.bukkit.block.banner.PatternType; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BannerMeta; public class Banner { static private List<Banner> all = new ArrayList<Banner>(); List<Pattern> patterns = new ArrayList<Pattern>(); private org.bukkit.block.Banner banner; private DyeColor baseColor; public static boolean exist(BannerMeta bm){ for(Banner b : all){ if(b.isSimilar(bm)) return true; } return false; } public static boolean exist(org.bukkit.block.Banner banner){ for(Banner b : all){ if(b.isSimilar(banner)) return true; } return false; } public static boolean exist(Banner banner){ for(Banner b : all){ if(b.isSimilar(banner)) return true; } return false; } public static Banner get(org.bukkit.block.Banner banner){ for(Banner b : all){ if(b.isSimilar(banner)) return b; } return new Banner(banner.getBaseColor(), banner.getPatterns()); } public static Banner get(BannerMeta bm) { for(Banner b : all){ if(b.isSimilar(bm)) return b; } return new Banner(bm.getBaseColor(), bm.getPatterns()); } public static void add(Banner banner){ for(Banner b : all){ if(b.isSimilar(banner)) return; } all.add(banner); } public boolean isSimilar(BannerMeta banner){ if(!banner.getBaseColor().equals(this.getBaseColor()))return false; if(banner.getPatterns().size() != this.getPatterns().size()) return false; for(int i = 0; i < banner.getPatterns().size(); i++){ if(!banner.getPatterns().get(i).getPattern().equals(this.getPatterns().get(i).getPattern())) return false; if(!banner.getPatterns().get(i).getColor().equals(this.getPatterns().get(i).getColor())) return false; } return true; } public boolean isSimilar(org.bukkit.block.Banner banner){ if(!banner.getBaseColor().equals(this.getBaseColor()))return false; if(banner.getPatterns().size() != this.getPatterns().size()) return false; for(int i = 0; i < banner.getPatterns().size(); i++){ if(!banner.getPatterns().get(i).getPattern().equals(this.getPatterns().get(i).getPattern())) return false; if(!banner.getPatterns().get(i).getColor().equals(this.getPatterns().get(i).getColor())) return false; } return true; } public boolean isSimilar(Banner banner){ if(!banner.getBaseColor().equals(this.getBaseColor()))return false; if(banner.getPatterns().size() != this.getPatterns().size()) return false; for(int i = 0; i < banner.getPatterns().size(); i++){ if(!banner.getPatterns().get(i).getPattern().equals(this.getPatterns().get(i).getPattern())) return false; if(!banner.getPatterns().get(i).getColor().equals(this.getPatterns().get(i).getColor())) return false; } return true; } public List<Pattern> getPatterns(){ return patterns; } public DyeColor getBaseColor(){ return baseColor; } public Banner(DyeColor baseColor, List<Pattern> patterns){ this.patterns = patterns; this.baseColor = baseColor; Banner.add(this); } public ItemStack getItemStack(){ ItemStack is = new ItemStack(Material.BANNER, 1); BannerMeta bm = (BannerMeta) is.getItemMeta(); bm.setBaseColor(getBaseColor()); bm.setPatterns(getPatterns()); is.setItemMeta(bm); return is; } public static Banner parse(String s){ try{ DyeColor baseColor = null; List<Pattern> patterns = new ArrayList<Pattern>(); String[] components = s.split(";"); if(components.length >= 2){ baseColor = DyeColor.valueOf(components[1]); } for(int i = 2; i < components.length; i++){ String str = components[i]; str = str.replaceAll("[{}]", ""); String[] pat = str.split(":"); patterns.add(new Pattern(DyeColor.valueOf(pat[1]), PatternType.valueOf(pat[0]))); } if(baseColor != null){ return new Banner(baseColor, patterns); } else { return null; } } catch (Exception e){ e.printStackTrace(); return null; } } @Override public String toString(){ StringBuilder sb = new StringBuilder("BANNER;"); sb.append(getBaseColor().toString() + ";"); for(Pattern p : getPatterns()){ sb.append("{" + p.getPattern().toString() + ":" + p.getColor().toString() + "};"); } return sb.toString(); } }
package net.sf.jaer.util; import java.io.PrintWriter; import java.io.StringWriter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; /** * A thread group that implements uncaughtException to log uncaught exceptions */ public class LoggingThreadGroup extends ThreadGroup { private static Logger logger; public LoggingThreadGroup(String name) { super(name); } /** * Thread and Throwable passed in here are passed to a Logger named * "UncaughtExceptionLogger" which has the handler LoggingWindowHandler. */ public void uncaughtException(Thread thread, Throwable throwable) { // Initialize logger once if (logger == null) { logger = Logger.getLogger("UncaughtExceptionLogger"); Handler handler = LoggingWindowHandler.getInstance(); logger.addHandler(handler); } try { logger.log(Level.WARNING, thread == null ? "(null thread supplied)" : thread.toString(), throwable == null ? "(null exception)" : throwable); } catch (RuntimeException rte) { System.out.println((thread == null ? "(null thread supplied)" : thread.toString()) + ": " + (throwable == null ? "(null exception)" : throwable.toString())); if (throwable != null) { throwable.printStackTrace(); if (throwable.getCause() != null) { throwable.getCause().printStackTrace(); } } } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); if (thread != null) { // throwable might have a null stack trace because of some optimization of JVM (tobi) if (throwable == null) { new Throwable().printStackTrace(pw); // get stack trace if throwable is somehow null } else { // even if throwable is not null, if it doesn't have stack trace, get one from current thread StackTraceElement[] st = throwable.getStackTrace(); if (st == null || st.length == 0) { new Throwable().printStackTrace(pw); // get stack trace if throwable is somehow null } } } if (throwable != null) { throwable.printStackTrace(pw); if (throwable.getCause() != null) { throwable.getCause().printStackTrace(pw); } } else { sw.write("(null exception, cannot provide stack trace)"); } pw.flush(); String st = sw.toString(); logger.log(Level.WARNING, st); } // public static void main(String args[]) throws Exception { // Thread.UncaughtExceptionHandler handler = new LoggingThreadGroup("Logger"); // Thread.currentThread().setUncaughtExceptionHandler(handler); //// System.out.println(1 / 0); // throw new RuntimeException("test RuntimeException"); }
// PrintRenderer is an abstract base class for renderers that produce printed type output. // Subclasses would be PDFRenderer, PCLRenderer and similar renderers. package org.apache.fop.render; // FOP import org.apache.fop.pdf.PDFPathPaint; import org.apache.fop.pdf.PDFColor; //import org.apache.fop.render.Renderer; //import org.apache.fop.messaging.MessageHandler; import org.apache.fop.image.ImageArea; //import org.apache.fop.image.FopImage; import org.apache.fop.apps.FOPException; import org.apache.fop.fo.properties.*; import org.apache.fop.layout.*; import org.apache.fop.layout.inline.*; import org.apache.fop.datatypes.*; //import org.apache.fop.configuration.Configuration; //import org.apache.fop.extensions.*; //import org.apache.fop.datatypes.IDReferences; import org.apache.fop.render.pdf.FontSetup; import org.apache.fop.dom.svg.*; // Java import java.io.IOException; import java.io.OutputStream; import java.util.Enumeration; /** * Abstract base class of "Print" type renderers. */ public abstract class PrintRenderer implements Renderer { // vvv These are not currently referenced by the PrintRenderer, but are common to PCL and PDF renderers - so declare here. /** the current (internal) font name */ protected String currentFontName; /** the current font size in millipoints */ protected int currentFontSize; /** the current color/gradient for borders, letters, etc. */ protected PDFPathPaint currentStroke = null; /** the current color/gradient to fill shapes with */ protected PDFPathPaint currentFill = null; /** the current colour's red component */ //protected float currentRed = 0; /** the current colour's green component */ //protected float currentGreen = 0; /** the current colour's blue component */ //protected float currentBlue = 0; /** the current vertical position in millipoints from bottom */ protected int currentYPosition = 0; /** the current horizontal position in millipoints from left */ protected int currentXPosition = 0; /** the horizontal position of the current area container */ protected int currentAreaContainerXPosition = 0; // previous values used for text-decoration drawing protected int prevUnderlineXEndPos; protected int prevUnderlineYEndPos; protected int prevUnderlineSize; protected PDFColor prevUnderlineColor; protected int prevOverlineXEndPos; protected int prevOverlineYEndPos; protected int prevOverlineSize; protected PDFColor prevOverlineColor; protected int prevLineThroughXEndPos; protected int prevLineThroughYEndPos; protected int prevLineThroughSize; protected PDFColor prevLineThroughColor; protected FontInfo fontInfo; /** the IDReferences for this document */ protected IDReferences idReferences; /** * set the document's producer * * @param producer string indicating application producing PDF */ public abstract void setProducer(String producer); /** * render the areas * * @param areaTree the laid-out area tree * @param stream the OutputStream to write to */ public abstract void render(AreaTree areaTree, OutputStream stream) throws IOException, FOPException; /** * add a line to the current stream * * @param x1 the start x location in millipoints * @param y1 the start y location in millipoints * @param x2 the end x location in millipoints * @param y2 the end y location in millipoints * @param th the thickness in millipoints * @param r the red component * @param g the green component * @param b the blue component */ protected abstract void addLine(int x1, int y1, int x2, int y2, int th, PDFPathPaint stroke); /** * add a line to the current stream * * @param x1 the start x location in millipoints * @param y1 the start y location in millipoints * @param x2 the end x location in millipoints * @param y2 the end y location in millipoints * @param th the thickness in millipoints * @param rs the rule style * @param r the red component * @param g the green component * @param b the blue component */ protected abstract void addLine(int x1, int y1, int x2, int y2, int th, int rs, PDFPathPaint stroke); /** * add a rectangle to the current stream * * @param x the x position of left edge in millipoints * @param y the y position of top edge in millipoints * @param w the width in millipoints * @param h the height in millipoints * @param stroke the stroke color/gradient */ protected abstract void addRect(int x, int y, int w, int h, PDFPathPaint stroke); /** * add a filled rectangle to the current stream * * @param x the x position of left edge in millipoints * @param y the y position of top edge in millipoints * @param w the width in millipoints * @param h the height in millipoints * @param fill the fill color/gradient * @param stroke the stroke color/gradient */ protected abstract void addRect(int x, int y, int w, int h, PDFPathPaint stroke, PDFPathPaint fill); /** * render area container * * @param area the area container to render */ public void renderAreaContainer(AreaContainer area) { int saveY = this.currentYPosition; int saveX = this.currentAreaContainerXPosition; if (area.getPosition() == Position.ABSOLUTE) { // Y position is computed assuming positive Y axis, adjust for negative postscript one this.currentYPosition = area.getYPosition() - 2 * area.getPaddingTop() - 2 * area.getBorderTopWidth(); this.currentAreaContainerXPosition = area.getXPosition(); } else if (area.getPosition() == Position.RELATIVE) { this.currentYPosition -= area.getYPosition(); this.currentAreaContainerXPosition += area.getXPosition(); } else if (area.getPosition() == Position.STATIC) { this.currentYPosition -= area.getPaddingTop() + area.getBorderTopWidth(); this.currentAreaContainerXPosition += area.getPaddingLeft() + area.getBorderLeftWidth(); } this.currentXPosition = this.currentAreaContainerXPosition; doFrame(area); Enumeration e = area.getChildren().elements(); while (e.hasMoreElements()) { Box b = (Box) e.nextElement(); b.render(this); } if (area.getPosition() != Position.STATIC) { this.currentYPosition = saveY; this.currentAreaContainerXPosition = saveX; } else this.currentYPosition -= area.getHeight(); } public void renderBodyAreaContainer(BodyAreaContainer area) { int saveY = this.currentYPosition; int saveX = this.currentAreaContainerXPosition; if (area.getPosition() == Position.ABSOLUTE) { // Y position is computed assuming positive Y axis, adjust for negative postscript one this.currentYPosition = area.getYPosition(); this.currentAreaContainerXPosition = area.getXPosition(); } else if (area.getPosition() == Position.RELATIVE) { this.currentYPosition -= area.getYPosition(); this.currentAreaContainerXPosition += area.getXPosition(); } this.currentXPosition = this.currentAreaContainerXPosition; int w, h; int rx = this.currentAreaContainerXPosition; w = area.getContentWidth(); h = area.getContentHeight(); int ry = this.currentYPosition; ColorType bg = area.getBackgroundColor(); // I'm not sure I should have to check for bg being null // but I do if ((bg != null) && (bg.alpha() == 0)) { this.addRect(rx, ry, w, -h, new PDFColor(bg), new PDFColor(bg)); } // floats & footnotes stuff renderAreaContainer(area.getBeforeFloatReferenceArea()); renderAreaContainer(area.getFootnoteReferenceArea()); // main reference area Enumeration e = area.getMainReferenceArea().getChildren().elements(); while (e.hasMoreElements()) { Box b = (Box) e.nextElement(); b.render(this); // span areas } if (area.getPosition() != Position.STATIC) { this.currentYPosition = saveY; this.currentAreaContainerXPosition = saveX; } else this.currentYPosition -= area.getHeight(); } public void renderSpanArea(SpanArea area) { Enumeration e = area.getChildren().elements(); while (e.hasMoreElements()) { Box b = (Box) e.nextElement(); b.render(this); // column areas } } private void doFrame(Area area) { int w, h; int rx = this.currentAreaContainerXPosition; w = area.getContentWidth(); if (area instanceof BlockArea) rx += ((BlockArea) area).getStartIndent(); h = area.getContentHeight(); int ry = this.currentYPosition; ColorType bg = area.getBackgroundColor(); rx = rx - area.getPaddingLeft(); ry = ry + area.getPaddingTop(); w = w + area.getPaddingLeft() + area.getPaddingRight(); h = h + area.getPaddingTop() + area.getPaddingBottom(); // I'm not sure I should have to check for bg being null // but I do if ((bg != null) && (bg.alpha() == 0)) { this.addRect(rx, ry, w, -h, new PDFColor(bg), new PDFColor(bg)); } //rx = rx - area.getBorderLeftWidth(); //ry = ry + area.getBorderTopWidth(); //w = w + area.getBorderLeftWidth() + area.getBorderRightWidth(); //h = h + area.getBorderTopWidth() + area.getBorderBottomWidth(); // Handle line style // Offset for haft the line width! BorderAndPadding bp = area.getBorderAndPadding(); int left = rx - area.getBorderLeftWidth() / 2; int right = rx + w + area.getBorderRightWidth() / 2; int top = ry + area.getBorderTopWidth() / 2; int bottom = ry - h - area.getBorderBottomWidth() / 2; if (area.getBorderTopWidth() != 0) addLine(left, top, right, top, area.getBorderTopWidth(), new PDFColor(bp.getBorderColor(BorderAndPadding.TOP))); if (area.getBorderLeftWidth() != 0) addLine(left, ry + area.getBorderTopWidth(), left, bottom, area.getBorderLeftWidth(), new PDFColor(bp.getBorderColor(BorderAndPadding.LEFT))); if (area.getBorderRightWidth() != 0) addLine(right, ry + area.getBorderTopWidth(), right, bottom, area.getBorderRightWidth(), new PDFColor(bp.getBorderColor(BorderAndPadding.RIGHT))); if (area.getBorderBottomWidth() != 0) addLine(rx - area.getBorderLeftWidth(), bottom, rx + w + area.getBorderRightWidth(), bottom, area.getBorderBottomWidth(), new PDFColor(bp.getBorderColor(BorderAndPadding.BOTTOM))); } /** * render block area * * @param area the block area to render */ public void renderBlockArea(BlockArea area) { // KLease: Temporary test to fix block positioning // Offset ypos by padding and border widths this.currentYPosition -= (area.getPaddingTop() + area.getBorderTopWidth()); doFrame(area); Enumeration e = area.getChildren().elements(); while (e.hasMoreElements()) { Box b = (Box) e.nextElement(); b.render(this); } this.currentYPosition -= (area.getPaddingBottom() + area.getBorderBottomWidth()); } /** * render display space * * @param space the display space to render */ public void renderDisplaySpace(DisplaySpace space) { int d = space.getSize(); this.currentYPosition -= d; } /** * render image area * * @param area the image area to render */ public abstract void renderImageArea(ImageArea area); /** render a foreign object area */ public abstract void renderForeignObjectArea(ForeignObjectArea area); /** * render SVG area * * @param area the SVG area to render */ public abstract void renderSVGArea(SVGArea area); /** * render inline area * * @param area inline area to render */ public abstract void renderWordArea(WordArea area); protected void addWordLines(WordArea area, int rx, int bl, int size, PDFColor theAreaColor) { if (area.getUnderlined()) { int yPos = bl - size/10; addLine(rx, yPos, rx + area.getContentWidth(), yPos, size/14, theAreaColor); // save position for underlining a following InlineSpace prevUnderlineXEndPos = rx + area.getContentWidth(); prevUnderlineYEndPos = yPos; prevUnderlineSize = size/14; prevUnderlineColor = theAreaColor; } if (area.getOverlined()) { int yPos = bl + area.getFontState().getAscender() + size/10; addLine(rx, yPos, rx + area.getContentWidth(), yPos, size/14, theAreaColor); prevOverlineXEndPos = rx + area.getContentWidth(); prevOverlineYEndPos = yPos; prevOverlineSize = size/14; prevOverlineColor = theAreaColor; } if (area.getLineThrough()) { int yPos = bl + area.getFontState().getAscender() * 3/8; addLine(rx, yPos, rx + area.getContentWidth(), yPos, size/14, theAreaColor); prevLineThroughXEndPos = rx + area.getContentWidth(); prevLineThroughYEndPos = yPos; prevLineThroughSize = size/14; prevLineThroughColor = theAreaColor; } } /** * render inline space * * @param space space to render */ public void renderInlineSpace(InlineSpace space) { this.currentXPosition += space.getSize(); if (space.getUnderlined()) { if (prevUnderlineColor != null) { addLine(prevUnderlineXEndPos, prevUnderlineYEndPos, prevUnderlineXEndPos + space.getSize(), prevUnderlineYEndPos, prevUnderlineSize, prevUnderlineColor); } } if (space.getOverlined()) { if (prevOverlineColor != null) { addLine(prevOverlineXEndPos, prevOverlineYEndPos, prevOverlineXEndPos + space.getSize(), prevOverlineYEndPos, prevOverlineSize, prevOverlineColor); } } if (space.getLineThrough()) { if (prevLineThroughColor != null) { addLine(prevLineThroughXEndPos, prevLineThroughYEndPos, prevLineThroughXEndPos + space.getSize(), prevLineThroughYEndPos, prevLineThroughSize, prevLineThroughColor); } } } /** * render line area * * @param area area to render */ public void renderLineArea(LineArea area) { int rx = this.currentAreaContainerXPosition + area.getStartIndent(); int ry = this.currentYPosition; int w = area.getContentWidth(); int h = area.getHeight(); this.currentYPosition -= area.getPlacementOffset(); this.currentXPosition = rx; int bl = this.currentYPosition; Enumeration e = area.getChildren().elements(); while (e.hasMoreElements()) { Box b = (Box) e.nextElement(); if(b instanceof InlineArea) { InlineArea ia = (InlineArea)b; this.currentYPosition = ry - ia.getYOffset(); } else { this.currentYPosition = ry - area.getPlacementOffset(); } b.render(this); } this.currentYPosition = ry - h; this.currentXPosition = rx; } /** * render page * * @param page page to render */ public abstract void renderPage(Page page); /** * render leader area * * @param area area to render */ public void renderLeaderArea(LeaderArea area) { int rx = this.currentXPosition; int ry = this.currentYPosition; int w = area.getContentWidth(); int h = area.getHeight(); int th = area.getRuleThickness(); int st = area.getRuleStyle(); //checks whether thickness is = 0, because of bug in pdf (or where?), //a line with thickness 0 is still displayed if (th != 0) { switch (st) { case org.apache.fop.fo.properties.RuleStyle.DOUBLE: addLine(rx, ry, rx + w, ry, th / 3, st, new PDFColor(area.getRed(), area.getGreen(), area.getBlue())); addLine(rx, ry + (2 * th / 3), rx + w, ry + (2 * th / 3), th / 3, st, new PDFColor(area.getRed(), area.getGreen(), area.getBlue())); break; case org.apache.fop.fo.properties.RuleStyle.GROOVE: addLine(rx, ry, rx + w, ry, th / 2, st, new PDFColor(area.getRed(), area.getGreen(), area.getBlue())); addLine(rx, ry + (th / 2), rx + w, ry + (th / 2), th / 2, st, new PDFColor(255, 255, 255)); break; case org.apache.fop.fo.properties.RuleStyle.RIDGE: addLine(rx, ry, rx + w, ry, th / 2, st, new PDFColor(255, 255, 255)); addLine(rx, ry + (th / 2), rx + w, ry + (th / 2), th / 2, st, new PDFColor(area.getRed(), area.getGreen(), area.getBlue())); break; default: addLine(rx, ry, rx + w, ry, th, st, new PDFColor(area.getRed(), area.getGreen(), area.getBlue())); } this.currentXPosition += area.getContentWidth(); this.currentYPosition += th; } } /** * set up the font info * * @param fontInfo font info to set up */ public void setupFontInfo(FontInfo fontInfo) { this.fontInfo = fontInfo; FontSetup.setup(fontInfo); } }
package org.apache.xerces.dom; import org.apache.xerces.impl.xs.psvi.XSTypeDefinition; import org.apache.xerces.util.URI; import org.apache.xerces.xni.NamespaceContext; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; /** * ElementNSImpl inherits from ElementImpl and adds namespace support. * <P> * The qualified name is the node name, and we store localName which is also * used in all queries. On the other hand we recompute the prefix when * necessary. * * @version $Id$ */ public class ElementNSImpl extends ElementImpl { // Constants /** Serialization version. */ static final long serialVersionUID = -9142310625494392642L; static final String xmlURI = "http: // Data /** DOM2: Namespace URI. */ protected String namespaceURI; /** DOM2: localName. */ protected String localName; /** DOM3: type information */ XSTypeDefinition type; protected ElementNSImpl() { super(); } /** * DOM2: Constructor for Namespace implementation. */ protected ElementNSImpl(CoreDocumentImpl ownerDocument, String namespaceURI, String qualifiedName) throws DOMException { super(ownerDocument, qualifiedName); setName(namespaceURI, qualifiedName); } private void setName(String namespaceURI, String qname) { String prefix; // DOM Level 3: namespace URI is never empty string. this.namespaceURI = namespaceURI; if (namespaceURI != null) { this.namespaceURI = (namespaceURI.length() == 0) ? null : namespaceURI; } int colon1 = qname.indexOf(':'); int colon2 = qname.lastIndexOf(':'); ownerDocument().checkNamespaceWF(qname, colon1, colon2); if (colon1 < 0) { // there is no prefix localName = qname; ownerDocument().checkQName(null, localName); if (qname.equals("xmlns") && (namespaceURI == null || !namespaceURI.equals(NamespaceContext.XMLNS_URI)) || (namespaceURI!=null && namespaceURI.equals(NamespaceContext.XMLNS_URI) && !qname.equals("xmlns"))) { String msg = DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "NAMESPACE_ERR", null); throw new DOMException(DOMException.NAMESPACE_ERR, msg); } } else { prefix = qname.substring(0, colon1); localName = qname.substring(colon2 + 1); ownerDocument().checkQName(prefix, localName); ownerDocument().checkDOMNSErr(prefix, namespaceURI); } } // when local name is known protected ElementNSImpl(CoreDocumentImpl ownerDocument, String namespaceURI, String qualifiedName, String localName) throws DOMException { super(ownerDocument, qualifiedName); this.localName = localName; this.namespaceURI = namespaceURI; } // for DeferredElementImpl protected ElementNSImpl(CoreDocumentImpl ownerDocument, String value) { super(ownerDocument, value); } // Support for DOM Level 3 renameNode method. // Note: This only deals with part of the pb. CoreDocumentImpl // does all the work. void rename(String namespaceURI, String qualifiedName) { if (needsSyncData()) { synchronizeData(); } this.name = qualifiedName; setName(namespaceURI, qualifiedName); reconcileDefaultAttributes(); } /** * NON-DOM: resets this node and sets specified values for the node * * @param ownerDocument * @param namespaceURI * @param qualifiedName * @param localName */ protected void setValues (CoreDocumentImpl ownerDocument, String namespaceURI, String qualifiedName, String localName){ // remove children first firstChild = null; previousSibling = null; nextSibling = null; fNodeListCache = null; // set owner document attributes = null; super.flags = 0; setOwnerDocument(ownerDocument); // synchronizeData will initialize attributes needsSyncData(true); super.name = qualifiedName; this.localName = localName; this.namespaceURI = namespaceURI; } // Node methods //DOM2: Namespace methods. /** * Introduced in DOM Level 2. <p> * * The namespace URI of this node, or null if it is unspecified.<p> * * This is not a computed value that is the result of a namespace lookup based on * an examination of the namespace declarations in scope. It is merely the * namespace URI given at creation time.<p> * * For nodes created with a DOM Level 1 method, such as createElement * from the Document interface, this is null. * @since WD-DOM-Level-2-19990923 */ public String getNamespaceURI() { if (needsSyncData()) { synchronizeData(); } return namespaceURI; } /** * Introduced in DOM Level 2. <p> * * The namespace prefix of this node, or null if it is unspecified. <p> * * For nodes created with a DOM Level 1 method, such as createElement * from the Document interface, this is null. <p> * * @since WD-DOM-Level-2-19990923 */ public String getPrefix() { if (needsSyncData()) { synchronizeData(); } int index = name.indexOf(':'); return index < 0 ? null : name.substring(0, index); } /** * Introduced in DOM Level 2. <p> * * Note that setting this attribute changes the nodeName attribute, which holds the * qualified name, as well as the tagName and name attributes of the Element * and Attr interfaces, when applicable.<p> * * @param prefix The namespace prefix of this node, or null(empty string) if it is unspecified. * * @exception INVALID_CHARACTER_ERR * Raised if the specified * prefix contains an invalid character. * @exception DOMException * @since WD-DOM-Level-2-19990923 */ public void setPrefix(String prefix) throws DOMException { if (needsSyncData()) { synchronizeData(); } if (ownerDocument().errorChecking) { if (isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException( DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } if (prefix != null && prefix.length() != 0) { if (!CoreDocumentImpl.isXMLName(prefix)) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_CHARACTER_ERR", null); throw new DOMException(DOMException.INVALID_CHARACTER_ERR, msg); } if (namespaceURI == null || prefix.indexOf(':') >=0) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NAMESPACE_ERR", null); throw new DOMException(DOMException.NAMESPACE_ERR, msg); } else if (prefix.equals("xml")) { if (!namespaceURI.equals(xmlURI)) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NAMESPACE_ERR", null); throw new DOMException(DOMException.NAMESPACE_ERR, msg); } } } } // update node name with new qualifiedName if (prefix !=null && prefix.length() != 0) { name = prefix + ":" + localName; } else { name = localName; } } /** * Introduced in DOM Level 2. <p> * * Returns the local part of the qualified name of this node. * @since WD-DOM-Level-2-19990923 */ public String getLocalName() { if (needsSyncData()) { synchronizeData(); } return localName; } /** * DOM Level 3 WD - Experimental. * Retrieve baseURI */ public String getBaseURI() { if (needsSyncData()) { synchronizeData(); } String baseURI = this.ownerNode.getBaseURI(); if (attributes != null) { Attr attrNode = (Attr)attributes.getNamedItemNS("http: if (attrNode != null) { String uri = attrNode.getNodeValue(); if (uri.length() != 0 ) {// attribute value is always empty string try { uri = new URI(new URI(baseURI), uri).toString(); } catch (org.apache.xerces.util.URI.MalformedURIException e){ // REVISIT: what should happen in this case? return null; } return uri; } } } return baseURI; } /** * @see org.apache.xerces.dom3.TypeInfo#getTypeName() */ public String getTypeName() { if (type !=null){ return type.getName(); } return null; } /** * @see org.apache.xerces.dom3.TypeInfo#getTypeNamespace() */ public String getTypeNamespace() { if (type !=null){ return type.getNamespace(); } return null; } /** * NON-DOM: setting type used by the DOM parser * @see NodeImpl#setReadOnly */ public void setType(XSTypeDefinition type) { this.type = type; } }
package org.javarosa.polishforms; import java.util.Stack; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Displayable; import org.javarosa.clforms.Controller; import org.javarosa.clforms.MVCComponent; import org.javarosa.clforms.api.Prompt; import org.javarosa.clforms.api.ResponseEvent; import org.javarosa.clforms.view.FormView; import org.javarosa.clforms.view.IPrompter; import de.enough.polish.ui.Item; import de.enough.polish.ui.ItemStateListener; import de.enough.polish.ui.UiAccess; /*** * The ChatScreen is a view for Mobile MRS that presents an entire XForm to the user. * * It implements both the IPrompter and FormView interfaces, to be responsible for presenting forms and prompts in * the same screen. * * The Screen presents each Prompt as a DisplayFrame, one at a time scrolling from the bottom of the screen to the top. * * @author ctsims * */ public class ChatScreen extends de.enough.polish.ui.FramedForm implements IPrompter, FormView, CommandListener, ItemStateListener{ Controller controller; Command menuCommand = new Command("Menu", Command.SCREEN, 1); Command selectCommand = new Command("Select", Command.BACK, 1); Command saveAndReloadCommand = new Command("Save and Reload", Command.SCREEN, 1); Command exitCommand = new Command("Exit", Command.EXIT, 1); Stack displayFrames = new Stack(); Stack prompts = new Stack(); /** * Creates a ChatScreen, and loads the menus */ public ChatScreen() { //#style framedForm super("Chatterbox"); this.addCommand(menuCommand); this.addCommand(selectCommand); UiAccess.addSubCommand(exitCommand, menuCommand,this); UiAccess.addSubCommand(saveAndReloadCommand, menuCommand,this); this.setCommandListener(this); } /** * Handler for when the answer for the previous question has been selected */ private void selectPressed() { System.out.println("selected!"); if(!displayFrames.empty()) { DisplayFrame topFrame = (DisplayFrame)(displayFrames.peek()); topFrame.evaluateResponse(); } } /** * Adds a new Prompt to the screen * * @param nextPrompt The prompt to be added */ private void addPrompt(Prompt nextPrompt) { DisplayFrame frame = new DisplayFrame(nextPrompt); this.setItemStateListener(this); displayFrames.push(frame); prompts.push(nextPrompt); frame.drawLargeFormOnScreen(this); } /** * Removes a generic MIDP Item that is contained in this screen * * @param theItem The item to be removed * * @return The old index of the removed item. -1 if the Item was not found. */ public int removeItem(Item theItem) { for(int i = 0 ; i < this.size(); i++ ) { if(this.get(i).equals(theItem)) { this.delete(i); return i; } } return -1; } /** * Exits this form */ private void exitForm() { controller.processEvent(new ResponseEvent(ResponseEvent.EXIT, -1)); clearForm(); } /** * Clears the current form from this display */ private void clearForm() { prompts.removeAllElements(); while(!displayFrames.isEmpty()) { DisplayFrame frame = (DisplayFrame)displayFrames.pop(); frame.removeFromScreen(this); } } /** * Identify whether the form is finished * * @param prompt The last prompt provided by the controller * @return true if the form is finished, false otherwise. */ private boolean checkFinishedWithForm(Prompt prompt) { if(prompts.contains(prompt)) { return true; } return false; } /** * (Inherited from FormView) Displays a prompt This is generally a sign that * we're either starting or finishing a form */ public void displayPrompt(Prompt prompt) { System.out.println("Display Prompt"); if (checkFinishedWithForm(prompt)) { exitForm(); } else { MVCComponent.display.setCurrent(this); showPrompt(prompt); } } /** * Shows a prompt on the screen */ public void showPrompt(Prompt prompt) { if(!displayFrames.empty()) { DisplayFrame topFrame = (DisplayFrame)(displayFrames.peek()); topFrame.evaluateResponse(); topFrame.removeFromScreen(this); topFrame.drawSmallFormOnScreen(this); } addPrompt(prompt); } /** * Shows a prompt on the screen at position screenIndex of totalScreens */ public void showPrompt(Prompt prompt, int screenIndex, int totalScreens) { showPrompt(prompt); } /** * Registers a controller with this FormView */ public void registerController(Controller controller) { this.controller = controller; } /** * Handles command events */ public void commandAction(Command command, Displayable s) { try { if (command == selectCommand) { selectPressed(); controller.processEvent(new ResponseEvent(ResponseEvent.NEXT, -1)); } else if (command == saveAndReloadCommand) { clearForm(); controller.processEvent(new ResponseEvent(ResponseEvent.SAVE_AND_RELOAD, -1)); } else if (command == exitCommand){ exitForm(); } } catch (Exception e) { Alert a = new Alert("error.screen" + " 2"); //$NON-NLS-1$ a.setString(e.getMessage()); a.setTimeout(Alert.FOREVER); MVCComponent.display.setCurrent(a); } } /** * Makes proper updates when an Item on this page is changed */ public void itemStateChanged(Item item) { if(!displayFrames.empty()) { DisplayFrame topFrame = (DisplayFrame)(displayFrames.peek()); if(topFrame.autoPlayItem(item)) { commandAction(selectCommand,this); } } } }
package com.competitionapp.nrgscouting; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.text.method.ScrollingMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Scroller; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, ActivityUtility{ Toolbar toolbar = null; FloatingActionButton fab; RefreshableFragment currentFragment; public static String CURRENT_VERSION = "3.5_0"; public static int EDITING_ENTRY = 1; public static int FINISHED_ENTRY = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fab = (FloatingActionButton)findViewById(R.id.fab); //Set about frag initially when app opens final MatchFragment matchFragment = new MatchFragment(); currentFragment = matchFragment; final android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, matchFragment, "mat"); fragmentTransaction.commit(); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); /*MatchFragment mat = (MatchFragment) getSupportFragmentManager().findFragmentByTag("mat"); mat.refreshEntryList();*/ fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, TeamSearchPop.class); intent.putExtra("isEdit", false); startActivityForResult(intent, 0); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); setActionBarTitle("Match Scouting"); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()); if(sharedPref.getInt("lastState", 0) == EDITING_ENTRY) { Intent intent = new Intent(MainActivity.this, TabbedActivity.class); intent.putExtra("isEdit", true); intent.putExtra("retrieveFrom", "cachedEntry"); startActivityForResult(intent, 0); } } public static void cacheSaver(String fileString) throws FileNotFoundException{ File cacheDir=new File("/storage/emulated/0/Hi"); cacheDir.mkdirs(); File cacheFile=new File(cacheDir.getPath()+File.separator+"CLASSIFIED.txt"); try { if(!cacheFile.exists()) { cacheFile.createNewFile(); } PrintStream printer=new PrintStream(cacheFile); printer.print(fileString); } catch(IOException IO){ //oops } } public void setActionBarTitle(String title) { getSupportActionBar().setTitle(title); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will //automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch (item.getItemId()) { case R.id.action_export: //Toast.makeText(MainActivity.this, (String) "help", Toast.LENGTH_SHORT).show(); AlertDialog dialog = new AlertDialog.Builder(this) .setTitle("Export Entries") .setMessage(RetrieveDataFromPrefs()) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setIcon(R.drawable.ic_download_yellow) .setNegativeButton("Copy to Clipboard", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { copyToClipboard(RetrieveDataFromPrefs()); Toast.makeText(MainActivity.this, "Entries copied to clipboard.", Toast.LENGTH_SHORT) .show(); } }) .setPositiveButton("Back", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); TextView textView = (TextView) dialog.findViewById(android.R.id.message); textView.setScroller(new Scroller(this)); textView.setVerticalScrollBarEnabled(true); textView.setTextIsSelectable(true); textView.setMovementMethod(new ScrollingMovementMethod()); return true; case R.id.action_import: final AlertDialog.Builder alertadd = new AlertDialog.Builder(this); LayoutInflater factory = LayoutInflater.from(this); final View alertView = factory.inflate(R.layout.import_dialog, null); alertadd.setView(alertView); alertadd.setTitle("Import Entries"); alertadd.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertadd.setPositiveButton("Import", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditText importText = (EditText) alertView.findViewById(R.id.import_text); String input = String.valueOf(importText.getText()); if(input.equals("") || Entry.getEntriesFromString(input).isEmpty()) { Toast.makeText(MainActivity.this, "No entries added.", Toast.LENGTH_LONG).show(); return; } ArrayList<Entry> importedEntries = Entry.getEntriesFromString(input); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = sharedPref.edit(); Set<String> entryList; int countReplaced = 0; int countSame = 0; if (sharedPref.contains("MatchEntryList") && sharedPref.getStringSet("MatchEntryList", null) != null) { entryList = sharedPref.getStringSet("MatchEntryList", null); } else { entryList = new HashSet<String>(); } //ADD FANCY STUFF HERE LATER!!!!!!!!! for(Entry x : importedEntries) { String keyName = TabbedActivity.getKeyName(x); if(!entryList.contains(String.valueOf(keyName))) { entryList.add(keyName); } else { if(sharedPref.contains(keyName) && x.toString().equals(Entry.retrieveFromString(sharedPref.getString(keyName, "")).toString())) { countSame++; } else { countReplaced++; } } editor.putString(keyName, x.toString()); editor.putInt(keyName + ":index", entryList.size() - 1); } editor.putString("SAVED_VERSION", MainActivity.CURRENT_VERSION); editor.putStringSet("MatchEntryList", entryList); editor.apply(); MainActivity.this.currentFragment.refreshFragment(); if(countSame == 0) { Toast.makeText(MainActivity.this, "Added " + String.valueOf(importedEntries.size() - countReplaced) + " new entries, replaced " + countReplaced + " entries.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "Added " + String.valueOf(importedEntries.size() - countReplaced - countSame) + " new entries, replaced " + countReplaced + " entries.\n(" + countSame +" entries were the same.)", Toast.LENGTH_LONG).show(); } } }); final AlertDialog alertDialog = alertadd.create(); alertDialog.show(); return true; case R.id.action_settings: Toast.makeText(MainActivity.this, "No settings yet.", Toast.LENGTH_SHORT).show(); return true; case R.id.action_clearMemory: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Delete ALL stored match entries?"); builder.setMessage("Warning: This cannot be undone!"); builder.setCancelable(true); builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if (sharedPreferences.contains("MatchEntryList") && sharedPreferences.getStringSet("MatchEntryList", null) != null) { SharedPreferences.Editor editor = sharedPreferences.edit(); for(String x : sharedPreferences.getStringSet("MatchEntryList", null)) { if(sharedPreferences.contains(x)) { editor.remove(x); } } editor.putStringSet("MatchEntryList", null); editor.commit(); Toast.makeText(MainActivity.this, "Cleared all stored match entries.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "No stored match entries found.", Toast.LENGTH_LONG).show(); } currentFragment.refreshFragment(); } }); builder.show(); return true; case R.id.sort_switch: ((RankScreen) currentFragment).ranker = new SwitchAlgorithm(); currentFragment.refreshFragment(); item.setChecked(true); return true; case R.id.sort_climb: ((RankScreen) currentFragment).ranker = new ClimbAlgorithm(); currentFragment.refreshFragment(); item.setChecked(true); return true; case R.id.sort_defense: ((RankScreen) currentFragment).ranker = new DefensiveAlgorithm(); currentFragment.refreshFragment(); item.setChecked(true); return true; case R.id.sort_scale: ((RankScreen) currentFragment).ranker = new ScaleAlgorithm(); item.setChecked(true); currentFragment.refreshFragment(); return true; } //noinspection SimplifiableIfStatement return super.onOptionsItemSelected(item); } public String RetrieveDataFromPrefs() { SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String matchString = ""; if(!sharedPref.contains("MatchEntryList")) { return ""; } for(String x : sharedPref.getStringSet("MatchEntryList", null)) { if(sharedPref.contains(x)) { matchString += sharedPref.getString(x, "") + MatchFragment.SPLITKEY; } } try { MainActivity.cacheSaver(matchString); } catch(FileNotFoundException e){ //Do nothing } //Remove last " ||||| " return matchString.substring(0, matchString.length() - MatchFragment.SPLITKEY.length()); } public void copyToClipboard(String copy) { int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(copy); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("?", copy); clipboard.setPrimaryClip(clip); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(currentFragment != null) { currentFragment.refreshFragment(); } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_match) { MatchFragment matchFragment = new MatchFragment(); android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); currentFragment = matchFragment; fragmentTransaction.replace(R.id.fragment_container, matchFragment, "mat"); fragmentTransaction.commit(); toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); fab.show(); setActionBarTitle("Scouting"); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); } else if (id == R.id.nav_leader){ fab.hide(); RankScreen rankScreen = new RankScreen(); android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); currentFragment = rankScreen; fragmentTransaction.replace(R.id.fragment_container, rankScreen, "mat"); fragmentTransaction.commit(); //toolbar = (Toolbar)findViewById(R.id.toolbar); //setSupportActionBar(toolbar); setActionBarTitle("Rankings"); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
package org.jgroups.conf; import org.jgroups.stack.Configurator; import org.jgroups.stack.IpAddress; import org.jgroups.stack.Protocol; import org.jgroups.util.StackType; import org.jgroups.util.Util; import java.lang.reflect.Field; import java.net.*; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.List; /** * Groups a set of standard PropertyConverter(s) supplied by JGroups. * * <p> * Third parties can provide their own converters if such need arises by implementing * {@link PropertyConverter} interface and by specifying that converter as converter on a specific * Property annotation of a field or a method instance. * @author Vladimir Blagojevic */ public final class PropertyConverters { private PropertyConverters() { throw new InstantiationError("Must not instantiate this class"); } public static class NetworkInterfaceList implements PropertyConverter { public Object convert(Object obj, Class<?> propertyFieldType, String propertyName, String propertyValue, boolean check_scope, StackType ip_version) throws Exception { return Util.parseInterfaceList(propertyValue); } public String toString(Object value) { List<NetworkInterface> list=(List<NetworkInterface>)value; return Util.print(list); } } public static class InitialHosts implements PropertyConverter { public Object convert(Object obj, Class<?> propertyFieldType, String propertyName, String prop_val, boolean check_scope, StackType ip_version) throws Exception { if(prop_val == null) return null; int port_range=getPortRange((Protocol)obj); return Util.parseCommaDelimitedHosts(prop_val, port_range); } public String toString(Object value) { if(value instanceof Collection) { StringBuilder sb=new StringBuilder(); Collection<IpAddress> list=(Collection<IpAddress>)value; boolean first=true; for(IpAddress addr : list) { if(first) first=false; else sb.append(","); sb.append(addr.getIpAddress().getHostAddress()).append("[").append(addr.getPort()).append("]"); } return sb.toString(); } else return value.getClass().getName(); } private static int getPortRange(Protocol protocol) throws Exception { Field f=Util.getField(protocol.getClass(), "port_range"); return (Integer)Util.getField(f, protocol); } } public static class InitialHosts2 implements PropertyConverter { public Object convert(Object obj, Class<?> propertyFieldType, String propertyName, String prop_val, boolean check_scope, StackType ip_version) throws Exception { // port range is 0 return Util.parseCommaDelimitedHosts2(prop_val, 0); } public String toString(Object value) { if(value instanceof Collection) { StringBuilder sb=new StringBuilder(); Collection<InetSocketAddress> list=(Collection<InetSocketAddress>)value; boolean first=true; for(InetSocketAddress addr : list) { if(first) first=false; else sb.append(","); sb.append(addr.getAddress().getHostAddress()).append("[").append(addr.getPort()).append("]"); } return sb.toString(); } else return value.getClass().getName(); } } public static class BindInterface implements PropertyConverter { public Object convert(Object obj, Class<?> propertyFieldType, String propertyName, String propertyValue, boolean check_scope, StackType ip_version) throws Exception { // get the existing bind address - possibly null InetAddress old_bind_addr=Configurator.getValueFromProtocol((Protocol)obj, "bind_addr"); // apply a bind interface constraint InetAddress new_bind_addr=Util.validateBindAddressFromInterface(old_bind_addr, propertyValue, ip_version); if(new_bind_addr != null) setBindAddress((Protocol)obj, new_bind_addr); // if no bind_interface specified, set it to the empty string to avoid exception from @Property processing return propertyValue != null? propertyValue : ""; } private static void setBindAddress(Protocol protocol, InetAddress bind_addr) throws Exception { Field f=Util.getField(protocol.getClass(), "bind_addr"); Util.setField(f, protocol, bind_addr); } // return a String version of the converted value public String toString(Object value) { return (String)value; } } public static class Default implements PropertyConverter { public Object convert(Object obj, Class<?> propertyFieldType, String propertyName, String propertyValue, boolean check_scope, StackType ip_version) throws Exception { if(propertyValue == null) throw new NullPointerException("Property value cannot be null"); if(Boolean.TYPE.equals(propertyFieldType)) return Boolean.parseBoolean(propertyValue); if(Integer.TYPE.equals(propertyFieldType)) return Util.readBytesInteger(propertyValue); if(Long.TYPE.equals(propertyFieldType)) return Util.readBytesLong(propertyValue); if(Byte.TYPE.equals(propertyFieldType)) return Byte.parseByte(propertyValue); if(Double.TYPE.equals(propertyFieldType)) return Util.readBytesDouble(propertyValue); if(Short.TYPE.equals(propertyFieldType)) return Short.parseShort(propertyValue); if(Float.TYPE.equals(propertyFieldType)) return Float.parseFloat(propertyValue); if(InetAddress.class.equals(propertyFieldType)) { InetAddress retval=null; if(propertyValue.contains(",")) { List<String> addrs=Util.parseCommaDelimitedStrings(propertyValue); for(String addr : addrs) { try { retval=Util.getAddress(addr, ip_version); if(retval != null) break; } catch(Throwable ignored) { } } if(retval == null) throw new IllegalArgumentException(String.format("failed parsing attribute %s with value %s", propertyName, propertyValue)); } else retval=Util.getAddress(propertyValue, ip_version); if(check_scope && retval instanceof Inet6Address && retval.isLinkLocalAddress()) { // check scope Inet6Address addr=(Inet6Address)retval; int scope=addr.getScopeId(); if(scope == 0) { // fix scope Inet6Address ret=getScopedInetAddress(addr); if(ret != null) retval=ret; } } return retval; } return propertyValue; } protected static Inet6Address getScopedInetAddress(Inet6Address addr) { if(addr == null) return null; Enumeration<NetworkInterface> en; List<InetAddress> retval=new ArrayList<>(); try { en=NetworkInterface.getNetworkInterfaces(); while(en.hasMoreElements()) { NetworkInterface intf=en.nextElement(); Enumeration<InetAddress> addrs=intf.getInetAddresses(); while(addrs.hasMoreElements()) { InetAddress address=addrs.nextElement(); if(address.isLinkLocalAddress() && address instanceof Inet6Address && address.equals(addr) && ((Inet6Address)address).getScopeId() != 0) { retval.add(address); } } } if(retval.size() == 1) { return (Inet6Address)retval.get(0); } else return null; } catch(SocketException e) { return null; } } public String toString(Object value) { if(value instanceof InetAddress) return ((InetAddress)value).getHostAddress(); return value != null? value.toString() : null; } } }
// $Id: NAKACK.java,v 1.75 2006/03/22 06:09:10 belaban Exp $ package org.jgroups.protocols.pbcast; import org.jgroups.*; import org.jgroups.stack.NakReceiverWindow; import org.jgroups.stack.Protocol; import org.jgroups.stack.Retransmitter; import org.jgroups.util.*; import java.io.IOException; import java.util.*; /** * Negative AcKnowledgement layer (NAKs). Messages are assigned a monotonically increasing sequence number (seqno). * Receivers deliver messages ordered according to seqno and request retransmission of missing messages. Retransmitted * messages are bundled into bigger ones, e.g. when getting an xmit request for messages 1-10, instead of sending 10 * unicast messages, we bundle all 10 messages into 1 and send it. However, since this protocol typically sits below * FRAG, we cannot count on FRAG to fragement/defragment the (possibly) large message into smaller ones. Therefore we * only bundle messages up to max_xmit_size bytes to prevent too large messages. For example, if the bundled message * size was a total of 34000 bytes, and max_xmit_size=16000, we'd send 3 messages: 2 16K and a 2K message. <em>Note that * max_xmit_size should be the same value as FRAG.frag_size (or smaller).</em><br/> Retransmit requests are always sent * to the sender. If the sender dies, and not everyone has received its messages, they will be lost. In the future, this * may be changed to have receivers store all messages, so that retransmit requests can be answered by any member. * Trivial to implement, but not done yet. For most apps, the default retransmit properties are sufficient, if not use * vsync. * * @author Bela Ban */ public class NAKACK extends Protocol implements Retransmitter.RetransmitCommand, NakReceiverWindow.Listener { private long[] retransmit_timeout={600, 1200, 2400, 4800}; // time(s) to wait before requesting retransmission private boolean is_server=false; private Address local_addr=null; private final Vector members=new Vector(11); private long seqno=-1; // current message sequence number (starts with 0) private long max_xmit_size=8192; // max size of a retransmit message (otherwise send multiple) private int gc_lag=20; // number of msgs garbage collection lags behind /** * Retransmit messages using multicast rather than unicast. This has the advantage that, if many receivers lost a * message, the sender only retransmits once. */ private boolean use_mcast_xmit=true; /** * Ask a random member for retransmission of a missing message. If set to true, discard_delivered_msgs will be * set to false */ private boolean xmit_from_random_member=false; /** * Messages that have been received in order are sent up the stack (= delivered to the application). Delivered * messages are removed from NakReceiverWindow.received_msgs and moved to NakReceiverWindow.delivered_msgs, where * they are later garbage collected (by STABLE). Since we do retransmits only from sent messages, never * received or delivered messages, we can turn the moving to delivered_msgs off, so we don't keep the message * around, and don't need to wait for garbage collection to remove them. */ private boolean discard_delivered_msgs=false; /** If value is > 0, the retransmit buffer is bounded: only the max_xmit_buf_size latest messages are kept, * older ones are discarded when the buffer size is exceeded. A value <= 0 means unbounded buffers */ private int max_xmit_buf_size=0; /** * Hashtable<Address,NakReceiverWindow>. Stores received messages (keyed by sender). Note that this is no long term * storage; messages are just stored until they can be delivered (ie., until the correct FIFO order is established) */ private final HashMap received_msgs=new HashMap(11); /** TreeMap<Long,Message>. Map of messages sent by me (keyed and sorted on sequence number) */ private final TreeMap sent_msgs=new TreeMap(); private boolean leaving=false; private boolean started=false; private TimeScheduler timer=null; private static final String name="NAKACK"; private long xmit_reqs_received; private long xmit_reqs_sent; private long xmit_rsps_received; private long xmit_rsps_sent; private long missing_msgs_received; /** Captures stats on XMIT_REQS, XMIT_RSPS per sender */ private HashMap sent=new HashMap(); /** Captures stats on XMIT_REQS, XMIT_RSPS per receiver */ private HashMap received=new HashMap(); private int stats_list_size=20; /** BoundedList<XmitRequest>. Keeps track of the last stats_list_size XMIT requests */ private BoundedList receive_history; /** BoundedList<MissingMessage>. Keeps track of the last stats_list_size missing messages received */ private BoundedList send_history; public NAKACK() { } public String getName() { return name; } public long getXmitRequestsReceived() {return xmit_reqs_received;} public long getXmitRequestsSent() {return xmit_reqs_sent;} public long getXmitResponsesReceived() {return xmit_rsps_received;} public long getXmitResponsesSent() {return xmit_rsps_sent;} public long getMissingMessagesReceived() {return missing_msgs_received;} public int getPendingRetransmissionRequests() { int num=0; NakReceiverWindow win; synchronized(received_msgs) { for(Iterator it=received_msgs.values().iterator(); it.hasNext();) { win=(NakReceiverWindow)it.next(); num+=win.size(); } } return num; } public int getSentTableSize() { int size; synchronized(sent_msgs) { size=sent_msgs.size(); } return size; } public int getReceivedTableSize() { int ret=0; NakReceiverWindow win; Set s=new LinkedHashSet(received_msgs.values()); for(Iterator it=s.iterator(); it.hasNext();) { win=(NakReceiverWindow)it.next(); ret+=win.size(); } return ret; } public void resetStats() { xmit_reqs_received=xmit_reqs_sent=xmit_rsps_received=xmit_rsps_sent=missing_msgs_received=0; sent.clear(); received.clear(); if(receive_history !=null) receive_history.removeAll(); if(send_history != null) send_history.removeAll(); } public void init() throws Exception { if(stats) { send_history=new BoundedList(stats_list_size); receive_history=new BoundedList(stats_list_size); } } public int getGcLag() { return gc_lag; } public void setGcLag(int gc_lag) { this.gc_lag=gc_lag; } public boolean isUseMcastXmit() { return use_mcast_xmit; } public void setUseMcastXmit(boolean use_mcast_xmit) { this.use_mcast_xmit=use_mcast_xmit; } public boolean isXmitFromRandomMember() { return xmit_from_random_member; } public void setXmitFromRandomMember(boolean xmit_from_random_member) { this.xmit_from_random_member=xmit_from_random_member; } public boolean isDiscardDeliveredMsgs() { return discard_delivered_msgs; } public void setDiscardDeliveredMsgs(boolean discard_delivered_msgs) { this.discard_delivered_msgs=discard_delivered_msgs; } public int getMaxXmitBufSize() { return max_xmit_buf_size; } public void setMaxXmitBufSize(int max_xmit_buf_size) { this.max_xmit_buf_size=max_xmit_buf_size; } public long getMaxXmitSize() { return max_xmit_size; } public void setMaxXmitSize(long max_xmit_size) { this.max_xmit_size=max_xmit_size; } public boolean setProperties(Properties props) { String str; long[] tmp; super.setProperties(props); str=props.getProperty("retransmit_timeout"); if(str != null) { tmp=Util.parseCommaDelimitedLongs(str); props.remove("retransmit_timeout"); if(tmp != null && tmp.length > 0) { retransmit_timeout=tmp; } } str=props.getProperty("gc_lag"); if(str != null) { gc_lag=Integer.parseInt(str); if(gc_lag < 0) { log.error("NAKACK.setProperties(): gc_lag cannot be negative, setting it to 0"); } props.remove("gc_lag"); } str=props.getProperty("max_xmit_size"); if(str != null) { max_xmit_size=Long.parseLong(str); props.remove("max_xmit_size"); } str=props.getProperty("use_mcast_xmit"); if(str != null) { use_mcast_xmit=Boolean.valueOf(str).booleanValue(); props.remove("use_mcast_xmit"); } str=props.getProperty("discard_delivered_msgs"); if(str != null) { discard_delivered_msgs=Boolean.valueOf(str).booleanValue(); props.remove("discard_delivered_msgs"); } str=props.getProperty("xmit_from_random_member"); if(str != null) { xmit_from_random_member=Boolean.valueOf(str).booleanValue(); props.remove("xmit_from_random_member"); } str=props.getProperty("max_xmit_buf_size"); if(str != null) { max_xmit_buf_size=Integer.parseInt(str); props.remove("max_xmit_buf_size"); } str=props.getProperty("stats_list_size"); if(str != null) { stats_list_size=Integer.parseInt(str); props.remove("stats_list_size"); } if(xmit_from_random_member) { if(discard_delivered_msgs) { discard_delivered_msgs=false; log.warn("xmit_from_random_member set to true: changed discard_delivered_msgs to false"); } } if(props.size() > 0) { log.error("NAKACK.setProperties(): these properties are not recognized: " + props); return false; } return true; } public Map dumpStats() { Map retval=super.dumpStats(); if(retval == null) retval=new HashMap(); retval.put("xmit_reqs_received", new Long(xmit_reqs_received)); retval.put("xmit_reqs_sent", new Long(xmit_reqs_sent)); retval.put("xmit_rsps_received", new Long(xmit_rsps_received)); retval.put("xmit_rsps_sent", new Long(xmit_rsps_sent)); retval.put("missing_msgs_received", new Long(missing_msgs_received)); retval.put("sent_msgs", printSentMsgs()); StringBuffer sb=new StringBuffer(); Map.Entry entry; Address addr; Object w; synchronized(received_msgs) { for(Iterator it=received_msgs.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); addr=(Address)entry.getKey(); w=entry.getValue(); sb.append(addr).append(": ").append(w.toString()).append('\n'); } } retval.put("received_msgs", sb.toString()); return retval; } public String printStats() { Map.Entry entry; Object key, val; StringBuffer sb=new StringBuffer(); sb.append("sent:\n"); for(Iterator it=sent.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); key=entry.getKey(); if(key == null) key="<mcast dest>"; val=entry.getValue(); sb.append(key).append(": ").append(val).append("\n"); } sb.append("\nreceived:\n"); for(Iterator it=received.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); key=entry.getKey(); val=entry.getValue(); sb.append(key).append(": ").append(val).append("\n"); } sb.append("\nXMIT_REQS sent:\n"); XmitRequest tmp; for(Enumeration en=send_history.elements(); en.hasMoreElements();) { tmp=(XmitRequest)en.nextElement(); sb.append(tmp).append("\n"); } sb.append("\nMissing messages received\n"); MissingMessage missing; for(Enumeration en=receive_history.elements(); en.hasMoreElements();) { missing=(MissingMessage)en.nextElement(); sb.append(missing).append("\n"); } return sb.toString(); } public Vector providedUpServices() { Vector retval=new Vector(5); retval.addElement(new Integer(Event.GET_DIGEST)); retval.addElement(new Integer(Event.GET_DIGEST_STABLE)); retval.addElement(new Integer(Event.GET_DIGEST_STATE)); retval.addElement(new Integer(Event.SET_DIGEST)); retval.addElement(new Integer(Event.MERGE_DIGEST)); return retval; } public Vector providedDownServices() { Vector retval=new Vector(2); retval.addElement(new Integer(Event.GET_DIGEST)); retval.addElement(new Integer(Event.GET_DIGEST_STABLE)); return retval; } public void start() throws Exception { timer=stack != null ? stack.timer : null; if(timer == null) throw new Exception("timer is null"); started=true; } public void stop() { started=false; reset(); // clears sent_msgs and destroys all NakReceiverWindows } /** * <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>passDown()</code> in this * method as the event is passed down by default by the superclass after this method returns !</b> */ public void down(Event evt) { Digest digest; Vector mbrs; switch(evt.getType()) { case Event.MSG: Message msg=(Message)evt.getArg(); Address dest=msg.getDest(); if(dest != null && !dest.isMulticastAddress()) { break; // unicast address: not null and not mcast, pass down unchanged } send(evt, msg); return; // don't pass down the stack case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg stable((Digest)evt.getArg()); return; // do not pass down further (Bela Aug 7 2001) case Event.GET_DIGEST: digest=getDigest(); passUp(new Event(Event.GET_DIGEST_OK, digest != null ? digest.copy() : null)); return; case Event.GET_DIGEST_STABLE: digest=getDigestHighestDeliveredMsgs(); passUp(new Event(Event.GET_DIGEST_STABLE_OK, digest != null ? digest.copy() : null)); return; case Event.GET_DIGEST_STATE: digest=getDigest(); passUp(new Event(Event.GET_DIGEST_STATE_OK, digest != null ? digest.copy() : null)); return; case Event.SET_DIGEST: setDigest((Digest)evt.getArg()); return; case Event.MERGE_DIGEST: mergeDigest((Digest)evt.getArg()); return; case Event.CONFIG: passDown(evt); if(log.isDebugEnabled()) { log.debug("received CONFIG event: " + evt.getArg()); } handleConfigEvent((HashMap)evt.getArg()); return; case Event.TMP_VIEW: mbrs=((View)evt.getArg()).getMembers(); members.clear(); members.addAll(mbrs); adjustReceivers(); break; case Event.VIEW_CHANGE: mbrs=((View)evt.getArg()).getMembers(); members.clear(); members.addAll(mbrs); adjustReceivers(); is_server=true; // check vids from now on Set tmp=new LinkedHashSet(members); tmp.add(null); // for null destination (= mcast) sent.keySet().retainAll(tmp); received.keySet().retainAll(tmp); break; case Event.BECOME_SERVER: is_server=true; break; case Event.DISCONNECT: leaving=true; reset(); break; } passDown(evt); } /** * <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>PassUp</code> in this * method as the event is passed up by default by the superclass after this method returns !</b> */ public void up(Event evt) { NakAckHeader hdr; Message msg; Digest digest; switch(evt.getType()) { case Event.MSG: msg=(Message)evt.getArg(); hdr=(NakAckHeader)msg.getHeader(name); if(hdr == null) break; // pass up (e.g. unicast msg) // discard messages while not yet server (i.e., until JOIN has returned) if(!is_server) { if(trace) log.trace("message was discarded (not yet server)"); return; } // Changed by bela Jan 29 2003: we must not remove the header, otherwise // further xmit requests will fail ! //hdr=(NakAckHeader)msg.removeHeader(getName()); switch(hdr.type) { case NakAckHeader.MSG: handleMessage(msg, hdr); return; // transmitter passes message up for us ! case NakAckHeader.XMIT_REQ: if(hdr.range == null) { if(log.isErrorEnabled()) { log.error("XMIT_REQ: range of xmit msg is null; discarding request from " + msg.getSrc()); } return; } handleXmitReq(msg.getSrc(), hdr.range.low, hdr.range.high, hdr.sender); return; case NakAckHeader.XMIT_RSP: if(trace) log.trace("received missing messages " + hdr.range); handleXmitRsp(msg); return; default: if(log.isErrorEnabled()) { log.error("NakAck header type " + hdr.type + " not known !"); } return; } case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg stable((Digest)evt.getArg()); return; // do not pass up further (Bela Aug 7 2001) case Event.GET_DIGEST: digest=getDigestHighestDeliveredMsgs(); passDown(new Event(Event.GET_DIGEST_OK, digest)); return; case Event.GET_DIGEST_STABLE: digest=getDigestHighestDeliveredMsgs(); passDown(new Event(Event.GET_DIGEST_STABLE_OK, digest)); return; case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); break; case Event.CONFIG: passUp(evt); if(log.isDebugEnabled()) { log.debug("received CONFIG event: " + evt.getArg()); } handleConfigEvent((HashMap)evt.getArg()); return; } passUp(evt); } private void send(Event evt, Message msg) { if(msg == null) throw new NullPointerException("msg is null; event is " + evt); if(!started) { if(warn) log.warn("discarded message as start() has not yet been called, message: " + msg); return; } synchronized(sent_msgs) { long msg_id; try { // incrementing seqno and adding the msg to sent_msgs needs to be atomic msg_id=seqno +1; msg.putHeader(name, new NakAckHeader(NakAckHeader.MSG, msg_id)); if(Global.copy) { sent_msgs.put(new Long(msg_id), msg.copy()); } else { sent_msgs.put(new Long(msg_id), msg); } seqno=msg_id; } catch(Throwable t) { if(t instanceof Error) throw (Error)t; if(t instanceof RuntimeException) throw (RuntimeException)t; else { throw new RuntimeException("failure adding msg " + msg + " to the retransmit table", t); } } try { if(trace) log.trace(local_addr + ": sending msg #" + msg_id); passDown(evt); // if this fails, since msg is in sent_msgs, it can be retransmitted } catch(Throwable t) { // eat the exception, don't pass it up the stack if(warn) { log.warn("failure passing message down", t); } } } } /** * Finds the corresponding NakReceiverWindow and adds the message to it (according to seqno). Then removes as many * messages as possible from the NRW and passes them up the stack. Discards messages from non-members. */ private void handleMessage(Message msg, NakAckHeader hdr) { NakReceiverWindow win; Message msg_to_deliver; Address sender=msg.getSrc(); if(sender == null) { if(log.isErrorEnabled()) log.error("sender of message is null"); return; } if(trace) { StringBuffer sb=new StringBuffer('['); sb.append(local_addr).append(": received ").append(sender).append('#').append(hdr.seqno); log.trace(sb.toString()); } // msg is potentially re-sent later as result of XMIT_REQ reception; that's why hdr is added ! // Changed by bela Jan 29 2003: we currently don't resend from received msgs, just from sent_msgs ! // msg.putHeader(getName(), hdr); synchronized(received_msgs) { win=(NakReceiverWindow)received_msgs.get(sender); } if(win == null) { // discard message if there is no entry for sender if(leaving) return; if(warn) { StringBuffer sb=new StringBuffer('['); sb.append(local_addr).append("] discarded message from non-member ").append(sender); if(warn) log.warn(sb); } return; } win.add(hdr.seqno, msg); // add in order, then remove and pass up as many msgs as possible // where lots of threads can come up to this point concurrently, but only 1 is allowed to pass at a time // We *can* deliver messages from *different* senders concurrently, e.g. reception of P1, Q1, P2, Q2 can result in // delivery of P1, Q1, Q2, P2: FIFO (implemented by NAKACK) says messages need to be delivered only in the // order in which they were sent by the sender synchronized(win) { while((msg_to_deliver=win.remove()) != null) { // Changed by bela Jan 29 2003: not needed (see above) //msg_to_deliver.removeHeader(getName()); passUp(new Event(Event.MSG, msg_to_deliver)); } } } /** * Retransmit from sent-table, called when XMIT_REQ is received. Bundles all messages to be xmitted into one large * message and sends them back with an XMIT_RSP header. Note that since we cannot count on a fragmentation layer * below us, we have to make sure the message doesn't exceed max_xmit_size bytes. If this is the case, we split the * message into multiple, smaller-chunked messages. But in most cases this still yields fewer messages than if each * requested message was retransmitted separately. * * @param xmit_requester The sender of the XMIT_REQ, we have to send the requested copy of the message to this address * @param first_seqno The first sequence number to be retransmitted (<= last_seqno) * @param last_seqno The last sequence number to be retransmitted (>= first_seqno) * @param original_sender The member who originally sent the messsage. Guaranteed to be non-null */ private void handleXmitReq(Address xmit_requester, long first_seqno, long last_seqno, Address original_sender) { Message m, tmp; LinkedList list; long size=0, marker=first_seqno, len; NakReceiverWindow win=null; boolean amISender; // am I the original sender ? if(trace) { StringBuffer sb=new StringBuffer(); sb.append(local_addr).append(": received xmit request from ").append(xmit_requester).append(" for "); sb.append(original_sender).append(" [").append(first_seqno).append(" - ").append(last_seqno).append("]"); log.trace(sb.toString()); } if(first_seqno > last_seqno) { if(log.isErrorEnabled()) log.error("first_seqno (" + first_seqno + ") > last_seqno (" + last_seqno + "): not able to retransmit"); return; } if(stats) { xmit_reqs_received+=last_seqno - first_seqno +1; updateStats(received, xmit_requester, 1, 0, 0); } amISender=local_addr.equals(original_sender); if(!amISender) win=(NakReceiverWindow)received_msgs.get(original_sender); list=new LinkedList(); for(long i=first_seqno; i <= last_seqno; i++) { if(amISender) { m=(Message)sent_msgs.get(new Long(i)); // no need to synchronize } else { m=win != null? win.get(i) : null; } if(m == null) { if(log.isErrorEnabled()) { StringBuffer sb=new StringBuffer(); sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr); sb.append(") message ").append(original_sender).append("::").append(i); sb.append(" not found in ").append((amISender? "sent" : "received")).append(" msgs. "); if(win != null) { sb.append("Received messages from ").append(original_sender).append(": ").append(win.toString()); } else { sb.append("\nSent messages: ").append(printSentMsgs()); } log.error(sb); } continue; } len=m.size(); size+=len; if(size > max_xmit_size && list.size() > 0) { // changed from >= to > (yaron-r, bug #943709) // yaronr: added &&listSize()>0 since protocols between FRAG and NAKACK add headers, and message exceeds size. // size has reached max_xmit_size. go ahead and send message (excluding the current message) if(trace) log.trace("xmitting msgs [" + marker + '-' + (i - 1) + "] to " + xmit_requester); sendXmitRsp(xmit_requester, (LinkedList)list.clone(), marker, i - 1); marker=i; list.clear(); // fixed Dec 15 2003 (bela, patch from Joel Dice (dicej)), see explanantion under // bug report #854887 size=len; } if(Global.copy) { tmp=m.copy(); } else { tmp=m; } // tmp.setDest(xmit_requester); // tmp.setSrc(local_addr); if(tmp.getSrc() == null) tmp.setSrc(local_addr); list.add(tmp); } if(list.size() > 0) { if(trace) log.trace("xmitting msgs [" + marker + '-' + last_seqno + "] to " + xmit_requester); sendXmitRsp(xmit_requester, (LinkedList)list.clone(), marker, last_seqno); list.clear(); } } private static void updateStats(HashMap map, Address key, int req, int rsp, int missing) { Entry entry=(Entry)map.get(key); if(entry == null) { entry=new Entry(); map.put(key, entry); } entry.xmit_reqs+=req; entry.xmit_rsps+=rsp; entry.missing_msgs_rcvd+=missing; } private void sendXmitRsp(Address dest, LinkedList xmit_list, long first_seqno, long last_seqno) { Buffer buf; if(xmit_list == null || xmit_list.size() == 0) { if(log.isErrorEnabled()) log.error("xmit_list is empty"); return; } if(use_mcast_xmit) dest=null; if(stats) { xmit_rsps_sent+=xmit_list.size(); updateStats(sent, dest, 0, 1, 0); } try { buf=Util.msgListToByteBuffer(xmit_list); Message msg=new Message(dest, null, buf.getBuf(), buf.getOffset(), buf.getLength()); msg.putHeader(name, new NakAckHeader(NakAckHeader.XMIT_RSP, first_seqno, last_seqno)); passDown(new Event(Event.MSG, msg)); } catch(IOException ex) { log.error("failed marshalling xmit list", ex); } } private void handleXmitRsp(Message msg) { LinkedList list; Message m; if(msg == null) { if(warn) log.warn("message is null"); return; } try { list=Util.byteBufferToMessageList(msg.getRawBuffer(), msg.getOffset(), msg.getLength()); if(list != null) { if(stats) { xmit_rsps_received+=list.size(); updateStats(received, msg.getSrc(), 0, 1, 0); } for(Iterator it=list.iterator(); it.hasNext();) { m=(Message)it.next(); up(new Event(Event.MSG, m)); } list.clear(); } } catch(Exception ex) { if(log.isErrorEnabled()) { log.error("message did not contain a list (LinkedList) of retransmitted messages", ex); } } } /** * Remove old members from NakReceiverWindows and add new members (starting seqno=0). Essentially removes all * entries from received_msgs that are not in <code>members</code> */ private void adjustReceivers() { Address sender; NakReceiverWindow win; synchronized(received_msgs) { // 1. Remove all senders in received_msgs that are not members anymore for(Iterator it=received_msgs.keySet().iterator(); it.hasNext();) { sender=(Address)it.next(); if(!members.contains(sender)) { win=(NakReceiverWindow)received_msgs.get(sender); win.reset(); if(log.isDebugEnabled()) { log.debug("removing " + sender + " from received_msgs (not member anymore)"); } it.remove(); } } // 2. Add newly joined members to received_msgs (starting seqno=0) for(int i=0; i < members.size(); i++) { sender=(Address)members.elementAt(i); if(!received_msgs.containsKey(sender)) { win=createNakReceiverWindow(sender, 0); received_msgs.put(sender, win); } } } } /** * Returns a message digest: for each member P the highest seqno received from P is added to the digest. */ private Digest getDigest() { Digest digest; Address sender; Range range; digest=new Digest(members.size()); for(int i=0; i < members.size(); i++) { sender=(Address)members.elementAt(i); range=getLowestAndHighestSeqno(sender, false); // get the highest received seqno if(range == null) { if(log.isErrorEnabled()) { log.error("range is null"); } continue; } digest.add(sender, range.low, range.high); // add another entry to the digest } return digest; } /** * Returns a message digest: for each member P the highest seqno received from P <em>without a gap</em> is added to * the digest. E.g. if the seqnos received from P are [+3 +4 +5 -6 +7 +8], then 5 will be returned. Also, the * highest seqno <em>seen</em> is added. The max of all highest seqnos seen will be used (in STABLE) to determine * whether the last seqno from a sender was received (see "Last Message Dropped" topic in DESIGN). */ private Digest getDigestHighestDeliveredMsgs() { Digest digest; Address sender; Range range; long high_seqno_seen; digest=new Digest(members.size()); for(int i=0; i < members.size(); i++) { sender=(Address)members.elementAt(i); range=getLowestAndHighestSeqno(sender, true); // get the highest deliverable seqno if(range == null) { if(log.isErrorEnabled()) { log.error("range is null"); } continue; } high_seqno_seen=getHighSeqnoSeen(sender); digest.add(sender, range.low, range.high, high_seqno_seen); // add another entry to the digest } return digest; } /** * Creates a NakReceiverWindow for each sender in the digest according to the sender's seqno. If NRW already exists, * reset it. */ private void setDigest(Digest d) { if(d == null || d.senders == null) { if(log.isErrorEnabled()) { log.error("digest or digest.senders is null"); } return; } clear(); Map.Entry entry; Address sender; org.jgroups.protocols.pbcast.Digest.Entry val; long initial_seqno; NakReceiverWindow win; for(Iterator it=d.senders.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); sender=(Address)entry.getKey(); val=(org.jgroups.protocols.pbcast.Digest.Entry)entry.getValue(); if(sender == null || val == null) { if(warn) { log.warn("sender or value is null"); } continue; } initial_seqno=val.high_seqno; win=createNakReceiverWindow(sender, initial_seqno); synchronized(received_msgs) { received_msgs.put(sender, win); } } } /** * For all members of the digest, adjust the NakReceiverWindows in the received_msgs hashtable. If the member * already exists, sets its seqno to be the max of the seqno and the seqno of the member in the digest. If no entry * exists, create one with the initial seqno set to the seqno of the member in the digest. */ private void mergeDigest(Digest d) { if(d == null || d.senders == null) { if(log.isErrorEnabled()) { log.error("digest or digest.senders is null"); } return; } Map.Entry entry; Address sender; org.jgroups.protocols.pbcast.Digest.Entry val; NakReceiverWindow win; long initial_seqno; for(Iterator it=d.senders.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); sender=(Address)entry.getKey(); val=(org.jgroups.protocols.pbcast.Digest.Entry)entry.getValue(); if(sender == null || val == null) { if(warn) { log.warn("sender or value is null"); } continue; } initial_seqno=val.high_seqno; synchronized(received_msgs) { win=(NakReceiverWindow)received_msgs.get(sender); if(win == null) { win=createNakReceiverWindow(sender, initial_seqno); received_msgs.put(sender, win); } else { if(win.getHighestReceived() < initial_seqno) { win.reset(); received_msgs.remove(sender); win=createNakReceiverWindow(sender, initial_seqno); received_msgs.put(sender, win); } } } } } private NakReceiverWindow createNakReceiverWindow(Address sender, long initial_seqno) { NakReceiverWindow win=new NakReceiverWindow(sender, this, initial_seqno, timer); win.setRetransmitTimeouts(retransmit_timeout); win.setDiscardDeliveredMessages(discard_delivered_msgs); win.setMaxXmitBufSize(this.max_xmit_buf_size); if(stats) win.setListener(this); return win; } /** * Returns the lowest seqno still in cache (so it can be retransmitted) and the highest seqno received so far. * * @param sender The address for which the highest and lowest seqnos are to be retrieved * @param stop_at_gaps If true, the highest seqno *deliverable* will be returned. If false, the highest seqno * *received* will be returned. E.g. for [+3 +4 +5 -6 +7 +8], the highest_seqno_received is 8, * whereas the higheset_seqno_seen (deliverable) is 5. */ private Range getLowestAndHighestSeqno(Address sender, boolean stop_at_gaps) { Range r=null; NakReceiverWindow win; if(sender == null) { if(log.isErrorEnabled()) { log.error("sender is null"); } return r; } synchronized(received_msgs) { win=(NakReceiverWindow)received_msgs.get(sender); } if(win == null) { if(log.isErrorEnabled()) { log.error("sender " + sender + " not found in received_msgs"); } return r; } if(stop_at_gaps) { r=new Range(win.getLowestSeen(), win.getHighestSeen()); // deliverable messages (no gaps) } else { r=new Range(win.getLowestSeen(), win.getHighestReceived() + 1); // received messages } return r; } /** * Returns the highest seqno seen from sender. E.g. if we received 1, 2, 4, 5 from P, then 5 will be returned * (doesn't take gaps into account). If we are the sender, we will return the highest seqno <em>sent</em> rather * then <em>received</em> */ private long getHighSeqnoSeen(Address sender) { NakReceiverWindow win; long ret=0; if(sender == null) { if(log.isErrorEnabled()) { log.error("sender is null"); } return ret; } if(sender.equals(local_addr)) { return seqno - 1; } synchronized(received_msgs) { win=(NakReceiverWindow)received_msgs.get(sender); } if(win == null) { if(log.isErrorEnabled()) { log.error("sender " + sender + " not found in received_msgs"); } return ret; } ret=win.getHighestReceived(); return ret; } /** * Garbage collect messages that have been seen by all members. Update sent_msgs: for the sender P in the digest * which is equal to the local address, garbage collect all messages <= seqno at digest[P]. Update received_msgs: * for each sender P in the digest and its highest seqno seen SEQ, garbage collect all delivered_msgs in the * NakReceiverWindow corresponding to P which are <= seqno at digest[P]. */ private void stable(Digest d) { NakReceiverWindow recv_win; long my_highest_rcvd; // highest seqno received in my digest for a sender P long stability_highest_rcvd; // highest seqno received in the stability vector for a sender P if(members == null || local_addr == null || d == null) { if(warn) log.warn("members, local_addr or digest are null !"); return; } if(trace) { log.trace("received stable digest " + d); } Map.Entry entry; Address sender; org.jgroups.protocols.pbcast.Digest.Entry val; long high_seqno_delivered, high_seqno_received; for(Iterator it=d.senders.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); sender=(Address)entry.getKey(); if(sender == null) continue; val=(org.jgroups.protocols.pbcast.Digest.Entry)entry.getValue(); high_seqno_delivered=val.high_seqno; high_seqno_received=val.high_seqno_seen; // check whether the last seqno received for a sender P in the stability vector is > last seqno // received for P in my digest. if yes, request retransmission (see "Last Message Dropped" topic // in DESIGN) synchronized(received_msgs) { recv_win=(NakReceiverWindow)received_msgs.get(sender); } if(recv_win != null) { my_highest_rcvd=recv_win.getHighestReceived(); stability_highest_rcvd=high_seqno_received; if(stability_highest_rcvd >= 0 && stability_highest_rcvd > my_highest_rcvd) { if(trace) { log.trace("my_highest_rcvd (" + my_highest_rcvd + ") < stability_highest_rcvd (" + stability_highest_rcvd + "): requesting retransmission of " + sender + '#' + stability_highest_rcvd); } retransmit(stability_highest_rcvd, stability_highest_rcvd, sender); } } high_seqno_delivered-=gc_lag; if(high_seqno_delivered < 0) { continue; } if(trace) log.trace("deleting msgs <= " + high_seqno_delivered + " from " + sender); // garbage collect from sent_msgs if sender was myself if(sender.equals(local_addr)) { synchronized(sent_msgs) { // gets us a subset from [lowest seqno - seqno] SortedMap stable_keys=sent_msgs.headMap(new Long(high_seqno_delivered)); if(stable_keys != null) { stable_keys.clear(); // this will modify sent_msgs directly } } } // delete *delivered* msgs that are stable // recv_win=(NakReceiverWindow)received_msgs.get(sender); if(recv_win != null) recv_win.stable(high_seqno_delivered); // delete all messages with seqnos <= seqno } } /** * Implementation of Retransmitter.RetransmitCommand. Called by retransmission thread when gap is detected. */ public void retransmit(long first_seqno, long last_seqno, Address sender) { NakAckHeader hdr; Message retransmit_msg; Address dest=sender; // to whom do we send the XMIT request ? if(xmit_from_random_member && !local_addr.equals(sender)) { Address random_member=(Address)Util.pickRandomElement(members); if(random_member != null && !local_addr.equals(random_member)) { dest=random_member; if(trace) log.trace("picked random member " + dest + " to send XMIT request to"); } } hdr=new NakAckHeader(NakAckHeader.XMIT_REQ, first_seqno, last_seqno, sender); retransmit_msg=new Message(dest, null, null); if(trace) log.trace(local_addr + ": sending XMIT_REQ ([" + first_seqno + ", " + last_seqno + "]) to " + dest); retransmit_msg.putHeader(name, hdr); passDown(new Event(Event.MSG, retransmit_msg)); if(stats) { xmit_reqs_sent+=last_seqno - first_seqno +1; updateStats(sent, dest, 1, 0, 0); for(long i=first_seqno; i <= last_seqno; i++) { XmitRequest req=new XmitRequest(sender, i, dest); send_history.add(req); } } } public void missingMessageReceived(long seqno, Message msg) { if(stats) { missing_msgs_received++; updateStats(received, msg.getSrc(), 0, 0, 1); MissingMessage missing=new MissingMessage(msg.getSrc(), seqno); receive_history.add(missing); } } private void clear() { NakReceiverWindow win; // changed April 21 2004 (bela): SourceForge bug# 938584. We cannot delete our own messages sent between // a join() and a getState(). Otherwise retransmission requests from members who missed those msgs might // fail. Not to worry though: those msgs will be cleared by STABLE (message garbage collection) // sent_msgs.clear(); synchronized(received_msgs) { for(Iterator it=received_msgs.values().iterator(); it.hasNext();) { win=(NakReceiverWindow)it.next(); win.reset(); } received_msgs.clear(); } } private void reset() { NakReceiverWindow win; synchronized(sent_msgs) { sent_msgs.clear(); seqno=-1; } synchronized(received_msgs) { for(Iterator it=received_msgs.values().iterator(); it.hasNext();) { win=(NakReceiverWindow)it.next(); win.destroy(); } received_msgs.clear(); } } public String printMessages() { StringBuffer ret=new StringBuffer(); Map.Entry entry; Address addr; Object w; ret.append("\nsent_msgs: ").append(printSentMsgs()); ret.append("\nreceived_msgs:\n"); synchronized(received_msgs) { for(Iterator it=received_msgs.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); addr=(Address)entry.getKey(); w=entry.getValue(); ret.append(addr).append(": ").append(w.toString()).append('\n'); } } return ret.toString(); } public String printSentMsgs() { StringBuffer sb=new StringBuffer(); Long min_seqno, max_seqno; synchronized(sent_msgs) { min_seqno=sent_msgs.size() > 0 ? (Long)sent_msgs.firstKey() : new Long(0); max_seqno=sent_msgs.size() > 0 ? (Long)sent_msgs.lastKey() : new Long(0); } sb.append('[').append(min_seqno).append(" - ").append(max_seqno).append("] (").append(sent_msgs.size()).append(")"); return sb.toString(); } private void handleConfigEvent(HashMap map) { if(map == null) { return; } if(map.containsKey("frag_size")) { max_xmit_size=((Integer)map.get("frag_size")).intValue(); if(log.isInfoEnabled()) { log.info("max_xmit_size=" + max_xmit_size); } } } static class Entry { long xmit_reqs, xmit_rsps, missing_msgs_rcvd; public String toString() { StringBuffer sb=new StringBuffer(); sb.append(xmit_reqs).append(" xmit_reqs").append(", ").append(xmit_rsps).append(" xmit_rsps"); sb.append(", ").append(missing_msgs_rcvd).append(" missing msgs"); return sb.toString(); } } static class XmitRequest { Address original_sender; // original sender of message long seq, timestamp=System.currentTimeMillis(); Address xmit_dest; // destination to which XMIT_REQ is sent, usually the original sender XmitRequest(Address original_sender, long seqno, Address xmit_dest) { this.original_sender=original_sender; this.xmit_dest=xmit_dest; this.seq=seqno; } public String toString() { StringBuffer sb=new StringBuffer(); sb.append(new Date(timestamp)).append(": ").append(original_sender).append(" #").append(seq); sb.append(" (XMIT_REQ sent to ").append(xmit_dest).append(")"); return sb.toString(); } } static class MissingMessage { Address original_sender; long seq, timestamp=System.currentTimeMillis(); MissingMessage(Address original_sender, long seqno) { this.original_sender=original_sender; this.seq=seqno; } public String toString() { StringBuffer sb=new StringBuffer(); sb.append(new Date(timestamp)).append(": ").append(original_sender).append(" #").append(seq); return sb.toString(); } } }
package com.junjunguo.pocketmaps.downloader; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import com.junjunguo.pocketmaps.model.MyMap; import com.junjunguo.pocketmaps.util.Variable; import android.annotation.TargetApi; import android.app.NotificationManager; import android.content.Context; import android.os.Build; import android.service.notification.StatusBarNotification; import android.util.Log; public class MapUnzip { public static final int ANDROID_API_MARSHMALLOW = Build.VERSION_CODES.LOLLIPOP + 2; public static final int BUFFER_SIZE = 8 * 1024; public void unzip(String zipFilePath, String mapName, ProgressPublisher pp) throws IOException { ZipInputStream zipIn = null; try{ File mapFolder = new File(Variable.getVariable().getMapsFolder(), mapName + "-gh"); File destDir = new File(mapFolder.getAbsolutePath()); if (destDir.exists()) { recursiveDelete(destDir); } if (!destDir.exists()) { destDir.mkdir(); } zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry entry = zipIn.getNextEntry(); int up = 0; // iterates over entries in the zip file while (entry != null) { up++; long fSize = entry.getSize(); pp.updateText(false, "" + up + " Unzipping " + mapName, 0); String filePath = mapFolder.getAbsolutePath() + File.separator + entry.getName(); if (!entry.isDirectory()) { // if the entry is a file, extracts it extractFile(zipIn, filePath, pp, "" + up + " Unzipping " + mapName, fSize); } else { // if the entry is a directory, make the directory File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } } finally { if (zipIn!=null) zipIn.close(); } } /** * Extracts a zip entry (file entry) * * @param zipIn * @param filePath * @param pp * @param mapName * @throws IOException */ private void extractFile(ZipInputStream zipIn, String filePath, ProgressPublisher pp, String ppText, long fSize) throws IOException { BufferedOutputStream bos = null; try{ bos = new BufferedOutputStream(new FileOutputStream(filePath)); byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; long readCounter = 0; while ((read = zipIn.read(bytesIn)) != -1) { bos.write(bytesIn, 0, read); float percent = 50.0f; if (fSize>0) { readCounter += read; percent = ((float)readCounter) / ((float)fSize); percent = percent * 100.0f; } pp.updateText(true, ppText, (int)percent); } } finally { if (bos!=null) bos.close(); } } /** * delete a recursively delete a folder or file * * @param fileOrDirectory */ public void recursiveDelete(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) for (File child : fileOrDirectory.listFiles()) recursiveDelete(child); try { fileOrDirectory.delete(); } catch (Exception e) { e.printStackTrace(); } } /** Check when status was updated from ProgressPublisher.java * Should update each second, otherwise the progress seems not alive. * @return False, when status was not updated for 30 sec. **/ public static boolean checkUnzipAlive(Context c, MyMap myMap) { if (Build.VERSION.SDK_INT < ANDROID_API_MARSHMALLOW) { return checkUnzipAliveOldVersion(c, myMap); } return checkUnzipAliveInternal(c, myMap); } private static boolean checkUnzipAliveOldVersion(Context c, MyMap myMap) { File mDir = MyMap.getMapFile(myMap, MyMap.MapFileType.MapFolder); if (timeCheck(mDir.lastModified())) { return true; } File list[] = mDir.listFiles(); if (list != null) { for (File f : list) { if (timeCheck(f.lastModified())) { return true; } } } return false; } @TargetApi(ANDROID_API_MARSHMALLOW) private static boolean checkUnzipAliveInternal(Context c, MyMap myMap) { String unzipKeyId = myMap.getMapName() + "-unzip"; NotificationManager notificationManager = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE); for (StatusBarNotification n : notificationManager.getActiveNotifications()) { if (n.getId() == unzipKeyId.hashCode()) { long postTime = n.getPostTime(); return timeCheck(postTime); } } return false; } private static boolean timeCheck(long lastTime) { long curTime = System.currentTimeMillis(); long diffTime = curTime - lastTime; if (diffTime > 30000) { return false; } return true; } }
package org.jgroups.stack; import org.jgroups.Message; import org.jgroups.util.Tuple; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReferenceArray; /** * Counterpart of AckSenderWindow. Simple FIFO buffer. * Every message received is ACK'ed (even duplicates) and added to a hashmap * keyed by seqno. The next seqno to be received is stored in <code>next_to_remove</code>. When a message with * a seqno less than next_to_remove is received, it will be discarded. The <code>remove()</code> method removes * and returns a message whose seqno is equal to next_to_remove, or null if not found.<br> * Change May 28 2002 (bela): replaced TreeSet with HashMap. Keys do not need to be sorted, and adding a key to * a sorted set incurs overhead. * * @author Bela Ban * @version $Id: AckReceiverWindow.java,v 1.44 2010/02/26 15:48:10 belaban Exp $ */ public class AckReceiverWindow { private final AtomicLong next_to_remove; private final AtomicBoolean processing=new AtomicBoolean(false); private final ConcurrentMap<Long,Segment> segments=new ConcurrentHashMap<Long,Segment>(); private volatile Segment current_segment=null; private final int segment_capacity; private long highest_segment_created=0; static final Message TOMBSTONE=new Message(false) { public String toString() { return "tombstone"; } }; public AckReceiverWindow(long initial_seqno) { this(initial_seqno, 20000); } public AckReceiverWindow(long initial_seqno, int segment_capacity) { next_to_remove=new AtomicLong(initial_seqno); this.segment_capacity=segment_capacity; long index=next_to_remove.get() / segment_capacity; long first_seqno=(next_to_remove.get() / segment_capacity) * segment_capacity; this.segments.put(index, new Segment(first_seqno, segment_capacity)); Segment initial_segment=findOrCreateSegment(next_to_remove.get()); current_segment=initial_segment; for(long i=0; i < next_to_remove.get(); i++) { initial_segment.add(i, TOMBSTONE); initial_segment.remove(i); } } public AtomicBoolean getProcessing() { return processing; } /** Adds a new message. Message cannot be null * @return True if the message was added, false if not (e.g. duplicate, message was already present) */ public boolean add(long seqno, Message msg) { return add2(seqno, msg) == 1; } /** * Adds a message if not yet received * @param seqno * @param msg * @return -1 if not added because seqno < next_to_remove, 0 if not added because already present, * 1 if added successfully */ public byte add2(long seqno, Message msg) { Segment segment=current_segment; if(segment == null || !segment.contains(seqno)) { segment=findOrCreateSegment(seqno); if(segment != null) current_segment=segment; } if(segment == null) return -1; return segment.add(seqno, msg); } /** * Removes a message whose seqno is equal to <code>next_to_remove</code>, increments the latter. Returns message * that was removed, or null, if no message can be removed. Messages are thus removed in order. */ public Message remove() { long next=next_to_remove.get(); Segment segment=findSegment(next); if(segment == null) return null; Message retval=segment.remove(next); if(retval != null) { next_to_remove.compareAndSet(next, next +1); if(segment.allRemoved()) segments.remove(next / segment_capacity); } return retval; } /** * Removes as many messages as possible (in sequence, without gaps) * @param max Max number of messages to be removed * @return Tuple<List<Message>,Long>: a tuple of the message list and the highest seqno removed */ public Tuple<List<Message>,Long> removeMany(final int max) { List<Message> list=new LinkedList<Message>(); // we remove msgs.size() messages *max* Tuple<List<Message>,Long> retval=new Tuple<List<Message>,Long>(list, 0L); int count=0; boolean looping=true; while(count < max && looping) { long next=next_to_remove.get(); Segment segment=findSegment(next); if(segment == null) return retval; long segment_id=next; long end=segment.getEndIndex(); while(next < end && count < max) { Message msg=segment.remove(next); if(msg == null) { looping=false; break; } list.add(msg); count++; retval.setVal2(next); next_to_remove.compareAndSet(next, ++next); if(segment.allRemoved()) segments.remove(segment_id / segment_capacity); } } return retval; } public void reset() { } public int size() { int retval=0; for(Segment segment: segments.values()) retval+=segment.size(); return retval; } public String toString() { StringBuilder sb=new StringBuilder(); int size=size(); sb.append(size + " messages"); if(size <= 100) sb.append(" in " + segments.size() + " segments: ").append(printMessages()); return sb.toString(); } public String printMessages() { StringBuilder sb=new StringBuilder(); List<Long> keys=new LinkedList<Long>(segments.keySet()); Collections.sort(keys); for(long key: keys) { Segment segment=segments.get(key); if(segment == null) continue; for(long i=segment.getStartIndex(); i < segment.getEndIndex(); i++) { Message msg=segment.get(i); if(msg == null) continue; if(msg == TOMBSTONE) sb.append("T "); else sb.append(i + " "); } } return sb.toString(); } private Segment findOrCreateSegment(long seqno) { long index=seqno / segment_capacity; if(index > highest_segment_created) { long start_seqno=seqno / segment_capacity * segment_capacity; Segment segment=new Segment(start_seqno, segment_capacity); Segment tmp=segments.putIfAbsent(index, segment); if(tmp != null) // segment already exists segment=tmp; else highest_segment_created=index; return segment; } return segments.get(index); } private Segment findSegment(long seqno) { long index=seqno / segment_capacity; return segments.get(index); } private static class Segment { final long start_index; // e.g. 5000. Then seqno 5100 would be at index 100 final int capacity; final AtomicReferenceArray<Message> array; final AtomicInteger num_tombstones=new AtomicInteger(0); public Segment(long start_index, int capacity) { this.start_index=start_index; this.capacity=capacity; this.array=new AtomicReferenceArray<Message>(capacity); } public long getStartIndex() { return start_index; } public long getEndIndex() { return start_index + capacity; } public boolean contains(long seqno) { return seqno >= start_index && seqno < getEndIndex(); } public Message get(long seqno) { int index=index(seqno); if(index < 0 || index >= array.length()) return null; return array.get(index); } public byte add(long seqno, Message msg) { int index=index(seqno); if(index < 0) return -1; boolean success=array.compareAndSet(index, null, msg); if(success) { return 1; } else return 0; } public Message remove(long seqno) { int index=index(seqno); if(index < 0) return null; Message retval=array.get(index); if(retval != null && array.compareAndSet(index, retval, TOMBSTONE)) { num_tombstones.incrementAndGet(); return retval; } return null; } public boolean allRemoved() { return num_tombstones.get() >= capacity; } public String toString() { return start_index + " - " + (start_index + capacity -1) + " (" + size() + " elements)"; } public int size() { int retval=0; for(int i=0; i < capacity; i++) { Message tmp=array.get(i); if(tmp != null && tmp != TOMBSTONE) retval++; } return retval; } private int index(long seqno) { if(seqno < start_index) return -1; int index=(int)(seqno - start_index); if(index < 0 || index >= capacity) { // todo: replace with returning -1 throw new IndexOutOfBoundsException("index=" + index + ", start_index=" + start_index + ", seqno=" + seqno); } return index; } } }
package br.com.fasam.projetoexemplo.entidades; import java.util.ArrayList; import java.util.List; public class Artigo { String titulo; String descricao; Usuario usuario; List<Comentario> comentarios; List<Tag> tags; /** * Metodo de inicializacao das variaveis * @param usuario */ public Artigo(Usuario usuario){ this.usuario = usuario; this.titulo = "Ciências aplicadas Globais"; this.descricao = "Artigo referente a materia de Ciências Aplicadas, necessario que o usuario tenha sido aprovado no Modulo01"; this.addTag(new Tag()); } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Comentario getComentario(Integer i){ return comentarios.get(i); } /** * Metodo que adiciona comentarios * @param comentario */ public void addComentario(Comentario comentario){ if(this.comentarios == null){ this.comentarios = new ArrayList<Comentario>(); } this.comentarios.add(comentario); } /** * Metodo que remove comentarios * @param comentario */ public void remComentario(Comentario comentario){ if(this.comentarios == null){ this.comentarios.remove(comentario); } } /** * Metodo que retorna tag * @param i * @return */ public Tag getTag(Integer i){ return tags.get(i); } /** * Metodo que adiciona uma tag a lista * @param tag */ public void addTag(Tag tag){ if(this.tags == null){ this.tags = new ArrayList<Tag>(); } this.tags.add(tag); } /** * Metodo que remove uma tag da lista * @param tag */ public void remTag(Tag tag){ if(this.tags == null){ this.tags.remove(tag); } } /** * Metodo que retorna titulo * @return */ public String getTitulo() { return titulo; } /** * Metodo que seta o titulo * @param titulo */ public void setTitulo(String titulo) { this.titulo = titulo; } /** * Metodo que retorna descricao * @return */ public String getDescricao() { return descricao; } /** * Metodo que seta descricao * @param descricao */ public void setDescricao(String descricao) { this.descricao = descricao; } }
package org.jitsi.meet.test; import junit.framework.*; import org.apache.commons.io.*; import org.apache.tools.ant.taskdefs.optional.junit.*; import org.openqa.selenium.*; import java.io.*; /** * Extends the xml formatter so we can detect failures and make screenshots * when this happen. * @author Damian Minkov */ public class FailureListener extends XMLJUnitResultFormatter { private File outputParentFolder = null; /** * Creates a screenshot named by the class and name of the failure. * @param test the test * @param t the assertion error */ @Override public void addFailure(Test test, AssertionFailedError t) { takeScreenshots(test); super.addFailure(test, t); } /** * Creates a screenshot named by the class and name of the failure. * @param test the test * @param t the assertion error */ @Override public void addError(Test test, Throwable t) { takeScreenshots(test); super.addError(test, t); } /** * Override to access parent output to get the destination folder. * @param out the xml formatter output */ @Override public void setOutput(OutputStream out) { // default reports folder outputParentFolder = new File("test-reports/screenshots"); // skip output so we do not print in console //super.setOutput(out); } /** * Takes screenshot of focus and participant. * * @param test which failed */ private void takeScreenshots(Test test) { takeScreenshot(ConferenceFixture.focus, JUnitVersionHelper.getTestCaseClassName(test) + "." +JUnitVersionHelper.getTestCaseName(test) + "-focus.png"); takeScreenshot(ConferenceFixture.secondParticipant, JUnitVersionHelper.getTestCaseClassName(test) + "." + JUnitVersionHelper.getTestCaseName(test) + "-participant.png"); } /** * Takes screenshot for the supplied page. * @param driver the driver controlling the page. * @param fileName the destination screenshot file name. */ private void takeScreenshot(WebDriver driver, String fileName) { TakesScreenshot takesScreenshot = (TakesScreenshot) driver; File scrFile = takesScreenshot.getScreenshotAs(OutputType.FILE); File destFile = new File(outputParentFolder, fileName); try { System.err.println("Took screenshot " + destFile); FileUtils.copyFile(scrFile, destFile); System.err.println("Saved screenshot " + destFile); } catch (IOException ioe) { throw new RuntimeException(ioe); } } }
/* * $Id: SqlStoredProcedures.java,v 1.6 2012-03-03 23:09:56 pgust Exp $ */ package org.lockss.util; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import org.lockss.app.LockssDaemon; import org.lockss.config.ConfigManager; import org.lockss.config.Tdb; import org.lockss.config.TdbAu; import org.lockss.config.TdbPublisher; import org.lockss.config.TdbTitle; import org.lockss.daemon.TitleConfig; import org.lockss.plugin.ArchivalUnit; import org.lockss.plugin.AuUtil; import org.lockss.plugin.CachedUrl; import org.lockss.plugin.PluginManager; import org.lockss.state.AuState; import org.lockss.util.Logger; /** * This utility class contains static methods that enable SQL stored * procedures to access LOCKSS functionality. * * @author pgust, mellen * */ public class SqlStoredProcedures { /** logger to report issues */ static Logger log = Logger.getLogger("SqlStoredProcedures"); /** logger to report query issues */ static Logger queryLog = Logger.getLogger("SqlStoredProcedureQueryLog"); /** Formatter for ISO formatted date */ static SimpleDateFormat isoDateFormatter = new SimpleDateFormat("yyyy-MM-dd"); /** The plugin manager */ static PluginManager pluginManager = null; /** * Constructor prevents creating instances. */ private SqlStoredProcedures() { } /** * Set the cached plugin manager for this class. Primarily used * in testing * * @param pluginManager the plugin manager */ static void setPluginManager(PluginManager pluginManager) { SqlStoredProcedures.pluginManager = pluginManager; } /** * Returns the plugin manager for the current LOCKSS daemon. Does * lazy initialization on first reference. * * @return the plugin manager */ static private PluginManager getPluginManager() { // get lockss daemon plugin manager if (pluginManager == null) { setPluginManager(LockssDaemon.getLockssDaemon().getPluginManager()); } return pluginManager; } /** * Return the title from the title title database that corresponds * to the URL of an article in that title. * * @param articleUrl the URL of the article * @return the title for the given URL and null otherwise */ static TdbAu getTdbAuFromArticleUrl(String articleUrl) { if (articleUrl == null) { throw new IllegalArgumentException("null articleUrl"); } // get the CachedUrl from the article URL CachedUrl cu = getPluginManager().findCachedUrl(articleUrl); if (cu == null) { queryLog.debug2("No CachedUrl for articleUrl " + articleUrl); return null; } // get the AU from the CachedUrl ArchivalUnit au = cu.getArchivalUnit(); // return the TdbAu from the AU TitleConfig tc = au.getTitleConfig(); if (tc == null) { log.debug2("no titleconfig for au " + au.toString()); return null; } return tc.getTdbAu(); } /** * Return the title from the title title database that corresponds * to an auid for an AU in that title. * * @param pluginId the pluginId * @param auKey the AU key * @return the title for the given URL and null otherwise */ static TdbAu getTdbAuFromAuId(String pluginId, String auKey) { if (StringUtil.isNullString(pluginId) || StringUtil.isNullString(auKey)) { return null; } String auId = PluginManager.generateAuId(pluginId, auKey); // get the AU from the Auid ArchivalUnit au = getPluginManager().getAuFromId(auId); if (au == null) { queryLog.debug2( "No ArchivalUnit for pluginId: " + pluginId + " auKey: " + auKey); return null; } // return the TdbAu from the AU TitleConfig tc = au.getTitleConfig(); if (tc == null) { log.debug2("no titleconfig for au " + au.toString()); return null; } return tc.getTdbAu(); } /** * Return the volume title that corresponds to the auid * of a journal or series AU. * * @param pluginId the pluginId part of the auid * @param auKey the auKey part of the auid * @return the publisher for the given auid */ static public String getVolumeTitleFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); return tdbAu == null ? null : tdbAu.getName(); } /** * Return the journal or series title from that corresponds * to the URL of an article in that journal. * * @param articleUrl the URL of the article * @return the title for the given URL or null if not available */ static public String getVolumeTitleFromArticleUrl(String articleUrl) { // get the TdbAu from the AU TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); return (tdbAu == null) ? null : tdbAu.getName(); } /** * Return the journal or series title that corresponds to the auid * of a journal or series AU. * * @param pluginId the pluginId part of the auid * @param auKey the auKey part of the auid * @return the publisher for the given auid */ static public String getTitleFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); return tdbAu == null ? null : tdbAu.getJournalTitle(); } /** * Return the journal or series title from that corresponds * to the URL of an article in that journal. * * @param articleUrl the URL of the article * @return the title for the given URL or null if not available */ static public String getTitleFromArticleUrl(String articleUrl) { // get the TdbAu from the AU TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); return (tdbAu == null) ? null : tdbAu.getJournalTitle(); } /** * Return the publisher from the title database that corresponds * to the URL of an article by that publisher. * * @param articleUrl the URL of the article * @return the publisher for the given URL or null if not available */ static public String getPublisherFromArticleUrl(String articleUrl) { // get the TdbAu from the AU TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); return (tdbAu == null) ? null : tdbAu.getTdbPublisher().getName(); } /** * Remove punctuation from a string. * * @param s the string * @return an unpunctated version of the string */ static private String unpunctuate(String s) { return (s == null) ? null : s.replaceAll("-", ""); } /** * Return the eISBN from that corresponds * to the URL of an article. * The value returned is without punctuation. * * @param articleUrl the URL of the article * @return the eISBN for the given URL or null if not available */ static public String getEisbnFromArticleUrl(String articleUrl) { // get the TdbAu from the AU TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); if (tdbAu == null) { queryLog.debug2("No TdbAu for article url: " + articleUrl); return null; } String eisbn = tdbAu.getEisbn(); return unpunctuate(eisbn); } /** * Return the eISBN from that corresponds * to the auId of an AU. * The value returned is without punctuation. * * @param pluginId the pluginID of an article AU * @param auKey the auKey of an article AU * @return the eISBN for the given auId or null if not available */ static public String getEisbnFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); if (tdbAu == null) { queryLog.debug2( "No TdbAu for pluginId: " + pluginId + " auKey: " + auKey); return null; } String eisbn = tdbAu.getEisbn(); return unpunctuate(eisbn); } /** * Return the print ISBN from that corresponds * to the URL of an article. * The value returned is without punctuation. * * @param articleUrl the URL of the article * @return the print ISBN for the given URL or null if not available */ static public String getPrintIsbnFromArticleUrl(String articleUrl) { // get the TdbAu from the AU TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); if (tdbAu == null) { queryLog.debug2("No TdbAu for article url: " + articleUrl); return null; } String printIsbn = tdbAu.getPrintIsbn(); return unpunctuate(printIsbn); } /** * Return the print ISBN from that corresponds * to the auId of an AU. * The value returned is without punctuation. * * @param pluginId the pluginID of an article AU * @param auKey the auKey of an article AU * @return the print ISBN for the given auId or null if not available */ static public String getPrintIsbnFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); if (tdbAu == null) { queryLog.debug2( "No TdbAu for pluginId: " + pluginId + " auKey: " + auKey); return null; } String printIsbn = tdbAu.getPrintIsbn(); return unpunctuate(printIsbn); } /** * Return an ISBN from that corresponds * to the URL of an article. * The value returned is without punctuation. * * @param articleUrl the URL of the article * @return the eISBN for the given URL or null if not available */ static public String getIsbnFromArticleUrl(String articleUrl) { // get the TdbAu from the AU TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); if (tdbAu == null) { queryLog.debug2("No TdbAu for article url: " + articleUrl); return null; } String isbn = tdbAu.getIsbn(); return unpunctuate(isbn); } /** * Return an ISBN from that corresponds * to the auId of an AU. * The value returned is without punctuation. * * @param pluginId the pluginID of an article AU * @param auKey the auKey of an article AU * @return an ISBN for the given auId or null if not available */ static public String getIsbnFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); if (tdbAu == null) { queryLog.debug2( "No TdbAu for pluginId: " + pluginId + " auKey: " + auKey); return null; } String isbn = tdbAu.getIsbn(); return unpunctuate(isbn); } /** * Return the eISSN from that corresponds to the URL * of an article in that journal or series. * The value returned is without punctuation. * * @param articleUrl the URL of the article * @return the eISSN for the given URL or null if not available */ static public String getEissnFromArticleUrl(String articleUrl) { // get the TdbAu from the AU TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); if (tdbAu == null) { queryLog.debug2("No TdbAu for article url: " + articleUrl); return null; } String eissn = tdbAu.getEissn(); return unpunctuate(eissn); } /** * Return the eISSN from that corresponds to the auId * of an AU in that journal or series * The value returned is without punctuation. * * @param pluginId the pluginID of an article AU * @param auKey the auKey of an article AU * @return the eISSN for the given auId or null if not available */ static public String getEissnFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); if (tdbAu == null) { queryLog.debug2( "No TdbAu for pluginId: " + pluginId + " auKey: " + auKey); return null; } String eissn = tdbAu.getEissn(); return unpunctuate(eissn); } /** * Return the ISSN-L from that corresponds to the URL * of an article in that journal or series. * The value returned is without punctuation. * * @param articleUrl the URL of the article * @return the ISSN-L for the given URL or null if not available */ static public String getIssnLFromArticleUrl(String articleUrl) { // get the TdbAu from the AU TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); if (tdbAu == null) { queryLog.debug2("No TdbAu for article url: " + articleUrl); return null; } String issnl = tdbAu.getIssnL(); return unpunctuate(issnl); } /** * Return the ISSN-L from that corresponds to the auId * of an AU in that journal or series. * The value returned is without punctuation. * * @param pluginId the pluginID of an article AU * @param auKey the auKey of an article AU * @return the ISSN-L for the given auId or null if not available */ static public String getIssnLFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); if (tdbAu == null) { return null; } String issnl = tdbAu.getEissn(); return unpunctuate(issnl); } /** * Return a ISSN that corresponds to the URL * of an article in that journal or series. * The value returned is without punctuation. * * @param articleUrl the URL of the article * @return an ISSN for the given URL or null if not available */ static public String getIssnFromArticleUrl(String articleUrl) { // get the TdbAu from the AU TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); if (tdbAu == null) { queryLog.debug2("No TdbAu for article url: " + articleUrl); return null; } String issn = tdbAu.getIssn(); return unpunctuate(issn); } /** * Return a ISSN that corresponds to the auId * of an AU in that journal or series. * The value returned is without punctuation. * * @param pluginId the pluginID of an article AU * @param auKey the auKey of an article AU * @return an ISSN for the given auId or null if not available */ static public String getIssnFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); if (tdbAu == null) { queryLog.debug2( "No TdbAu for pluginId: " + pluginId + " auKey: " + auKey); return null; } String issn = tdbAu.getIssn(); return unpunctuate(issn); } /** * Return the print ISSN from that corresponds to the URL * of an article in that journal or series. * The value returned is without punctuation. * * @param articleUrl the URL of the article * @return the print ISSN for the given URL or null if not available */ static public String getPrintIssnFromArticleUrl(String articleUrl) { // get the TdbAu from the AU TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); if (tdbAu == null) { queryLog.debug2("No tdbAu for articleUrl: " + articleUrl); return null; } String printIssn = tdbAu.getPrintIssn(); return unpunctuate(printIssn); } /** * Return the print ISSN from that corresponds to the auId * of an AU in that journal or series * The value returned is without punctuation. * * @param pluginId the pluginID of an article AU * @param auKey the auKey of an article AU * @return the print ISSN for the given auId or null if not available */ static public String getPrintIssnFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); if (tdbAu == null) { queryLog.debug2( "No tdbAu for pluginId: " + pluginId + " auKey: " + auKey); return null; } String printIssn = tdbAu.getPrintIssn(); return unpunctuate(printIssn); } /** * Return the year from an ISO formatted date string of the form * yyyy or yyyy-mm or yyyy-mm-dd * @param dateStr the date string * @return the year */ static public String getYearFromDate(String dateStr) { if (dateStr != null) { int i = dateStr.indexOf('-'); String year = (i > 0) ? dateStr.substring(0,i) : dateStr; try { if (Integer.parseInt(year) > 0) { return year; } } catch (NumberFormatException ex) { queryLog.debug2("Year field of date is not a number: " + dateStr); } } return null; } /** * Return the ingest year from the daemon that corresponds * to the URL of an article in that publisher. * * @param articleUrl the URL of the article * @return the ingest date for the given URL or null if not available */ static public String getIngestYearFromArticleUrl(String articleUrl) { String ingestDate = getIngestDateFromArticleUrl(articleUrl); String ingestYear = getYearFromDate(ingestDate); return ingestYear; } /** * Return the article ingest date from the daemon that corresponds * to the URL of an article in that publisher. * * @param articleUrl the URL of the article * @return the ingest date for the given URL or null if not available */ static public String getIngestDateFromArticleUrl(String articleUrl) { // get the CachedUrl from the article URL CachedUrl cu = getPluginManager().findCachedUrl(articleUrl); if (cu == null) { queryLog.debug2("No CachedUrl for articleUrl: " + articleUrl); return null; } // get the ingest date from the CachedUrl CIProperties ciProps = cu.getProperties(); String fetchTime = ciProps.getProperty(CachedUrl.PROPERTY_FETCH_TIME); if (fetchTime == null) { log.warning("No fetch time for articleUrl: " + articleUrl); return null; } try { Date date = new Date(Long.parseLong(fetchTime)); String ingestDate = isoDateFormatter.format(date); return ingestDate; } catch (NumberFormatException ex) { log.warning( "error parsing fetchtime: " + fetchTime + " for article url: " + articleUrl); return null; } } /** * Return the title from the title database that corresponds * to the ISBN of a book volume. * * @param isbn the ISBN of the book * @return the book title for the given ISBN */ static public String getVolumeTitleFromIsbn(String isbn) { if (isbn == null) { return null; } // get the tdb Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); if (tdb == null) { log.debug2("No Tdb in configuration"); return null; } // get the tdbAus for this isbn Collection<TdbAu> tdbAus = tdb.getTdbAusByIsbn(isbn); // return the title return tdbAus.isEmpty() ? null : tdbAus.iterator().next().getName(); } /** * Return the series title from the title database that corresponds * to the ISSB of the volume. * * @param isbn the ISBN of the series * @return the series title for the given ISBN */ static public String getTitleFromIsbn(String isbn) { if (isbn == null) { return null; } // get the tdb Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); if (tdb == null) { log.debug2("No Tdb in configuration"); return null; } // get the tdbAus from the ISBN Collection<TdbAu> tdbAus = tdb.getTdbAusByIsbn(isbn); // return the title return tdbAus.isEmpty() ? null : tdbAus.iterator().next().getJournalTitle(); } /** * Return the title from the title database that corresponds * to the ISSN of the journal or series. * * @param issn the ISSN of the journal or series * @return the title for the given ISSN */ static public String getTitleFromIssn(String issn) { if (issn == null) { return null; } // get the tdb Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); if (tdb == null) { log.debug2("No Tdb in configuration"); return null; } // get the title from the ISSN TdbTitle tdbTitle = tdb.getTdbTitleByIssn(issn); // return the title return tdbTitle == null ? null : tdbTitle.getName(); } /** * Return the publisher from the title database that corresponds * to the ISBN of a book volume. If the volume has multiple publishers, * the name of the first one is returned. * * @param journalIssn the ISSN of the journal * @return the publisher for the given ISSN */ static public String getPublisherFromIsbn(String isbn) { if (isbn == null) { return null; } Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); if (tdb == null) { log.debug2("No Tdb in configuration"); return null; } // get the publisher from the ISSN Collection<TdbAu> tdbAus = tdb.getTdbAusByIsbn(isbn); if (tdbAus.isEmpty()) { queryLog.debug2("No TdbAus for isbn: " + isbn); return null; } // return the publisher return tdbAus.iterator().next().getPublisherName(); } /** * Return the publisher from the title database that corresponds * to the ISSN of the journal. * * @param journalIssn the ISSN of the journal * @return the publisher for the given ISSN */ static public String getPublisherFromIssn(String journalIssn) { if (journalIssn == null) { return null; } Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); if (tdb == null) { log.debug2("No Tdb in configuration"); return null; } // get the publisher from the ISSN TdbTitle tdbTitle = tdb.getTdbTitleByIssn(journalIssn); if (tdbTitle == null) { queryLog.debug2("No TdbTitle for journal issn: " + journalIssn); return null; } // return the publisher TdbPublisher tdbPublisher = tdbTitle.getTdbPublisher(); return tdbPublisher == null ? null : tdbPublisher.getName(); } /** * Return the journal publisher that corresponds to the auid of a journal AU. * * @param pluginId the pluginId part of the auid * @param auKey the auKey part of the auid * @return the publisher for the given auid */ static public String getPublisherFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); return tdbAu == null ? null : tdbAu.getPublisherName(); } /** * Return the creation date of an Au of the form YYYY-MM-DD. * @param au the Archival Unit * @return the date */ static String getAuDateFromAu(ArchivalUnit au) { if (au == null) { return null; } AuState auState = AuUtil.getAuState(au); if (auState == null) { return null; } long creationTime = AuUtil.getAuState(au).getAuCreationTime(); if (creationTime < 0) { return null; } // AU date is of the form: Wed, 02 Nov 2011 06:11:51 GMT String ingestDate = isoDateFormatter.format(creationTime); return ingestDate; } /** * Return the au creation year from the daemon that corresponds * to an AU. This method is faster than * getIngestDateFromArticleUrl(String articleUrl) because it does * not require a disk access per article. Au creation date is a * close approximation to article ingest date because articles for an * AU are generally ingested close to the time when the AU is created. * * @param pluginId the pluginId * @param au_key the au key * @return the AU creation date for the given URL or null if not available */ static public String getIngestYearFromAuId(String pluginId, String auKey) { if (StringUtil.isNullString(pluginId) || StringUtil.isNullString(auKey)) { return null; } String ingestDate = getIngestDateFromAuId(pluginId, auKey); String ingestYear = getYearFromDate(ingestDate); return ingestYear; } /** * Return the au creation date from the daemon that corresponds * to the AU. This method is faster than * getIngestDateFromArticleUrl(String articleUrl) because it does * not require a disk access per article. Au creation date is a * close approximation to article ingest date because articles for an * AU are generally ingested close to the time when the AU is created. * * @param pluginId the pluginId * @param au_key the au key * @return the AU creation date for the given AU or null if not available */ static public String getIngestDateFromAuId(String pluginId, String auKey) { if (StringUtil.isNullString(pluginId) || StringUtil.isNullString(auKey)) { return null; } String auId = PluginManager.generateAuId(pluginId, auKey); ArchivalUnit au = getPluginManager().getAuFromId(auId); return getAuDateFromAu(au); } /** * Return the starting volume for the specified AU. * * @param pluginId the pluginId * @param au_key the au key * @return the starting volume for the given AU or null if not available */ static public String getStartVolumeFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); return (tdbAu == null) ? null : tdbAu.getStartVolume(); } /** * Return the starting volume for the specified article URL * * @param articleUrl * @return the starting volume for the given url or null if not available */ static public String getStartVolumeFromArticleUrl(String articleUrl) { TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); return (tdbAu == null) ? null : tdbAu.getStartVolume(); } /** * Return the ending volume for the specified AU. * * @param pluginId the pluginId * @param au_key the au key * @return the ending volume for the given AU or null if not available */ static public String getEndVolumeFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); return (tdbAu == null) ? null : tdbAu.getEndVolume(); } /** * Return the ending volume for the specified article URL * * @param articleUrl * @return the ending volume for the given url or null if not available */ static public String getEndVolumeFromArticleUrl(String articleUrl) { TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); return (tdbAu == null) ? null : tdbAu.getEndVolume(); } /** * Return the starting year for the specified AU. * * @param pluginId the pluginId * @param au_key the au key * @return the starting year for the given AU or null if not available */ static public String getStartYearFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); return (tdbAu == null) ? null : tdbAu.getStartYear(); } /** * Return the starting year for the specified article URL. * * @param articleUrl the article URL * @return the starting year for the given url or null if not available */ static public String getStartYearFromArticleUrl(String articleUrl) { TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); return (tdbAu == null) ? null : tdbAu.getStartYear(); } /** * Return the ending year for the specified AU. * * @param pluginId the pluginId * @param au_key the au key * @return the ending year for the given AU or null if not available */ static public String getEndYearFromAuId(String pluginId, String auKey) { TdbAu tdbAu = getTdbAuFromAuId(pluginId, auKey); return (tdbAu == null) ? null : tdbAu.getEndYear(); } /** * Return the ending year for the specified article URL. * * @param articleUrl the article URL * @return the ending year for the given url or null if not available */ static public String getEndYearFromArticleUrl(String articleUrl) { TdbAu tdbAu = getTdbAuFromArticleUrl(articleUrl); return (tdbAu == null) ? null : tdbAu.getEndYear(); } static public void main(String[] args) { } }
package org.mozilla.mozstumbler; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.graphics.Paint.Style; import android.graphics.Point; import android.net.wifi.ScanResult; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.widget.Toast; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.Void; import java.net.MalformedURLException; import java.net.HttpURLConnection; import java.net.URL; import java.util.Collections; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.osmdroid.tileprovider.MapTileProviderBasic; import org.osmdroid.tileprovider.tilesource.ITileSource; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView.Projection; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.SafeDrawOverlay; import org.osmdroid.views.overlay.TilesOverlay; import org.osmdroid.views.safecanvas.ISafeCanvas; import org.osmdroid.views.safecanvas.SafePaint; import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase; import org.osmdroid.tileprovider.tilesource.XYTileSource; public final class MapActivity extends Activity { private static final String LOGTAG = MapActivity.class.getName(); // TODO factor this out into something that can be shared with Reporter.java private static final String LOCATION_URL = "https://location.services.mozilla.com/v1/search"; private static final String USER_AGENT_HEADER = "User-Agent"; private static String MOZSTUMBLER_USER_AGENT_STRING; private static final String COVERAGE_URL = "https://location.services.mozilla.com/tiles/"; private MapView mMap; private AccuracyCircleOverlay mAccuracyCircleOverlay; private ReporterBroadcastReceiver mReceiver; // TODO add cell data private List<ScanResult> mWifiData; private class ReporterBroadcastReceiver extends BroadcastReceiver { private boolean mDone; @Override public void onReceive(Context context, Intent intent) { if (mDone) { return; } String action = intent.getAction(); if (!action.equals(ScannerService.MESSAGE_TOPIC)) { Log.e(LOGTAG, "Received an unknown intent: " + action); return; } String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); if (!WifiScanner.WIFI_SCANNER_EXTRA_SUBJECT.equals(subject)) { // might be another scanner return; } mWifiData = intent.getParcelableArrayListExtra(WifiScanner.WIFI_SCANNER_ARG_SCAN_RESULTS); new GetLocationAndMapItTask().execute(""); mDone = true; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); mWifiData = Collections.emptyList(); MOZSTUMBLER_USER_AGENT_STRING = NetworkUtils.getUserAgentString(this); mMap = (MapView) this.findViewById(R.id.map); mMap.setTileSource(getTileSource()); mMap.setBuiltInZoomControls(true); mMap.setMultiTouchControls(true); TilesOverlay coverageTilesOverlay = CoverageTilesOverlay(this); mAccuracyCircleOverlay = new AccuracyCircleOverlay(this); mMap.getOverlays().add(coverageTilesOverlay); mMap.getOverlays().add(mAccuracyCircleOverlay); mReceiver = new ReporterBroadcastReceiver(); registerReceiver(mReceiver, new IntentFilter(ScannerService.MESSAGE_TOPIC)); Log.d(LOGTAG, "onCreate"); } @SuppressWarnings("ConstantConditions") private static OnlineTileSourceBase getTileSource() { if (BuildConfig.TILE_SERVER_URL == null) { return TileSourceFactory.DEFAULT_TILE_SOURCE; } return new XYTileSource("MozStumbler Tile Store", null, 1, 20, 256, ".png", BuildConfig.TILE_SERVER_URL); } private static TilesOverlay CoverageTilesOverlay(Context context) { final MapTileProviderBasic coverageTileProvider = new MapTileProviderBasic(context); final ITileSource coverageTileSource = new XYTileSource("Mozilla Location Service Coverage Map", null, 1, 13, 256, ".png", COVERAGE_URL); coverageTileProvider.setTileSource(coverageTileSource); final TilesOverlay coverageTileOverlay = new TilesOverlay(coverageTileProvider,context); coverageTileOverlay.setLoadingBackgroundColor(Color.TRANSPARENT); return coverageTileOverlay; } private static class AccuracyCircleOverlay extends SafeDrawOverlay { private GeoPoint mPoint; private float mAccuracy; public AccuracyCircleOverlay(Context ctx) { super(ctx); } public void set(GeoPoint point, float accuracy) { mPoint = (GeoPoint) point.clone(); mAccuracy = accuracy; } protected void drawSafe(ISafeCanvas c, MapView osmv, boolean shadow) { if (shadow || mPoint == null) { return; } Projection pj = osmv.getProjection(); Point center = pj.toPixels(mPoint, null); float radius = pj.metersToEquatorPixels(mAccuracy); SafePaint circle = new SafePaint(); circle.setARGB(0, 100, 100, 255); // Fill circle.setAlpha(40); circle.setStyle(Style.FILL); c.drawCircle(center.x, center.y, radius, circle); // Border circle.setAlpha(165); circle.setStyle(Style.STROKE); c.drawCircle(center.x, center.y, radius, circle); } } private void positionMapAt(float lat, float lon, float accuracy) { GeoPoint point = new GeoPoint(lat, lon); mMap.getController().setCenter(point); mMap.getController().setZoom(17); mMap.getController().animateTo(point); mAccuracyCircleOverlay.set(point, accuracy); mMap.invalidate(); } @Override protected void onStart() { super.onStart(); Context context = getApplicationContext(); Intent i = new Intent(ScannerService.MESSAGE_TOPIC); i.putExtra(Intent.EXTRA_SUBJECT, "Scanner"); i.putExtra("enable", 1); context.sendBroadcast(i); Log.d(LOGTAG, "onStart"); } @Override protected void onStop() { super.onStop(); Log.d(LOGTAG, "onStop"); mMap.getTileProvider().clearTileCache(); if (mReceiver != null) { unregisterReceiver(mReceiver); mReceiver = null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { return false; } private final class GetLocationAndMapItTask extends AsyncTask<String, Void, String> { private String mStatus; private float mLat; private float mLon; private float mAccuracy; @Override public String doInBackground(String... params) { Log.d(LOGTAG, "requesting location..."); HttpURLConnection urlConnection = null; try { URL url; try { url = new URL(LOCATION_URL + "?key=" + BuildConfig.MOZILLA_API_KEY); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestProperty(USER_AGENT_HEADER, MOZSTUMBLER_USER_AGENT_STRING); Log.d(LOGTAG, "mWifiData: " + mWifiData); JSONObject wrapper = new JSONObject("{}"); try { JSONArray wifiData = new JSONArray(); for (ScanResult result : mWifiData) { JSONObject item = new JSONObject(); item.put("key", BSSIDBlockList.canonicalizeBSSID(result.BSSID)); item.put("frequency", result.frequency); item.put("signal", result.level); wifiData.put(item); } wrapper.put("wifi", wifiData); } catch (JSONException jsonex) { Log.w(LOGTAG, "json exception", jsonex); return ""; } String data = wrapper.toString(); byte[] bytes = data.getBytes(); urlConnection.setFixedLengthStreamingMode(bytes.length); OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(bytes); out.flush(); int code = urlConnection.getResponseCode(); Log.d(LOGTAG, "uploaded data: " + data + " to " + LOCATION_URL); Log.d(LOGTAG, "urlConnection returned " + code); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader r = new BufferedReader(new InputStreamReader(in)); StringBuilder total = new StringBuilder(in.available()); String line; while ((line = r.readLine()) != null) { total.append(line); } r.close(); JSONObject result = new JSONObject(total.toString()); mStatus = result.getString("status"); Log.d(LOGTAG, "Location status: " + mStatus); if ("ok".equals(mStatus)) { mLat = Float.parseFloat(result.getString("lat")); mLon = Float.parseFloat(result.getString("lon")); mAccuracy = Float.parseFloat(result.getString("accuracy")); Log.d(LOGTAG, "Location lat: " + mLat); Log.d(LOGTAG, "Location lon: " + mLon); Log.d(LOGTAG, "Location accuracy: " + mAccuracy); } } catch (JSONException jsonex) { Log.e(LOGTAG, "json parse error", jsonex); } catch (Exception ex) { Log.e(LOGTAG, "error submitting data", ex); } finally { urlConnection.disconnect(); } return mStatus; } @Override protected void onPostExecute(String result) { if (mStatus != null && "ok".equals(mStatus)) { positionMapAt(mLat, mLon, mAccuracy); } else if (mStatus != null && "not_found".equals(mStatus)) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.location_not_found), Toast.LENGTH_LONG).show(); } else { Log.e(LOGTAG, "", new IllegalStateException("mStatus=" + mStatus)); } } } }
// ZAP: 2011/05/15 Support for exclusions // ZAP: 2011/09/06 Fix alert save plus concurrent mod exceptions // ZAP: 2011/11/04 Correct getHierarchicNodeName // ZAP: 2011/11/29 Added blank image to node names to fix redrawing issue // ZAP: 2012/02/11 Re-ordered icons, added spider icon and notify via SiteMap // ZAP: 2012/03/11 Issue 280: Escape URLs in sites tree // ZAP: 2012/03/15 Changed the method toString to use the class StringBuilder // and reworked the method toString and getIcons. Renamed the method // getIcons to appendIcons. // ZAP: 2012/07/29 Issue 43: Added support for Scope // ZAP: 2012/08/29 Issue 250 Support for authentication management // ZAP: 2012/10/02 Issue 385: Added support for Contexts // ZAP: 2013/01/23 Ignore Active scanner history refs // ZAP: 2013/08/23 Make sure #nodeChanged() is called after removing a custom icon // ZAP: 2013/11/16 Issue 869: Differentiate proxied requests from (ZAP) user requests // ZAP: 2014/03/23 Issue 1084: NullPointerException while selecting a node in the "Sites" tab // ZAP: 2014/04/10 Do not allow to set the parent node as itself // ZAP: 2014/04/10 Issue 1118: Alerts Tab can get out of sync // ZAP: 2014/05/05 Issue 1181: Vulnerable pages active scanned only once // ZAP: 2014/05/23 Issue 1209: Reliability becomes Confidence and add levels // ZAP: 2014/06/16 Fixed an issue in SiteNode#setHistoryReference(HistoryReference) that led // to multiple occurrences of same HistoryReference(s) in the pastHistoryList. // ZAP: 2014/06/16 Issue 990: Allow to delete alerts through the API // ZAP: 2014/11/19 Issue 1412: Prevent ConcurrentModificationException when icons updated frequently // ZAP: 2014/12/17 Issue 1174: Support a Site filter // ZAP: 2015/04/02 Issue 1582: Low memory option // ZAP: 2015/10/21 Issue 1576: Support data driven content // ZAP: 2016/01/26 Fixed findbugs warning // ZAP: 2016/03/24 Do not access EDT in daemon mode // ZAP: 2016/04/12 Notify of changes when an alert is updated // ZAP: 2016/08/30 Use a Set instead of a List for the alerts // ZAP: 2017/02/22 Issue 3224: Use TreeCellRenderers to prevent HTML injection issues // ZAP: 2017/07/09: Issue 3727: Add getName() function, returning the node name without HTTP method (verb) // ZAP: 2018/01/24 Clear highest alert when all deleted. package org.parosproxy.paros.model; import java.awt.EventQueue; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.MutableTreeNode; import org.apache.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.core.scanner.Alert; import org.parosproxy.paros.view.View; import org.zaproxy.zap.model.SessionStructure; public class SiteNode extends DefaultMutableTreeNode { private static final long serialVersionUID = 7987615016786179150L; private String nodeName = null; private String hierarchicNodeName = null; private HistoryReference historyReference = null; private Vector<HistoryReference> pastHistoryList = new Vector<>(10); // ZAP: Support for linking Alerts to SiteNodes private SiteMap siteMap = null; private Set<Alert> alerts = Collections.synchronizedSet(new HashSet<Alert>()); private boolean justSpidered = false; //private boolean justAJAXSpidered = false; private ArrayList<String> icons = null; private ArrayList<Boolean> clearIfManual = null; private static Logger log = Logger.getLogger(SiteNode.class); private boolean isIncludedInScope = false; private boolean isExcludedFromScope = false; private boolean filtered = false; private boolean dataDriven = false; /** * Flag that indicates whether or not the {@link #calculateHighestAlert() highest alert needs to be calculated}, when * {@link #appendIcons(StringBuilder) building the string representation}. */ private boolean calculateHighestAlert; /** * The {@code Alert} with highest risk (and not a false positive). * * @see #isHighestAlert(Alert) */ private Alert highestAlert; public SiteNode(SiteMap siteMap, int type, String nodeName) { super(); this.siteMap = siteMap; this.nodeName = nodeName; if (nodeName.startsWith(SessionStructure.DATA_DRIVEN_NODE_PREFIX)) { this.dataDriven = true; } this.icons = new ArrayList<>(); this.clearIfManual = new ArrayList<>(); if (type == HistoryReference.TYPE_SPIDER) { this.justSpidered = true; } } public void setCustomIcons(ArrayList<String> i, ArrayList<Boolean> c) { synchronized (this.icons) { this.icons.clear(); this.icons.addAll(i); this.clearIfManual = c; } } public void addCustomIcon(String resourceName, boolean clearIfManual) { synchronized (this.icons) { if (! this.icons.contains(resourceName)) { this.icons.add(resourceName); this.clearIfManual.add(clearIfManual); this.nodeChanged(); } } } public void removeCustomIcon(String resourceName) { synchronized (this.icons) { if (this.icons.contains(resourceName)) { int i = this.icons.indexOf(resourceName); this.icons.remove(i); this.clearIfManual.remove(i); this.nodeChanged(); } } } /** * Gets any custom icons that have been set for this node * @return any custom icons that have been set for this node * @since 2.6.0 */ public List<ImageIcon> getCustomIcons() { List<ImageIcon> iconList = new ArrayList<ImageIcon>(); if (justSpidered) { iconList.add(new ImageIcon(Constant.class.getResource("/resource/icon/10/spider.png"))); } synchronized (this.icons) { if (!this.icons.isEmpty()) { for(String icon : this.icons) { iconList.add(new ImageIcon(Constant.class.getResource(icon))); } } } return iconList; } /** * Calculates the highest alert. * <p> * After a call to this method the {@link #highestAlert} will have the highest alert (or {@code null} if none) and the flag * {@link #calculateHighestAlert} will have the value {@code false}. * * @see #isHighestAlert(Alert) */ private void calculateHighestAlert() { synchronized (alerts) { highestAlert = null; for (Alert alert : alerts) { if (isHighestAlert(alert)) { highestAlert = alert; } } calculateHighestAlert = false; } } /** * Tells whether or not the given alert is the alert with highest risk than the current highest alert. * <p> * {@link Alert#CONFIDENCE_FALSE_POSITIVE False positive alerts} are ignored. * * @param alert the alert to check * @return {@code true} if it's the alert with highest risk, {@code false} otherwise. */ private boolean isHighestAlert(Alert alert) { if (alert.getConfidence() == Alert.CONFIDENCE_FALSE_POSITIVE) { return false; } if (highestAlert == null) { return true; } return alert.getRisk() > highestAlert.getRisk(); } public Alert getHighestAlert() { return this.highestAlert; } @Override public String toString() { if (calculateHighestAlert) { calculateHighestAlert(); } return nodeName; } public boolean isParentOf (String nodeName) { if (nodeName == null) { return false; } return nodeName.compareTo(this.nodeName) < 0; } public String getNodeName() { return this.nodeName; } /** * Returns the node's name without the HTTP Method (verb) prefixing the string. * * @return the name of the site node * @see #getNodeName() * @see #getCleanNodeName() * @see #getCleanNodeName(boolean) * @since 2.7.0 */ public String getName() { String name = this.getNodeName(); if (this.isLeaf()) { int colonIndex = name.indexOf(":"); if (colonIndex > 0) { // Strip the GET/POST etc off name = name.substring(colonIndex+1); } } return name; } public String getCleanNodeName() { return getCleanNodeName(true); } public String getCleanNodeName(boolean specialNodesAsRegex) { String name = this.getNodeName(); if (specialNodesAsRegex && this.isDataDriven()) { // Non-greedy regex pattern name = "(.+?)"; } else if (this.isLeaf()) { int colonIndex = name.indexOf(":"); if (colonIndex > 0) { // Strip the GET/POST etc off name = name.substring(colonIndex+1); } int bracketIndex = name.lastIndexOf("("); if (bracketIndex > 0) { // Strip the param summary off name = name.substring(0, bracketIndex); } int quesIndex = name.indexOf("?"); if (quesIndex > 0) { // Strip the parameters off name = name.substring(0, quesIndex); } } return name; } public String getHierarchicNodeName() { return getHierarchicNodeName(true); } public String getHierarchicNodeName(boolean specialNodesAsRegex) { if (hierarchicNodeName != null && specialNodesAsRegex) { // The regex version is used most frequently, so cache return hierarchicNodeName; } if (this.isRoot()) { hierarchicNodeName = ""; } else if (this.getParent().isRoot()) { hierarchicNodeName = this.getNodeName(); } else { String name = this.getParent().getHierarchicNodeName(specialNodesAsRegex) + "/" + this.getCleanNodeName(specialNodesAsRegex); if (!specialNodesAsRegex) { // Dont cache the non regex version return name; } hierarchicNodeName = name; } return hierarchicNodeName; } public HistoryReference getHistoryReference() { return historyReference; } /** * Set current node reference. * If there is any existing reference, delete if spider record. * Otherwise, put into past history list. * @param historyReference */ public void setHistoryReference(HistoryReference historyReference) { if (getHistoryReference() != null) { // if (getHistoryReference().getHistoryType() == HistoryReference.TYPE_SPIDER) { // getHistoryReference().delete(); // getHistoryReference().setSiteNode(null); // } else if (!getPastHistoryReference().contains(historyReference)) { // getPastHistoryReference().add(getHistoryReference()); if (this.justSpidered && (historyReference.getHistoryType() == HistoryReference.TYPE_PROXIED || historyReference.getHistoryType() == HistoryReference.TYPE_ZAP_USER)) { this.justSpidered = false; this.nodeChanged(); } // we remove the icons of the node that has to be cleaned when manually visiting them if (!this.icons.isEmpty() && (historyReference.getHistoryType() == HistoryReference.TYPE_PROXIED || historyReference.getHistoryType() == HistoryReference.TYPE_ZAP_USER)) { synchronized (this.icons) { for (int i = 0; i < this.clearIfManual.size(); ++i) { if (this.clearIfManual.get(i) && this.icons.size() > i) { this.icons.remove(i); this.clearIfManual.remove(i); } } } this.nodeChanged(); } if (HistoryReference.TYPE_SCANNER == historyReference.getHistoryType()) { getPastHistoryReference().add(historyReference); return; } // above code commented as to always add all into past reference. For use in scanner if (!getPastHistoryReference().contains(getHistoryReference())) { getPastHistoryReference().add(getHistoryReference()); } } this.historyReference = historyReference; this.historyReference.setSiteNode(this); } private void nodeChanged() { if (this.siteMap == null || !View.isInitialised()) { return; } if (EventQueue.isDispatchThread()) { nodeChangedEventHandler(); } else { try { EventQueue.invokeLater(new Runnable() { @Override public void run() { nodeChangedEventHandler(); } }); } catch (Exception e) { log.error(e.getMessage(), e); } } } private void nodeChangedEventHandler() { this.siteMap.nodeChanged(this); } public Vector<HistoryReference> getPastHistoryReference() { return pastHistoryList; } public boolean hasAlert(Alert alert) { if (alert == null) { throw new IllegalArgumentException("Alert must not be null"); } return alerts.contains(alert); } public void addAlert(Alert alert) { if (alert == null) { throw new IllegalArgumentException("Alert must not be null"); } if (!this.alerts.add(alert)) { return; } if (isHighestAlert(alert)) { highestAlert = alert; } if (this.getParent() != null) { this.getParent().addAlert(alert); } if (this.siteMap != null) { // Adding alert might affect the nodes visibility in a filtered tree siteMap.applyFilter(this); } this.nodeChanged(); } public void updateAlert(Alert alert) { if (alert == null) { throw new IllegalArgumentException("Alert must not be null"); } boolean updated = false; synchronized (alerts) { for (Iterator<Alert> it = alerts.iterator(); it.hasNext();) { if (it.next().getAlertId() == alert.getAlertId()) { it.remove(); updated = true; this.alerts.add(alert); setCalculateHighestAlertIfSameAlert(alert); break; } } } if (updated) { if (this.getParent() != null) { this.getParent().updateAlert(alert); } if (this.siteMap != null) { // Updating an alert might affect the nodes visibility in a filtered tree siteMap.applyFilter(this); } this.nodeChanged(); } } /** * Gets the alerts of the node. * <p> * The returned {@code List} is a copy of the internal collection. * * @return a new {@code List} containing the {@code Alert}s */ public List<Alert> getAlerts() { synchronized (alerts) { return new ArrayList<>(alerts); } } private void clearChildAlert (Alert alert, SiteNode child) { // Alerts are propagated up, which means when one is deleted we need to work out if it still // is present in another child node boolean removed = true; alerts.remove(alert); if (this.getChildCount() > 0) { SiteNode c = (SiteNode) this.getFirstChild(); while (c != null) { if (! c.equals(child)) { if (c.hasAlert(alert)) { alerts.add(alert); removed = false; break; } } c = (SiteNode) this.getChildAfter(c); } } if (removed) { setCalculateHighestAlertIfSameAlert(alert); nodeChanged(); if (this.getParent() != null) { this.getParent().clearChildAlert(alert, this); } } } public void deleteAlert(Alert alert) { if (alert == null) { throw new IllegalArgumentException("Alert must not be null"); } if (!alerts.remove(alert)) { return; } setCalculateHighestAlertIfSameAlert(alert); // Remove from parents, if not in siblings if (this.getParent() != null) { this.getParent().clearChildAlert(alert, this); } if (this.siteMap != null) { // Deleting alert might affect the nodes visibility in a filtered tree siteMap.applyFilter(this); } this.nodeChanged(); } /** * Sets whether or not the highest alert needs to be calculated, based on the given alert. * <p> * The highest alert needs to be calculated if the given alert is the highest alert. * * @param alert the alert to check */ private void setCalculateHighestAlertIfSameAlert(Alert alert) { if (highestAlert != null && highestAlert.getAlertId() == alert.getAlertId()) { calculateHighestAlert = true; highestAlert = null; } } public void deleteAlerts(List<Alert> alerts) { if (this.alerts.removeAll(alerts)) { // Remove from parents, if not in siblings if (this.getParent() != null) { this.getParent().clearChildAlerts(alerts); } if (this.siteMap != null) { // Deleting alerts might affect the nodes visibility in a filtered tree siteMap.applyFilter(this); } calculateHighestAlert = true; this.nodeChanged(); } } /** * Deletes all alerts of this node and all child nodes recursively. */ public void deleteAllAlerts() { for(int i = 0; i < getChildCount(); i++) { ((SiteNode) getChildAt(i)).deleteAllAlerts(); } if (!alerts.isEmpty()) { alerts.clear(); highestAlert = null; calculateHighestAlert = false; if (this.siteMap != null) { // Deleting alert might affect the nodes visibility in a filtered tree siteMap.applyFilter(this); } nodeChanged(); } } private void clearChildAlerts(List<Alert> alerts) { List<Alert> alertsToRemove = new ArrayList<>(alerts); if (this.getChildCount() > 0) { SiteNode c = (SiteNode) this.getFirstChild(); while (c != null) { alertsToRemove.removeAll(c.alerts); c = (SiteNode) this.getChildAfter(c); } } boolean changed = this.alerts.removeAll(alertsToRemove); if (changed) { calculateHighestAlert = true; if (this.getParent() != null) { this.getParent().clearChildAlerts(alertsToRemove); } nodeChangedEventHandler(); } } public boolean hasHistoryType (int type) { if (this.historyReference == null) { return false; } if (this.historyReference.getHistoryType() == type) { return true; } for (HistoryReference href : this.pastHistoryList) { if (href.getHistoryType() == type) { return true; } } return false; } public boolean hasJustHistoryType (int type) { if (this.historyReference == null) { return false; } if (this.historyReference.getHistoryType() != type) { return false; } for (HistoryReference href : this.pastHistoryList) { if (href.getHistoryType() != type) { return false; } } return true; } public boolean isIncludedInScope() { return isIncludedInScope; } public void setIncludedInScope(boolean isIncludedInScope, boolean applyToChildNodes) { this.isIncludedInScope = isIncludedInScope; if (siteMap != null) { // This could have affected its visibility siteMap.applyFilter(this); } this.nodeChanged(); // Recurse down if (this.getChildCount() > 0 && applyToChildNodes) { SiteNode c = (SiteNode) this.getFirstChild(); while (c != null) { c.setIncludedInScope(isIncludedInScope, applyToChildNodes); c = (SiteNode) this.getChildAfter(c); } } } public boolean isExcludedFromScope() { return isExcludedFromScope; } public void setExcludedFromScope(boolean isExcludedFromScope, boolean applyToChildNodes) { this.isExcludedFromScope = isExcludedFromScope; if (isExcludedFromScope) { this.isIncludedInScope = false; } if (siteMap != null) { // This could have affected its visibility siteMap.applyFilter(this); } this.nodeChanged(); // Recurse down if (this.getChildCount() > 0 && applyToChildNodes) { SiteNode c = (SiteNode) this.getFirstChild(); while (c != null) { c.setExcludedFromScope(isExcludedFromScope, applyToChildNodes); c = (SiteNode) this.getChildAfter(c); } } } @Override public void setParent(MutableTreeNode newParent) { if (newParent == this) { return; } super.setParent(newParent); } /** * Returns this node's parent or null if this node has no parent. * * @return this node's parent SiteNode, or null if this node has no parent */ @Override public SiteNode getParent() { return (SiteNode)super.getParent(); } public boolean isFiltered() { return filtered; } protected void setFiltered(boolean filtered) { this.filtered = filtered; } public boolean isDataDriven() { return dataDriven; } }
// ZAP: 2011/05/31 Added option to dynamically change the display // ZAP: 2012/03/15 Changed so the change display option stays visually selected. // ZAP: 2012/04/26 Removed the method setStatus(String) and instance variable // "txtStatus". // ZAP: 2013/07/23 Issue 738: Options to hide tabs // ZAP: 2015/01/29 Issue 1489: Version number in window title // ZAP: 2016/04/04 Do not require a restart to show/hide the tool bar // ZAP: 2016/04/06 Fix layouts' issues // ZAP: 2017/06/01 Issue 3555: setTitle() functionality moved in order to ensure consistent application package org.parosproxy.paros.view; import java.awt.CardLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.net.URL; import javax.swing.AbstractAction; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JToggleButton; import javax.swing.WindowConstants; import org.apache.commons.configuration.ConfigurationException; import org.apache.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.extension.AbstractPanel; import org.parosproxy.paros.model.Model; import org.parosproxy.paros.model.OptionsParam; import org.parosproxy.paros.model.Session; import org.zaproxy.zap.utils.DisplayUtils; import org.zaproxy.zap.view.MainToolbarPanel; import org.zaproxy.zap.view.ZapToggleButton; public class MainFrame extends AbstractFrame { private static final Logger LOGGER = Logger.getLogger(MainFrame.class); private static final String TABS_VIEW_TOOL_TIP = Constant.messages.getString("view.toolbar.messagePanelsPosition.tabs"); private static final String DISABLED_TABS_VIEW_TOOL_TIP = Constant.messages.getString("view.toolbar.messagePanelsPosition.tabs.disabled"); private static final String ABOVE_VIEW_TOOL_TIP = Constant.messages.getString("view.toolbar.messagePanelsPosition.above"); private static final String DISABLED_ABOVE_VIEW_TOOL_TIP = Constant.messages.getString("view.toolbar.messagePanelsPosition.above.disabled"); private static final String SIDE_BY_SIDE_VIEW_TOOL_TIP = Constant.messages.getString("view.toolbar.messagePanelsPosition.sideBySide"); private static final String DISABLED_SIDE_BY_SIDE_VIEW_TOOL_TIP = Constant.messages.getString("view.toolbar.messagePanelsPosition.sideBySide.disabled"); private static final long serialVersionUID = -1430550461546083192L; private final OptionsParam options; private JPanel paneContent = null; // ZAP: Removed instance variable (JLabel txtStatus). The status label that // was in the footer panel is no longer used. private final WorkbenchPanel paneStandard; private org.parosproxy.paros.view.MainMenuBar mainMenuBar = null; private JPanel paneDisplay = null; private MainToolbarPanel mainToolbarPanel = null; private MainFooterPanel mainFooterPanel = null; /** * The {@code ZapToggleButton} that sets whether or not the tabs should show the panels' names. * <p> * Lazily initialised. * * @see #getShowTabIconNamesButton() */ private ZapToggleButton showTabIconNamesButton; /** * The {@code JButton} that shows all tabs. * <p> * Lazily initialised. * * @see #getShowAllTabsButton() */ private JButton showAllTabsButton; /** * The {@code JButton} that hides all tabs (if hideable and not pinned). * <p> * Lazily initialised. * * @see #getHideAllTabsButton() */ private JButton hideAllTabsButton; /** * The current workbench layout, never {@code null}. * * @see #setWorkbenchLayout(WorkbenchPanel.Layout) */ private WorkbenchPanel.Layout workbenchLayout; /** * The {@code JToggleButton} that sets the layout {@link WorkbenchPanel.Layout#EXPAND_SELECT}. * <p> * Lazily initialised. * * @see #getExpandSelectLayoutButton() */ private JToggleButton expandSelectLayoutButton; /** * The {@code JToggleButton} that sets the layout {@link WorkbenchPanel.Layout#EXPAND_STATUS}. * <p> * Lazily initialised. * * @see #getExpandStatusLayoutButton() */ private JToggleButton expandStatusLayoutButton; /** * The {@code JToggleButton} that sets the layout {@link WorkbenchPanel.Layout#FULL}. * <p> * Lazily initialised. * * @see #getFullLayoutButton() */ private JToggleButton fullLayoutButton; /** * The current position of the response panel, never {@code null}. * * @see #setResponsePanelPosition(WorkbenchPanel.ResponsePanelPosition) */ private WorkbenchPanel.ResponsePanelPosition responsePanelPosition; /** * The {@code ZapToggleButton} that sets the response panel position * {@link WorkbenchPanel.ResponsePanelPosition#TABS_SIDE_BY_SIDE}. * <p> * Lazily initialised. * * @see #getTabsResponsePanelPositionButton() */ private ZapToggleButton tabsResponsePanelPositionButton; /** * The {@code ZapToggleButton} that sets the response panel position * {@link WorkbenchPanel.ResponsePanelPosition#PANEL_ABOVE}. * <p> * Lazily initialised. * * @see #getAboveResponsePanelPositionButton() */ private ZapToggleButton aboveResponsePanelPositionButton; /** * The {@code ZapToggleButton} that sets the response panel position * {@link WorkbenchPanel.ResponsePanelPosition#PANELS_SIDE_BY_SIDE}. * <p> * Lazily initialised. * * @see #getPanelsResponsePanelPositionButton() */ private ZapToggleButton panelsResponsePanelPositionButton; /** * @deprecated (2.5.0) Use {@link #MainFrame(OptionsParam, AbstractPanel, AbstractPanel)} instead. */ @Deprecated @SuppressWarnings("javadoc") public MainFrame(int displayOption) { this(Model.getSingleton().getOptionsParam(), View.getSingleton().getRequestPanel(), View.getSingleton().getResponsePanel()); changeDisplayOption(displayOption); } public MainFrame(OptionsParam options, AbstractPanel requestPanel, AbstractPanel responsePanel) { super(); if (options == null) { throw new IllegalArgumentException("Parameter options must not be null"); } if (requestPanel == null) { throw new IllegalArgumentException("Parameter requestPanel must not be null"); } if (responsePanel == null) { throw new IllegalArgumentException("Parameter responsePanel must not be null"); } this.options = options; paneStandard = new WorkbenchPanel(options.getViewParam(), requestPanel, responsePanel); paneStandard.setLayout(new CardLayout()); paneStandard.setName("paneStandard"); initialize(); applyViewOptions(); } /** * This method initializes this */ private void initialize() { this.setJMenuBar(getMainMenuBar()); this.setContentPane(getPaneContent()); this.setPreferredSize(new Dimension(1000, 800)); this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { getMainMenuBar().getMenuFileControl().exit(); } }); this.setVisible(false); } /** * This method initializes paneContent * * @return JPanel */ private JPanel getPaneContent() { if (paneContent == null) { paneContent = new JPanel(); paneContent.setLayout(new BoxLayout(getPaneContent(), BoxLayout.Y_AXIS)); paneContent.setEnabled(true); paneContent.add(getMainToolbarPanel(), null); paneContent.add(getPaneDisplay(), null); paneContent.add(getMainFooterPanel(), null); } return paneContent; } /** * Gets the {@code WorkbenchPanel}. * * @return the workbench panel * @since 2.2.0 */ public WorkbenchPanel getWorkbench() { return paneStandard; } /** * This method initializes mainMenuBar * * @return org.parosproxy.paros.view.MenuDisplay */ public org.parosproxy.paros.view.MainMenuBar getMainMenuBar() { if (mainMenuBar == null) { mainMenuBar = new org.parosproxy.paros.view.MainMenuBar(); } return mainMenuBar; } // ZAP: Removed the method getTxtStatus() // ZAP: Removed the method setStatus(String). The status label // ("txtStatus") that was in the footer panel is no longer used. /** * This method initializes paneDisplay * * @return JPanel */ public JPanel getPaneDisplay() { if (paneDisplay == null) { paneDisplay = new JPanel(); paneDisplay.setLayout(new CardLayout()); paneDisplay.setName("paneDisplay"); paneDisplay.add(getWorkbench(), getWorkbench().getName()); } return paneDisplay; } // ZAP: Added main toolbar panel public MainToolbarPanel getMainToolbarPanel() { if (mainToolbarPanel == null) { mainToolbarPanel = new MainToolbarPanel(); mainToolbarPanel.addButton(getShowAllTabsButton()); mainToolbarPanel.addButton(getHideAllTabsButton()); mainToolbarPanel.addButton(getShowTabIconNamesButton()); mainToolbarPanel.addSeparator(); ButtonGroup layoutsButtonGroup = new ButtonGroup(); mainToolbarPanel.addButton(getExpandSelectLayoutButton()); layoutsButtonGroup.add(getExpandSelectLayoutButton()); mainToolbarPanel.addButton(getExpandStatusLayoutButton()); layoutsButtonGroup.add(getExpandStatusLayoutButton()); mainToolbarPanel.addButton(getFullLayoutButton()); layoutsButtonGroup.add(getFullLayoutButton()); mainToolbarPanel.addSeparator(); ButtonGroup responsePanelPositionsButtonGroup = new ButtonGroup(); mainToolbarPanel.addButton(getTabsResponsePanelPositionButton()); responsePanelPositionsButtonGroup.add(getTabsResponsePanelPositionButton()); mainToolbarPanel.addButton(getPanelsResponsePanelPositionButton()); responsePanelPositionsButtonGroup.add(getPanelsResponsePanelPositionButton()); mainToolbarPanel.addButton(getAboveResponsePanelPositionButton()); responsePanelPositionsButtonGroup.add(getAboveResponsePanelPositionButton()); mainToolbarPanel.addSeparator(); } return mainToolbarPanel; } private JButton getShowAllTabsButton() { if (showAllTabsButton == null) { showAllTabsButton = new JButton(); showAllTabsButton.setIcon(new ImageIcon(WorkbenchPanel.class.getResource("/resource/icon/fugue/ui-tab-show.png"))); showAllTabsButton.setToolTipText(Constant.messages.getString("menu.view.tabs.show")); DisplayUtils.scaleIcon(showAllTabsButton); showAllTabsButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(ActionEvent e) { View.getSingleton().showAllTabs(); } }); } return showAllTabsButton; } private JButton getHideAllTabsButton() { if (hideAllTabsButton == null) { hideAllTabsButton = new JButton(); hideAllTabsButton.setIcon(new ImageIcon(WorkbenchPanel.class.getResource("/resource/icon/fugue/ui-tab-hide.png"))); hideAllTabsButton.setToolTipText(Constant.messages.getString("menu.view.tabs.hide")); DisplayUtils.scaleIcon(hideAllTabsButton); hideAllTabsButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(ActionEvent e) { View.getSingleton().hideAllTabs(); } }); } return hideAllTabsButton; } private JToggleButton getShowTabIconNamesButton() { if (showTabIconNamesButton == null) { showTabIconNamesButton = new ZapToggleButton(); showTabIconNamesButton.setIcon(new ImageIcon(WorkbenchPanel.class.getResource("/resource/icon/ui_tab_icon.png"))); showTabIconNamesButton.setToolTipText(Constant.messages.getString("view.toolbar.showNames")); showTabIconNamesButton .setSelectedIcon(new ImageIcon(WorkbenchPanel.class.getResource("/resource/icon/ui_tab_text.png"))); showTabIconNamesButton.setSelectedToolTipText(Constant.messages.getString("view.toolbar.showIcons")); showTabIconNamesButton.setSelected(Model.getSingleton().getOptionsParam().getViewParam().getShowTabNames()); DisplayUtils.scaleIcon(showTabIconNamesButton); showTabIconNamesButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(ActionEvent evt) { boolean showTabNames = getShowTabIconNamesButton().isSelected(); setShowTabNames(showTabNames); Model.getSingleton().getOptionsParam().getViewParam().setShowTabNames(showTabNames); try { Model.getSingleton().getOptionsParam().getViewParam().getConfig().save(); } catch (ConfigurationException e) { LOGGER.error(e.getMessage(), e); } } }); } return showTabIconNamesButton; } private JToggleButton getExpandSelectLayoutButton() { if (expandSelectLayoutButton == null) { expandSelectLayoutButton = new JToggleButton( new ChangeWorkbenchLayoutAction( WorkbenchPanel.class.getResource("/resource/icon/expand_sites.png"), WorkbenchPanel.Layout.EXPAND_SELECT)); expandSelectLayoutButton.setToolTipText(Constant.messages.getString("view.toolbar.expandSites")); } return expandSelectLayoutButton; } private JToggleButton getExpandStatusLayoutButton() { if (expandStatusLayoutButton == null) { expandStatusLayoutButton = new JToggleButton( new ChangeWorkbenchLayoutAction( WorkbenchPanel.class.getResource("/resource/icon/expand_info.png"), WorkbenchPanel.Layout.EXPAND_STATUS)); expandStatusLayoutButton.setToolTipText(Constant.messages.getString("view.toolbar.expandInfo")); } return expandStatusLayoutButton; } private JToggleButton getFullLayoutButton() { if (fullLayoutButton == null) { fullLayoutButton = new JToggleButton( new ChangeWorkbenchLayoutAction( WorkbenchPanel.class.getResource("/resource/icon/expand_full.png"), WorkbenchPanel.Layout.FULL)); fullLayoutButton.setToolTipText(Constant.messages.getString("view.toolbar.expandFull")); } return fullLayoutButton; } private ZapToggleButton getTabsResponsePanelPositionButton() { if (tabsResponsePanelPositionButton == null) { tabsResponsePanelPositionButton = new ZapToggleButton( new SetResponsePanelPositionAction( WorkbenchPanel.class.getResource("/resource/icon/layout_tabbed.png"), WorkbenchPanel.ResponsePanelPosition.TABS_SIDE_BY_SIDE)); tabsResponsePanelPositionButton.setToolTipText(TABS_VIEW_TOOL_TIP); tabsResponsePanelPositionButton.setDisabledToolTipText(DISABLED_TABS_VIEW_TOOL_TIP); } return tabsResponsePanelPositionButton; } private ZapToggleButton getPanelsResponsePanelPositionButton() { if (panelsResponsePanelPositionButton == null) { panelsResponsePanelPositionButton = new ZapToggleButton( new SetResponsePanelPositionAction( WorkbenchPanel.class.getResource("/resource/icon/layout_horizontal_split.png"), WorkbenchPanel.ResponsePanelPosition.PANELS_SIDE_BY_SIDE)); panelsResponsePanelPositionButton.setToolTipText(SIDE_BY_SIDE_VIEW_TOOL_TIP); panelsResponsePanelPositionButton.setDisabledToolTipText(DISABLED_SIDE_BY_SIDE_VIEW_TOOL_TIP); } return panelsResponsePanelPositionButton; } private ZapToggleButton getAboveResponsePanelPositionButton() { if (aboveResponsePanelPositionButton == null) { aboveResponsePanelPositionButton = new ZapToggleButton( new SetResponsePanelPositionAction( WorkbenchPanel.class.getResource("/resource/icon/layout_vertical_split.png"), WorkbenchPanel.ResponsePanelPosition.PANEL_ABOVE)); aboveResponsePanelPositionButton.setToolTipText(ABOVE_VIEW_TOOL_TIP); aboveResponsePanelPositionButton.setDisabledToolTipText(DISABLED_ABOVE_VIEW_TOOL_TIP); } return aboveResponsePanelPositionButton; } // ZAP: Added footer toolbar panel public MainFooterPanel getMainFooterPanel() { if (mainFooterPanel == null) { mainFooterPanel = new MainFooterPanel(); } return mainFooterPanel; } /** * @deprecated (2.5.0) Use {@link #setWorkbenchLayout(WorkbenchPanel.Layout)} instead. */ @Deprecated @SuppressWarnings("javadoc") public void changeDisplayOption(int displayOption) { setWorkbenchLayout(WorkbenchPanel.Layout.getLayout(displayOption)); } /** * Applies the view options to the main frame components. * <p> * It controls the visibility of the main tool bar, the layout and response panel position of the workbench panel and if the * tabs should display the panels' names. * * @since 2.5.0 * @see #setMainToolbarVisible(boolean) * @see #setWorkbenchLayout(WorkbenchPanel.Layout) * @see #setResponsePanelPosition(WorkbenchPanel.ResponsePanelPosition) * @see #setShowTabNames(boolean) * @see org.parosproxy.paros.extension.option.OptionsParamView */ public void applyViewOptions() { setMainToolbarVisible(options.getViewParam().isShowMainToolbar()); setWorkbenchLayout(WorkbenchPanel.Layout.getLayout(options.getViewParam().getDisplayOption())); WorkbenchPanel.ResponsePanelPosition position = WorkbenchPanel.ResponsePanelPosition.TABS_SIDE_BY_SIDE; try { position = WorkbenchPanel.ResponsePanelPosition.valueOf(options.getViewParam().getResponsePanelPosition()); } catch (IllegalArgumentException e) { LOGGER.warn("Failed to restore the position of response panel: ", e); } setResponsePanelPosition(position); setShowTabNames(options.getViewParam().getShowTabNames()); } public void setWorkbenchLayout(WorkbenchPanel.Layout layout) { if (layout == null) { throw new IllegalArgumentException("Parameter layout must not be null."); } if (workbenchLayout == layout) { return; } workbenchLayout = layout; switch (workbenchLayout) { case EXPAND_STATUS: getExpandStatusLayoutButton().setSelected(true); setResponsePanelPositionButtonsEnabled(true); break; case FULL: getFullLayoutButton().setSelected(true); setResponsePanelPositionButtonsEnabled(false); break; case EXPAND_SELECT: default: getExpandSelectLayoutButton().setSelected(true); setResponsePanelPositionButtonsEnabled(true); break; } getWorkbench().setWorkbenchLayout(workbenchLayout); options.getViewParam().setDisplayOption(workbenchLayout.getId()); } /** * Sets whether or not the buttons that control the response panel position should be enabled. * * @param enabled {@code true} if the buttons should be enabled, {@code false} otherwise. */ private void setResponsePanelPositionButtonsEnabled(boolean enabled) { tabsResponsePanelPositionButton.setEnabled(enabled); panelsResponsePanelPositionButton.setEnabled(enabled); aboveResponsePanelPositionButton.setEnabled(enabled); } /** * Gets the workbench layout. * * @return the workbench layout, never {@code null}. * @since 2.5.0 * @see #setWorkbenchLayout(WorkbenchPanel.Layout) */ public WorkbenchPanel.Layout getWorkbenchLayout() { return workbenchLayout; } public void setResponsePanelPosition(WorkbenchPanel.ResponsePanelPosition position) { if (position == null) { throw new IllegalArgumentException("Parameter position must not be null."); } if (responsePanelPosition == position) { return; } responsePanelPosition = position; switch (position) { case PANEL_ABOVE: aboveResponsePanelPositionButton.setSelected(true); break; case PANELS_SIDE_BY_SIDE: panelsResponsePanelPositionButton.setSelected(true); break; case TABS_SIDE_BY_SIDE: default: tabsResponsePanelPositionButton.setSelected(true); } getWorkbench().setResponsePanelPosition(responsePanelPosition); options.getViewParam().setResponsePanelPosition(responsePanelPosition.toString()); } /** * Gets the response panel position. * * @return the response panel position, never {@code null}. * @since 2.5.0 * @see #setResponsePanelPosition(WorkbenchPanel.ResponsePanelPosition) */ public WorkbenchPanel.ResponsePanelPosition getResponsePanelPosition() { return responsePanelPosition; } /** * Sets whether or not the tabs should display the name of the panels. * * @param showTabNames {@code true} if the names should be shown, {@code false} otherwise. * @since 2.5.0 */ public void setShowTabNames(boolean showTabNames) { getWorkbench().toggleTabNames(showTabNames); getShowTabIconNamesButton().setSelected(showTabNames); } /** * Sets the title of the main window. * <p> * The actual title set is the current session name, then the filename of the session (if persisted), * followed by the program name and version. * * @param session the {@code Session} from which the window title is being built * * @see Constant#PROGRAM_NAME * @see Constant#PROGRAM_VERSION * @since TODO add version */ public void setTitle(Session session) { StringBuilder strBuilder = new StringBuilder(); if (session != null) { strBuilder.append(session.getSessionName()).append(" - "); if (!session.isNewState()) { File file = new File(session.getFileName()); strBuilder.append(file.getName().replaceAll(".session\\z", "")).append(" - "); } } strBuilder.append(Constant.PROGRAM_NAME).append(' ').append(Constant.PROGRAM_VERSION); super.setTitle(strBuilder.toString()); } /** * Sets the title of the main window. * <p> * The actual title set is the given {@code title} followed by the program name and version. * * @see Constant#PROGRAM_NAME * @see Constant#PROGRAM_VERSION * @deprecated as of TODO add version, replaced by {@link #setTitle(Session)} */ @Override @Deprecated public void setTitle(String title) { StringBuilder strBuilder = new StringBuilder(); if (title != null && !title.isEmpty()) { strBuilder.append(title); strBuilder.append(" - "); } strBuilder.append(Constant.PROGRAM_NAME).append(' ').append(Constant.PROGRAM_VERSION); super.setTitle(strBuilder.toString()); } /** * Sets whether or not the main tool bar should be visible. * * @param visible {@code true} if the main tool bar should be visible, {@code false} otherwise. * @since 2.5.0 */ public void setMainToolbarVisible(boolean visible) { getMainToolbarPanel().setVisible(visible); } /** * An {@code Action} that changes the layout of the workbench panels. * * @see MainFrame#setWorkbenchLayout(WorkbenchPanel.Layout) */ private class ChangeWorkbenchLayoutAction extends AbstractAction { private static final long serialVersionUID = 8323387638733162321L; private final WorkbenchPanel.Layout layout; public ChangeWorkbenchLayoutAction(URL iconURL, WorkbenchPanel.Layout layout) { super("", DisplayUtils.getScaledIcon(new ImageIcon(iconURL))); this.layout = layout; } @Override public void actionPerformed(ActionEvent evt) { setWorkbenchLayout(layout); } } /** * An {@code Action} that changes the position of the response panel. * * @see MainFrame#setResponsePanelPosition(org.parosproxy.paros.view.WorkbenchPanel.ResponsePanelPosition) */ private class SetResponsePanelPositionAction extends AbstractAction { private static final long serialVersionUID = 756133292459364854L; private final WorkbenchPanel.ResponsePanelPosition position; public SetResponsePanelPositionAction(URL iconLocation, WorkbenchPanel.ResponsePanelPosition position) { super("", new ImageIcon(iconLocation)); this.position = position; } @Override public void actionPerformed(ActionEvent e) { setResponsePanelPosition(position); } } }
package org.phenoscape.bridge; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.apache.log4j.Logger; import org.bbop.dataadapter.DataAdapterException; import org.obd.model.CompositionalDescription; import org.obd.model.Graph; import org.obd.model.LinkStatement; import org.obd.model.Node; import org.obd.model.NodeAlias; import org.obd.model.Node.Metatype; import org.obd.query.Shard; import org.obd.query.impl.OBDSQLShard; import org.obo.dataadapter.OBOAdapter; import org.obo.dataadapter.OBOFileAdapter; import org.obo.datamodel.Dbxref; import org.obo.datamodel.IdentifiedObject; import org.obo.datamodel.OBOClass; import org.obo.datamodel.OBOSession; import org.obo.util.TermUtil; import org.purl.obo.vocab.RelationVocabulary; public class ZfinObdBridge { /** The db-host system property should contain the name of the database server. */ public static final String DB_HOST = "db-host"; /** The db-name system property should contain the name of the database. */ public static final String DB_NAME = "db-name"; /** The db-user system property should contain the database username. */ public static final String DB_USER = "db-user"; /** The db-password system property should contain the database password. */ public static final String DB_PASSWORD = "db-password"; /** The ontology-dir system property should contain the path to a folder with ontologies to be loaded. */ public static final String ONTOLOGY_DIR = "ontology-dir"; /** The phenotype-url system property should contain the URL of the ZFIN phenotypes file. */ public static final String PHENOTYPE_URL = "phenotype-url"; /** The missing-markers-url system property should contain the URL of the ZFIN missing markers file. */ public static final String MISSING_MARKERS_URL = "missing-markers-url"; /** The genotype-url system property should contain the URL of the ZFIN genotypes file. */ public static final String GENOTYPE_URL = "genotype-url"; /** The gene-name-url system property should contain the URL of the ZFIN genetic markers file. */ public static final String GENE_NAME_URL = "gene-name-url"; /** The morpholino-url system property should contain the URL of the ZFIN morpholinos file. */ public static final String MORPHOLINO_URL = "morpholino-url"; /** The pheno-environment-url system property should contain the URL of the ZFIN pheno environment file. */ public static final String PHENO_ENVIRONMENT_URL = "pheno-environment-url"; public static final String DATASET_TYPE_ID = "cdao:CharacterStateDataMatrix"; public static final String GENOTYPE_PHENOTYPE_REL_ID = "PHENOSCAPE:exhibits"; public static final String GENE_GENOTYPE_REL_ID = "PHENOSCAPE:has_allele"; public static final String PUBLICATION_TYPE_ID = "PHENOSCAPE:Publication"; public static final String HAS_PUB_REL_ID = "PHENOSCAPE:has_publication"; public static final String GENOTYPE_TYPE_ID = "SO:0001027"; public static final String GENE_TYPE_ID = "SO:0000704"; public static final String POSITED_BY_REL_ID = "posited_by"; private final String MORPHOLINO_STRING = "morpholino"; private final String WILD_TYPE_STRING = "wild type (unspecified)"; private static final RelationVocabulary relationVocabulary = new RelationVocabulary(); private Shard shard; private Graph graph; private OBOSession oboSession; private Map<String, String> zfinGeneIdToNameMap; private Map<String, String> zfinGeneIdToSymbolMap; private Map<String, String> envToMorpholinoMap; private Map<String, String> morpholinoToGeneMap; private Map<String, String> genotypeToGeneMap; /* * This map has been created to keep track of main IDs and their mapping to alternate IDs * These are stored in key=ALTERNATE-ID value=ID format */ private Map<String, String> id2AlternateIdMap; public ZfinObdBridge() throws SQLException, ClassNotFoundException, IOException { super(); this.shard = this.initializeShard(); this.graph = new Graph(); this.setOboSession(this.loadOBOSession()); this.id2AlternateIdMap = createAltIdMappings(this.getOboSession()); this.zfinGeneIdToNameMap = new HashMap<String, String>(); this.zfinGeneIdToSymbolMap = new HashMap<String, String>(); this.envToMorpholinoMap = new HashMap<String, String>(); this.morpholinoToGeneMap = new HashMap<String, String>(); this.genotypeToGeneMap = new HashMap<String, String>(); this.createZfinNameDirectory(); this.mapEnvToMorpholino(); this.mapMorpholinoToGene(); this.mapGenotypeToGene(); this.mapGenotypeToGeneViaMissingMarkers(); } public OBOSession getOboSession() { return oboSession; } public void setOboSession(OBOSession oboSession) { this.oboSession = oboSession; } private OBOSession loadOBOSession() { final OBOFileAdapter fileAdapter = new OBOFileAdapter(); OBOFileAdapter.OBOAdapterConfiguration config = new OBOFileAdapter.OBOAdapterConfiguration(); config.setReadPaths(this.getOntologyPaths()); config.setBasicSave(false); config.setAllowDangling(true); config.setFollowImports(false); try { return fileAdapter.doOperation(OBOAdapter.READ_ONTOLOGY, config, null); } catch (DataAdapterException e) { log().fatal("Failed to load ontologies", e); return null; } } private List<String> getOntologyPaths() { List<String> paths = new ArrayList<String>(); File ontCache = new File(System.getProperty(ONTOLOGY_DIR)); for (File f : ontCache.listFiles()) { paths.add(f.getAbsolutePath()); log().trace(paths.toString()); } return paths; } private Shard initializeShard() throws SQLException, ClassNotFoundException { OBDSQLShard obdsql = new OBDSQLShard(); obdsql.connect("jdbc:postgresql://" + System.getProperty(DB_HOST) + "/" + System.getProperty(DB_NAME), System.getProperty(DB_USER), System.getProperty(DB_PASSWORD)); return obdsql; } private Logger log() { return Logger.getLogger(this.getClass()); } private void createZfinNameDirectory() throws IOException{ URL geneticMarkersURL = new URL(System.getProperty(GENE_NAME_URL)); BufferedReader reader = new BufferedReader(new InputStreamReader(geneticMarkersURL.openStream())); String line, zfinId, zfinName, zfinAlias; while((line = reader.readLine()) != null){ if(line.startsWith("ZDB-GENE")){ String[] lineComps = line.split("\\t"); zfinId = normalizetoZfin(lineComps[0]); zfinAlias = lineComps[1]; zfinName = lineComps[2]; this.zfinGeneIdToNameMap.put(zfinId, zfinName); this.zfinGeneIdToSymbolMap.put(zfinId, zfinAlias); } } reader.close(); } private Map<String, String> createAltIdMappings(OBOSession session) { Map<String, String> altIDMappings = new HashMap<String, String>(); log().trace("Called alt_id search"); final Collection<IdentifiedObject> terms = session.getObjects(); for (IdentifiedObject object : terms) { if (object instanceof OBOClass) { final OBOClass term = (OBOClass)object; if (term.getSecondaryIDs() != null && term.getSecondaryIDs().size() > 0) { for(String altID : term.getSecondaryIDs()) altIDMappings.put(altID, term.getID()); } } } return altIDMappings; } private void mapEnvToMorpholino() throws IOException{ String line, environmentId, morpholinoId; URL phenoEnvironmentURL = new URL(System.getProperty(PHENO_ENVIRONMENT_URL)); BufferedReader reader = new BufferedReader(new InputStreamReader(phenoEnvironmentURL.openStream())); while((line = reader.readLine()) != null){ String[] lComps = line.split("\\t"); if(lComps[1].equals(MORPHOLINO_STRING)){ environmentId = normalizetoZfin(lComps[0]); morpholinoId = lComps[2]; this.envToMorpholinoMap.put(environmentId, morpholinoId); } } reader.close(); } private void mapMorpholinoToGene() throws IOException{ String line, geneId, morpholinoId; URL morpholinoURL = new URL(System.getProperty(MORPHOLINO_URL)); BufferedReader reader = new BufferedReader(new InputStreamReader(morpholinoURL.openStream())); while((line = reader.readLine()) != null){ String[] lComps = line.split("\\t"); geneId = this.normalizetoZfin(lComps[0]); morpholinoId = lComps[2]; this.morpholinoToGeneMap.put(morpholinoId, geneId); } reader.close(); } /** * Finds the equivalent TAO term for the given ZFA term * @param entityId * @return */ private String getEquivalentTAOID(String entityId) { for(OBOClass oboClass : TermUtil.getTerms(oboSession)){ if(oboClass.getID().equals(entityId)){ for(Dbxref dbx : oboClass.getDbxrefs()){ if(dbx.getDatabase().toString().equals("TAO")){ return dbx.getDatabase().toString() + ":" + dbx.getDatabaseID().toString(); } } } } return "Not found"; } private CompositionalDescription postComposeTerms(String[] comps){ String entityId, qualityId, towardsId, ab; Set<LinkStatement> diffs = new HashSet<LinkStatement>(); entityId = comps[4]; qualityId = comps[5]; towardsId = comps[6]; ab = comps[7]; if(entityId != null){ entityId = replaceZfinEntityWithTaoEntity(entityId); entityId = replaceAlternateId(entityId); LinkStatement diffFromInheresIn = new LinkStatement(); diffFromInheresIn.setRelationId(relationVocabulary.inheres_in()); diffFromInheresIn.setTargetId(entityId); diffs.add(diffFromInheresIn); } if(towardsId != null && towardsId.trim().length() > 0 && towardsId.matches("[A-Z]+:[0-9]+")){ towardsId = replaceZfinEntityWithTaoEntity(towardsId); towardsId = replaceAlternateId(towardsId); LinkStatement diffFromTowards = new LinkStatement(); diffFromTowards.setRelationId(relationVocabulary.towards()); diffFromTowards.setTargetId(towardsId); diffs.add(diffFromTowards); } qualityId = replaceAlternateId(qualityId); if(ab != null){ for (String qual : ab.split("/")) { if(qualityId.equals("PATO:0000001")){ String patoId = replaceDefaultQualityIdWithPatoId(qual); qualityId = patoId; } } } CompositionalDescription desc = new CompositionalDescription(qualityId, diffs); return desc; } private String replaceZfinEntityWithTaoEntity(String zfinEntity){ String taoEntity = getEquivalentTAOID(zfinEntity); String target = taoEntity.equals("Not found")? zfinEntity : taoEntity; return target; } private String replaceAlternateId(String alternateId){ String id = alternateId; if(id2AlternateIdMap.containsKey(alternateId)){ log().info("Replacing alternate ID: " + alternateId); id = id2AlternateIdMap.get(alternateId); } return id; } private String replaceDefaultQualityIdWithPatoId(String qual){ String patoId; if (qual.equals("normal")) patoId = "PATO:0000461"; else if (qual.equals("absent")) patoId = "PATO:0000462"; else if (qual.equals("present")) patoId = "PATO:0000467"; else patoId = "PATO:0000460"; // abnormal return patoId; } private void mapGenotypeToGene() throws IOException{ String lineFromGenotypeToPhenotypeFile; String genotypeId, geneId = null; URL genotypeURL = new URL(System.getProperty(GENOTYPE_URL)); BufferedReader reader = new BufferedReader(new InputStreamReader(genotypeURL.openStream())); while((lineFromGenotypeToPhenotypeFile = reader.readLine()) != null){ String[] comps = lineFromGenotypeToPhenotypeFile.split("\\t"); genotypeId = normalizetoZfin(comps[0]); if(comps.length > 9){ geneId = normalizetoZfin(comps[9]); this.genotypeToGeneMap.put(genotypeId, geneId); } } reader.close(); } private void mapGenotypeToGeneViaMissingMarkers() throws IOException{ String lineFromFile; String genotypeId, geneId; URL missingMarkersURL = new URL(System.getProperty(MISSING_MARKERS_URL)); BufferedReader reader = new BufferedReader(new InputStreamReader(missingMarkersURL.openStream())); while((lineFromFile = reader.readLine()) != null){ String[] comps = lineFromFile.split("\\t"); genotypeId = normalizetoZfin(comps[0]); if(comps[4] != null && comps[4].trim().length() > 0){ geneId = normalizetoZfin(comps[4]); this.genotypeToGeneMap.put(genotypeId, geneId); } } reader.close(); } public void loadZfinData() throws MalformedURLException, IOException { String phenoFileLine; String genotypeId, genotype, pub, qualityId, environmentId, geneId = null; LinkStatement genotypeToPhenotypeLink; URL phenotypeURL = new URL(System.getProperty(PHENOTYPE_URL)); BufferedReader br1 = new BufferedReader(new InputStreamReader(phenotypeURL.openStream())); while ((phenoFileLine = br1.readLine()) != null) { String[] pComps = phenoFileLine.split("\\t"); genotypeId = pComps[0]; genotype = pComps[1]; qualityId = pComps[5]; pub = pComps[8]; environmentId = pComps[9]; if(genotype.equals(this.WILD_TYPE_STRING)){ String morpholinoId = this.envToMorpholinoMap.get(environmentId); if(morpholinoId != null) geneId = this.morpholinoToGeneMap.get(morpholinoId); } else{ geneId = this.genotypeToGeneMap.get(genotypeId); } if(geneId != null){ CompositionalDescription cd = this.postComposeTerms(pComps); String phenoId = cd.generateId(); cd.setId(phenoId); graph.addStatements(cd); Node geneNode = createInstanceNode(geneId, GENE_TYPE_ID); String geneName = this.zfinGeneIdToNameMap.get(geneId); String geneSymbol = this.zfinGeneIdToSymbolMap.get(geneId); if(geneName != null){ geneNode.setLabel(geneName); NodeAlias na = new NodeAlias(); na.setNodeId(geneId); na.setTargetId(geneSymbol); graph.addStatement(na); } else{ geneNode.setLabel(geneSymbol); } graph.addNode(geneNode); Node genotypeNode = createInstanceNode(genotypeId, GENOTYPE_TYPE_ID); genotypeNode.setLabel(genotype); graph.addNode(genotypeNode); this.createLinkStatementAndAddToGraph(geneId, GENE_GENOTYPE_REL_ID, genotypeId); genotypeToPhenotypeLink = this.createLinkStatementAndAddToGraph(genotypeId, GENOTYPE_PHENOTYPE_REL_ID, phenoId); if (!pub.equals("")) { Node publicationNode = createInstanceNode(pub, PUBLICATION_TYPE_ID); graph.addNode(publicationNode); String dsId = UUID.randomUUID().toString(); Node dsNode = createInstanceNode(dsId, DATASET_TYPE_ID); graph.addNode(dsNode); LinkStatement dsLink = new LinkStatement(); dsLink.setRelationId(POSITED_BY_REL_ID); dsLink.setTargetId(dsId); genotypeToPhenotypeLink.addSubStatement(dsLink); this.createLinkStatementAndAddToGraph(dsId, HAS_PUB_REL_ID, pub); } this.createLinkStatementAndAddToGraph(phenoId, relationVocabulary.is_a(), qualityId); } } this.shard.putGraph(graph); } private String normalizetoZfin(String string) { return "ZFIN:" + string; } protected Node createInstanceNode(String id, String typeId) { Node n = new Node(id); n.setMetatype(Metatype.CLASS); n.addStatement(new LinkStatement(id, relationVocabulary.instance_of(), typeId)); return n; } private LinkStatement createLinkStatementAndAddToGraph(String subject, String predicate, String object){ LinkStatement ls = new LinkStatement(); ls.setNodeId(subject); ls.setRelationId(predicate); ls.setTargetId(object); graph.addStatement(ls); return ls; } public static void main(String[] args) throws SQLException, ClassNotFoundException, MalformedURLException, IOException { ZfinObdBridge zob = new ZfinObdBridge(); zob.loadZfinData(); } }
package org.torproject.onionoo; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Iterator; import java.util.Locale; import java.util.SortedMap; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeMap; import java.util.TreeSet; import org.torproject.descriptor.BridgeNetworkStatus; import org.torproject.descriptor.Descriptor; import org.torproject.descriptor.DescriptorFile; import org.torproject.descriptor.DescriptorReader; import org.torproject.descriptor.DescriptorSourceFactory; import org.torproject.descriptor.NetworkStatusEntry; import org.torproject.descriptor.RelayNetworkStatusConsensus; import com.maxmind.geoip.Location; import com.maxmind.geoip.LookupService; /* Store relays and bridges that have been running in the past seven * days. */ public class CurrentNodes { private File internalRelaySearchDataFile = new File("status/summary.csv"); /* Read the internal relay search data file from disk. */ public void readRelaySearchDataFile() { if (this.internalRelaySearchDataFile.exists() && !this.internalRelaySearchDataFile.isDirectory()) { try { BufferedReader br = new BufferedReader(new FileReader( this.internalRelaySearchDataFile)); String line; SimpleDateFormat dateTimeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); while ((line = br.readLine()) != null) { if (line.startsWith("r ")) { String[] parts = line.split(" "); if (parts.length < 9) { System.err.println("Line '" + line + "' in '" + this.internalRelaySearchDataFile.getAbsolutePath() + " is invalid. Exiting."); System.exit(1); } String nickname = parts[1]; String fingerprint = parts[2]; String address = parts[3]; long validAfterMillis = dateTimeFormat.parse(parts[4] + " " + parts[5]).getTime(); int orPort = Integer.parseInt(parts[6]); int dirPort = Integer.parseInt(parts[7]); SortedSet<String> relayFlags = new TreeSet<String>( Arrays.asList(parts[8].split(","))); this.addRelay(nickname, fingerprint, address, validAfterMillis, orPort, dirPort, relayFlags); } else if (line.startsWith("b ")) { String[] parts = line.split(" "); if (parts.length < 9) { System.err.println("Line '" + line + "' in '" + this.internalRelaySearchDataFile.getAbsolutePath() + " is invalid. Exiting."); System.exit(1); } String hashedFingerprint = parts[2]; String address = parts[3]; long publishedMillis = dateTimeFormat.parse(parts[4] + " " + parts[5]).getTime(); int orPort = Integer.parseInt(parts[6]); int dirPort = Integer.parseInt(parts[7]); SortedSet<String> relayFlags = new TreeSet<String>( Arrays.asList(parts[8].split(","))); this.addBridge(hashedFingerprint, address, publishedMillis, orPort, dirPort, relayFlags); } } br.close(); } catch (IOException e) { System.err.println("Could not read " + this.internalRelaySearchDataFile.getAbsolutePath() + ". Exiting."); e.printStackTrace(); System.exit(1); } catch (ParseException e) { System.err.println("Could not read " + this.internalRelaySearchDataFile.getAbsolutePath() + ". Exiting."); e.printStackTrace(); System.exit(1); } } } /* Write the internal relay search data file to disk. */ public void writeRelaySearchDataFile() { try { this.internalRelaySearchDataFile.getParentFile().mkdirs(); BufferedWriter bw = new BufferedWriter(new FileWriter( this.internalRelaySearchDataFile)); SimpleDateFormat dateTimeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); for (Node entry : this.currentRelays.values()) { String nickname = entry.getNickname(); String fingerprint = entry.getFingerprint(); String address = entry.getAddress(); String validAfter = dateTimeFormat.format( entry.getLastSeenMillis()); String orPort = String.valueOf(entry.getOrPort()); String dirPort = String.valueOf(entry.getDirPort()); StringBuilder sb = new StringBuilder(); for (String relayFlag : entry.getRelayFlags()) { sb.append("," + relayFlag); } String relayFlags = sb.toString().substring(1); bw.write("r " + nickname + " " + fingerprint + " " + address + " " + validAfter + " " + orPort + " " + dirPort + " " + relayFlags + "\n"); } for (Node entry : this.currentBridges.values()) { String fingerprint = entry.getFingerprint(); String published = dateTimeFormat.format( entry.getLastSeenMillis()); String address = String.valueOf(entry.getAddress()); String orPort = String.valueOf(entry.getOrPort()); String dirPort = String.valueOf(entry.getDirPort()); StringBuilder sb = new StringBuilder(); for (String relayFlag : entry.getRelayFlags()) { sb.append("," + relayFlag); } String relayFlags = sb.toString().substring(1); bw.write("b Unnamed " + fingerprint + " " + address + " " + published + " " + orPort + " " + dirPort + " " + relayFlags + "\n"); } bw.close(); } catch (IOException e) { System.err.println("Could not write '" + this.internalRelaySearchDataFile.getAbsolutePath() + "' to disk. Exiting."); e.printStackTrace(); System.exit(1); } } private long lastValidAfterMillis = 0L; private long lastPublishedMillis = 0L; private long cutoff = System.currentTimeMillis() - 7L * 24L * 60L * 60L * 1000L; public void readRelayNetworkConsensuses() { DescriptorReader reader = DescriptorSourceFactory.createDescriptorReader(); reader.addDirectory(new File("in/relay-descriptors/consensuses")); reader.setExcludeFiles(new File("status/relay-consensus-history")); Iterator<DescriptorFile> descriptorFiles = reader.readDescriptors(); while (descriptorFiles.hasNext()) { DescriptorFile descriptorFile = descriptorFiles.next(); if (descriptorFile.getDescriptors() != null) { for (Descriptor descriptor : descriptorFile.getDescriptors()) { if (descriptor instanceof RelayNetworkStatusConsensus) { updateRelayNetworkStatusConsensus((RelayNetworkStatusConsensus) descriptor); } } } } } public void setRelayRunningBits() { if (this.lastValidAfterMillis > 0L) { for (Node entry : this.currentRelays.values()) { entry.setRunning(entry.getLastSeenMillis() == this.lastValidAfterMillis); } } } private void updateRelayNetworkStatusConsensus( RelayNetworkStatusConsensus consensus) { long validAfterMillis = consensus.getValidAfterMillis(); for (NetworkStatusEntry entry : consensus.getStatusEntries().values()) { String nickname = entry.getNickname(); String fingerprint = entry.getFingerprint(); String address = entry.getAddress(); int orPort = entry.getOrPort(); int dirPort = entry.getDirPort(); SortedSet<String> relayFlags = entry.getFlags(); this.addRelay(nickname, fingerprint, address, validAfterMillis, orPort, dirPort, relayFlags); } } public void addRelay(String nickname, String fingerprint, String address, long validAfterMillis, int orPort, int dirPort, SortedSet<String> relayFlags) { if (validAfterMillis >= cutoff && (!this.currentRelays.containsKey(fingerprint) || this.currentRelays.get(fingerprint).getLastSeenMillis() < validAfterMillis)) { Node entry = new Node(nickname, fingerprint, address, validAfterMillis, orPort, dirPort, relayFlags); this.currentRelays.put(fingerprint, entry); if (validAfterMillis > this.lastValidAfterMillis) { this.lastValidAfterMillis = validAfterMillis; } } } public void lookUpCountries() { File geoLiteCityDatFile = new File("GeoLiteCity.dat"); if (!geoLiteCityDatFile.exists()) { System.err.println("No GeoLiteCity.dat file in /."); return; } try { LookupService ls = new LookupService(geoLiteCityDatFile, LookupService.GEOIP_MEMORY_CACHE); for (Node relay : currentRelays.values()) { Location location = ls.getLocation(relay.getAddress()); if (location != null) { relay.setLatitude(String.format(Locale.US, "%.6f", location.latitude)); relay.setLongitude(String.format(Locale.US, "%.6f", location.longitude)); relay.setCountryCode(location.countryCode); } } ls.close(); } catch (IOException e) { System.err.println("Could not look up countries for relays."); } } public void readBridgeNetworkStatuses() { DescriptorReader reader = DescriptorSourceFactory.createDescriptorReader(); reader.addDirectory(new File("in/bridge-descriptors/statuses")); reader.setExcludeFiles(new File("status/bridge-status-history")); Iterator<DescriptorFile> descriptorFiles = reader.readDescriptors(); while (descriptorFiles.hasNext()) { DescriptorFile descriptorFile = descriptorFiles.next(); if (descriptorFile.getDescriptors() != null) { for (Descriptor descriptor : descriptorFile.getDescriptors()) { if (descriptor instanceof BridgeNetworkStatus) { updateBridgeNetworkStatus((BridgeNetworkStatus) descriptor); } } } } } public void setBridgeRunningBits() { if (this.lastPublishedMillis > 0L) { for (Node entry : this.currentBridges.values()) { entry.setRunning(entry.getLastSeenMillis() == this.lastPublishedMillis); } } } private void updateBridgeNetworkStatus(BridgeNetworkStatus status) { long publishedMillis = status.getPublishedMillis(); for (NetworkStatusEntry entry : status.getStatusEntries().values()) { String fingerprint = entry.getFingerprint(); String address = entry.getAddress(); int orPort = entry.getOrPort(); int dirPort = entry.getDirPort(); SortedSet<String> relayFlags = entry.getFlags(); this.addBridge(fingerprint, address, publishedMillis, orPort, dirPort, relayFlags); } } public void addBridge(String fingerprint, String address, long publishedMillis, int orPort, int dirPort, SortedSet<String> relayFlags) { if (publishedMillis >= cutoff && (!this.currentBridges.containsKey(fingerprint) || this.currentBridges.get(fingerprint).getLastSeenMillis() < publishedMillis)) { Node entry = new Node("Unnamed", fingerprint, address, publishedMillis, orPort, dirPort, relayFlags); this.currentBridges.put(fingerprint, entry); if (publishedMillis > this.lastPublishedMillis) { this.lastPublishedMillis = publishedMillis; } } } private SortedMap<String, Node> currentRelays = new TreeMap<String, Node>(); public SortedMap<String, Node> getCurrentRelays() { return new TreeMap<String, Node>(this.currentRelays); } private SortedMap<String, Node> currentBridges = new TreeMap<String, Node>(); public SortedMap<String, Node> getCurrentBridges() { return new TreeMap<String, Node>(this.currentBridges); } public long getLastValidAfterMillis() { return this.lastValidAfterMillis; } public long getLastPublishedMillis() { return this.lastPublishedMillis; } }
package org.uct.cs.simplify; import org.apache.commons.cli.*; import org.json.JSONArray; import org.json.JSONObject; import org.uct.cs.simplify.util.OrderedArrayList; import org.uct.cs.simplify.util.Outputter; import org.uct.cs.simplify.util.ProgressBar; import org.uct.cs.simplify.util.Useful; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.*; public class OutputValidator { public static final int BYTES_PER_VERTEX = 12; public static final int BYTES_PER_FACE = 12; public static void run(File file) throws IOException { try (BufferedInputStream istream = new BufferedInputStream(new FileInputStream(file))) { int streamLength = istream.available(); int headerLength = Useful.readIntLE(istream); String jsonHeader = Useful.readString(istream, headerLength); Outputter.info2f("header length: %s%n", headerLength); JSONObject o = new JSONObject(jsonHeader); boolean hasVertexColour = o.getBoolean("vertex_colour"); Outputter.info2f("vertex_colour: %b%n", hasVertexColour); JSONArray nodesJ = o.getJSONArray("nodes"); Outputter.info2f("number of nodes: %d%n", nodesJ.length()); List<SomeNode> nodes = new ArrayList<>(); for (int i = 0; i < nodesJ.length(); i++) { nodes.add(new SomeNode(nodesJ.getJSONObject(i))); } Collections.sort(nodes); long currentPosition = 0; try (ProgressBar pb = new ProgressBar("Checking Nodes", nodes.size())) { for (SomeNode node : nodes) { check(currentPosition, node.blockOffset); long l = node.numVertices * BYTES_PER_VERTEX + ((hasVertexColour) ? node.numVertices * 3 : 0) + node.numFaces * BYTES_PER_FACE; check(node.blockLength, l); for (int i = 0; i < node.numVertices; i++) { float x = Useful.readFloatLE(istream); float y = Useful.readFloatLE(istream); float z = Useful.readFloatLE(istream); checkInRange(node.min_x - 1, x, node.max_x + 1); checkInRange(node.min_y - 1, y, node.max_y + 1); checkInRange(node.min_z - 1, z, node.max_z + 1); } if (hasVertexColour) { for (int i = 0; i < node.numVertices; i++) { byte r = (byte) istream.read(); byte g = (byte) istream.read(); byte b = (byte) istream.read(); check(r, g); check(g, b); } } for (int i = 0; i < node.numFaces; i++) { int f = Useful.readIntLE(istream); int g = Useful.readIntLE(istream); int h = Useful.readIntLE(istream); checkLt(f, node.numVertices); checkLt(g, node.numVertices); checkLt(h, node.numVertices); } currentPosition += node.blockLength; pb.tick(); } } check(istream.available(), 0); check(streamLength, currentPosition + 4 + jsonHeader.length()); Outputter.info3ln("All checks passed successfully"); HashMap<Integer, NumberSummary> summaries = new HashMap<>(); for (SomeNode node : nodes) { if (summaries.containsKey(node.depth)) { summaries.get(node.depth).add(node.numFaces); } else { summaries.put(node.depth, new NumberSummary(10, node.numFaces)); } } Outputter.info1ln("Face Summaries per depth:"); for (Map.Entry<Integer, NumberSummary> entry : summaries.entrySet()) { Outputter.info1f("%2d | nodes: %4d | min: %8.0f | max: %8.0f | median: %11.2f | mean: %11.2f | %.0f %n", entry.getKey(), entry.getValue().count, entry.getValue().min, entry.getValue().max, entry.getValue().mean, entry.getValue().p50, entry.getValue().mean, entry.getValue().total ); } } } public static void main(String[] args) throws IOException { CommandLine cmd = getCommandLine(args); run(new File(cmd.getOptionValue("input"))); } private static void check(byte a, byte b) { if (a != b) throw new RuntimeException(String.format("%s != %s", a, b)); } private static void check(long a, long b) { if (a != b) throw new RuntimeException(String.format("%s != %s", a, b)); } private static void checkLt(long a, long b) { if (a >= b) throw new RuntimeException(String.format("%s >= %s", a, b)); } private static void checkInRange(double a, double v, double b) { if (v > b || v < a) throw new RuntimeException(String.format("%s is out of range %s..%s", v, a, b)); } private static CommandLine getCommandLine(String[] args) { CommandLineParser clp = new BasicParser(); Options options = new Options(); Option inputFile = new Option("i", "input", true, "path to first PLY file"); inputFile.setRequired(true); options.addOption(inputFile); CommandLine cmd; try { cmd = clp.parse(options, args); return cmd; } catch (ParseException e) { Outputter.errorf("%s : %s%n%n", e.getClass().getName(), e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("--input <path>", options); System.exit(1); return null; } } private static class NumberSummary { private final OrderedArrayList<Double> data; private double min; private double p50; private double max; private double mean; private int count; private double total; public NumberSummary(int initialCapacity) { data = new OrderedArrayList<>(initialCapacity); } public NumberSummary(int initialCapacity, double initialvalue) { this(initialCapacity); add(initialvalue); } public void add(double v) { data.put(v); count++; min = data.get(0); max = data.get(count - 1); total += v; mean = total / count; if (count % 2 == 1) { int middle = (count - 1) / 2; p50 = data.get(middle); } else { int middle = count / 2; p50 = (data.get(middle - 1) + data.get(middle)) / 2; } } } private static class SomeNode implements Comparable<SomeNode> { public final int id; public final int parentId; public final long numFaces; public final long numVertices; public final long blockLength; public final long blockOffset; public final double min_x; public final double max_x; public final double min_y; public final double max_y; public final double min_z; public final double max_z; public final int depth; public SomeNode(JSONObject o) { this.id = o.getInt("id"); this.parentId = o.isNull("parent_id") ? -1 : o.getInt("parent_id"); this.numFaces = o.getLong("num_faces"); this.numVertices = o.getLong("num_vertices"); this.blockLength = o.getLong("block_length"); this.blockOffset = o.getLong("block_offset"); this.min_x = o.getDouble("min_x"); this.max_x = o.getDouble("max_x"); this.min_y = o.getDouble("min_y"); this.max_y = o.getDouble("max_y"); this.min_z = o.getDouble("min_z"); this.max_z = o.getDouble("max_z"); this.depth = o.getInt("depth"); } @Override public int compareTo(SomeNode o) { return Long.compare(this.blockOffset, o.blockOffset); } } }
package org.usfirst.frc.team2503.r2015; import java.net.MalformedURLException; import java.net.URI; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; public class Main { public static void main(String[] args) { URI uri = new URI("ws://localhost:5080/"); WebSocketClient wsc = new WebSocketClient(uri); } }
package org.vaadin.applet; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.vaadin.applet.client.ui.VAppletIntegration; import com.vaadin.Application; import com.vaadin.service.ApplicationContext; import com.vaadin.terminal.PaintException; import com.vaadin.terminal.PaintTarget; import com.vaadin.terminal.gwt.server.PortletApplicationContext; import com.vaadin.terminal.gwt.server.WebApplicationContext; import com.vaadin.ui.AbstractComponent; /** * Server side component for the VAppletIntegration widget. */ @com.vaadin.ui.ClientWidget(org.vaadin.applet.client.ui.VAppletIntegration.class) public class AppletIntegration extends AbstractComponent { private static final long serialVersionUID = 6061722679712017720L; private String appletClass = null; private String codebase; private String name; private List<String> appletArchives = null; private Map<String, String> appletParams = null; private String command = null; private String[] commandParams = null; @Override public void paintContent(PaintTarget target) throws PaintException { super.paintContent(target); // Applet class if (appletClass == null) { // Do not paint anything of class is missing return; } target.addAttribute(VAppletIntegration.ATTR_APPLET_CLASS, appletClass); // Applet HTTP Session id String sid = getHttpSessionId(); if (sid != null) { target.addAttribute(VAppletIntegration.ATTR_APPLET_SESSION, sid); } // Applet archives if (appletArchives != null) { target.addAttribute(VAppletIntegration.ATTR_APPLET_ARCHIVES, appletArchives.toArray(new String[appletArchives.size()])); } // Applet codebase if (codebase != null) { target.addAttribute(VAppletIntegration.ATTR_APPLET_CODEBASE, codebase); } // Applet name if (name != null) { target.addAttribute(VAppletIntegration.ATTR_APPLET_NAME, name); } // Applet parameters if (appletParams != null) { target.addAttribute(VAppletIntegration.ATTR_APPLET_PARAM_NAMES, appletParams); } // Commands if (command != null) { target.addAttribute(VAppletIntegration.ATTR_CMD, command); command = null; } if (commandParams != null) { target.addAttribute(VAppletIntegration.ATTR_CMD_PARAMS, commandParams); commandParams = null; } } /** * Read the HTTP session id. * * This method cannot be called if this component has not been attached to * the application. * * @return */ protected String getHttpSessionId() { Application app = getApplication(); if (app != null) { ApplicationContext ctx = app.getContext(); if (ctx instanceof WebApplicationContext) { return ((WebApplicationContext)ctx).getHttpSession().getId(); } else if (ctx instanceof PortletApplicationContext) { return ((PortletApplicationContext)ctx).getHttpSession().getId(); } } return null; } /** * Execute command in applet. * * @param command */ public void executeCommand(String command) { this.command = command; commandParams = null; requestRepaint(); } /** * Execute command with parameter in applet. * * @param command * @param params */ public void executeCommand(String command, String[] params) { this.command = command; commandParams = params; requestRepaint(); } /** * Set the fully qualified class name of the applet. * * This method is protected so that overriding classes can publish it if * needed. * * @param appletClass */ protected void setAppletClass(String appletClass) { this.appletClass = appletClass; } /** * Get the fully qualified class name of the applet. * * This method is protected so that overriding classes can publish it if * needed. * * @param appletClass */ protected String getAppletClass() { return appletClass; } /** * Set list of archives needed to run the applet. * * This method is protected so that overriding classes can publish it if * needed. * * @param appletClass */ protected void setAppletArchives(List<String> appletArchives) { this.appletArchives = appletArchives; } /** * Get list of archives needed to run the applet. * * This method is protected so that overriding classes can publish it if * needed. * * @param appletClass */ protected List<String> getAppletArchives() { return appletArchives; } /** * Get an applet paramter. These are name value pairs passed to the applet * element as PARAM& elements. * * This method is protected so that overriding classes can publish it if * needed. * */ protected String getAppletParams(String paramName) { if (appletParams == null) { return null; } return appletParams.get(paramName); } /** * Set an applet paramter. These are name value pairs passed to the applet * element as PARAM elements and should therefore be applied before first * the applet integration. * * This method is protected so that overriding classes can publish it if * needed. * */ protected void setAppletParams(String paramName, String paramValue) { if (appletParams == null) { appletParams = new HashMap<String, String>(); } appletParams.put(paramName, paramValue); } /** * Get map (name-value pairs) of parameter passed to the applet. * * This method is protected so that overriding classes can publish it if * needed. * * @param appletClass */ protected Map<String, String> getAppletParams() { return Collections.unmodifiableMap(appletParams); } /** * Set the codebase attribute for the applet. * * By default the codebase points to GWT modulepath, but this can be * overrided by setting it explicitly. * * @param codebase */ public void setCodebase(String codebase) { this.codebase = codebase; } /** * Set the codebase attribute for the applet. * * By default the codebase points to GWT modulepath, but this can be * overrided by setting it explicitly. * * @see #setCodebase(String) * @return codebase */ public String getCodebase() { return codebase; } /** * Set the name attribute for the applet. * * By default the is the same as the autogenerated id, but this can be * overridden by setting this explicitly. * * @param name */ public void setName(String name) { this.name = name; } /** * Get the name attribute for the applet. * * By default the is the same as the autogenerated id, but this can be * overridden by setting this explicitly. * * @see #setName(String) * @return name */ public String getName() { return name; } }
/* * This samples uses the native asynchronous request processing protocol * to post requests to the VoltDB server, thus leveraging to the maximum * VoltDB's ability to run requests in parallel on multiple database * partitions, and multiple servers. * * While asynchronous processing is (marginally) more convoluted to work * with and not adapted to all workloads, it is the preferred interaction * model to VoltDB as it guarantees blazing performance. * * Because there is a risk of 'firehosing' a database cluster (if the * cluster is too slow (slow or too few CPUs), this sample performs * self-tuning to target a specific latency (10ms by default). * This tuning process, as demonstrated here, is important and should be * part of your pre-launch evalution so you can adequately provision your * VoltDB cluster with the number of servers required for your needs. */ package genqa; import java.io.File; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLongArray; import org.voltcore.logging.VoltLogger; import org.voltdb.VoltDB; import org.voltdb.VoltTable; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.ClientResponseWithPartitionKey; import org.voltdb.ClientResponseImpl; import org.voltdb.client.ClientStats; import org.voltdb.client.ClientStatsContext; import org.voltdb.client.ProcedureCallback; import org.voltdb.client.ProcCallException; import org.voltdb.client.exampleutils.AppHelper; public class AsyncExportClient { static VoltLogger log = new VoltLogger("ExportClient"); // Operations matched with operations defined in ExportTupleStream::STREAM_ROW_TYPE private static enum OperationType { INSERT(0), DELETE(1), UPDATE(2); final int op; OperationType(int type) { this.op = type; } public int get() { return op; } } static class ExportCallback implements ProcedureCallback { private final OperationType m_op; private final AtomicLongArray m_transactionCounts; private final AtomicLongArray m_committedCounts; private final AtomicLong m_failedCounts; public ExportCallback(OperationType op, AtomicLongArray trancationCounts, AtomicLongArray committedCounts, AtomicLong failedCounts) { m_op = op; m_transactionCounts = trancationCounts; m_committedCounts = committedCounts; m_failedCounts = failedCounts; } @Override public void clientCallback(ClientResponse clientResponse) { if (clientResponse.getStatus() == ClientResponse.SUCCESS) { VoltTable v = clientResponse.getResults()[0]; // Increase the count only when the sql statement affects rows. // DELETE/UPDATE may not affect any rows if INSERT with the same row id fails. // See proc TableExport if (m_op == OperationType.INSERT || v.getRowCount() > 0) { m_committedCounts.incrementAndGet(m_op.get()); } } else { log.info("Transaction failed: " + ((ClientResponseImpl)clientResponse).toJSONString()); m_failedCounts.incrementAndGet(); } m_transactionCounts.incrementAndGet(m_op.get()); } } // Connection configuration private final static class ConnectionConfig { final long displayInterval; final long duration; final String servers; final int port; final int poolSize; final int rateLimit; final String [] parsedServers; final String procedure; final int exportTimeout; final boolean migrateWithTTL; final boolean usetableexport; final boolean migrateWithoutTTL; final long migrateNoTTLInterval; ConnectionConfig( AppHelper apph) { displayInterval = apph.longValue("displayinterval"); duration = apph.longValue("duration"); servers = apph.stringValue("servers"); port = apph.intValue("port"); poolSize = apph.intValue("poolsize"); rateLimit = apph.intValue("ratelimit"); procedure = apph.stringValue("procedure"); parsedServers = servers.split(","); exportTimeout = apph.intValue("timeout"); migrateWithTTL = apph.booleanValue("migrate-ttl"); usetableexport = apph.booleanValue("usetableexport"); migrateWithoutTTL = apph.booleanValue("migrate-nottl"); migrateNoTTLInterval = apph.longValue("nottl-interval"); } } // Connection Configuration private static ConnectionConfig config; private static String[] TABLES = { "EXPORT_PARTITIONED_TABLE_JDBC", "EXPORT_REPLICATED_TABLE_JDBC", "EXPORT_PARTITIONED_TABLE_KAFKA", "EXPORT_REPLICATED_TABLE_KAFKA"}; static { VoltDB.setDefaultTimezone(); } // Application entry point public static void main(String[] args) { VoltLogger log = new VoltLogger("ExportClient.main"); Client clientRef = null; long export_table_expected = 0; try { // Use the AppHelper utility class to retrieve command line application parameters // Define parameters and pull from command line AppHelper apph = new AppHelper(AsyncBenchmark.class.getCanonicalName()) .add("displayinterval", "display_interval_in_seconds", "Interval for performance feedback, in seconds.", 10) .add("duration", "run_duration_in_seconds", "Benchmark duration, in seconds.", 120) .add("servers", "comma_separated_server_list", "List of VoltDB servers to connect to.", "localhost") .add("port", "port_number", "Client port to connect to on cluster nodes.", 21212) .add("poolsize", "pool_size", "Size of the record pool to operate on - larger sizes will cause a higher insert/update-delete rate.", 100000) .add("procedure", "procedure_name", "Procedure to call.", "JiggleExportSinglePartition") .add("ratelimit", "rate_limit", "Rate limit to start from (number of transactions per second).", 100000) .add("timeout","export_timeout","max seconds to wait for export to complete",300) .add("migrate-ttl","false","use DDL that includes TTL MIGRATE action","false") .add("usetableexport", "usetableexport","use DDL that includes CREATE TABLE with EXPORT ON ... action","false") .add("migrate-nottl", "false","use DDL that includes MIGRATE without TTL","false") .add("nottl-interval", "milliseconds", "approximate migrate command invocation interval (in milliseconds)", 2500) .setArguments(args); config = new ConnectionConfig(apph); // Retrieve parameters final String csv = apph.stringValue("statsfile"); // Validate parameters apph.validate("duration", (config.duration > 0)) .validate("poolsize", (config.poolSize > 0)) .validate("ratelimit", (config.rateLimit > 0)); // Display actual parameters, for reference apph.printActualUsage(); // Get a client connection - we retry for a while in case the server hasn't started yet final Client client = createClient(); clientRef = client; // Statistics manager objects from the client ClientStatsContext periodicStatsContext = client.createStatsContext(); ClientStatsContext fullStatsContext = client.createStatsContext(); // Create a Timer task to display performance data on the procedure Timer timer = new Timer(true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { printStatistics(periodicStatsContext,true); } } , config.displayInterval*1000l , config.displayInterval*1000l ); // If migrate without TTL is enabled, set things up so a migrate is triggered // roughly every 2.5 seconds, with the first one happening 3 seconds from now // Use a separate Timer object to get a dedicated manual migration thread Timer migrateTimer = new Timer(true); Random migrateInterval = new Random(); if (config.migrateWithoutTTL) { migrateTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { trigger_migrate(migrateInterval.nextInt(10), client); // vary the migrate/delete interval a little } } , 3000l , config.migrateNoTTLInterval ); } // Keep track of various counts for INSERT (0), UPDATE (3) and DEELTE (2) AtomicLongArray transactionCounts = new AtomicLongArray(3); AtomicLongArray committedCounts = new AtomicLongArray(3); AtomicLongArray queuedCounts = new AtomicLongArray(3); AtomicLong failedCounts = new AtomicLong(0); AtomicLong rowId = new AtomicLong(0); // Run the benchmark loop for the requested duration final long endTime = System.currentTimeMillis() + (1000l * config.duration); OperationType [] ops = {OperationType.INSERT, OperationType.UPDATE, OperationType.DELETE}; while (endTime > System.currentTimeMillis()) { long currentRowId = rowId.incrementAndGet(); // Table with Export, do insert, update and delete if (config.usetableexport) { for (OperationType op : ops) { try { client.callProcedure( new ExportCallback(op, transactionCounts, committedCounts, failedCounts), "TableExport", currentRowId, op.get()); queuedCounts.incrementAndGet(op.get()); } catch (Exception e) { log.info("Exception: " + e); } } } else { try { client.callProcedure( new ExportCallback(OperationType.INSERT, transactionCounts, committedCounts, failedCounts), config.procedure, currentRowId, 0); } catch (Exception e) { log.info("Exception: " + e); e.printStackTrace(); } } } // We're done - stop the performance statistics display task timer.cancel(); migrateTimer.cancel(); if (config.migrateWithoutTTL) { for (String t : TABLES) { log_migrating_counts(t, client); } // trigger last "migrate from" cycle and wait a little bit for table to empty, assuming all is working. // otherwise, we'll check the table row count at a higher level and fail the test if the table is not empty. log.info("triggering final migrate"); trigger_migrate(0, client); Thread.sleep(7500); for (String t : TABLES) { log_migrating_counts(t, client); } } client.drain(); Thread.sleep(10000); long totalCount = 0, totalQueued = 0; for (OperationType op : ops) { totalCount += transactionCounts.get(op.get()); totalQueued += totalQueued; export_table_expected += committedCounts.get(op.get()); } // Opeation UPDATE will produce 2 export rows from both old and new tuples. export_table_expected += committedCounts.get(OperationType.UPDATE.get()); if (totalCount != totalQueued) { log.info("The transaction count " + totalCount + " does not match with the quened count " + totalQueued); } //Write to export table to get count to be expected on other side. log.info("Writing export count as: " + export_table_expected + " final rowid:" + rowId); client.callProcedure("InsertExportDoneDetails", export_table_expected); // 1. Tracking statistics log.info( String.format( " + "A total of %d calls was received...\n" + " - %,9d Succeeded\n" + " - %,9d Failed (Transaction Error)\n\n\n" , totalCount, export_table_expected, failedCounts.get() )); // 2. Print TABLE EXPORT stats if that's configured if (config.usetableexport) { String msg = String.format( " + "A total of %d calls were committed, a total of %d calls were queued\n" + " - %,9d Committed-Inserts\n" + " - %,9d Committed-Deletes\n" + " - %,9d Committed-Updates\n" + " - %,9d Transaction-Inserts\n" + " - %,9d Transaction-Deletes\n" + " - %,9d Transaction-Updates\n" + " - %,9d Queued-Inserts\n" + " - %,9d Queued-Deletes\n" + " - %,9d Queued-Updates" + "\n\n" , totalCount, totalQueued , committedCounts.get(OperationType.INSERT.get()) , committedCounts.get(OperationType.DELETE.get()) , committedCounts.get(OperationType.UPDATE.get()) , transactionCounts.get(OperationType.INSERT.get()) , transactionCounts.get(OperationType.DELETE.get()) , transactionCounts.get(OperationType.UPDATE.get()) , queuedCounts.get(OperationType.INSERT.get()) , queuedCounts.get(OperationType.DELETE.get()) , queuedCounts.get(OperationType.UPDATE.get())); log.info(msg); long export_table_count = get_table_count("EXPORT_PARTITIONED_TABLE_CDC", client); log.info("\nEXPORT_PARTITIONED_TABLE_CDC count: " + export_table_count); if (export_table_count != export_table_expected) { log.info("Insert and delete count " + export_table_expected + " does not match export table count: " + export_table_count + "\n"); } } // 3. Performance statistics (we only care about the procedure that we're benchmarking) log.info("\n\n printStatistics(fullStatsContext,false); // Dump statistics to a CSV file client.writeSummaryCSV( fullStatsContext.getStatsByProc().get(config.procedure), csv ); } catch(Exception ex) { log.fatal("Exception: " + ex); ex.printStackTrace(); } finally { if (clientRef != null) { try { clientRef.close(); } catch (Exception e) {} } } // if we didn't get any successes we need to fail if ( export_table_expected == 0 ) { log.error("No successful transactions"); System.exit(-1); } } private static void log_migrating_counts(String table, Client client) { try { VoltTable[] results = client.callProcedure("@AdHoc", "SELECT COUNT(*) FROM " + table + " WHERE MIGRATING; " + "SELECT COUNT(*) FROM " + table + " WHERE NOT MIGRATING; " + "SELECT COUNT(*) FROM " + table ).getResults(); long migrating = results[0].asScalarLong(); long not_migrating = results[1].asScalarLong(); long total = results[2].asScalarLong(); log.info("row counts for " + table + ": total: " + total + ", migrating: " + migrating + ", not migrating: " + not_migrating); } catch (ProcCallException e) { // Proc call failed. OK if connection went down, tests expect that. // In any case, no action taken other than logging. byte st = e.getClientResponse().getStatus(); String err = String.format("Procedure call failed in log_migrating_counts: %s (status %d)", e.getClientResponse().getStatusString(), st); if (st == ClientResponse.CONNECTION_LOST || st == ClientResponse.CONNECTION_TIMEOUT) { log.info(err); } else { log.error(err); } } catch (Exception e) { // log it and otherwise ignore it. it's not fatal to fail if the // SELECTS due to a migrate or some other exception log.fatal("log_migrating_counts exception: " + e); e.printStackTrace(); } } private static void trigger_migrate(int time_window, Client client) { try { VoltTable[] results; if (config.procedure.equals("JiggleExportGroupSinglePartition")) { ClientResponseWithPartitionKey[] responses = client.callAllPartitionProcedure("MigratePartitionedExport", time_window); for (ClientResponseWithPartitionKey resp : responses) { if (ClientResponse.SUCCESS == resp.response.getStatus()){ VoltTable res = resp.response.getResults()[0]; log.info("Partitioned Migrate - window: " + time_window + " seconds" + ", kafka: " + res.asScalarLong() + ", rabbit: " + res.asScalarLong() + ", file: " + res.asScalarLong() + ", jdbc: " + res.asScalarLong() + ", on partition " + resp.partitionKey ); } else { log.info("WARNING: fail to migrate on partition:" + resp.partitionKey); } } } else { results = client.callProcedure("MigrateReplicatedExport", time_window).getResults(); log.info("Replicated Migrate - window: " + time_window + " seconds" + ", kafka: " + results[0].asScalarLong() + ", rabbit: " + results[1].asScalarLong() + ", file: " + results[2].asScalarLong() + ", jdbc: " + results[3].asScalarLong() ); } } catch (ProcCallException e1) { if (e1.getMessage().contains("was lost before a response was received")) { log.warn("Possible problem executing " + config.procedure + ", procedure may not have completed"); } else { log.fatal("Exception: " + e1); e1.printStackTrace(); System.exit(-1); } } catch (Exception e) { log.fatal("Exception: " + e); e.printStackTrace(); System.exit(-1); } } private static long get_table_count(String sqlTable, Client client) { long count = 0; try { count = client.callProcedure("@AdHoc", "SELECT COUNT(*) FROM " + sqlTable + ";").getResults()[0].asScalarLong(); } catch (Exception e) { log.error("Exception in get_table_count: " + e); log.error("SELECT COUNT from table " + sqlTable + " failed"); } return count; } static Client createClient() { ClientConfig clientConfig = new ClientConfig("", ""); clientConfig.setReconnectOnConnectionLoss(true); // needed so clients reconnect on node stop/restarts clientConfig.setClientAffinity(true); clientConfig.setTopologyChangeAware(true); clientConfig.setMaxTransactionsPerSecond(config.rateLimit); Client client = ClientFactory.createClient(clientConfig); String[] serverArray = config.parsedServers; for (final String server : serverArray) { // connect to the first server in list; with TopologyChangeAware set, no need for more try { client.createConnection(server, config.port); break; }catch (Exception e) { log.error("Connection to " + server + " failed.\n"); } } return client; } /** * Prints a one line update on performance that can be printed * periodically during a benchmark. ** * @return */ static private synchronized void printStatistics(ClientStatsContext context, boolean resetBaseline) { if (resetBaseline) { context = context.fetchAndResetBaseline(); } else { context = context.fetch(); } ClientStats stats = context .getStatsByProc() .get(config.procedure); if (stats == null) return; // switch from app's runtime to VoltLogger clock time so results line up // with apprunner if running in that framework String stats_out = String.format(" Throughput %d/s, ", stats.getTxnThroughput()); stats_out += String.format("Aborts/Failures %d/%d, ", stats.getInvocationAborts(), stats.getInvocationErrors()); stats_out += String.format("Avg/95%% Latency %.2f/%.2fms\n", stats.getAverageLatency(), stats.kPercentileLatencyAsDouble(0.95)); log.info(stats_out); } }
package ifc.io; import lib.MultiMethodTest; import com.sun.star.io.XActiveDataSource; import com.sun.star.io.XOutputStream; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; /** * Testing <code>com.sun.star.io.XActiveDataSource</code> * interface methods: * <ul> * <li><code>setOutputStream()</code></li> * <li><code>getOutputStream()</code></li> * </ul> <p> * * This test needs the following object relations : * <ul> * <li> <code>'OutputStream'</code> * (of type <code>com.sun.star.io.OutputStream</code>): * acceptable output stream which can be set by <code>setOutputStream</code> </li> * <ul> <p> * * After test completion object environment has to be recreated. * @see com.sun.star.io.XActiveDataSource * @see com.sun.star.io.XOutputStream */ public class _XActiveDataSource extends MultiMethodTest { public XActiveDataSource oObj = null; private XOutputStream oStream = null; /** * Take the XOutputStream from the environment for setting and getting. */ public void before() { XInterface x = (XInterface)tEnv.getObjRelation("OutputStream"); oStream = (XOutputStream) UnoRuntime.queryInterface (XOutputStream.class, x) ; } /** * Test calls the method using interface <code>XOutputStream</code> * received in method <code>before()</code> as parameter. <p> * Has <b> OK </b> status if the method successfully returns. <p> */ public void _setOutputStream() { oObj.setOutputStream(oStream); tRes.tested("setOutputStream()", true); } /** * Test calls the method and compares returned value with value that was * set in the method <code>setOutputStream()</code>. <p> * Has <b> OK </b> status if values are equal. <p> * The following method tests are to be completed successfully before : * <ul> * <li> <code> setOutputStream() </code></li> * </ul> */ public void _getOutputStream() { requiredMethod("setOutputStream()"); tRes.tested("getOutputStream()", oStream.equals(oObj.getOutputStream())); } /** * Forces object environment recreation. */ public void after() { this.disposeEnvironment() ; } }
package android.lib.recaptcha; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.widget.ImageView; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ReCaptcha extends ImageView { public interface OnShowChallengeListener { void onChallengeShown(boolean shown); } public interface OnVerifyAnswerListener { void onAnswerVerified(boolean success); } private static final String TAG = "ReCaptcha"; private static final String VERIFICATION_URL = "http: private static final String CHALLENGE_URL = "http: private static final String RECAPTCHA_OBJECT_TOKEN_URL = "http: private static final String IMAGE_URL = "http: private String imageToken; private HashMap<String, String> publicKeyChallengeMap = new HashMap<String, String>(); public ReCaptcha(final Context context) { super(context); } public ReCaptcha(final Context context, final AttributeSet attrs) { super(context, attrs); } public ReCaptcha(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); } /** * Returns a new instance of {@link org.apache.http.client.HttpClient} for downloading ReCaptcha images. * <p>Subclasses may override this method and return customized {@link org.apache.http.client.HttpClient}, * such as an {@link android.net.http.AndroidHttpClient} with custom {@link org.apache.http.params.HttpParams}.</p> * <p>The default behavior returns a {@link org.apache.http.impl.client.DefaultHttpClient}</p> * * @return a {@link org.apache.http.client.HttpClient} for downloading ReCaptcha images. */ protected HttpClient createHttpClient() { return new DefaultHttpClient(); } public final boolean showChallenge(final String publicKey) throws ReCaptchaException, IOException { if (TextUtils.isEmpty(publicKey)) { throw new IllegalArgumentException("publicKey cannot be null or empty"); } this.setImageDrawable(null); this.imageToken = null; final Bitmap bitmap = this.downloadImage(publicKey); this.setImageBitmap(bitmap); return bitmap != null; } public final void showChallengeAsync(final String publicKey, final OnShowChallengeListener listener) { if (TextUtils.isEmpty(publicKey)) { throw new IllegalArgumentException("publicKey cannot be null or empty"); } this.setImageDrawable(null); this.imageToken = null; final Handler handler = new Handler() { @Override public void handleMessage(final Message message) { final Bitmap bitmap = (Bitmap) message.obj; final Bitmap scaled = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth() * 2, bitmap.getHeight() * 2, true); bitmap.recycle(); ReCaptcha.this.setImageBitmap(scaled); if (listener != null) { listener.onChallengeShown(message.obj != null); } } }; new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(final String... publicKeys) { try { return ReCaptcha.this.downloadImage(publicKeys[0]); } catch (final ReCaptchaException e) { Log.e(ReCaptcha.TAG, "The downloaded CAPTCHA content is malformed", e); } catch (final IOException e) { Log.e(ReCaptcha.TAG, "A protocol or network connection problem has occurred", e); } return null; } @Override protected void onPostExecute(final Bitmap bitmap) { handler.sendMessage(handler.obtainMessage(0, bitmap)); } }.execute(publicKey); } public final boolean verifyAnswer(final String privateKey, final String answer) throws IOException { if (TextUtils.isEmpty(privateKey)) { throw new IllegalArgumentException("privateKey cannot be null or empty"); } if (TextUtils.isEmpty(answer)) { throw new IllegalArgumentException("answer cannot be null or empty"); } return this.submitAnswer(privateKey, answer); } public final void verifyAnswerAsync(final String privateKey, final String answer, final OnVerifyAnswerListener listener) { if (TextUtils.isEmpty(privateKey)) { throw new IllegalArgumentException("privateKey cannot be null or empty"); } if (TextUtils.isEmpty(answer)) { throw new IllegalArgumentException("answer cannot be null or empty"); } final Handler handler = new Handler() { @Override public void handleMessage(final Message message) { if (listener != null) { listener.onAnswerVerified((Boolean) message.obj); } } }; new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(final String... params) { try { return ReCaptcha.this.submitAnswer(params[0], params[1]); } catch (final IOException e) { Log.e(ReCaptcha.TAG, "A protocol or network connection problem has occurred", e); } return Boolean.FALSE; } @Override protected void onPostExecute(final Boolean result) { handler.sendMessage(handler.obtainMessage(0, result)); } }.execute(privateKey, answer); } private Bitmap downloadImage(final String publicKey) throws ReCaptchaException, IOException { final HttpClient httpClient = this.createHttpClient(); try { String challenge = getChallenge(publicKey); if (challenge == null) { throw new ReCaptchaException("ReCaptcha challenge not found"); } String imageToken = getImageToken(challenge, publicKey); if (imageToken == null) { throw new ReCaptchaException("Image token not found"); } final String imageUrl = String.format(ReCaptcha.IMAGE_URL, imageToken); final HttpResponse response = httpClient.execute(new HttpGet(imageUrl)); try { final Bitmap bitmap = BitmapFactory.decodeStream(response.getEntity().getContent()); if (bitmap == null) { throw new ReCaptchaException("Invalid CAPTCHA image"); } return bitmap; } finally { if (response.getEntity() != null) { response.getEntity().consumeContent(); } } } catch (JSONException e) { throw new ReCaptchaException("Unable to parse challenge response"); } finally { httpClient.getConnectionManager().shutdown(); } return null; } private String getImageToken(String challenge, String publicKey) throws IOException { HttpClient httpClient = this.createHttpClient(); String imageTokenUrl = String.format(ReCaptcha.RECAPTCHA_OBJECT_TOKEN_URL, challenge, publicKey, "image"); String imageTokenResponse = httpClient.execute(new HttpGet(imageTokenUrl), new BasicResponseHandler()); return substringBetween(imageTokenResponse, "('", "',"); } private String getChallenge(String publicKey) throws IOException, JSONException { if (!publicKeyChallengeMap.containsKey(publicKey)) { HttpClient httpClient = this.createHttpClient(); String challenegeResponse = httpClient.execute(new HttpGet(String.format(ReCaptcha.CHALLENGE_URL, publicKey)), new BasicResponseHandler()); final String recaptchaStateString = substringBetween( challenegeResponse , "RecaptchaState = ", "}") + "}"; JSONObject recaptchaStateObject = new JSONObject(recaptchaStateString); String challenge = recaptchaStateObject.getString("challenge"); publicKeyChallengeMap.put(publicKey, challenge); return challenge; } else { return publicKeyChallengeMap.get(publicKey); } } private boolean submitAnswer(final String privateKey, final String answer) throws IOException { final HttpClient httpClient = this.createHttpClient(); final HttpPost request = new HttpPost(ReCaptcha.VERIFICATION_URL); final List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("privatekey", privateKey)); params.add(new BasicNameValuePair("remoteip", "127.0.0.1")); params.add(new BasicNameValuePair("challenge", this.imageToken)); params.add(new BasicNameValuePair("response", answer)); try { request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); return httpClient.execute(request, new BasicResponseHandler()).startsWith("true"); } catch (final UnsupportedEncodingException e) { Log.e(ReCaptcha.TAG, "UTF-8 encoding is not supported by this platform", e); } finally { httpClient.getConnectionManager().shutdown(); } return false; } private static String substringBetween(String str, String open, String close) { if (str == null || open == null || close == null) { return null; } int start = str.indexOf(open); if (start != -1) { int end = str.indexOf(close, start + open.length()); if (end != -1) { return str.substring(start + open.length(), end); } } return null; } }
package me.thekey.android; import java.util.Date; import android.util.Pair; public interface TheKey { public static final String ACTION_LOGIN = TheKey.class.getName() + ".ACTION_LOGIN"; public static final String ACTION_LOGOUT = TheKey.class.getName() + ".ACTION_LOGOUT"; public static final String ACTION_ATTRIBUTES_LOADED = TheKey.class.getName() + ".ACTION_ATTRIBUTES_LOADED"; public static final String EXTRA_GUID = "guid"; public static final String EXTRA_CHANGING_USER = "changing_user"; public static final long INVALID_CLIENT_ID = -1; interface Attributes { String getGuid(); Date getLoadedTime(); boolean areValid(); String getEmail(); String getFirstName(); String getLastName(); } /** * This method will return the guid of the current OAuth session. This is a * non-blocking method and may be called on the UI thread. * * @return the user's guid */ String getGuid(); /** * This method will load the attributes for the current OAuth session from * The Key. This method is a blocking method and should never be called * directly on the UI thread. * * @return whether or not attributes were loaded */ boolean loadAttributes() throws TheKeySocketException; /** * This method will return the most recently loaded attributes for the * current OAuth session. This method does not attempt to load the * attributes if they haven't been loaded yet, to load the attributes see * {@link TheKey#loadAttributes()}. This is a non-blocking method and may be * called on the UI thread. * * @return The attributes for the current OAuth session */ Attributes getAttributes(); /** * This method returns a ticket for the specified service. This method is a * blocking method and should never be called directly on the UI thread. * * @param service * @return The ticket */ String getTicket(String service) throws TheKeySocketException; /** * This method returns a ticket for the specified service and attributes the * ticket was issued for. This is a blocking method and should never be * called directly on the UI thread. * * @param service * @return The ticket & attributes for the current session, or null if no * ticket could be retrieved */ Pair<String, Attributes> getTicketAndAttributes(String service) throws TheKeySocketException; }
package hudson.remoting; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.net.HttpURLConnection; import java.net.Socket; import java.net.URL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.List; import java.util.Collections; import java.util.logging.Logger; import static java.util.logging.Level.SEVERE; /** * Slave agent engine that proactively connects to Hudson master. * * @author Kohsuke Kawaguchi */ public class Engine extends Thread { /** * Thread pool that sets {@link #CURRENT}. */ private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() { private final ThreadFactory defaultFactory = Executors.defaultThreadFactory(); public Thread newThread(final Runnable r) { return defaultFactory.newThread(new Runnable() { public void run() { CURRENT.set(Engine.this); r.run(); } }); } }); public final EngineListener listener; private List<URL> candidateUrls; private URL hudsonUrl; private final String secretKey; public final String slaveName; private String credentials; /** * See Main#tunnel in the jnlp-agent module for the details. */ private String tunnel; private boolean noReconnect; public Engine(EngineListener listener, List<URL> hudsonUrls, String secretKey, String slaveName) { this.listener = listener; this.candidateUrls = hudsonUrls; this.secretKey = secretKey; this.slaveName = slaveName; if(candidateUrls.isEmpty()) throw new IllegalArgumentException("No URLs given"); } public URL getHudsonUrl() { return hudsonUrl; } public void setTunnel(String tunnel) { this.tunnel = tunnel; } public void setCredentials(String creds) { this.credentials = creds; } public void setNoReconnect(boolean noReconnect) { this.noReconnect = noReconnect; } @SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Override public void run() { try { boolean first = true; while(true) { if(first) { first = false; } else { if(noReconnect) return; // exit } listener.status("Locating server among " + candidateUrls); Throwable firstError=null; String port=null; for (URL url : candidateUrls) { String s = url.toExternalForm(); if(!s.endsWith("/")) s+='/'; URL salURL = new URL(s+"tcpSlaveAgentListener/"); // find out the TCP port HttpURLConnection con = (HttpURLConnection)salURL.openConnection(); if (con instanceof HttpURLConnection && credentials != null) { String encoding = new sun.misc.BASE64Encoder().encode(credentials.getBytes()); con.setRequestProperty("Authorization", "Basic " + encoding); } try { try { con.setConnectTimeout(30000); con.setReadTimeout(60000); con.connect(); } catch (IOException x) { if (firstError == null) { firstError = new IOException("Failed to connect to " + salURL + ": " + x.getMessage()).initCause(x); } continue; } port = con.getHeaderField("X-Hudson-JNLP-Port"); if(con.getResponseCode()!=200) { if(firstError==null) firstError = new Exception(salURL+" is invalid: "+con.getResponseCode()+" "+con.getResponseMessage()); continue; } if(port ==null) { if(firstError==null) firstError = new Exception(url+" is not Hudson"); continue; } } finally { con.disconnect(); } // this URL works. From now on, only try this URL hudsonUrl = url; firstError = null; candidateUrls = Collections.singletonList(hudsonUrl); break; } if(firstError!=null) { listener.error(firstError); return; } final Socket s = connect(port); listener.status("Handshaking"); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:JNLP-connect"); dos.writeUTF(secretKey); dos.writeUTF(slaveName); BufferedInputStream in = new BufferedInputStream(s.getInputStream()); String greeting = readLine(in); // why, oh why didn't I use DataOutputStream when writing to the network? if (!greeting.equals(GREETING_SUCCESS)) { listener.error(new Exception("The server rejected the connection: "+greeting)); Thread.sleep(10*1000); continue; } final Channel channel = new Channel("channel", executor, in, new BufferedOutputStream(s.getOutputStream())); PingThread t = new PingThread(channel) { protected void onDead() { try { if (!channel.isInClosed()) { LOGGER.info("Ping failed. Terminating the socket."); s.close(); } } catch (IOException e) { LOGGER.log(SEVERE, "Failed to terminate the socket", e); } } }; t.start(); listener.status("Connected"); channel.join(); listener.status("Terminated"); t.interrupt(); // make sure the ping thread is terminated listener.onDisconnect(); if(noReconnect) return; // exit // try to connect back to the server every 10 secs. waitForServerToBack(); } } catch (Throwable e) { listener.error(e); } } /** * Read until '\n' and returns it as a string. */ private static String readLine(InputStream in) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (true) { int ch = in.read(); if (ch<0 || ch=='\n') return baos.toString().trim(); // trim off possible '\r' baos.write(ch); } } /** * Connects to TCP slave port, with a few retries. */ private Socket connect(String port) throws IOException, InterruptedException { String host = this.hudsonUrl.getHost(); if(tunnel!=null) { String[] tokens = tunnel.split(":",3); if(tokens.length!=2) throw new IOException("Illegal tunneling parameter: "+tunnel); if(tokens[0].length()>0) host = tokens[0]; if(tokens[1].length()>0) port = tokens[1]; } String msg = "Connecting to " + host + ':' + port; listener.status(msg); int retry = 1; while(true) { try { Socket s = new Socket(host, Integer.parseInt(port)); s.setTcpNoDelay(true); // we'll do buffering by ourselves // set read time out to avoid infinite hang. the time out should be long enough so as not // to interfere with normal operation. the main purpose of this is that when the other peer dies // abruptly, we shouldn't hang forever, and at some point we should notice that the connection // is gone. s.setSoTimeout(30*60*1000); // 30 mins. See PingThread for the ping interval return s; } catch (IOException e) { if(retry++>10) throw (IOException)new IOException("Failed to connect to "+host+':'+port).initCause(e); Thread.sleep(1000*10); listener.status(msg+" (retrying:"+retry+")",e); } } } /** * Waits for the server to come back. */ private void waitForServerToBack() throws InterruptedException { while(true) { Thread.sleep(1000*10); try { HttpURLConnection con = (HttpURLConnection)new URL(hudsonUrl,"tcpSlaveAgentListener/").openConnection(); con.connect(); if(con.getResponseCode()==200) return; } catch (IOException e) { // retry } } } /** * When invoked from within remoted {@link Callable} (that is, * from the thread that carries out the remote requests), * this method returns the {@link Engine} in which the remote operations * run. */ public static Engine current() { return CURRENT.get(); } private static final ThreadLocal<Engine> CURRENT = new ThreadLocal<Engine>(); private static final Logger LOGGER = Logger.getLogger(Engine.class.getName()); public static final String GREETING_SUCCESS = "Welcome"; }
package hudson.cli; import hudson.console.ModelHyperlinkNote; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Cause.UserIdCause; import hudson.model.ParametersAction; import hudson.model.ParameterValue; import hudson.model.ParametersDefinitionProperty; import hudson.model.ParameterDefinition; import hudson.Extension; import hudson.AbortException; import hudson.model.Item; import hudson.model.Result; import hudson.model.TaskListener; import hudson.model.queue.QueueTaskFuture; import hudson.scm.PollingResult.Change; import hudson.util.EditDistance; import hudson.util.StreamTaskListener; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Map.Entry; import java.io.FileNotFoundException; import java.io.PrintStream; import jenkins.model.Jenkins; /** * Builds a job, and optionally waits until its completion. * * @author Kohsuke Kawaguchi */ @Extension public class BuildCommand extends CLICommand { @Override public String getShortDescription() { return Messages.BuildCommand_ShortDescription(); } @Argument(metaVar="JOB",usage="Name of the job to build",required=true) public AbstractProject<?,?> job; @Option(name="-f", usage="Follow the build progress. Like -s only interrupts are not passed through to the build.") public boolean follow = false; @Option(name="-s",usage="Wait until the completion/abortion of the command. Interrupts are passed through to the build.") public boolean sync = false; @Option(name="-w",usage="Wait until the start of the command") public boolean wait = false; @Option(name="-c",usage="Check for SCM changes before starting the build, and if there's no change, exit without doing a build") public boolean checkSCM = false; @Option(name="-p",usage="Specify the build parameters in the key=value format.") public Map<String,String> parameters = new HashMap<String, String>(); @Option(name="-v",usage="Prints out the console output of the build. Use with -s") public boolean consoleOutput = false; @Option(name="-r", usage="Number of times to retry reading of the output log if it does not exists on first attempt. Defaults to 0. Use with -v.") public String retryCntStr = "0"; // hold parsed retryCnt; private int retryCnt = 0; protected int run() throws Exception { job.checkPermission(Item.BUILD); ParametersAction a = null; if (!parameters.isEmpty()) { ParametersDefinitionProperty pdp = job.getProperty(ParametersDefinitionProperty.class); if (pdp==null) throw new AbortException(job.getFullDisplayName()+" is not parameterized but the -p option was specified"); List<ParameterValue> values = new ArrayList<ParameterValue>(); for (Entry<String, String> e : parameters.entrySet()) { String name = e.getKey(); ParameterDefinition pd = pdp.getParameterDefinition(name); if (pd==null) throw new AbortException(String.format("\'%s\' is not a valid parameter. Did you mean %s?", name, EditDistance.findNearest(name, pdp.getParameterDefinitionNames()))); values.add(pd.createValue(this,e.getValue())); } // handle missing parameters by adding as default values ISSUE JENKINS-7162 for(ParameterDefinition pd : pdp.getParameterDefinitions()) { if (parameters.containsKey(pd.getName())) continue; // not passed in use default values.add(pd.getDefaultParameterValue()); } a = new ParametersAction(values); } retryCnt = Integer.parseInt(retryCntStr); if (checkSCM) { if (job.poll(new StreamTaskListener(stdout, getClientCharset())).change == Change.NONE) { return 0; } } if (!job.isBuildable()) { String msg = Messages.BuildCommand_CLICause_CannotBuildUnknownReasons(job.getFullDisplayName()); if (job.isDisabled()) { msg = Messages.BuildCommand_CLICause_CannotBuildDisabled(job.getFullDisplayName()); } else if (job.isHoldOffBuildUntilSave()){ msg = Messages.BuildCommand_CLICause_CannotBuildConfigNotSaved(job.getFullDisplayName()); } stderr.println(msg); return -1; } QueueTaskFuture<? extends AbstractBuild> f = job.scheduleBuild2(0, new CLICause(Jenkins.getAuthentication().getName()), a); if (wait || sync || follow) { AbstractBuild b = f.waitForStart(); // wait for the start stdout.println("Started "+b.getFullDisplayName()); if (sync || follow) { try { if (consoleOutput) { // read output in a retry loop, by default try only once // writeWholeLogTo may fail with FileNotFound // exception on a slow/busy machine, if it takes // longish to create the log file int retryInterval = 100; for (int i=0;i<=retryCnt;) { try { b.writeWholeLogTo(stdout); break; } catch (FileNotFoundException e) { if ( i == retryCnt ) { throw e; } i++; Thread.sleep(retryInterval); } } } f.get(); // wait for the completion stdout.println("Completed "+b.getFullDisplayName()+" : "+b.getResult()); return b.getResult().ordinal; } catch (InterruptedException e) { if (follow) { return 125; } else { // if the CLI is aborted, try to abort the build as well f.cancel(true); throw e; } } } } return 0; } @Override protected void printUsageSummary(PrintStream stderr) { stderr.println( "Starts a build, and optionally waits for a completion.\n" + "Aside from general scripting use, this command can be\n" + "used to invoke another job from within a build of one job.\n" + "With the -s option, this command changes the exit code based on\n" + "the outcome of the build (exit code 0 indicates a success)\n" + "and interrupting the command will interrupt the job.\n" + "With the -f option, this command changes the exit code based on\n" + "the outcome of the build (exit code 0 indicates a success)\n" + "however, unlike -s, interrupting the command will not interrupt\n" + "the job (exit code 125 indicates the command was interrupted)\n" + "With the -c option, a build will only run if there has been\n" + "an SCM change" ); } public static class CLICause extends UserIdCause { private String startedBy; public CLICause(){ startedBy = "unknown"; } public CLICause(String startedBy){ this.startedBy = startedBy; } @Override public String getShortDescription() { return Messages.BuildCommand_CLICause_ShortDescription(startedBy); } @Override public void print(TaskListener listener) { listener.getLogger().println(Messages.BuildCommand_CLICause_ShortDescription( ModelHyperlinkNote.encodeTo("/user/" + startedBy, startedBy))); } @Override public boolean equals(Object o) { return o instanceof CLICause; } @Override public int hashCode() { return 7; } } }
package be.ibridge.kettle.trans.step; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.Hashtable; import java.util.List; import java.util.Map; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.KettleVariables; import be.ibridge.kettle.core.LocalVariables; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.ResultFile; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.RowSet; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleRowException; import be.ibridge.kettle.core.exception.KettleStepException; import be.ibridge.kettle.core.exception.KettleStepLoaderException; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.trans.StepLoader; import be.ibridge.kettle.trans.StepPlugin; import be.ibridge.kettle.trans.StepPluginMeta; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.XMLInputSax.XMLInputSaxMeta; import be.ibridge.kettle.trans.step.abort.AbortMeta; import be.ibridge.kettle.trans.step.accessoutput.AccessOutputMeta; import be.ibridge.kettle.trans.step.addsequence.AddSequenceMeta; import be.ibridge.kettle.trans.step.addxml.AddXMLMeta; import be.ibridge.kettle.trans.step.aggregaterows.AggregateRowsMeta; import be.ibridge.kettle.trans.step.blockingstep.BlockingStepMeta; import be.ibridge.kettle.trans.step.calculator.CalculatorMeta; import be.ibridge.kettle.trans.step.combinationlookup.CombinationLookupMeta; import be.ibridge.kettle.trans.step.constant.ConstantMeta; import be.ibridge.kettle.trans.step.cubeinput.CubeInputMeta; import be.ibridge.kettle.trans.step.cubeoutput.CubeOutputMeta; import be.ibridge.kettle.trans.step.databasejoin.DatabaseJoinMeta; import be.ibridge.kettle.trans.step.databaselookup.DatabaseLookupMeta; import be.ibridge.kettle.trans.step.dbproc.DBProcMeta; import be.ibridge.kettle.trans.step.delete.DeleteMeta; import be.ibridge.kettle.trans.step.denormaliser.DenormaliserMeta; import be.ibridge.kettle.trans.step.dimensionlookup.DimensionLookupMeta; import be.ibridge.kettle.trans.step.dummytrans.DummyTransMeta; import be.ibridge.kettle.trans.step.excelinput.ExcelInputMeta; import be.ibridge.kettle.trans.step.exceloutput.ExcelOutputMeta; import be.ibridge.kettle.trans.step.fieldsplitter.FieldSplitterMeta; import be.ibridge.kettle.trans.step.filesfromresult.FilesFromResultMeta; import be.ibridge.kettle.trans.step.filestoresult.FilesToResultMeta; import be.ibridge.kettle.trans.step.filterrows.FilterRowsMeta; import be.ibridge.kettle.trans.step.flattener.FlattenerMeta; import be.ibridge.kettle.trans.step.formula.FormulaMeta; import be.ibridge.kettle.trans.step.getfilenames.GetFileNamesMeta; import be.ibridge.kettle.trans.step.getvariable.GetVariableMeta; import be.ibridge.kettle.trans.step.groupby.GroupByMeta; import be.ibridge.kettle.trans.step.http.HTTPMeta; import be.ibridge.kettle.trans.step.injector.InjectorMeta; import be.ibridge.kettle.trans.step.insertupdate.InsertUpdateMeta; import be.ibridge.kettle.trans.step.joinrows.JoinRowsMeta; import be.ibridge.kettle.trans.step.mapping.MappingMeta; import be.ibridge.kettle.trans.step.mappinginput.MappingInputMeta; import be.ibridge.kettle.trans.step.mappingoutput.MappingOutputMeta; import be.ibridge.kettle.trans.step.mergejoin.MergeJoinMeta; import be.ibridge.kettle.trans.step.mergerows.MergeRowsMeta; import be.ibridge.kettle.trans.step.normaliser.NormaliserMeta; import be.ibridge.kettle.trans.step.nullif.NullIfMeta; import be.ibridge.kettle.trans.step.rowgenerator.RowGeneratorMeta; import be.ibridge.kettle.trans.step.rowsfromresult.RowsFromResultMeta; import be.ibridge.kettle.trans.step.rowstoresult.RowsToResultMeta; import be.ibridge.kettle.trans.step.scriptvalues.ScriptValuesMeta; import be.ibridge.kettle.trans.step.scriptvalues_mod.ScriptValuesMetaMod; import be.ibridge.kettle.trans.step.selectvalues.SelectValuesMeta; import be.ibridge.kettle.trans.step.setvariable.SetVariableMeta; import be.ibridge.kettle.trans.step.socketreader.SocketReaderMeta; import be.ibridge.kettle.trans.step.socketwriter.SocketWriterMeta; import be.ibridge.kettle.trans.step.sortedmerge.SortedMergeMeta; import be.ibridge.kettle.trans.step.sortrows.SortRowsMeta; import be.ibridge.kettle.trans.step.sql.ExecSQLMeta; import be.ibridge.kettle.trans.step.streamlookup.StreamLookupMeta; import be.ibridge.kettle.trans.step.systemdata.SystemDataMeta; import be.ibridge.kettle.trans.step.tableinput.TableInputMeta; import be.ibridge.kettle.trans.step.tableoutput.TableOutputMeta; import be.ibridge.kettle.trans.step.textfileinput.TextFileInputMeta; import be.ibridge.kettle.trans.step.textfileoutput.TextFileOutputMeta; import be.ibridge.kettle.trans.step.uniquerows.UniqueRowsMeta; import be.ibridge.kettle.trans.step.update.UpdateMeta; import be.ibridge.kettle.trans.step.valuemapper.ValueMapperMeta; import be.ibridge.kettle.trans.step.webservices.WebServiceMeta; import be.ibridge.kettle.trans.step.xbaseinput.XBaseInputMeta; import be.ibridge.kettle.trans.step.xmlinput.XMLInputMeta; import be.ibridge.kettle.trans.step.xmloutput.XMLOutputMeta; import be.ibridge.kettle.trans.step.orabulkloader.OraBulkLoaderMeta; import be.ibridge.kettle.trans.step.xmlinputpath.XMLInputPathMeta; public class BaseStep extends Thread { public static final String CATEGORY_INPUT = Messages.getString("BaseStep.Category.Input"); public static final String CATEGORY_OUTPUT = Messages.getString("BaseStep.Category.Output"); public static final String CATEGORY_TRANSFORM = Messages.getString("BaseStep.Category.Transform"); public static final String CATEGORY_SCRIPTING = Messages.getString("BaseStep.Category.Scripting"); public static final String CATEGORY_LOOKUP = Messages.getString("BaseStep.Category.Lookup"); public static final String CATEGORY_JOINS = Messages.getString("BaseStep.Category.Joins"); public static final String CATEGORY_DATA_WAREHOUSE = Messages.getString("BaseStep.Category.DataWarehouse"); public static final String CATEGORY_JOB = Messages.getString("BaseStep.Category.Job"); public static final String CATEGORY_MAPPING = Messages.getString("BaseStep.Category.Mapping"); public static final String CATEGORY_INLINE = Messages.getString("BaseStep.Category.Inline"); public static final String CATEGORY_EXPERIMENTAL = Messages.getString("BaseStep.Category.Experimental"); public static final String CATEGORY_DEPRECATED = Messages.getString("BaseStep.Category.Deprecated"); protected static LocalVariables localVariables = LocalVariables.getInstance(); public static final StepPluginMeta[] steps = { new StepPluginMeta(TextFileInputMeta.class, "TextFileInput", Messages.getString("BaseStep.TypeLongDesc.TextFileInput"), Messages .getString("BaseStep.TypeTooltipDesc.TextInputFile", Const.CR), "TFI.png", CATEGORY_INPUT), new StepPluginMeta(TextFileOutputMeta.class, "TextFileOutput", Messages.getString("BaseStep.TypeLongDesc.TextFileOutput"), Messages .getString("BaseStep.TypeTooltipDesc.TextOutputFile"), "TFO.png", CATEGORY_OUTPUT), new StepPluginMeta(TableInputMeta.class, "TableInput", Messages.getString("BaseStep.TypeLongDesc.TableInput"), Messages .getString("BaseStep.TypeTooltipDesc.TableInput"), "TIP.png", CATEGORY_INPUT), new StepPluginMeta(TableOutputMeta.class, "TableOutput", Messages.getString("BaseStep.TypeLongDesc.Output"), Messages .getString("BaseStep.TypeTooltipDesc.TableOutput"), "TOP.png", CATEGORY_OUTPUT), new StepPluginMeta(SelectValuesMeta.class, "SelectValues", Messages.getString("BaseStep.TypeLongDesc.SelectValues"), Messages.getString( "BaseStep.TypeTooltipDesc.SelectValues", Const.CR), "SEL.png", CATEGORY_TRANSFORM), new StepPluginMeta(FilterRowsMeta.class, "FilterRows", Messages.getString("BaseStep.TypeLongDesc.FilterRows"), Messages .getString("BaseStep.TypeTooltipDesc.FilterRows"), "FLT.png", CATEGORY_TRANSFORM), new StepPluginMeta(DatabaseLookupMeta.class, "DBLookup", Messages.getString("BaseStep.TypeLongDesc.DatabaseLookup"), Messages .getString("BaseStep.TypeTooltipDesc.Databaselookup"), "DLU.png", CATEGORY_LOOKUP), new StepPluginMeta(SortRowsMeta.class, "SortRows", Messages.getString("BaseStep.TypeLongDesc.SortRows"), Messages .getString("BaseStep.TypeTooltipDesc.Sortrows"), "SRT.png", CATEGORY_TRANSFORM), new StepPluginMeta(StreamLookupMeta.class, "StreamLookup", Messages.getString("BaseStep.TypeLongDesc.StreamLookup"), Messages .getString("BaseStep.TypeTooltipDesc.Streamlookup"), "SLU.png", CATEGORY_LOOKUP), new StepPluginMeta(AddSequenceMeta.class, "Sequence", Messages.getString("BaseStep.TypeLongDesc.AddSequence"), Messages .getString("BaseStep.TypeTooltipDesc.Addsequence"), "SEQ.png", CATEGORY_TRANSFORM), new StepPluginMeta(DimensionLookupMeta.class, "DimensionLookup", Messages.getString("BaseStep.TypeLongDesc.DimensionUpdate"), Messages .getString("BaseStep.TypeTooltipDesc.Dimensionupdate", Const.CR), "DIM.png", CATEGORY_DATA_WAREHOUSE), new StepPluginMeta(CombinationLookupMeta.class, "CombinationLookup", Messages.getString("BaseStep.TypeLongDesc.CombinationUpdate"), Messages.getString("BaseStep.TypeTooltipDesc.CombinationUpdate", Const.CR, Const.CR), "CMB.png", CATEGORY_DATA_WAREHOUSE), new StepPluginMeta(DummyTransMeta.class, "Dummy", Messages.getString("BaseStep.TypeLongDesc.Dummy"), Messages.getString( "BaseStep.TypeTooltipDesc.Dummy", Const.CR), "DUM.png", CATEGORY_TRANSFORM), new StepPluginMeta(JoinRowsMeta.class, "JoinRows", Messages.getString("BaseStep.TypeLongDesc.JoinRows"), Messages.getString( "BaseStep.TypeTooltipDesc.JoinRows", Const.CR), "JRW.png", CATEGORY_JOINS), new StepPluginMeta(AggregateRowsMeta.class, "AggregateRows", Messages.getString("BaseStep.TypeLongDesc.AggregateRows"), Messages .getString("BaseStep.TypeTooltipDesc.AggregateRows", Const.CR), "AGG.png", CATEGORY_DEPRECATED), new StepPluginMeta(SystemDataMeta.class, "SystemInfo", Messages.getString("BaseStep.TypeLongDesc.GetSystemInfo"), Messages .getString("BaseStep.TypeTooltipDesc.GetSystemInfo"), "SYS.png", CATEGORY_INPUT), new StepPluginMeta(RowGeneratorMeta.class, "RowGenerator", Messages.getString("BaseStep.TypeLongDesc.GenerateRows"), Messages .getString("BaseStep.TypeTooltipDesc.GenerateRows"), "GEN.png", CATEGORY_INPUT), new StepPluginMeta(ScriptValuesMeta.class, "ScriptValue", Messages.getString("BaseStep.TypeLongDesc.JavaScript"), Messages .getString("BaseStep.TypeTooltipDesc.JavaScriptValue"), "SCR.png", CATEGORY_SCRIPTING), new StepPluginMeta(ScriptValuesMetaMod.class, "ScriptValueMod", Messages.getString("BaseStep.TypeLongDesc.JavaScriptMod"), Messages .getString("BaseStep.TypeTooltipDesc.JavaScriptValueMod"), "SCR_mod.png", CATEGORY_SCRIPTING), new StepPluginMeta(DBProcMeta.class, "DBProc", Messages.getString("BaseStep.TypeLongDesc.CallDBProcedure"), Messages .getString("BaseStep.TypeTooltipDesc.CallDBProcedure"), "PRC.png", CATEGORY_LOOKUP), new StepPluginMeta(InsertUpdateMeta.class, "InsertUpdate", Messages.getString("BaseStep.TypeLongDesc.InsertOrUpdate"), Messages .getString("BaseStep.TypeTooltipDesc.InsertOrUpdate"), "INU.png", CATEGORY_OUTPUT), new StepPluginMeta(UpdateMeta.class, "Update", Messages.getString("BaseStep.TypeLongDesc.Update"), Messages .getString("BaseStep.TypeTooltipDesc.Update"), "UPD.png", CATEGORY_OUTPUT), new StepPluginMeta(DeleteMeta.class, "Delete", Messages.getString("BaseStep.TypeLongDesc.Delete"), Messages .getString("BaseStep.TypeTooltipDesc.Delete"), "Delete.png", CATEGORY_OUTPUT), new StepPluginMeta(NormaliserMeta.class, "Normaliser", Messages.getString("BaseStep.TypeLongDesc.RowNormaliser"), Messages .getString("BaseStep.TypeTooltipDesc.RowNormaliser"), "NRM.png", CATEGORY_TRANSFORM), new StepPluginMeta(FieldSplitterMeta.class, "FieldSplitter", Messages.getString("BaseStep.TypeLongDesc.SplitFields"), Messages .getString("BaseStep.TypeTooltipDesc.SplitFields"), "SPL.png", CATEGORY_TRANSFORM), new StepPluginMeta(UniqueRowsMeta.class, "Unique", Messages.getString("BaseStep.TypeLongDesc.UniqueRows"), Messages.getString( "BaseStep.TypeTooltipDesc.Uniquerows", Const.CR, Const.CR), "UNQ.png", CATEGORY_TRANSFORM), new StepPluginMeta(GroupByMeta.class, "GroupBy", Messages.getString("BaseStep.TypeLongDesc.GroupBy"), Messages.getString( "BaseStep.TypeTooltipDesc.Groupby", Const.CR, Const.CR), "GRP.png", CATEGORY_TRANSFORM), new StepPluginMeta(RowsFromResultMeta.class, "RowsFromResult", Messages.getString("BaseStep.TypeLongDesc.GetRows"), Messages .getString("BaseStep.TypeTooltipDesc.GetRowsFromResult"), "FCH.png", CATEGORY_JOB), new StepPluginMeta(RowsToResultMeta.class, "RowsToResult", Messages.getString("BaseStep.TypeLongDesc.CopyRows"), Messages.getString( "BaseStep.TypeTooltipDesc.CopyRowsToResult", Const.CR), "TCH.png", CATEGORY_JOB), new StepPluginMeta(CubeInputMeta.class, "CubeInput", Messages.getString("BaseStep.TypeLongDesc.CubeInput"), Messages .getString("BaseStep.TypeTooltipDesc.Cubeinput"), "CIP.png", CATEGORY_INPUT), new StepPluginMeta(CubeOutputMeta.class, "CubeOutput", Messages.getString("BaseStep.TypeLongDesc.CubeOutput"), Messages .getString("BaseStep.TypeTooltipDesc.Cubeoutput"), "COP.png", CATEGORY_OUTPUT), new StepPluginMeta(DatabaseJoinMeta.class, "DBJoin", Messages.getString("BaseStep.TypeLongDesc.DatabaseJoin"), Messages .getString("BaseStep.TypeTooltipDesc.Databasejoin"), "DBJ.png", CATEGORY_JOINS), new StepPluginMeta(XBaseInputMeta.class, "XBaseInput", Messages.getString("BaseStep.TypeLongDesc.XBaseInput"), Messages .getString("BaseStep.TypeTooltipDesc.XBaseinput"), "XBI.png", CATEGORY_INPUT), new StepPluginMeta(ExcelInputMeta.class, "ExcelInput", Messages.getString("BaseStep.TypeLongDesc.ExcelInput"), Messages .getString("BaseStep.TypeTooltipDesc.ExcelInput"), "XLI.png", CATEGORY_INPUT), new StepPluginMeta(NullIfMeta.class, "NullIf", Messages.getString("BaseStep.TypeLongDesc.NullIf"), Messages .getString("BaseStep.TypeTooltipDesc.Nullif"), "NUI.png", CATEGORY_TRANSFORM), new StepPluginMeta(CalculatorMeta.class, "Calculator", Messages.getString("BaseStep.TypeLongDesc.Caculator"), Messages .getString("BaseStep.TypeTooltipDesc.Calculator"), "CLC.png", CATEGORY_TRANSFORM), new StepPluginMeta(ExecSQLMeta.class, "ExecSQL", Messages.getString("BaseStep.TypeLongDesc.ExcuteSQL"), Messages .getString("BaseStep.TypeTooltipDesc.ExecuteSQL"), "SQL.png", CATEGORY_SCRIPTING), new StepPluginMeta(MappingMeta.class, "Mapping", Messages.getString("BaseStep.TypeLongDesc.MappingSubTransformation"), Messages .getString("BaseStep.TypeTooltipDesc.MappingSubTransformation"), "MAP.png", CATEGORY_MAPPING), new StepPluginMeta(MappingInputMeta.class, "MappingInput", Messages.getString("BaseStep.TypeLongDesc.MappingInput"), Messages .getString("BaseStep.TypeTooltipDesc.MappingInputSpecification"), "MPI.png", CATEGORY_MAPPING), new StepPluginMeta(MappingOutputMeta.class, "MappingOutput", Messages.getString("BaseStep.TypeLongDesc.MappingOutput"), Messages .getString("BaseStep.TypeTooltipDesc.MappingOutputSpecification"), "MPO.png", CATEGORY_MAPPING), new StepPluginMeta(XMLInputMeta.class, "XMLInput", Messages.getString("BaseStep.TypeLongDesc.XMLInput"), Messages .getString("BaseStep.TypeTooltipDesc.XMLInput"), "XIN.png", CATEGORY_INPUT), new StepPluginMeta(XMLInputSaxMeta.class, "XMLInputSax", Messages.getString("BaseStep.TypeLongDesc.XMLInputSax"), Messages .getString("BaseStep.TypeTooltipDesc.XMLInputSax"), "XIS.png", CATEGORY_INPUT), new StepPluginMeta(XMLOutputMeta.class, "XMLOutput", Messages.getString("BaseStep.TypeLongDesc.XMLOutput"), Messages .getString("BaseStep.TypeTooltipDesc.XMLOutput"), "XOU.png", CATEGORY_OUTPUT), new StepPluginMeta(AddXMLMeta.class, "AddXML", Messages.getString("BaseStep.TypeLongDesc.AddXML"), Messages .getString("BaseStep.TypeTooltipDesc.AddXML"), "XIN.png", CATEGORY_TRANSFORM), new StepPluginMeta(MergeRowsMeta.class, "MergeRows", Messages.getString("BaseStep.TypeLongDesc.MergeRows"), Messages .getString("BaseStep.TypeTooltipDesc.MergeRows"), "MRG.png", CATEGORY_JOINS), new StepPluginMeta(ConstantMeta.class, "Constant", Messages.getString("BaseStep.TypeLongDesc.AddConstants"), Messages .getString("BaseStep.TypeTooltipDesc.Addconstants"), "CST.png", CATEGORY_TRANSFORM), new StepPluginMeta(DenormaliserMeta.class, "Denormaliser", Messages.getString("BaseStep.TypeLongDesc.RowDenormaliser"), Messages .getString("BaseStep.TypeTooltipDesc.RowsDenormalises", Const.CR), "UNP.png", CATEGORY_TRANSFORM), new StepPluginMeta(FlattenerMeta.class, new String[] { "Flattener", "Flatterner" }, Messages .getString("BaseStep.TypeLongDesc.RowFalttener"), Messages.getString("BaseStep.TypeTooltipDesc.Rowflattener"), "FLA.png", CATEGORY_TRANSFORM), new StepPluginMeta(ValueMapperMeta.class, "ValueMapper", Messages.getString("BaseStep.TypeLongDesc.ValueMapper"), Messages .getString("BaseStep.TypeTooltipDesc.MapValues"), "VMP.png", CATEGORY_TRANSFORM), new StepPluginMeta(SetVariableMeta.class, "SetVariable", Messages.getString("BaseStep.TypeLongDesc.SetVariable"), Messages .getString("BaseStep.TypeTooltipDesc.SetVariable"), "SVA.png", CATEGORY_JOB), new StepPluginMeta(GetVariableMeta.class, "GetVariable", Messages.getString("BaseStep.TypeLongDesc.GetVariable"), Messages .getString("BaseStep.TypeTooltipDesc.GetVariable"), "GVA.png", CATEGORY_JOB), new StepPluginMeta(GetFileNamesMeta.class, "GetFileNames", Messages.getString("BaseStep.TypeLongDesc.GetFileNames"), Messages .getString("BaseStep.TypeTooltipDesc.GetFileNames"), "GFN.png", CATEGORY_INPUT), new StepPluginMeta(FilesFromResultMeta.class, "FilesFromResult", Messages.getString("BaseStep.TypeLongDesc.FilesFromResult"), Messages .getString("BaseStep.TypeTooltipDesc.FilesFromResult"), "FFR.png", CATEGORY_JOB), new StepPluginMeta(FilesToResultMeta.class, "FilesToResult", Messages.getString("BaseStep.TypeLongDesc.FilesToResult"), Messages .getString("BaseStep.TypeTooltipDesc.FilesToResult"), "FTR.png", CATEGORY_JOB), new StepPluginMeta(BlockingStepMeta.class, "BlockingStep", Messages.getString("BaseStep.TypeLongDesc.BlockingStep"), Messages .getString("BaseStep.TypeTooltipDesc.BlockingStep"), "BLK.png", CATEGORY_TRANSFORM), new StepPluginMeta(InjectorMeta.class, "Injector", Messages.getString("BaseStep.TypeLongDesc.Injector"), Messages .getString("BaseStep.TypeTooltipDesc.Injector"), "INJ.png", CATEGORY_INLINE), new StepPluginMeta(ExcelOutputMeta.class, "ExcelOutput", Messages.getString("BaseStep.TypeLongDesc.ExcelOutput"), Messages .getString("BaseStep.TypeTooltipDesc.ExcelOutput"), "XLO.png", CATEGORY_OUTPUT), new StepPluginMeta(AccessOutputMeta.class, "AccessOutput", Messages.getString("BaseStep.TypeLongDesc.AccessOutput"), Messages .getString("BaseStep.TypeTooltipDesc.AccessOutput"), "ACO.png", CATEGORY_OUTPUT), new StepPluginMeta(SortedMergeMeta.class, "SortedMerge", Messages.getString("BaseStep.TypeLongDesc.SortedMerge"), Messages .getString("BaseStep.TypeTooltipDesc.SortedMerge"), "SMG.png", CATEGORY_JOINS), new StepPluginMeta(MergeJoinMeta.class, "MergeJoin", Messages.getString("BaseStep.TypeLongDesc.MergeJoin"), Messages .getString("BaseStep.TypeTooltipDesc.MergeJoin"), "MJOIN.png", CATEGORY_JOINS), new StepPluginMeta(SocketReaderMeta.class, "SocketReader", Messages.getString("BaseStep.TypeLongDesc.SocketReader"), Messages .getString("BaseStep.TypeTooltipDesc.SocketReader"), "SKR.png", CATEGORY_INLINE), new StepPluginMeta(SocketWriterMeta.class, "SocketWriter", Messages.getString("BaseStep.TypeLongDesc.SocketWriter"), Messages .getString("BaseStep.TypeTooltipDesc.SocketWriter"), "SKW.png", CATEGORY_INLINE), new StepPluginMeta(HTTPMeta.class, "HTTP", Messages.getString("BaseStep.TypeLongDesc.HTTP"), Messages .getString("BaseStep.TypeTooltipDesc.HTTP"), "WEB.png", CATEGORY_LOOKUP), new StepPluginMeta(WebServiceMeta.class, "WebServiceLookup", Messages.getString("BaseStep.TypeLongDesc.WebServiceLookup"), Messages .getString("BaseStep.TypeTooltipDesc.WebServiceLookup"), "WSL.png", CATEGORY_EXPERIMENTAL), new StepPluginMeta(FormulaMeta.class, "Formula", Messages.getString("BaseStep.TypeLongDesc.Formula"), Messages .getString("BaseStep.TypeTooltipDesc.Formula"), "FRM.png", CATEGORY_EXPERIMENTAL), new StepPluginMeta(AbortMeta.class, "Abort", Messages.getString("BaseStep.TypeLongDesc.Abort"), Messages .getString("BaseStep.TypeTooltipDesc.Abort"), "ABR.png", CATEGORY_TRANSFORM), new StepPluginMeta(OraBulkLoaderMeta.class, "OraBulkLoader", Messages.getString("BaseStep.TypeLongDesc.OraBulkLoader"), Messages .getString("BaseStep.TypeTooltipDesc.OraBulkLoader"), "OBL.png", CATEGORY_EXPERIMENTAL), new StepPluginMeta(XMLInputPathMeta.class, "XMLInputPath", Messages.getString("BaseStep.TypeLongDesc.XMLInputPath"), Messages .getString("BaseStep.TypeTooltipDesc.XMLInputPath"), "XMP.png", CATEGORY_EXPERIMENTAL), }; public static final String category_order[] = { CATEGORY_INPUT, CATEGORY_OUTPUT, CATEGORY_LOOKUP, CATEGORY_TRANSFORM, CATEGORY_JOINS, CATEGORY_SCRIPTING, CATEGORY_DATA_WAREHOUSE, CATEGORY_MAPPING, CATEGORY_JOB, CATEGORY_INLINE, CATEGORY_EXPERIMENTAL, CATEGORY_DEPRECATED, }; private static final int MIN_PRIORITY = 1; private static final int LOW_PRIORITY = 3; private static final int NORMAL_PRIORITY = 5; private static final int HIGH_PRIORITY = 7; private static final int MAX_PRIORITY = 10; public static final String[] statusDesc = { Messages.getString("BaseStep.status.Empty"), Messages.getString("BaseStep.status.Init"), Messages.getString("BaseStep.status.Running"), Messages.getString("BaseStep.status.Idle"), Messages.getString("BaseStep.status.Finished"), Messages.getString("BaseStep.status.Stopped"), Messages.getString("BaseStep.status.Disposed"), Messages.getString("BaseStep.status.Halted"), }; private TransMeta transMeta; private StepMeta stepMeta; private String stepname; protected LogWriter log; private Trans trans; public ArrayList previewBuffer; public int previewSize; /** nr of lines read from previous step(s) */ public long linesRead; /** nr of lines written to next step(s) */ public long linesWritten; /** nr of lines read from file or database */ public long linesInput; /** nr of lines written to file or database */ public long linesOutput; /** nr of updates in a database table or file */ public long linesUpdated; /** nr of lines skipped */ public long linesSkipped; /** total sleep time in ns caused by an empty input buffer (previous step is slow) */ public long linesRejected; /** total sleep time in ns caused by an empty input buffer (previous step is slow) */ private long nrGetSleeps; /** total sleep time in ns cause by a full output buffer (next step is slow) */ private long nrPutSleeps; private boolean distributed; private long errors; private StepMeta nextSteps[]; private StepMeta prevSteps[]; private int in_handling, out_handling; public ArrayList thr; /** The rowsets on the input, size() == nr of source steps */ public List inputRowSets; /** the rowsets on the output, size() == nr of target steps */ public List outputRowSets; /** the rowset for the error rows */ public RowSet errorRowSet; public boolean stopped; public boolean waiting; public boolean init; /** the copy number of this thread */ private int stepcopy; /** the output rowset nr, for fixed input channels like Stream Lookup */ private int output_rowset_nr; private Date start_time, stop_time; public boolean first; public boolean terminator; public ArrayList terminator_rows; private StepMetaInterface stepMetaInterface; private StepDataInterface stepDataInterface; /** The list of RowListener interfaces */ private List rowListeners; /** * Map of files that are generated or used by this step. After execution, these can be added to result. * The entry to the map is the filename */ private Map resultFiles; /** * Set this to true if you want to have extra checking enabled on the rows that are entering this step. All too * often people send in bugs when it is really the mixing of different types of rows that is causing the problem. */ private boolean safeModeEnabled; /** * This contains the first row received and will be the reference row. We used it to perform extra checking: see if * we don't get rows with "mixed" contents. */ private Row referenceRow; /** * This field tells the putRow() method that we are in partitioned mode */ private boolean partitioned; /** * The partition ID at which this step copy runs, or null if this step is not running partitioned. */ private String partitionID; /** * This field tells the putRow() method to re-partition the incoming data, See also StepPartitioningMeta.PARTITIONING_METHOD_* */ private int repartitioning; /** * True if the step needs to perform a sorted merge on the incoming partitioned data */ private boolean partitionMerging; /** * The index of the column to partition or -1 if not known yet (before first row) */ private int partitionColumnIndex; /** * The partitionID to rowset mapping */ private Map partitionTargets; /** * Cache for the partition IDs */ private static String[] partitionIDs; /** * step partitioning information of the NEXT step */ private static StepPartitioningMeta nextStepPartitioningMeta; /** * This is the base step that forms that basis for all steps. You can derive from this class to implement your own * steps. * * @param stepMeta The StepMeta object to run. * @param stepDataInterface the data object to store temporary data, database connections, caches, result sets, * hashtables etc. * @param copyNr The copynumber for this step. * @param transMeta The TransInfo of which the step stepMeta is part of. * @param trans The (running) transformation to obtain information shared among the steps. */ public BaseStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { log = LogWriter.getInstance(); this.stepMeta = stepMeta; this.stepDataInterface = stepDataInterface; this.stepcopy = copyNr; this.transMeta = transMeta; this.trans = trans; this.stepname = stepMeta.getName(); // Set the name of the thread if (stepMeta.getName() != null) { setName(toString() + " (" + super.getName() + ")"); } else { throw new RuntimeException("A step in transformation [" + transMeta.toString() + "] doesn't have a name. A step should always have a name to identify it by."); } first = true; stopped = false; init = false; linesRead = 0L; // Keep some statistics! linesWritten = 0L; linesUpdated = 0L; linesSkipped = 0L; nrGetSleeps = 0L; nrPutSleeps = 0L; inputRowSets = null; outputRowSets = null; nextSteps = null; terminator = stepMeta.hasTerminator(); if (terminator) { terminator_rows = new ArrayList(); } else { terminator_rows = null; } // debug="-"; //$NON-NLS-1$ output_rowset_nr = -1; start_time = null; stop_time = null; distributed = stepMeta.isDistributes(); if (distributed) if (log.isDetailed()) logDetailed(Messages.getString("BaseStep.Log.DistributionActivated")); //$NON-NLS-1$ else if (log.isDetailed()) logDetailed(Messages.getString("BaseStep.Log.DistributionDeactivated")); //$NON-NLS-1$ rowListeners = new ArrayList(); resultFiles = new Hashtable(); repartitioning = StepPartitioningMeta.PARTITIONING_METHOD_NONE; partitionColumnIndex = -1; partitionTargets = new Hashtable(); dispatch(); } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { sdi.setStatus(StepDataInterface.STATUS_INIT); return true; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { sdi.setStatus(StepDataInterface.STATUS_DISPOSED); } public long getProcessed() { return linesRead; } public void setCopy(int cop) { stepcopy = cop; } /** * @return The steps copy number (default 0) */ public int getCopy() { return stepcopy; } public long getErrors() { return errors; } public void setErrors(long e) { errors = e; } /** * @return Returns the linesInput. */ public long getLinesInput() { return linesInput; } /** * @return Returns the linesOutput. */ public long getLinesOutput() { return linesOutput; } /** * @return Returns the linesRead. */ public long getLinesRead() { return linesRead; } /** * @return Returns the linesWritten. */ public long getLinesWritten() { return linesWritten; } /** * @return Returns the linesUpdated. */ public long getLinesUpdated() { return linesUpdated; } public String getStepname() { return stepname; } public void setStepname(String stepname) { this.stepname = stepname; } public Trans getDispatcher() { return trans; } public String getStatusDescription() { return statusDesc[getStatus()]; } /** * @return Returns the stepMetaInterface. */ public StepMetaInterface getStepMetaInterface() { return stepMetaInterface; } /** * @param stepMetaInterface The stepMetaInterface to set. */ public void setStepMetaInterface(StepMetaInterface stepMetaInterface) { this.stepMetaInterface = stepMetaInterface; } /** * @return Returns the stepDataInterface. */ public StepDataInterface getStepDataInterface() { return stepDataInterface; } /** * @param stepDataInterface The stepDataInterface to set. */ public void setStepDataInterface(StepDataInterface stepDataInterface) { this.stepDataInterface = stepDataInterface; } /** * @return Returns the stepMeta. */ public StepMeta getStepMeta() { return stepMeta; } /** * @param stepMeta The stepMeta to set. */ public void setStepMeta(StepMeta stepMeta) { this.stepMeta = stepMeta; } /** * @return Returns the transMeta. */ public TransMeta getTransMeta() { return transMeta; } /** * @param transMeta The transMeta to set. */ public void setTransMeta(TransMeta transMeta) { this.transMeta = transMeta; } /** * @return Returns the trans. */ public Trans getTrans() { return trans; } /** * putRow is used to copy a row, to the alternate rowset(s) This should get priority over everything else! * (synchronized) If distribute is true, a row is copied only once to the output rowsets, otherwise copies are sent * to each rowset! * * @param row The row to put to the destination rowset(s). * @throws KettleStepException */ public synchronized void putRow(Row row) throws KettleStepException { // Have all threads started? // Are we running yet? If not, wait a bit until all threads have been started. while (!trans.isRunning() && !stopped) { try { Thread.sleep(1); } catch (InterruptedException e) { } } if (previewSize > 0 && previewBuffer.size() < previewSize) { previewBuffer.add(new Row(row)); } // call all rowlisteners... for (int i = 0; i < rowListeners.size(); i++) { RowListener rowListener = (RowListener) rowListeners.get(i); rowListener.rowWrittenEvent(row); } // Keep adding to terminator_rows buffer... if (terminator && terminator_rows != null) { terminator_rows.add(new Row(row)); } if (outputRowSets.isEmpty()) { // No more output rowsets! return; // we're done here! } // Before we copy this row to output, wait for room... for (int i = 0; i < outputRowSets.size(); i++) // Wait for all rowsets: keep synchronised! { int sleeptime = transMeta.getSleepTimeFull(); RowSet rs = (RowSet) outputRowSets.get(i); // Set the priority every 128k rows only if (transMeta.isUsingThreadPriorityManagment()) { if (linesWritten>0 && (linesWritten & 0xFF) == 0) { rs.setPriorityFrom(calcPutPriority(rs)); } } while (rs.isFull() && !stopped) { try { if (sleeptime > 0) { sleep(0, sleeptime); } else { super.notifyAll(); } } catch (Exception e) { logError(Messages.getString("BaseStep.Log.ErrorInThreadSleeping") + e.toString()); //$NON-NLS-1$ setErrors(1); stopAll(); return; } nrPutSleeps += sleeptime; if (sleeptime < 100) sleeptime = ((int) (sleeptime * 1.2)) + 1; else sleeptime = 100; } } if (stopped) { if (log.isDebug()) logDebug(Messages.getString("BaseStep.Log.StopPuttingARow")); //$NON-NLS-1$ stopAll(); return; } // Repartitioning happens when the current step is not partitioned, but the next one is. // That means we need to look up the partitioning information in the next step.. // If there are multiple steps, we need to look at the first (they should be all the same) // TODO: make something smart later to allow splits etc. switch(repartitioning) { case StepPartitioningMeta.PARTITIONING_METHOD_MOD: { // Do some pre-processing on the first row... // This is only done once and should cost very little in terms of processing time. if (partitionColumnIndex < 0) { StepMeta nextSteps[] = transMeta.getNextSteps(stepMeta); if (nextSteps == null || nextSteps.length == 0) { throw new KettleStepException( "Re-partitioning is enabled but no next steps could be found: developer error!"); } // Take the partitioning logic from one of the next steps nextStepPartitioningMeta = nextSteps[0].getStepPartitioningMeta(); // What's the column index of the partitioning fieldname? partitionColumnIndex = row.searchValueIndex(nextStepPartitioningMeta.getFieldName()); if (partitionColumnIndex < 0) { throw new KettleStepException("Unable to find partitioning field name [" + nextStepPartitioningMeta.getFieldName() + "] in the output row : " + row); } // Cache the partition IDs as well... partitionIDs = nextSteps[0].getStepPartitioningMeta().getPartitionSchema().getPartitionIDs(); // OK, we also want to cache the target rowset // We know that we have to partition in N pieces // We should also have N rowsets to the next step // This is always the case, wheter the target is partitioned or not. // So what we do is now count the number of rowsets // And we take the steps copy nr to map. // It's simple for the time being. // P1 : MOD(field,N)==0 // P2 : MOD(field,N)==1 // PN : MOD(field,N)==N-1 for (int r = 0; r < outputRowSets.size(); r++) { RowSet rowSet = (RowSet) outputRowSets.get(r); if (rowSet.getOriginStepName().equalsIgnoreCase(getStepname()) && rowSet.getOriginStepCopy() == getCopy()) { // Find the target step metadata StepMeta targetStep = transMeta.findStep(rowSet.getDestinationStepName()); // What are the target partition ID's String targetPartitions[] = targetStep.getStepPartitioningMeta().getPartitionSchema().getPartitionIDs(); // The target partitionID: String targetPartitionID = targetPartitions[rowSet.getDestinationStepCopy()]; // Save the mapping: if we want to know to which rowset belongs to a partition this is the place // to be. partitionTargets.put(targetPartitionID, rowSet); } } } // End of the one-time init code. // Here we go with the regular show int partitionNr = nextStepPartitioningMeta.getPartitionNr(row.getValue(partitionColumnIndex), partitionIDs.length); String targetPartition = partitionIDs[partitionNr]; // Put the row forward to the next step according to the partition rule. RowSet rs = (RowSet) partitionTargets.get(targetPartition); rs.putRow(row); linesWritten++; } break; case StepPartitioningMeta.PARTITIONING_METHOD_MIRROR: { // Copy always to all target steps/copies. for (int r = 0; r < outputRowSets.size(); r++) { RowSet rowSet = (RowSet) outputRowSets.get(r); rowSet.putRow(row); } } break; case StepPartitioningMeta.PARTITIONING_METHOD_NONE: { if (distributed) { // Copy the row to the "next" output rowset. // We keep the next one in out_handling RowSet rs = (RowSet) outputRowSets.get(out_handling); rs.putRow(row); linesWritten++; // Now determine the next output rowset! // Only if we have more then one output... if (outputRowSets.size() > 1) { out_handling++; if (out_handling >= outputRowSets.size()) out_handling = 0; } } else // Copy the row to all output rowsets! { // Copy to the row in the other output rowsets... for (int i = 1; i < outputRowSets.size(); i++) // start at 1 { RowSet rs = (RowSet) outputRowSets.get(i); rs.putRow(new Row(row)); } // set row in first output rowset RowSet rs = (RowSet) outputRowSets.get(0); rs.putRow(row); linesWritten++; } } break; } } /** * This version of getRow() only takes data from certain rowsets We select these rowsets that have name = step * Otherwise it's the same as the other one. * * @param row the row to send to the destination step * @param to the name of the step to send the row to */ public synchronized void putRowTo(Row row, String to) throws KettleStepException { output_rowset_nr = findOutputRowSetNumber(stepname, getCopy(), to, 0); if (output_rowset_nr < 0) { // No rowset found: normally it can't happen: // we deleted the rowset because it was // finished throw new KettleStepException(Messages.getString("BaseStep.Exception.UnableToFindRowset", to)); //$NON-NLS-1$ //$NON-NLS-2$ } putRowTo(row, output_rowset_nr); } /** * putRow is used to copy a row, to the alternate rowset(s) This should get priority over everything else! * (synchronized) If distribute is true, a a row is copied only once to a single output rowset! * * @param row The row to put to the destination rowsets. * @param output_rowset_nr the number of the rowset to put the row to. */ public synchronized void putRowTo(Row row, int output_rowset_nr) { int sleeptime; if (previewSize > 0 && previewBuffer.size() < previewSize) { previewBuffer.add(new Row(row)); } // call all rowlisteners... for (int i = 0; i < rowListeners.size(); i++) { RowListener rowListener = (RowListener) rowListeners.get(i); rowListener.rowWrittenEvent(row); } // Keep adding to terminator_rows buffer... if (terminator && terminator_rows != null) { terminator_rows.add(new Row(row)); } if (outputRowSets.isEmpty()) return; // nothing to do here! RowSet rs = (RowSet) outputRowSets.get(output_rowset_nr); sleeptime = transMeta.getSleepTimeFull(); while (rs.isFull() && !stopped) { try { if (sleeptime > 0) { sleep(0, sleeptime); } else { super.notifyAll(); } } catch (Exception e) { logError(Messages.getString("BaseStep.Log.ErrorInThreadSleeping") + e.toString()); //$NON-NLS-1$ setErrors(1); stopAll(); return; } nrPutSleeps += sleeptime; if (sleeptime < 100) sleeptime = ((int) (sleeptime * 1.2)) + 1; else sleeptime = 100; } if (stopped) { if (log.isDebug()) logDebug(Messages.getString("BaseStep.Log.StopPuttingARow")); //$NON-NLS-1$ stopAll(); return; } // Don't distribute or anything, only go to this rowset! rs.putRow(row); linesWritten++; } public synchronized void putError(Row row, long nrErrors, String errorDescriptions, String fieldNames, String errorCodes) { StepErrorMeta stepErrorMeta = stepMeta.getStepErrorMeta(); Row add = stepErrorMeta.getErrorFields(nrErrors, errorDescriptions, fieldNames, errorCodes); row.addRow(add); // call all rowlisteners... for (int i = 0; i < rowListeners.size(); i++) { RowListener rowListener = (RowListener) rowListeners.get(i); rowListener.errorRowWrittenEvent(row); } linesRejected++; if (errorRowSet!=null) errorRowSet.putRow(row); verifyRejectionRates(); } private void verifyRejectionRates() { StepErrorMeta stepErrorMeta = stepMeta.getStepErrorMeta(); if (stepErrorMeta==null) return; // nothing to verify. // Was this one error too much? if (stepErrorMeta.getMaxErrors()>0 && linesRejected>stepErrorMeta.getMaxErrors()) { logError(Messages.getString("BaseStep.Log.TooManyRejectedRows", Long.toString(stepErrorMeta.getMaxErrors()), Long.toString(linesRejected))); setErrors(1L); stopAll(); } if ( stepErrorMeta.getMaxPercentErrors()>0 && linesRejected>0 && ( stepErrorMeta.getMinPercentRows()<=0 || linesRead>=stepErrorMeta.getMinPercentRows()) ) { int pct = (int) (100 * linesRejected / linesRead ); if (pct>stepErrorMeta.getMaxPercentErrors()) { logError(Messages.getString("BaseStep.Log.MaxPercentageRejectedReached", Integer.toString(pct) ,Long.toString(linesRejected), Long.toString(linesRead))); setErrors(1L); stopAll(); } } } private synchronized RowSet currentInputStream() { return (RowSet) inputRowSets.get(in_handling); } /** * Find the next not-finished input-stream... in_handling says which one... */ private synchronized void nextInputStream() { int streams = inputRowSets.size(); // No more streams left: exit! if (streams == 0) return; // If we have some left: take the next! in_handling++; if (in_handling >= inputRowSets.size()) in_handling = 0; // logDebug("nextInputStream advanced to in_handling="+in_handling); } /** * In case of getRow, we receive data from previous steps through the input rowset. In case we split the stream, we * have to copy the data to the alternate splits: rowsets 1 through n. */ public synchronized Row getRow() throws KettleException { int sleeptime; int switches; // Have all threads started? // Are we running yet? If not, wait a bit until all threads have been started. while (!trans.isRunning() && !stopped) { try { Thread.sleep(1); } catch (InterruptedException e) { } } // If everything is finished, we can stop immediately! if (inputRowSets.isEmpty()) { return null; } // What's the current input stream? RowSet in = currentInputStream(); switches = 0; sleeptime = transMeta.getSleepTimeEmpty(); while (in.isEmpty() && !stopped) { // in : empty synchronized(in) { if (in.isEmpty() && in.isDone()) // nothing more here: remove it from input { inputRowSets.remove(in_handling); if (inputRowSets.isEmpty()) // nothing more to be found! { return null; } } } nextInputStream(); in = currentInputStream(); switches++; if (switches >= inputRowSets.size()) // every n looks, wait a bit! Don't use too much CPU! { switches = 0; try { if (sleeptime > 0) { sleep(0, sleeptime); } else { super.notifyAll(); } } catch (Exception e) { logError(Messages.getString("BaseStep.Log.SleepInterupted") + e.toString()); //$NON-NLS-1$ setErrors(1); stopAll(); return null; } if (sleeptime < 100) sleeptime = ((int) (sleeptime * 1.2)) + 1; else sleeptime = 100; nrGetSleeps += sleeptime; } } if (stopped) { if (log.isDebug()) logDebug(Messages.getString("BaseStep.Log.StopLookingForMoreRows")); //$NON-NLS-1$ stopAll(); return null; } // Set the appropriate priority depending on the amount of data in the rowset: // Only do this every 4096 rows... // Mmm, the less we do it, the faster the tests run, let's leave this out for now ;-) if (transMeta.isUsingThreadPriorityManagment()) { if (linesRead>0 && (linesRead & 0xFF) == 0) { in.setPriorityTo(calcGetPriority(in)); } } // Get this row! Row row = in.getRow(); linesRead++; // Notify all rowlisteners... for (int i = 0; i < rowListeners.size(); i++) { RowListener rowListener = (RowListener) rowListeners.get(i); rowListener.rowReadEvent(row); } nextInputStream(); // Look for the next input stream to get row from. // OK, before we return the row, let's see if we need to check on mixing row compositions... if (safeModeEnabled) { safeModeChecking(row); } // Extra checking // Check the rejection rates etc. as well. verifyRejectionRates(); return row; } protected synchronized void safeModeChecking(Row row) throws KettleRowException { // String saveDebug=debug; // debug="Safe mode checking"; if (referenceRow == null) { referenceRow = new Row(row); // copy it! // Check for double fieldnames. String[] fieldnames = row.getFieldNames(); Arrays.sort(fieldnames); for (int i=0;i<fieldnames.length-1;i++) { if (fieldnames[i].equals(fieldnames[i+1])) { throw new KettleRowException(Messages.getString("BaseStep.SafeMode.Exception.DoubleFieldnames", fieldnames[i])); } } } else { safeModeChecking(referenceRow, row); } // debug=saveDebug; } public static void safeModeChecking(Row referenceRow, Row row) throws KettleRowException { // See if the row we got has the same layout as the reference row. // First check the number of fields if (referenceRow.size() != row.size()) { throw new KettleRowException(Messages.getString("BaseStep.SafeMode.Exception.VaryingSize", ""+referenceRow.size(), ""+row.size(), row.toString())); } else { // Check field by field for the position of the names... for (int i = 0; i < referenceRow.size(); i++) { Value referenceValue = referenceRow.getValue(i); Value compareValue = row.getValue(i); if (!referenceValue.getName().equalsIgnoreCase(compareValue.getName())) { throw new KettleRowException(Messages.getString("BaseStep.SafeMode.Exception.MixingLayout", ""+(i+1), referenceValue.getName()+" "+referenceValue.toStringMeta(), compareValue.getName()+" "+compareValue.toStringMeta())); } if (referenceValue.getType()!=compareValue.getType()) { throw new KettleRowException(Messages.getString("BaseStep.SafeMode.Exception.MixingTypes", ""+(i+1), referenceValue.getName()+" "+referenceValue.toStringMeta(), compareValue.getName()+" "+compareValue.toStringMeta())); } } } } /** * This version of getRow() only takes data from certain rowsets We select these rowsets that have name = step * Otherwise it's the same as the other one. */ public synchronized Row getRowFrom(String from) { output_rowset_nr = findInputRowSetNumber(from, 0, stepname, 0); if (output_rowset_nr < 0) // No rowset found: normally it can't happen: we deleted the rowset because it was // finished { return null; } return getRowFrom(output_rowset_nr); } public synchronized Row getRowFrom(int input_rowset_nr) { // Read from one specific rowset int sleeptime = transMeta.getSleepTimeEmpty(); RowSet in = (RowSet) inputRowSets.get(input_rowset_nr); while (in.isEmpty() && !in.isDone() && !stopped) { try { if (sleeptime > 0) { sleep(0, sleeptime); } else { super.notifyAll(); } } catch (Exception e) { logError(Messages.getString("BaseStep.Log.SleepInterupted2", in.getOriginStepName()) + e.toString()); //$NON-NLS-1$ //$NON-NLS-2$ setErrors(1); stopAll(); return null; } nrGetSleeps += sleeptime; } if (stopped) { logError(Messages.getString("BaseStep.Log.SleepInterupted3", in.getOriginStepName())); //$NON-NLS-1$ //$NON-NLS-2$ stopAll(); return null; } if (in.isEmpty() && in.isDone()) { inputRowSets.remove(input_rowset_nr); return null; } Row row = in.getRow(); // Get this row! linesRead++; // call all rowlisteners... for (int i = 0; i < rowListeners.size(); i++) { RowListener rowListener = (RowListener) rowListeners.get(i); rowListener.rowWrittenEvent(row); } return row; } private synchronized int findInputRowSetNumber(String from, int fromcopy, String to, int tocopy) { int i; for (i = 0; i < inputRowSets.size(); i++) { RowSet rs = (RowSet) inputRowSets.get(i); if (rs.getOriginStepName().equalsIgnoreCase(from) && rs.getDestinationStepName().equalsIgnoreCase(to) && rs.getOriginStepCopy() == fromcopy && rs.getDestinationStepCopy() == tocopy) return i; } return -1; } private synchronized int findOutputRowSetNumber(String from, int fromcopy, String to, int tocopy) { int i; for (i = 0; i < outputRowSets.size(); i++) { RowSet rs = (RowSet) outputRowSets.get(i); if (rs.getOriginStepName().equalsIgnoreCase(from) && rs.getDestinationStepName().equalsIgnoreCase(to) && rs.getOriginStepCopy() == fromcopy && rs.getDestinationStepCopy() == tocopy) return i; } return -1; } // We have to tell the next step we're finished with // writing to output rowset(s)! public synchronized void setOutputDone() { if (log.isDebug()) logDebug(Messages.getString("BaseStep.Log.OutputDone", String.valueOf(outputRowSets.size()))); //$NON-NLS-1$ //$NON-NLS-2$ synchronized(outputRowSets) { for (int i = 0; i < outputRowSets.size(); i++) { RowSet rs = (RowSet) outputRowSets.get(i); rs.setDone(); } if (errorRowSet!=null) errorRowSet.setDone(); } } /** * This method finds the surrounding steps and rowsets for this base step. This steps keeps it's own list of rowsets * (etc.) to prevent it from having to search every time. */ public void dispatch() { if (transMeta == null) // for preview reasons, no dispatching is done! { return; } StepMeta stepMeta = transMeta.findStep(stepname); if (log.isDetailed()) logDetailed(Messages.getString("BaseStep.Log.StartingBuffersAllocation")); //$NON-NLS-1$ // How many next steps are there? 0, 1 or more?? // How many steps do we send output to? int nrInput = transMeta.findNrPrevSteps(stepMeta, true); int nrOutput = transMeta.findNrNextSteps(stepMeta); inputRowSets = Collections.synchronizedList( new ArrayList() ); // new RowSet[nrinput]; outputRowSets = Collections.synchronizedList( new ArrayList() ); // new RowSet[nroutput+out_copies]; errorRowSet = null; prevSteps = new StepMeta[nrInput]; nextSteps = new StepMeta[nrOutput]; in_handling = 0; // we start with input[0]; logDetailed(Messages.getString("BaseStep.Log.StepInfo", String.valueOf(nrInput), String.valueOf(nrOutput))); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < nrInput; i++) { prevSteps[i] = transMeta.findPrevStep(stepMeta, i, true); // sir.getHopFromWithTo(stepname, i); logDetailed(Messages.getString("BaseStep.Log.GotPreviousStep", stepname, String.valueOf(i), prevSteps[i].getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Looking at the previous step, you can have either 1 rowset to look at or more then one. int prevCopies = prevSteps[i].getCopies(); int nextCopies = stepMeta.getCopies(); logDetailed(Messages.getString("BaseStep.Log.InputRowInfo", String.valueOf(prevCopies), String.valueOf(nextCopies))); //$NON-NLS-1$ //$NON-NLS-2$ int nrCopies; int dispatchType; if (prevCopies == 1 && nextCopies == 1) { dispatchType = Trans.TYPE_DISP_1_1; nrCopies = 1; } else { if (prevCopies == 1 && nextCopies > 1) { dispatchType = Trans.TYPE_DISP_1_N; nrCopies = 1; } else { if (prevCopies > 1 && nextCopies == 1) { dispatchType = Trans.TYPE_DISP_N_1; nrCopies = prevCopies; } else { if (prevCopies == nextCopies) { dispatchType = Trans.TYPE_DISP_N_N; nrCopies = 1; } else { dispatchType = Trans.TYPE_DISP_N_M; nrCopies = prevCopies; } } } } for (int c = 0; c < nrCopies; c++) { RowSet rowSet = null; switch (dispatchType) { case Trans.TYPE_DISP_1_1: rowSet = trans.findRowSet(prevSteps[i].getName(), 0, stepname, 0); break; case Trans.TYPE_DISP_1_N: rowSet = trans.findRowSet(prevSteps[i].getName(), 0, stepname, getCopy()); break; case Trans.TYPE_DISP_N_1: rowSet = trans.findRowSet(prevSteps[i].getName(), c, stepname, 0); break; case Trans.TYPE_DISP_N_N: rowSet = trans.findRowSet(prevSteps[i].getName(), getCopy(), stepname, getCopy()); break; case Trans.TYPE_DISP_N_M: rowSet = trans.findRowSet(prevSteps[i].getName(), c, stepname, getCopy()); break; } if (rowSet != null) { inputRowSets.add(rowSet); logDetailed(Messages.getString("BaseStep.Log.FoundInputRowset", rowSet.getName())); //$NON-NLS-1$ //$NON-NLS-2$ } else { logError(Messages.getString("BaseStep.Log.UnableToFindInputRowset")); //$NON-NLS-1$ setErrors(1); stopAll(); return; } } } // And now the output part! for (int i = 0; i < nrOutput; i++) { nextSteps[i] = transMeta.findNextStep(stepMeta, i); int prevCopies = stepMeta.getCopies(); int nextCopies = nextSteps[i].getCopies(); logDetailed(Messages.getString("BaseStep.Log.OutputRowInfo", String.valueOf(prevCopies), String.valueOf(nextCopies))); //$NON-NLS-1$ //$NON-NLS-2$ int nrCopies; int dispatchType; if (prevCopies == 1 && nextCopies == 1) { dispatchType = Trans.TYPE_DISP_1_1; nrCopies = 1; } else { if (prevCopies == 1 && nextCopies > 1) { dispatchType = Trans.TYPE_DISP_1_N; nrCopies = nextCopies; } else { if (prevCopies > 1 && nextCopies == 1) { dispatchType = Trans.TYPE_DISP_N_1; nrCopies = 1; } else { if (prevCopies == nextCopies) { dispatchType = Trans.TYPE_DISP_N_N; nrCopies = 1; } else { dispatchType = Trans.TYPE_DISP_N_M; nrCopies = nextCopies; } } } } for (int c = 0; c < nrCopies; c++) { RowSet rowSet = null; switch (dispatchType) { case Trans.TYPE_DISP_1_1: rowSet = trans.findRowSet(stepname, 0, nextSteps[i].getName(), 0); break; case Trans.TYPE_DISP_1_N: rowSet = trans.findRowSet(stepname, 0, nextSteps[i].getName(), c); break; case Trans.TYPE_DISP_N_1: rowSet = trans.findRowSet(stepname, getCopy(), nextSteps[i].getName(), 0); break; case Trans.TYPE_DISP_N_N: rowSet = trans.findRowSet(stepname, getCopy(), nextSteps[i].getName(), getCopy()); break; case Trans.TYPE_DISP_N_M: rowSet = trans.findRowSet(stepname, getCopy(), nextSteps[i].getName(), c); break; } if (rowSet != null) { outputRowSets.add(rowSet); logDetailed(Messages.getString("BaseStep.Log.FoundOutputRowset", rowSet.getName())); //$NON-NLS-1$ //$NON-NLS-2$ } else { logError(Messages.getString("BaseStep.Log.UnableToFindOutputRowset")); //$NON-NLS-1$ setErrors(1); stopAll(); return; } } } logDetailed(Messages.getString("BaseStep.Log.FinishedDispatching")); //$NON-NLS-1$ } public void logMinimal(String s) { log.println(LogWriter.LOG_LEVEL_MINIMAL, stepname + "." + stepcopy, s); //$NON-NLS-1$ } public void logBasic(String s) { log.println(LogWriter.LOG_LEVEL_BASIC, stepname + "." + stepcopy, s); //$NON-NLS-1$ } public void logError(String s) { log.println(LogWriter.LOG_LEVEL_ERROR, stepname + "." + stepcopy, s); //$NON-NLS-1$ } public void logDetailed(String s) { log.println(LogWriter.LOG_LEVEL_DETAILED, stepname + "." + stepcopy, s); //$NON-NLS-1$ } public void logDebug(String s) { log.println(LogWriter.LOG_LEVEL_DEBUG, stepname + "." + stepcopy, s); //$NON-NLS-1$ } public void logRowlevel(String s) { log.println(LogWriter.LOG_LEVEL_ROWLEVEL, stepname + "." + stepcopy, s); //$NON-NLS-1$ } public int getNextClassNr() { int ret = trans.class_nr; trans.class_nr++; return ret; } public boolean outputIsDone() { int nrstopped = 0; RowSet rs; int i; for (i = 0; i < outputRowSets.size(); i++) { rs = (RowSet) outputRowSets.get(i); if (rs.isDone()) nrstopped++; } return nrstopped >= outputRowSets.size(); } public void stopAll() { stopped = true; trans.stopAll(); } public boolean isStopped() { return stopped; } public boolean isInitialising() { return init; } public void markStart() { Calendar cal = Calendar.getInstance(); start_time = cal.getTime(); setInternalVariables(); } public void setInternalVariables() { KettleVariables kettleVariables = KettleVariables.getNamedInstance(getName()); kettleVariables.setVariable(Const.INTERNAL_VARIABLE_STEP_NAME, stepname); kettleVariables.setVariable(Const.INTERNAL_VARIABLE_STEP_COPYNR, Integer.toString(getCopy())); // Also set the internal variable for the partition if (!Const.isEmpty(partitionID)) { kettleVariables.setVariable(Const.INTERNAL_VARIABLE_STEP_PARTITION_ID, partitionID); } } public void markStop() { Calendar cal = Calendar.getInstance(); stop_time = cal.getTime(); } public long getRuntime() { long lapsed; if (start_time != null && stop_time == null) { Calendar cal = Calendar.getInstance(); long now = cal.getTimeInMillis(); long st = start_time.getTime(); lapsed = now - st; } else if (start_time != null && stop_time != null) { lapsed = stop_time.getTime() - start_time.getTime(); } else { lapsed = 0; } return lapsed; } public Row buildLog(String sname, int copynr, long lines_read, long lines_written, long lines_updated, long lines_skipped, long errors, Value start_date, Value end_date) { Row r = new Row(); r.addValue(new Value(Messages.getString("BaseStep.ColumnName.Stepname"), sname)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.Copy"), (double) copynr)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesReaded"), (double) lines_read)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesWritten"), (double) lines_written)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesUpdated"), (double) lines_updated)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesSkipped"), (double) lines_skipped)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.Errors"), (double) errors)); //$NON-NLS-1$ r.addValue(start_date); r.addValue(end_date); return r; } public static final Row getLogFields(String comm) { Row r = new Row(); int i; Value sname = new Value(Messages.getString("BaseStep.ColumnName.Stepname"), ""); //$NON-NLS-1$ //$NON-NLS-2$ sname.setLength(256); r.addValue(sname); r.addValue(new Value(Messages.getString("BaseStep.ColumnName.Copy"), 0.0)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesReaded"), 0.0)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesWritten"), 0.0)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesUpdated"), 0.0)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesSkipped"), 0.0)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.Errors"), 0.0)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.StartDate"), Const.MIN_DATE)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.EndDate"), Const.MAX_DATE)); //$NON-NLS-1$ for (i = 0; i < r.size(); i++) { r.getValue(i).setOrigin(comm); } return r; } public String toString() { return stepname + "." + getCopy(); //$NON-NLS-1$ } public Thread getThread() { return this; } private int calcPutPriority(RowSet rs) { if (rs.size() > transMeta.getSizeRowset() * 0.95) return MIN_PRIORITY; if (rs.size() > transMeta.getSizeRowset() * 0.75) return LOW_PRIORITY; if (rs.size() > transMeta.getSizeRowset() * 0.50) return NORMAL_PRIORITY; if (rs.size() > transMeta.getSizeRowset() * 0.25) return HIGH_PRIORITY; return MAX_PRIORITY; } private int calcGetPriority(RowSet rs) { if (rs.size() > transMeta.getSizeRowset() * 0.95) return MAX_PRIORITY; if (rs.size() > transMeta.getSizeRowset() * 0.75) return HIGH_PRIORITY; if (rs.size() > transMeta.getSizeRowset() * 0.50) return NORMAL_PRIORITY; if (rs.size() > transMeta.getSizeRowset() * 0.25) return LOW_PRIORITY; return MIN_PRIORITY; } public int rowsetOutputSize() { int size = 0; int i; for (i = 0; i < outputRowSets.size(); i++) { size += ((RowSet) outputRowSets.get(i)).size(); } return size; } public int rowsetInputSize() { int size = 0; int i; for (i = 0; i < inputRowSets.size(); i++) { size += ((RowSet) inputRowSets.get(i)).size(); } return size; } /** * Create a new empty StepMeta class from the steploader * * @param stepplugin The step/plugin to use * @param steploader The StepLoader to load from * @return The requested class. */ public static final StepMetaInterface getStepInfo(StepPlugin stepplugin, StepLoader steploader) throws KettleStepLoaderException { return steploader.getStepClass(stepplugin); } public static final String getIconFilename(int steptype) { return steps[steptype].getImageFileName(); } /** * Perform actions to stop a running step. This can be stopping running SQL queries (cancel), etc. Default it * doesn't do anything. * * @param stepDataInterface The interface to the step data containing the connections, resultsets, open files, etc. * @throws KettleException in case something goes wrong * */ public void stopRunning(StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface) throws KettleException { } /** * Stops running operations This method is deprecated, please use the method specifying the metadata and data * interfaces. * * @deprecated */ public void stopRunning() { } public void logSummary() { logBasic(Messages.getString("BaseStep.Log.SummaryInfo", String.valueOf(linesInput), String.valueOf(linesOutput), String.valueOf(linesRead), String.valueOf(linesWritten), String.valueOf(linesUpdated), String.valueOf(errors+linesRejected))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ } public String getStepID() { if (stepMeta != null) return stepMeta.getStepID(); return null; } /** * @return Returns the inputRowSets. */ public List getInputRowSets() { return inputRowSets; } /** * @param inputRowSets The inputRowSets to set. */ public void setInputRowSets(ArrayList inputRowSets) { this.inputRowSets = inputRowSets; } /** * @return Returns the outputRowSets. */ public List getOutputRowSets() { return outputRowSets; } /** * @param outputRowSets The outputRowSets to set. */ public void setOutputRowSets(ArrayList outputRowSets) { this.outputRowSets = outputRowSets; } /** * @return Returns the distributed. */ public boolean isDistributed() { return distributed; } /** * @param distributed The distributed to set. */ public void setDistributed(boolean distributed) { this.distributed = distributed; } public void addRowListener(RowListener rowListener) { rowListeners.add(rowListener); } public void removeRowListener(RowListener rowListener) { rowListeners.remove(rowListener); } public List getRowListeners() { return rowListeners; } public void addResultFile(ResultFile resultFile) { resultFiles.put(resultFile.getFile().toString(), resultFile); } public Map getResultFiles() { return resultFiles; } /** * @return Returns the total sleep time in ns in case nothing was found in an input buffer for this step. */ public long getNrGetSleeps() { return nrGetSleeps; } /** * @param nrGetSleeps the total sleep time in ns in case nothing was found in an input buffer for this step. */ public void setNrGetSleeps(long nrGetSleeps) { this.nrGetSleeps = nrGetSleeps; } /** * @return Returns the total sleep time in ns in case the output buffer was full for this step. */ public long getNrPutSleeps() { return nrPutSleeps; } /** * @param nrPutSleeps the total sleep time in ns in case the output buffer was full for this step. */ public void setNrPutSleeps(long nrPutSleeps) { this.nrPutSleeps = nrPutSleeps; } /** * @return Returns true is this step is running in safe mode, with extra checking enabled... */ public boolean isSafeModeEnabled() { return safeModeEnabled; } /** * @param safeModeEnabled set to true is this step has to be running in safe mode, with extra checking enabled... */ public void setSafeModeEnabled(boolean safeModeEnabled) { this.safeModeEnabled = safeModeEnabled; } public int getStatus() { if (isAlive()) return StepDataInterface.STATUS_RUNNING; if (isStopped()) return StepDataInterface.STATUS_STOPPED; // Get the rest in StepDataInterface object: StepDataInterface sdi = trans.getStepDataInterface(stepname, stepcopy); if (sdi != null) { if (sdi.getStatus() == StepDataInterface.STATUS_DISPOSED && !isAlive()) return StepDataInterface.STATUS_FINISHED; return sdi.getStatus(); } return StepDataInterface.STATUS_EMPTY; } /** * @return the partitionID */ public String getPartitionID() { return partitionID; } /** * @param partitionID the partitionID to set */ public void setPartitionID(String partitionID) { this.partitionID = partitionID; } /** * @return the partitionTargets */ public Map getPartitionTargets() { return partitionTargets; } /** * @param partitionTargets the partitionTargets to set */ public void setPartitionTargets(Map partitionTargets) { this.partitionTargets = partitionTargets; } /** * @return the partitionColumnIndex */ public int getPartitionColumnIndex() { return partitionColumnIndex; } /** * @param partitionColumnIndex the partitionColumnIndex to set */ public void setPartitionColumnIndex(int partitionColumnIndex) { this.partitionColumnIndex = partitionColumnIndex; } /** * @return the repartitioning */ public int getRepartitioning() { return repartitioning; } /** * @param repartitioning the repartitioning to set */ public void setRepartitioning(int repartitioning) { this.repartitioning = repartitioning; } /** * @return the partitioned */ public boolean isPartitioned() { return partitioned; } /** * @param partitioned the partitioned to set */ public void setPartitioned(boolean partitioned) { this.partitioned = partitioned; } /** * @return the partitionMerging */ public boolean isPartitionMerging() { return partitionMerging; } /** * @param partitionMerging the partitionMerging to set */ public void setPartitionMerging(boolean partitionMerging) { this.partitionMerging = partitionMerging; } protected boolean checkFeedback(long lines) { return getTransMeta().isFeedbackShown() && (lines > 0) && (getTransMeta().getFeedbackSize() > 0) && (lines % getTransMeta().getFeedbackSize()) == 0; } /** * @return the linesRejected */ public long getLinesRejected() { return linesRejected; } /** * @param linesRejected the linesRejected to set */ public void setLinesRejected(long linesRejected) { this.linesRejected = linesRejected; } }
package io.spine.type; import com.google.common.base.Predicate; import com.google.common.collect.BiMap; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.protobuf.Any; import com.google.protobuf.Api; import com.google.protobuf.BoolValue; import com.google.protobuf.BytesValue; import com.google.protobuf.Descriptors; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.GenericDescriptor; import com.google.protobuf.DoubleValue; import com.google.protobuf.Duration; import com.google.protobuf.Empty; import com.google.protobuf.EnumValue; import com.google.protobuf.Field; import com.google.protobuf.FieldMask; import com.google.protobuf.FloatValue; import com.google.protobuf.GeneratedMessageV3; import com.google.protobuf.Int32Value; import com.google.protobuf.Int64Value; import com.google.protobuf.Internal.EnumLite; import com.google.protobuf.ListValue; import com.google.protobuf.Message; import com.google.protobuf.Method; import com.google.protobuf.Mixin; import com.google.protobuf.NullValue; import com.google.protobuf.Option; import com.google.protobuf.SourceContext; import com.google.protobuf.StringValue; import com.google.protobuf.Struct; import com.google.protobuf.Syntax; import com.google.protobuf.Timestamp; import com.google.protobuf.Type; import com.google.protobuf.UInt32Value; import com.google.protobuf.UInt64Value; import com.google.protobuf.Value; import io.spine.annotation.Internal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.Map; import java.util.Properties; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Maps.newHashMap; import static com.google.protobuf.DescriptorProtos.DescriptorProto; import static com.google.protobuf.DescriptorProtos.EnumDescriptorProto; import static com.google.protobuf.DescriptorProtos.EnumOptions; import static com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto; import static com.google.protobuf.DescriptorProtos.EnumValueOptions; import static com.google.protobuf.DescriptorProtos.FieldDescriptorProto; import static com.google.protobuf.DescriptorProtos.FieldOptions; import static com.google.protobuf.DescriptorProtos.FileDescriptorProto; import static com.google.protobuf.DescriptorProtos.FileDescriptorSet; import static com.google.protobuf.DescriptorProtos.FileOptions; import static com.google.protobuf.DescriptorProtos.GeneratedCodeInfo; import static com.google.protobuf.DescriptorProtos.MessageOptions; import static com.google.protobuf.DescriptorProtos.MethodDescriptorProto; import static com.google.protobuf.DescriptorProtos.MethodOptions; import static com.google.protobuf.DescriptorProtos.OneofDescriptorProto; import static com.google.protobuf.DescriptorProtos.ServiceDescriptorProto; import static com.google.protobuf.DescriptorProtos.ServiceOptions; import static com.google.protobuf.DescriptorProtos.SourceCodeInfo; import static com.google.protobuf.DescriptorProtos.UninterpretedOption; import static io.spine.io.IoUtil.loadAllProperties; import static io.spine.util.Exceptions.newIllegalStateException; /** * A map which contains all Protobuf types known to the application. * * @author Mikhail Mikhaylov * @author Alexander Yevsyukov * @author Alexander Litus */ @Internal public class KnownTypes { /** * The name of the file generated by the Spine model compiler, which contains * a map from a proto type URL to corresponding Java class name. * * <p>The file is generated during the build process of an application. */ private static final String PROPS_FILE_PATH = "known_types.properties"; /** * The separator character for package names in a fully qualified proto type name. */ private static final char PACKAGE_SEPARATOR = '.'; /** * A map from Protobuf type URL to Java class name. * * <p>For example, for a key {@code type.spine.io/spine.base.EventId}, * there will be the value {@code EventId}. */ private static final BiMap<TypeUrl, ClassName> knownTypes = Builder.build(); /** * A map from Protobuf type name to type URL. * * <p>For example, for a key {@code spine.base.EventId}, * there will be the value {@code type.spine.io/spine.base.EventId}. * * @see TypeUrl */ private static final ImmutableMap<String, TypeUrl> typeUrls = buildTypeToUrlMap(knownTypes); /** * The method name for obtaining a type descriptor from a Java message class. */ private static final String METHOD_GET_DESCRIPTOR = "getDescriptor"; private KnownTypes() { // Prevent instantiation of this utility class. } /** * Retrieves Protobuf type URLs known to the application. */ public static Set<TypeUrl> getAllUrls() { final Set<TypeUrl> result = knownTypes.keySet(); return ImmutableSet.copyOf(result); } /** * Retrieves a Java class name generated for the Protobuf type by its type url * to be used to parse {@link com.google.protobuf.Message Message} from {@link Any}. * * @param typeUrl {@link Any} type url * @return Java class name * @throws UnknownTypeException if there is no such type known to the application */ public static ClassName getClassName(TypeUrl typeUrl) throws UnknownTypeException { if (!knownTypes.containsKey(typeUrl)) { throw new UnknownTypeException(typeUrl.getTypeName()); } final ClassName result = knownTypes.get(typeUrl); return result; } public static TypeUrl getTypeUrl(ClassName className) { final TypeUrl result = knownTypes.inverse() .get(className); if (result == null) { throw newIllegalStateException("No Protobuf type URL found for the Java class %s", className); } return result; } /** Returns a Protobuf type URL by Protobuf type name. */ @Nullable static TypeUrl getTypeUrl(String typeName) { final TypeUrl typeUrl = typeUrls.get(typeName); return typeUrl; } /** * Retrieves all the types that belong to the given package or its subpackages. * * @param packageName proto package name * @return set of {@link TypeUrl TypeUrl}s of types that belong to the given package */ public static Set<TypeUrl> getAllFromPackage(final String packageName) { final Collection<TypeUrl> knownTypeUrls = knownTypes.keySet(); final Collection<TypeUrl> resultCollection = Collections2.filter( knownTypeUrls, new Predicate<TypeUrl>() { @Override public boolean apply(@Nullable TypeUrl input) { if (input == null) { return false; } final String typeName = input.getTypeName(); final boolean inPackage = typeName.startsWith(packageName) && typeName.charAt(packageName.length()) == PACKAGE_SEPARATOR; return inPackage; } }); final Set<TypeUrl> resultSet = ImmutableSet.copyOf(resultCollection); return resultSet; } private static ImmutableMap<String, TypeUrl> buildTypeToUrlMap(BiMap<TypeUrl, ClassName> knownTypes) { final ImmutableMap.Builder<String, TypeUrl> builder = ImmutableMap.builder(); for (TypeUrl typeUrl : knownTypes.keySet()) { builder.put(typeUrl.getTypeName(), typeUrl); } return builder.build(); } /** * Obtains a Java class for the passed type URL. * * @throws UnknownTypeException if there is no Java class for the passed type URL */ static <T extends Message> Class<T> getJavaClass(TypeUrl typeUrl) throws UnknownTypeException { checkNotNull(typeUrl); final ClassName className = getClassName(typeUrl); try { @SuppressWarnings("unchecked") // the client considers this message is of this class final Class<T> result = (Class<T>) Class.forName(className.value()); return result; } catch (ClassNotFoundException e) { throw new UnknownTypeException(typeUrl.getTypeName(), e); } } static GenericDescriptor getDescriptor(String typeName) { final TypeUrl typeUrl = getTypeUrl(typeName); checkArgument(typeUrl != null, "Given type name is invalid"); final Class<?> cls = getJavaClass(typeUrl); final GenericDescriptor descriptor; try { final java.lang.reflect.Method descriptorGetter = cls.getDeclaredMethod(METHOD_GET_DESCRIPTOR); descriptor = (GenericDescriptor) descriptorGetter.invoke(null); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw newIllegalStateException(e, "Unable to get descriptor for the type %s", typeName); } return descriptor; } /** The helper class for building internal immutable typeUrl-to-JavaClass map. */ private static class Builder { private final Map<TypeUrl, ClassName> resultMap = newHashMap(); private static ImmutableBiMap<TypeUrl, ClassName> build() { final Builder builder = new Builder() .addStandardProtobufTypes() .loadNamesFromProperties(); final ImmutableBiMap<TypeUrl, ClassName> result = ImmutableBiMap.copyOf(builder.resultMap); return result; } private Builder loadNamesFromProperties() { final Set<Properties> propertiesSet = loadAllProperties(PROPS_FILE_PATH); for (Properties properties : propertiesSet) { putProperties(properties); } return this; } private void putProperties(Properties properties) { final Set<String> typeUrls = properties.stringPropertyNames(); for (String typeUrlStr : typeUrls) { final TypeUrl typeUrl = TypeUrl.parse(typeUrlStr); final ClassName className = ClassName.of(properties.getProperty(typeUrlStr)); put(typeUrl, className); } } /** * Returns classes from the {@code com.google.protobuf} package that need to be present * in the result map. * * <p>This method needs to be updated with introduction of new Google Protobuf types * after they are used in the framework. */ @SuppressWarnings("OverlyLongMethod") // OK as there are many types in Protobuf and we want to keep this code in one place. private Builder addStandardProtobufTypes() { // Types from `any.proto`. put(Any.class); // Types from `api.proto` put(Api.class); put(Method.class); put(Mixin.class); // Types from `descriptor.proto` put(FileDescriptorSet.class); put(FileDescriptorProto.class); put(DescriptorProto.class); // Inner types of `DescriptorProto` put(DescriptorProto.ExtensionRange.class); put(DescriptorProto.ReservedRange.class); put(FieldDescriptorProto.class); putEnum(FieldDescriptorProto.Type.getDescriptor(), FieldDescriptorProto.Type.class); putEnum(FieldDescriptorProto.Label.getDescriptor(), FieldDescriptorProto.Label.class); put(OneofDescriptorProto.class); put(EnumDescriptorProto.class); put(EnumValueDescriptorProto.class); put(ServiceDescriptorProto.class); put(MethodDescriptorProto.class); put(FileOptions.class); putEnum(FileOptions.OptimizeMode.getDescriptor(), FileOptions.OptimizeMode.class); put(MessageOptions.class); put(FieldOptions.class); putEnum(FieldOptions.CType.getDescriptor(), FieldOptions.CType.class); putEnum(FieldOptions.JSType.getDescriptor(), FieldOptions.JSType.class); put(EnumOptions.class); put(EnumValueOptions.class); put(ServiceOptions.class); put(MethodOptions.class); put(UninterpretedOption.class); put(SourceCodeInfo.class); // Inner types of `SourceCodeInfo`. put(SourceCodeInfo.Location.class); put(GeneratedCodeInfo.class); // Inner types of `GeneratedCodeInfo`. put(GeneratedCodeInfo.Annotation.class); // Types from `duration.proto`. put(Duration.class); // Types from `empty.proto`. put(Empty.class); // Types from `field_mask.proto`. put(FieldMask.class); // Types from `source_context.proto`. put(SourceContext.class); // Types from `struct.proto`. put(Struct.class); put(Value.class); putEnum(NullValue.getDescriptor(), NullValue.class); put(ListValue.class); // Types from `timestamp.proto`. put(Timestamp.class); // Types from `type.proto`. put(Type.class); put(Field.class); putEnum(Field.Kind.getDescriptor(), Field.Kind.class); putEnum(Field.Cardinality.getDescriptor(), Field.Cardinality.class); put(com.google.protobuf.Enum.class); put(EnumValue.class); put(Option.class); putEnum(Syntax.getDescriptor(), Syntax.class); // Types from `wrappers.proto`. put(DoubleValue.class); put(FloatValue.class); put(Int64Value.class); put(UInt64Value.class); put(Int32Value.class); put(UInt32Value.class); put(BoolValue.class); put(StringValue.class); put(BytesValue.class); return this; } private void put(Class<? extends GeneratedMessageV3> clazz) { final TypeUrl typeUrl = TypeUrl.of(clazz); final ClassName className = ClassName.of(clazz); put(typeUrl, className); } private void putEnum(EnumDescriptor desc, Class<? extends EnumLite> enumClass) { final TypeUrl typeUrl = TypeUrl.from(desc); final ClassName className = ClassName.of(enumClass); put(typeUrl, className); } private void put(TypeUrl typeUrl, ClassName className) { if (resultMap.containsKey(typeUrl)) { // No worries; // probably `task.descriptorSetOptions.includeImports` is set to `true`. return; } resultMap.put(typeUrl, className); } private static Logger log() { return LogSingleton.INSTANCE.value; } private enum LogSingleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Logger value = LoggerFactory.getLogger(KnownTypes.class); } } }
package ca.ipredict.database; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import ca.ipredict.predictor.profile.Profile; public class SequenceDatabase { private List<Sequence> sequences = new ArrayList<Sequence>(); public SequenceDatabase() { } //Setter public void setSequences(List<Sequence> newSequences) { this.sequences = new ArrayList<Sequence>(newSequences); } //Getter public List<Sequence> getSequences() { return sequences; } public int size() { return sequences.size(); } public void clear() { sequences.clear(); } public void loadFileCustomFormat(String filepath, int maxCount, int minSize, int maxSize) throws IOException { String line; BufferedReader reader = null; try { //Opening the file reader = new BufferedReader(new FileReader(filepath)); //For each line in the files -- up to the end of the file or the max number of sequences int count = 0; while( (line = reader.readLine()) != null && count < maxCount) { //Spliting into items String[] split = line.split(" "); //Checks the size requirements of this sequence if(split.length >= minSize && split.length <= maxSize ) { Sequence sequence = new Sequence(-1); for (String value : split) { Item item = new Item(Integer.valueOf(value)); //adding current val to current sequence sequence.addItem(item); } //Saving the sequence sequences.add(sequence); count++; } } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } } } public void loadFileBMSFormat(String filepath, int maxCount, int minSize, int maxSize) throws IOException { String thisLine; BufferedReader myInput = null; try { FileInputStream fin = new FileInputStream(new File(filepath)); myInput = new BufferedReader(new InputStreamReader(fin)); int lastId = 0; int count = 0; Sequence sequence = null; //current sequence while ((thisLine = myInput.readLine()) != null && count < maxCount) { //until end of file String[] split = thisLine.split(" "); int id = Integer.parseInt(split[0]); int val = Integer.parseInt(split[1]); if(lastId != id){ //if new sequence if(lastId !=0 && sequence.size() >= minSize && sequence.size() <= maxSize ){ //adding last sequence to sequences list sequences.add(sequence); count++; } sequence = new Sequence(id); //creating new sequence with current id lastId = id; } Item item = new Item(val); //adding current val to current sequence sequence.addItem(item); } } catch (Exception e) { e.printStackTrace(); } finally { if (myInput != null) { myInput.close(); } } } public void loadFileFIFAFormat(String filepath, int maxCount, int minSize, int maxSize) throws IOException { String thisLine; BufferedReader myInput = null; try { FileInputStream fin = new FileInputStream(new File(filepath)); myInput = new BufferedReader(new InputStreamReader(fin)); int i = 0; while ((thisLine = myInput.readLine()) != null) { // ajoute une squence String[] split = thisLine.split(" "); if (maxCount == i) { break; } if(split.length >= minSize && split.length <= maxSize ) { Sequence sequence = new Sequence(-1); Set<Integer> alreadySeen = new HashSet<Integer>(); int lastValue = -1; for (String value : split) { int intVal = Integer.valueOf(value); //If removeDuplicatesMethod==2 , then any duplicates is removed //eg: 1 1 2 3 3 4 1 2 -> 1 2 3 4 if(Profile.paramInt("removeDuplicatesMethod") == 2){ if(alreadySeen.contains(intVal)){ continue; }else{ alreadySeen.add(intVal); } } //If removeDuplicatesMethod==1 , then only consecutive repetitions are trimmed //eg: 1 1 2 3 3 4 1 2 -> 1 2 3 4 1 2 else if(Profile.paramInt("removeDuplicatesMethod") == 1){ //approach B if(lastValue == intVal) { continue; } lastValue = intVal; } Item item = new Item(intVal); //adding current val to current sequence sequence.addItem(item); } i++; sequences.add(sequence); } } } catch (Exception e) { e.printStackTrace(); } finally { if (myInput != null) { myInput.close(); } } } public void loadFileMsnbsFormat(String filepath, int maxCount, int minSize, int maxSize) throws IOException { String thisLine; BufferedReader myInput = null; try { FileInputStream fin = new FileInputStream(new File(filepath)); myInput = new BufferedReader(new InputStreamReader(fin)); int i = 0; while ((thisLine = myInput.readLine()) != null) { Set<Integer> alreadySeen = new HashSet<Integer>(); String[] split = thisLine.trim().split(" "); if (maxCount == i) { break; } Sequence sequence = new Sequence(-1); int lastValue = 0; for (String val : split) { int value = Integer.valueOf(val); // PHIL08: J'ai ajout le choix de la mthode // pour enlever les duplicats. // 2 = tous les duplicats // 1 = seulement les duplicats conscutifs if(Profile.paramInt("removeDuplicatesMethod") == 2){ if(alreadySeen.contains(value)){ continue; }else{ alreadySeen.add(value); } }else if(Profile.paramInt("removeDuplicatesMethod") == 1){ //approach B if(lastValue == value) { continue; } lastValue = value; } sequence.addItem(new Item(value)); } if(sequence.size() >= minSize && sequence.size() <= maxSize ) { sequences.add(sequence); i++; } } } catch (Exception e) { e.printStackTrace(); } finally { if (myInput != null) { myInput.close(); } } } public void loadFileLargeTextFormatAsCharacter(String filepath, int maxCount, int minSize, int maxSize) throws IOException { String thisLine; BufferedReader myInput = null; try { FileInputStream fin = new FileInputStream(new File(filepath)); myInput = new BufferedReader(new InputStreamReader(fin)); int i = 0; while ((thisLine = myInput.readLine()) != null) { if (maxCount == i) { break; } if(thisLine.length() >= minSize && thisLine.length() <= maxSize ) { Sequence sequence = new Sequence(-1); for(int k = 0 ; k < thisLine.length(); k++) { int value = thisLine.charAt(k); sequence.addItem(new Item(value)); } i++; sequences.add(sequence); } } } catch (Exception e) { e.printStackTrace(); } finally { if (myInput != null) { myInput.close(); } } } public void loadFileLargeTextFormatAsWords(String filepath, int maxCount, int minSize, int maxSize, boolean doNotAllowSentenceToContinueOnNextLine) throws IOException { String thisLine; BufferedReader myInput = null; try { FileInputStream fin = new FileInputStream(new File(filepath)); myInput = new BufferedReader(new InputStreamReader(fin)); // variable to count the number of sequences found until now int seqCount = 0; // variable to remember the last assigned item ID. int lastWordID = 1; // map to store the mapping between word (key) to item ID (value) Map<String, Integer> mapWordToID = new HashMap<String, Integer>(); // the current sequence Sequence sequence = new Sequence(-1); // for each line while ((thisLine = myInput.readLine()) != null) { // if we have found enough sequences, stop if (maxCount == seqCount) { break; } // filter unwanted characters (integers, [], #, 0,1,2,..) StringBuffer modifiedLine = new StringBuffer(thisLine.length()); for(int i=0; i < thisLine.length(); i++){ char currentChar = thisLine.charAt(i); if(Character.isLetter(currentChar) || currentChar == '.' || currentChar == '?' || currentChar == ':' || currentChar == ' '){ modifiedLine.append(currentChar); } } // split the string into tokens String split [] = modifiedLine.toString().split(" "); for(int i=0; i < split.length; i++){ String token = split[i]; // if the current token contains a end of sentence character (. ? or :) // of if it is the last word of the line, // we consider this as the end of the sequence. boolean containsPunctuation = token.contains(".") || token.contains("?") || token.contains(":"); if(containsPunctuation){ seqCount++; // if there is a punctuation character in this word, remove it // IMPORTANT: ADD THIS CONDITION: || i == split.length -1 // IF YOU WANT TO ALLOW SENTENCES TO CONTINUE ON THE NEXT LINE if(containsPunctuation || i == split.length -1 && doNotAllowSentenceToContinueOnNextLine){ token = token.substring(0, token.length()-1); } // get the itemID Integer itemID = mapWordToID.get(token); if(itemID == null){ itemID = lastWordID++; mapWordToID.put(token, itemID); } // add the item to the sequence sequence.addItem(new Item(itemID)); // add the sequence to the set of sequences, if the size is ok. if(sequence.size() >= minSize && sequence.size() <= maxSize ) { sequences.add(sequence); } // create a new sequence sequence = new Sequence(-1); } else{ // if it is not the last word of a sentence Integer itemID = mapWordToID.get(token); if(itemID == null){ itemID = lastWordID++; mapWordToID.put(token, itemID); } sequence.addItem(new Item(itemID)); } } } } catch (Exception e) { e.printStackTrace(); } finally { if (myInput != null) { myInput.close(); } } } public void loadFileSignLanguage(String fileToPath, int maxCount, int minsize, int maxsize) { String thisLine; BufferedReader myInput = null; try { FileInputStream fin = new FileInputStream(new File(fileToPath)); myInput = new BufferedReader(new InputStreamReader(fin)); String oldUtterance = "-1"; Sequence sequence = null; int count = 0; HashSet<Integer> alreadySeen = new HashSet<Integer>(); int id =0; int lastValue = -1; while ((thisLine = myInput.readLine()) != null) { if(thisLine.length() >= 1 && thisLine.charAt(0) != ' String []tokens = thisLine.split(" "); String currentUtterance = tokens[0]; if(!currentUtterance.equals(oldUtterance)){ if(sequence != null){ if(sequence.size() >= minsize && sequence.size() <= maxsize){ sequences.add(sequence); count++; } } sequence = new Sequence(id++); alreadySeen = new HashSet<Integer>(); oldUtterance = currentUtterance; } for(int j=1; j< tokens.length; j++){ int character = Integer.parseInt(tokens[j]); if(character == -11 || character == -12){ continue; } if(Profile.paramInt("removeDuplicatesMethod") == 2){ if(alreadySeen.contains(character)){ continue; } alreadySeen.add(character); }else if(Profile.paramInt("removeDuplicatesMethod") == 1){ if(lastValue == character){ continue; } lastValue = character; } sequence.getItems().add(new Item(character)); } } if (maxCount == count) { break; } } if(sequence.size() >= minsize && sequence.size() <= maxsize){ sequences.add(sequence); } } catch (Exception e) { e.printStackTrace(); } } public void loadFileSPMFFormat(String path, int maxCount, int minSize, int maxSize) { String thisLine; BufferedReader myInput = null; try { int count = 0; FileInputStream fin = new FileInputStream(new File(path)); myInput = new BufferedReader(new InputStreamReader(fin)); Set<Integer> alreadySeen = new HashSet<Integer>(); while ((thisLine = myInput.readLine()) != null && count < maxCount) { Sequence sequence = new Sequence(sequences.size()); for (String entier : thisLine.split(" ")) { if (entier.equals("-1")) { // separateur d'itemsets } else if (entier.equals("-2")) { // indicateur de fin de squence if(sequence.size()>= minSize && sequence.size() <= maxSize){ sequences.add(sequence); count++; } } else { int val = Integer.parseInt(entier); if(alreadySeen.contains(val)){ continue; } alreadySeen.add(val); sequence.getItems().add(new Item(val)); } } } if (myInput != null) { myInput.close(); } } catch (Exception e) { e.printStackTrace(); } } public void loadSnakeDataset(String filepath, int nbLine, int minSize, int maxSize) { String thisLine; BufferedReader myInput = null; try { FileInputStream fin = new FileInputStream(new File(filepath)); myInput = new BufferedReader(new InputStreamReader(fin)); while ((thisLine = myInput.readLine()) != null) { if(thisLine.length() >= 50){ Sequence sequence = new Sequence(sequences.size()); for(int i=0; i< thisLine.length(); i++){ int character = thisLine.toCharArray()[i ] - 65; // System.out.println(thisLine.toCharArray()[i ] + " " + character); sequence.addItem(new Item(character)); } if(sequence.size()>= minSize && sequence.size() <= maxSize){ sequences.add(sequence); } sequences.add(sequence); } } } catch (Exception e) { e.printStackTrace(); } } }
package hex.deeplearning; import hex.*; import hex.deeplearning.DeepLearningModel.DeepLearningModelOutput; import hex.schemas.DeepLearningV3; import hex.schemas.ModelBuilderSchema; import water.*; import water.exceptions.H2OIllegalArgumentException; import water.exceptions.H2OModelBuilderIllegalArgumentException; import water.fvec.Frame; import water.fvec.RebalanceDataSet; import water.fvec.Vec; import water.init.Linpack; import water.init.NetworkTest; import water.util.ArrayUtils; import water.util.Log; import water.util.MRUtils; import water.util.PrettyPrint; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import static water.util.MRUtils.sampleFrame; import static water.util.MRUtils.sampleFrameStratified; /** * Deep Learning Neural Net implementation based on MRTask */ public class DeepLearning extends ModelBuilder<DeepLearningModel,DeepLearningParameters,DeepLearningModelOutput> { /** * Main constructor from Deep Learning parameters * @param parms */ public DeepLearning( DeepLearningParameters parms ) { super("DeepLearning", parms); init(false); } /** * Types of models we can build with DeepLearning * @return */ @Override public ModelCategory[] can_build() { return new ModelCategory[]{ ModelCategory.Regression, ModelCategory.Binomial, ModelCategory.Multinomial, ModelCategory.AutoEncoder }; } public ModelBuilderSchema schema() { return new DeepLearningV3(); } @Override public BuilderVisibility builderVisibility() { return BuilderVisibility.Stable; }; @Override public boolean isSupervised() { return !_parms._autoencoder; } /** Start the DeepLearning training Job on an F/J thread. * @param work * @param restartTimer*/ @Override protected Job<DeepLearningModel> trainModelImpl(long work, boolean restartTimer) { // We look at _train before init(true) is called, so step around that here: return start(new DeepLearningDriver(), work, restartTimer); } @Override public long progressUnits() { long work = 1; if (null != _train) work = (long)(_parms._epochs * _train.numRows()); return Math.max(1, work); } /** Initialize the ModelBuilder, validating all arguments and preparing the * training frame. This call is expected to be overridden in the subclasses * and each subclass will start with "super.init();". This call is made * by the front-end whenever the GUI is clicked, and needs to be fast; * heavy-weight prep needs to wait for the trainModel() call. * * Validate the very large number of arguments in the DL Parameter directly. */ @Override public void init(boolean expensive) { super.init(expensive); _parms.validate(this, expensive); if (expensive && error_count() == 0) checkMemoryFootPrint(); } /** * Helper to create the DataInfo object from training/validation frames and the DL parameters * @param train Training frame * @param valid Validation frame * @param parms Model parameters * @return */ static DataInfo makeDataInfo(Frame train, Frame valid, DeepLearningParameters parms) { double x = 0.782347234; boolean identityLink = new Distribution(parms._distribution, parms._tweedie_power).link(x) == x; return new DataInfo( Key.make(), //dest key train, valid, parms._autoencoder ? 0 : 1, //nResponses parms._autoencoder || parms._use_all_factor_levels, //use all FactorLevels for auto-encoder parms._autoencoder ? DataInfo.TransformType.NORMALIZE : parms._sparse ? DataInfo.TransformType.DESCALE : DataInfo.TransformType.STANDARDIZE, //transform predictors train.lastVec().isCategorical() ? DataInfo.TransformType.NONE : identityLink ? DataInfo.TransformType.STANDARDIZE : DataInfo.TransformType.NONE, //transform response for regression with identity link parms._missing_values_handling == DeepLearningParameters.MissingValuesHandling.Skip, //whether to skip missing false, // do not replace NAs in numeric cols with mean true, // always add a bucket for missing values parms._weights_column != null, // observation weights parms._offset_column != null, parms._fold_column != null ); } @Override protected void checkMemoryFootPrint() { if (_parms._checkpoint != null) return; long p = _train.degreesOfFreedom() - (_parms._autoencoder ? 0 : _train.lastVec().cardinality()); String[][] dom = _train.domains(); // hack: add the factor levels for the NAs for (int i=0; i<_train.numCols()-(_parms._autoencoder ? 0 : 1); ++i) { if (dom[i] != null) { p++; } } // assert(makeDataInfo(_train, _valid, _parms).fullN() == p); long output = _parms._autoencoder ? p : Math.abs(_train.lastVec().cardinality()); // weights long model_size = p * _parms._hidden[0]; int layer=1; for (; layer < _parms._hidden.length; ++layer) model_size += _parms._hidden[layer-1] * _parms._hidden[layer]; model_size += _parms._hidden[layer-1] * output; // biases for (layer=0; layer < _parms._hidden.length; ++layer) model_size += _parms._hidden[layer]; model_size += output; if (model_size > 1e8) { String msg = "Model is too large: " + model_size + " parameters. Try reducing the number of neurons in the hidden layers (or reduce the number of categorical factors)."; error("_hidden", msg); cancel(msg); } } @Override public void modifyParmsForCrossValidationSplits(int i, int N, Key<Model> model_id) { super.modifyParmsForCrossValidationSplits(i, N, model_id); if (_parms._overwrite_with_best_model) { if (!_parms._quiet_mode) warn("_overwrite_with_best_model", "Disabling overwrite_with_best_model for cross-validation split " + (i+1) + "/" + N + ": No early stopping."); _parms._overwrite_with_best_model = false; } } @Override public void modifyParmsForCrossValidationMainModel(int N, Key<Model>[] cvModelBuilderKeys) { super.modifyParmsForCrossValidationMainModel(N, cvModelBuilderKeys); if (_parms._overwrite_with_best_model) { if (!_parms._quiet_mode) warn("_overwrite_with_best_model", "Disabling overwrite_with_best_model for cross-validation main model: No early stopping."); _parms._overwrite_with_best_model = false; } if (cvModelBuilderKeys !=null) { if (_parms._stopping_rounds > 0) { double[] epochs = new double[cvModelBuilderKeys.length]; for (int i=0;i<epochs.length;++i) { epochs[i] = ((DeepLearningModel)DKV.getGet((((DeepLearning)DKV.getGet(cvModelBuilderKeys[i])).dest()))).last_scored().epoch_counter; } _parms._epochs = ArrayUtils.sum(epochs)/epochs.length; if (!_parms._quiet_mode) warn("_epochs", "Setting optimal _epochs to " + _parms._epochs + " for cross-validation main model based on early stopping of cross-validation models."); _parms._stopping_rounds = 0; if (!_parms._quiet_mode) warn("_stopping_rounds", "Disabling convergence-based early stopping for cross-validation main model."); } } } public class DeepLearningDriver extends H2O.H2OCountedCompleter<DeepLearningDriver> { protected DeepLearningDriver() { super(true); } // bump priority of drivers @Override protected void compute2() { try { long cs = _parms.checksum(); init(true); // Read lock input _parms.read_lock_frames(DeepLearning.this); // Something goes wrong if (error_count() > 0){ DeepLearning.this.updateValidationMessages(); throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(DeepLearning.this); } buildModel(); if (isRunning()) done(); // Job done! //check that _parms isn't changed during DL model training long cs2 = _parms.checksum(); assert(cs == cs2); } catch( Throwable t ) { Job thisJob = DKV.getGet(_key); if (thisJob._state == JobState.CANCELLED) { Log.info("Job cancelled by user."); } else { t.printStackTrace(); failed(t); throw t; } } finally { updateModelOutput(); _parms.read_unlock_frames(DeepLearning.this); } tryComplete(); } Key self() { return _key; } /** * Train a Deep Learning model, assumes that all members are populated * If checkpoint == null, then start training a new model, otherwise continue from a checkpoint */ public final void buildModel() { Scope.enter(); DeepLearningModel cp = null; if (_parms._checkpoint == null) { cp = new DeepLearningModel(dest(), _parms, new DeepLearningModel.DeepLearningModelOutput(DeepLearning.this), _train, _valid, nclasses()); cp.model_info().initializeMembers(); } else { final DeepLearningModel previous = DKV.getGet(_parms._checkpoint); if (previous == null) throw new IllegalArgumentException("Checkpoint not found."); Log.info("Resuming from checkpoint."); new ProgressUpdate("Resuming from checkpoint").fork(_progressKey); if( isClassifier() != previous._output.isClassifier() ) throw new H2OIllegalArgumentException("Response type must be the same as for the checkpointed model."); if( isSupervised() != previous._output.isSupervised() ) throw new H2OIllegalArgumentException("Model type must be the same as for the checkpointed model."); // check the user-given arguments for consistency DeepLearningParameters oldP = previous._parms; //sanitized parameters for checkpointed model DeepLearningParameters newP = _parms; //user-given parameters for restart DeepLearningParameters oldP2 = (DeepLearningParameters)oldP.clone(); DeepLearningParameters newP2 = (DeepLearningParameters)newP.clone(); DeepLearningParameters.Sanity.modifyParms(oldP, oldP2, nclasses()); //sanitize the user-given parameters DeepLearningParameters.Sanity.modifyParms(newP, newP2, nclasses()); //sanitize the user-given parameters DeepLearningParameters.Sanity.checkpoint(oldP2, newP2); DataInfo dinfo; try { dinfo = makeDataInfo(_train, _valid, _parms); DKV.put(dinfo); cp = new DeepLearningModel(dest(), _parms, previous, false, dinfo); cp.write_lock(self()); if (!Arrays.equals(cp._output._names, previous._output._names)) { throw new H2OIllegalArgumentException("The columns of the training data must be the same as for the checkpointed model. Check ignored columns (or disable ignore_const_cols)."); } if (!Arrays.deepEquals(cp._output._domains, previous._output._domains)) { throw new H2OIllegalArgumentException("Categorical factor levels of the training data must be the same as for the checkpointed model."); } if (dinfo.fullN() != previous.model_info().data_info().fullN()) { throw new H2OIllegalArgumentException("Total number of predictors is different than for the checkpointed model."); } if (_parms._epochs <= previous.epoch_counter) { throw new H2OIllegalArgumentException("Total number of epochs must be larger than the number of epochs already trained for the checkpointed model (" + previous.epoch_counter + ")."); } // these are the mutable parameters that are to be used by the model (stored in model_info._parms) final DeepLearningParameters actualNewP = cp.model_info().get_params(); //actually used parameters for model building (defaults filled in, etc.) assert (actualNewP != previous.model_info().get_params()); assert (actualNewP != newP); assert (actualNewP != oldP); DeepLearningParameters.Sanity.update(actualNewP, newP, nclasses()); Log.info("Continuing training after " + String.format("%.3f", previous.epoch_counter) + " epochs from the checkpointed model."); cp.update(self()); } catch (H2OIllegalArgumentException ex){ if (cp != null) { cp.unlock(self()); cp.delete(); cp = null; } throw ex; } finally { if (cp != null) cp.unlock(self()); } } trainModel(cp); // clean up, but don't delete the model and the training/validation model metrics List<Key> keep = new ArrayList<>(); try { keep.add(dest()); keep.add(cp.model_info().data_info()._key); // Do not remove training metrics keep.add(cp._output._training_metrics._key); // And validation model metrics if (cp._output._validation_metrics != null) { keep.add(cp._output._validation_metrics._key); } if (cp._output.weights != null && cp._output.biases != null) { for (Key k : Arrays.asList(cp._output.weights)) { keep.add(k); for (Vec vk : ((Frame) DKV.getGet(k)).vecs()) { keep.add(vk._key); } } for (Key k : Arrays.asList(cp._output.biases)) { keep.add(k); for (Vec vk : ((Frame) DKV.getGet(k)).vecs()) { keep.add(vk._key); } } } } finally { Scope.exit(keep.toArray(new Key[0])); } } /** * Train a Deep Learning neural net model * @param model Input model (e.g., from initModel(), or from a previous training run) * @return Trained model */ public final DeepLearningModel trainModel(DeepLearningModel model) { Frame validScoreFrame = null; Frame train, trainScoreFrame; try { // if (checkpoint == null && !quiet_mode) logStart(); //if checkpoint is given, some Job's params might be uninitialized (but the restarted model's parameters are correct) if (model == null) { model = DKV.get(dest()).get(); } Log.info("Model category: " + (_parms._autoencoder ? "Auto-Encoder" : isClassifier() ? "Classification" : "Regression")); final long model_size = model.model_info().size(); Log.info("Number of model parameters (weights/biases): " + String.format("%,d", model_size)); model.write_lock(self()); new ProgressUpdate("Setting up training data...").fork(_progressKey); final DeepLearningParameters mp = model.model_info().get_params(); // temporary frames of the same "name" as the orig _train/_valid (asking the parameter's Key, not the actual frame) // Note: don't put into DKV or they would overwrite the _train/_valid frames! Frame tra_fr = new Frame(mp._train, _train.names(), _train.vecs()); Frame val_fr = _valid != null ? new Frame(mp._valid,_valid.names(), _valid.vecs()) : null; train = tra_fr; if (mp._force_load_balance) { new ProgressUpdate("Load balancing training data...").fork(_progressKey); train = reBalance(train, mp._replicate_training_data /*rebalance into only 4*cores per node*/, mp._train.toString() + "." + model._key.toString() + ".temporary.train"); } if (model._output.isClassifier() && mp._balance_classes) { new ProgressUpdate("Balancing class distribution of training data...").fork(_progressKey); float[] trainSamplingFactors = new float[train.lastVec().domain().length]; //leave initialized to 0 -> will be filled up below if (mp._class_sampling_factors != null) { if (mp._class_sampling_factors.length != train.lastVec().domain().length) throw new IllegalArgumentException("class_sampling_factors must have " + train.lastVec().domain().length + " elements"); trainSamplingFactors = mp._class_sampling_factors.clone(); //clone: don't modify the original } train = sampleFrameStratified( train, train.lastVec(), train.vec(model._output.weightsName()), trainSamplingFactors, (long)(mp._max_after_balance_size*train.numRows()), mp._seed, true, false); Vec l = train.lastVec(); Vec w = train.vec(model._output.weightsName()); MRUtils.ClassDist cd = new MRUtils.ClassDist(l); model._output._modelClassDist = _weights != null ? cd.doAll(l, w).rel_dist() : cd.doAll(l).rel_dist(); } model.training_rows = train.numRows(); trainScoreFrame = sampleFrame(train, mp._score_training_samples, mp._seed); //training scoring dataset is always sampled uniformly from the training dataset if( trainScoreFrame != train ) _delete_me.add(trainScoreFrame); if (!_parms._quiet_mode) Log.info("Number of chunks of the training data: " + train.anyVec().nChunks()); if (val_fr != null) { model.validation_rows = val_fr.numRows(); // validation scoring dataset can be sampled in multiple ways from the given validation dataset if (model._output.isClassifier() && mp._balance_classes && mp._score_validation_sampling == DeepLearningParameters.ClassSamplingMethod.Stratified) { new ProgressUpdate("Sampling validation data (stratified)...").fork(_progressKey); validScoreFrame = sampleFrameStratified(val_fr, val_fr.lastVec(), val_fr.vec(model._output.weightsName()), null, mp._score_validation_samples > 0 ? mp._score_validation_samples : val_fr.numRows(), mp._seed +1, false /* no oversampling */, false); } else { new ProgressUpdate("Sampling validation data...").fork(_progressKey); validScoreFrame = sampleFrame(val_fr, mp._score_validation_samples, mp._seed +1); if( validScoreFrame != val_fr ) _delete_me.add(validScoreFrame); } if (mp._force_load_balance) { new ProgressUpdate("Balancing class distribution of validation data...").fork(_progressKey); validScoreFrame = reBalance(validScoreFrame, false /*always split up globally since scoring should be distributed*/, mp._valid.toString() + "." + model._key.toString() + ".temporary.valid"); } if (!_parms._quiet_mode) Log.info("Number of chunks of the validation data: " + validScoreFrame.anyVec().nChunks()); } // Set train_samples_per_iteration size (cannot be done earlier since this depends on whether stratified sampling is done) model.actual_train_samples_per_iteration = computeTrainSamplesPerIteration(mp, train.numRows(), model); // Determine whether shuffling is enforced if(mp._replicate_training_data && (model.actual_train_samples_per_iteration == train.numRows()*(mp._single_node_mode ?1:H2O.CLOUD.size())) && !mp._shuffle_training_data && H2O.CLOUD.size() > 1 && !mp._reproducible) { if (!mp._quiet_mode) Log.info("Enabling training data shuffling, because all nodes train on the full dataset (replicated training data)."); mp._shuffle_training_data = true; } if(!mp._shuffle_training_data && model.actual_train_samples_per_iteration == train.numRows() && train.anyVec().nChunks()==1) { if (!mp._quiet_mode) Log.info("Enabling training data shuffling to avoid training rows in the same order over and over (no Hogwild since there's only 1 chunk)."); mp._shuffle_training_data = true; } // if (!mp._quiet_mode) Log.info("Initial model:\n" + model.model_info()); model._timeLastIterationEnter = System.currentTimeMillis(); if (_parms._autoencoder) { new ProgressUpdate("Scoring null model of autoencoder...").fork(_progressKey); if (!mp._quiet_mode) Log.info("Scoring the null model of the autoencoder."); model.doScoring(trainScoreFrame, validScoreFrame, self(), null, 0, false); //get the null model reconstruction error } // put the initial version of the model into DKV model.update(self()); Log.info("Starting to train the Deep Learning model."); new ProgressUpdate("Training...").fork(_progressKey); //main loop do { model.iterations++; model.set_model_info(mp._epochs == 0 ? model.model_info() : H2O.CLOUD.size() > 1 && mp._replicate_training_data ? (mp._single_node_mode ? new DeepLearningTask2(self(), train, model.model_info(), rowFraction(train, mp, model), model.iterations).doAll(Key.make(H2O.SELF)).model_info() : //replicated data + single node mode new DeepLearningTask2(self(), train, model.model_info(), rowFraction(train, mp, model), model.iterations).doAllNodes( ).model_info()): //replicated data + multi-node mode new DeepLearningTask (self(), model.model_info(), rowFraction(train, mp, model), model.iterations).doAll ( train ).model_info()); //distributed data (always in multi-node mode) } while (isRunning() && model.doScoring(trainScoreFrame, validScoreFrame, self(), _progressKey, model.iterations, false)); // replace the model with the best model so far (if it's better) if (isRunning() && _parms._overwrite_with_best_model && model.actual_best_model_key != null && _parms._nfolds == 0) { DeepLearningModel best_model = DKV.getGet(model.actual_best_model_key); if (best_model != null && best_model.loss() < model.loss() && Arrays.equals(best_model.model_info().units, model.model_info().units)) { if (!_parms._quiet_mode) Log.info("Setting the model to be the best model so far (based on scoring history)."); DeepLearningModelInfo mi = best_model.model_info().deep_clone(); // Don't cheat - count full amount of training samples, since that's the amount of training it took to train (without finding anything better) mi.set_processed_global(model.model_info().get_processed_global()); mi.set_processed_local(model.model_info().get_processed_local()); model.set_model_info(mi); model.update(self()); model.doScoring(trainScoreFrame, validScoreFrame, self(), _progressKey, model.iterations, true); assert(best_model.loss() == model.loss()); } } if (!_parms._quiet_mode) { Log.info("=============================================================================================================================================================================="); if (isCancelledOrCrashed()) { Log.info("Deep Learning model training was interrupted."); } else { Log.info("Finished training the Deep Learning model."); Log.info(model); } Log.info("=============================================================================================================================================================================="); } } finally { if (model != null) { model.deleteElasticAverageModels(); model.unlock(self()); if (model.actual_best_model_key != null) { assert (model.actual_best_model_key != model._key); DKV.remove(model.actual_best_model_key); } } for (Frame f : _delete_me) f.delete(); //delete internally rebalanced frames } return model; } transient HashSet<Frame> _delete_me = new HashSet<>(); /** * Rebalance a frame for load balancing * @param fr Input frame * @param local whether to only create enough chunks to max out all cores on one node only * @return Frame that has potentially more chunks */ private Frame reBalance(final Frame fr, boolean local, final String name) { int chunks = (int)Math.min( 4 * H2O.NUMCPUS * (local ? 1 : H2O.CLOUD.size()), fr.numRows()); if (fr.anyVec().nChunks() > chunks && !_parms._reproducible) { if (!_parms._quiet_mode) Log.info("Dataset already contains " + fr.anyVec().nChunks() + " chunks. No need to rebalance."); return fr; } else if (_parms._reproducible) { if (!_parms._quiet_mode) Log.warn("Reproducibility enforced - using only 1 thread - can be slow."); chunks = 1; } if (!_parms._quiet_mode) Log.info("ReBalancing dataset into (at least) " + chunks + " chunks."); Key newKey = Key.make(name + ".chunks" + chunks); RebalanceDataSet rb = new RebalanceDataSet(fr, newKey, chunks); H2O.submitTask(rb); rb.join(); Frame f = DKV.get(newKey).get(); _delete_me.add(f); return f; } /** * Compute the actual train_samples_per_iteration size from the user-given parameter * @param mp Model parameter (DeepLearning object) * @param numRows number of training rows * @param model DL model * @return The total number of training rows to be processed per iteration (summed over on all nodes) */ private long computeTrainSamplesPerIteration(final DeepLearningParameters mp, final long numRows, final DeepLearningModel model) { long tspi = mp._train_samples_per_iteration; assert(tspi == 0 || tspi == -1 || tspi == -2 || tspi >= 1); if (tspi == 0 || (!mp._replicate_training_data && tspi == -1) ) { tspi = numRows; if (!mp._quiet_mode) Log.info("Setting train_samples_per_iteration (" + mp._train_samples_per_iteration + ") to one epoch: #rows (" + tspi + ")."); } else if (tspi == -1) { tspi = (mp._single_node_mode ? 1 : H2O.CLOUD.size()) * numRows; if (!mp._quiet_mode) Log.info("Setting train_samples_per_iteration (" + mp._train_samples_per_iteration + ") to #nodes x #rows (" + tspi + ")."); } else if (tspi == -2) { // automatic tuning based on CPU speed, network speed and model size // measure cpu speed double total_gflops = 0; for (H2ONode h2o : H2O.CLOUD._memary) { HeartBeat hb = h2o._heartbeat; total_gflops += hb._gflops; } if (mp._single_node_mode) total_gflops /= H2O.CLOUD.size(); if (total_gflops == 0) { total_gflops = Linpack.run(H2O.SELF._heartbeat._cpus_allowed) * (mp._single_node_mode ? 1 : H2O.CLOUD.size()); } final long model_size = model.model_info().size(); int[] msg_sizes = new int[]{ 1, (int)(model_size*4) == (model_size*4) ? (int)(model_size*4) : Integer.MAX_VALUE }; double[] microseconds_collective = new double[msg_sizes.length]; NetworkTest.NetworkTester nt = new NetworkTest.NetworkTester(msg_sizes,null,microseconds_collective,model_size>1e6 ? 1 : 5 /*repeats*/,false,true /*only collectives*/); nt.compute2(); //length of the network traffic queue based on log-tree rollup (2 log(nodes)) int network_queue_length = mp._single_node_mode || H2O.CLOUD.size() == 1? 1 : 2*(int)Math.floor(Math.log(H2O.CLOUD.size())/Math.log(2)); // heuristics double flops_overhead_per_row = 50; if (mp._activation == DeepLearningParameters.Activation.Maxout || mp._activation == DeepLearningParameters.Activation.MaxoutWithDropout) { flops_overhead_per_row *= 8; } else if (mp._activation == DeepLearningParameters.Activation.Tanh || mp._activation == DeepLearningParameters.Activation.TanhWithDropout) { flops_overhead_per_row *= 5; } // target fraction of comm vs cpu time: 5% double fraction = mp._single_node_mode || H2O.CLOUD.size() == 1 ? 1e-3 : mp._target_ratio_comm_to_comp; //one single node mode, there's no model averaging effect, so less need to shorten the M/R iteration // estimate the time for communication (network) and training (compute) model.time_for_communication_us = (H2O.CLOUD.size() == 1 ? 1e4 /* add 10ms for single-node */ : 1e5 /* add 100ms for multi-node MR overhead */) + network_queue_length * microseconds_collective[1]; double time_per_row_us = (flops_overhead_per_row * model_size + 10000 * model.model_info().units[0]) / (total_gflops * 1e9) / H2O.SELF._heartbeat._cpus_allowed * 1e6; // compute the optimal number of training rows per iteration // fraction := time_comm_us / (time_comm_us + tspi * time_per_row_us) ==> tspi = (time_comm_us/fraction - time_comm_us)/time_per_row_us tspi = (long)((model.time_for_communication_us / fraction - model.time_for_communication_us)/ time_per_row_us); tspi = Math.min(tspi, (mp._single_node_mode ? 1 : H2O.CLOUD.size()) * numRows * 10); //not more than 10x of what train_samples_per_iteration=-1 would do // If the number is close to a multiple of epochs, use that -> prettier scoring if (tspi > numRows && Math.abs(tspi % numRows)/(double)numRows < 0.2) tspi = tspi - tspi % numRows; tspi = Math.min(tspi, (long)(mp._epochs * numRows / 10)); //limit to number of epochs desired, but at least 10 iterations total if (H2O.CLOUD.size() == 1 || mp._single_node_mode) { tspi = Math.min(tspi, 10*(int)(1e6/time_per_row_us)); //in single-node mode, only run for at most 10 seconds } tspi = Math.max(1, tspi); //at least 1 row tspi = Math.min(100000*H2O.CLOUD.size(), tspi); //at most 100k rows per node for initial guess - can always relax later on if (!mp._quiet_mode) { Log.info("Auto-tuning parameter 'train_samples_per_iteration':"); Log.info("Estimated compute power : " + (int)total_gflops + " GFlops"); Log.info("Estimated time for comm : " + PrettyPrint.usecs((long) model.time_for_communication_us)); Log.info("Estimated time per row : " + ((long)time_per_row_us > 0 ? PrettyPrint.usecs((long) time_per_row_us) : time_per_row_us + " usecs")); Log.info("Estimated training speed: " + (int)(1e6/time_per_row_us) + " rows/sec"); Log.info("Setting train_samples_per_iteration (" + mp._train_samples_per_iteration + ") to auto-tuned value: " + tspi); } } else { // limit user-given value to number of epochs desired tspi = Math.max(1, Math.min(tspi, (long) (mp._epochs * numRows))); } assert(tspi != 0 && tspi != -1 && tspi != -2 && tspi >= 1); model.tspiGuess = tspi; return tspi; } /** * Compute the fraction of rows that need to be used for training during one iteration * @param numRows number of training rows * @param train_samples_per_iteration number of training rows to be processed per iteration * @param replicate_training_data whether of not the training data is replicated on each node * @return fraction of rows to be used for training during one iteration */ private float computeRowUsageFraction(final long numRows, final long train_samples_per_iteration, final boolean replicate_training_data) { float rowUsageFraction = (float)train_samples_per_iteration / numRows; if (replicate_training_data) rowUsageFraction /= H2O.CLOUD.size(); assert(rowUsageFraction > 0); return rowUsageFraction; } private float rowFraction(Frame train, DeepLearningParameters p, DeepLearningModel m) { return computeRowUsageFraction(train.numRows(), m.actual_train_samples_per_iteration, p._replicate_training_data); } } }
package com.health.control; import java.awt.Container; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import org.jfree.chart.JFreeChart; import org.xml.sax.SAXException; import com.health.Column; import com.health.EventList; import com.health.EventSequence; import com.health.Table; import com.health.input.Input; import com.health.input.InputException; import com.health.interpreter.Interpreter; import com.health.operations.Code; import com.health.operations.ReadTime; import com.health.operations.TableWithDays; import com.health.output.Output; import com.health.script.runtime.BooleanValue; import com.health.script.runtime.Context; import com.health.script.runtime.EventListValue; import com.health.script.runtime.EventSequenceValue; import com.health.script.runtime.NumberValue; import com.health.script.runtime.StringValue; import com.health.script.runtime.WrapperValue; import com.health.visuals.BoxPlot; import com.health.visuals.FreqBar; import com.health.visuals.Histogram; import com.health.visuals.StateTransitionMatrix; import com.xeiam.xchart.Chart; public final class ControlModule { private String script; private List<InputData> data; private Map<String, Object> output = new HashMap<String, Object>(); private int numBoxPlots, numFreqBars, numTransitionMatrices, numHistograms; /** * Start analysis based on the script. * * @return nothing. * @throws IOException * if any I/O errors occur. */ public Context startAnalysis() throws IOException { if (this.script == null) { throw new IllegalStateException( "Script cannot be null. Set the script to a String isntance using setScript(String)."); } Context context = this.createContext(); this.loadAllData(context); Interpreter.interpret(this.script, context); return context; } public Map<String, Object> getOutput() { return Collections.unmodifiableMap(this.output); } /** * Gets the data of this control module. * * @return the data of this control module. */ public List<InputData> getData() { return data; } /** * Sets the data of this control module. * * @param data * the data of this control module. */ public void setData(final List<InputData> data) { this.data = data; } /** * Gets the script of this control module. * * @return the script of this control module. */ public String getScript() { return script; } /** * Sets the script of this control module. * * @param script * the script of this control module. */ public void setScript(final String script) { this.script = script; } @Override public String toString() { return "ControlModule [data=" + data.toString() + ", script=" + script + "]"; } private Context createContext() { Context context = new Context(); context.declareStaticMethod("println", (args) -> { System.out.println(((StringValue) args[0]).getValue()); return null; }); context.declareStaticMethod("write", (args) -> { String filename = ((StringValue) args[0]).getValue(); Table table = ((WrapperValue<Table>) args[1]).getValue(); if (args.length >= 3) { Output.writeTable( filename, table, ((StringValue) args[2]).getValue()); } else { Output.writeTable(filename, table); } this.output.put(new File(filename).getName(), table); return null; }); context.declareStaticMethod("freqbar", (args) -> { Chart chart; String filename = null; int baseIndex = 0; if (args[0] instanceof StringValue) { filename = ((StringValue) args[0]).getValue(); baseIndex++; } if (args.length >= baseIndex + 2) { chart = FreqBar.frequencyBar( ((WrapperValue<Table>) args[baseIndex + 0]).getValue(), ((StringValue) args[baseIndex + 1]).getValue()); } else { chart = FreqBar.frequencyBar(((WrapperValue<Table>) args[baseIndex + 0]).getValue()); } if (filename != null) { FreqBar.saveGraph(chart, filename); } this.output.put("freqbar" + ++numFreqBars, FreqBar.getContainer(chart)); return null; }); context.declareStaticMethod("boxplot", (args) -> { JFreeChart panel; if (args.length >= 2) { panel = BoxPlot.createBoxPlot(((WrapperValue<Table>) args[0]).getValue(), ((StringValue) args[1]).getValue()); } else { panel = BoxPlot.createBoxPlot(((WrapperValue<Table>) args[0]).getValue()); } this.output.put("boxplot" + ++numBoxPlots, BoxPlot.visualBoxPlot(panel)); return null; }); context.declareStaticMethod("hist", (args) -> { double bins = ((NumberValue) args[2]).getValue(); JFreeChart panel = Histogram.createHist( ((WrapperValue<Table>) args[0]).getValue(), ((StringValue) args[1]).getValue(), (int) bins); this.output.put("histogram" + ++numHistograms, Histogram.visualHist(panel)); return null; }); context.declareStaticMethod("sequence", (args) -> { String[] sequence; boolean connected = true; if (args.length > 0 && args[args.length - 1] instanceof BooleanValue) { connected = ((BooleanValue) args[args.length - 1]).getValue(); sequence = new String[args.length - 1]; for (int i = 0; i < args.length - 1; i++) { sequence[i] = ((StringValue) args[i]).getValue(); } } else { sequence = new String[args.length]; for (int i = 0; i < args.length; i++) { sequence[i] = ((StringValue) args[i]).getValue(); } } return new EventSequenceValue(new EventSequence(sequence, connected)); }); context.declareStaticMethod("findSequences", (args) -> { EventList events = ((EventListValue) args[0]).getValue(); EventSequence sequence = ((EventSequenceValue) args[1]).getValue(); Code.fillEventSequence(sequence, events); return new EventSequenceValue(sequence); }); context.declareStaticMethod( "transitionMatrix", (args) -> { String filename = null; int baseIndex = 0; if (args[0] instanceof StringValue) { filename = ((StringValue) args[0]).getValue(); baseIndex++; } EventList codes = ((EventListValue) args[baseIndex + 0]).getValue(); Container table; if (args.length >= baseIndex + 2) { EventSequence sequence = ((EventSequenceValue) args[baseIndex + 1]).getValue(); table = StateTransitionMatrix.createStateTrans(codes, Code.fillEventSequence(sequence, codes)); } else { table = StateTransitionMatrix.createStateTrans(codes); } if (filename != null) { StateTransitionMatrix.saveFile(filename, table); } this.output.put("transitionMatrix" + ++numBoxPlots, table); return null; }); context.declareStaticMethod("tableWithDays", (args) -> { return new WrapperValue<Table>(TableWithDays.TableDays(((WrapperValue<Table>) args[0]).getValue())); }); context.declareStaticMethod("tableWithHoursOfDay", (args) -> { return new WrapperValue<Table>(TableWithDays.TableHours(((WrapperValue<Table>) args[0]).getValue())); }); context.declareStaticMethod("addTimeToDate", (args) -> { Table table = ((WrapperValue<Table>) args[0]).getValue(); Column dateCol = table.getColumn(((StringValue) args[1]).getValue()); Column timeCol = table.getColumn(((StringValue) args[2]).getValue()); ReadTime.addTimeToDate(table, dateCol, timeCol); return null; }); return context; } private void loadAllData(final Context context) { if (this.data != null) { for (int i = 0; i < this.data.size(); i++) { this.loadData(this.data.get(i), context); } } } private void loadData(final InputData input, final Context context) { Table table = null; try { table = Input.readTable(input.getFilePath(), input.getConfigPath()); } catch (IOException | ParserConfigurationException | SAXException | InputException e) { System.out.println("Error: Something went wrong parsing the config and data!"); e.printStackTrace(); return; } WrapperValue<Table> value = new WrapperValue<Table>(table); context.declareLocal(input.getName(), value.getType(), value); } }
// $Id: DistributedQueueTest.java,v 1.8 2005/12/27 14:38:35 belaban Exp $ package org.jgroups.blocks; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.log4j.Logger; import java.util.Vector; public class DistributedQueueTest extends TestCase { final int NUM_ITEMS = 10; static Logger logger = Logger.getLogger(DistributedQueueTest.class.getName()); String props; public DistributedQueueTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(DistributedQueueTest.class); } protected DistributedQueue queue1; protected DistributedQueue queue2; protected DistributedQueue queue3; public void setUp() throws Exception { super.setUp(); props="UDP(mcast_recv_buf_size=80000;mcast_send_buf_size=150000;mcast_port=45566;" + "mcast_addr=228.8.8.8;ip_ttl=32):" + "PING(timeout=2000;num_initial_members=3):" + "FD_SOCK:" + "VERIFY_SUSPECT(timeout=1500):" + "UNICAST(timeout=600,1200,2000,2500):" + "FRAG(frag_size=8096;down_thread=false;up_thread=false):" + "TOTAL_TOKEN(unblock_sending=10;block_sending=50):" + "pbcast.GMS(print_local_addr=true;join_timeout=3000;join_retry_timeout=2000;shun=true):" + "STATE_TRANSFER:" + "QUEUE"; queue1 = new DistributedQueue("testing", null, props, 5000); log("created queue1"); // give some time for the channel to become a coordinator try { Thread.sleep(1000); } catch (Exception ex) { } queue2 = new DistributedQueue("testing", null, props, 5000); log("created queue2"); try { Thread.sleep(1000); } catch (InterruptedException ex) { } queue3 = new DistributedQueue("testing", null, props, 5000); log("created queue3"); try { Thread.sleep(1000); } catch (InterruptedException ex) { } } public void tearDown() throws Exception { super.tearDown(); log("stopping queue1"); queue1.stop(); log("stopped queue1"); log("stopping queue2"); queue2.stop(); log("stopped queue2"); log("stopping queue3"); queue3.stop(); log("stopped queue3"); } void log(String msg) { System.out.println("-- [" + Thread.currentThread().getName() + "]: " + msg); } class PutTask implements Runnable { protected DistributedQueue queue; protected String name; protected boolean finished; public PutTask(String name, DistributedQueue q) { queue = q; this.name = name; finished = false; } public void run() { for (int i = 0; i < NUM_ITEMS; i++) { queue.add(name + '_' + i); } finished = true; log("added " + NUM_ITEMS + " elements - done"); } public boolean finished() { return finished; } } public void testMultipleWriter() throws Exception { PutTask t1 = new PutTask("Queue1", queue1); PutTask t2 = new PutTask("Queue2", queue2); PutTask t3 = new PutTask("Queue3", queue3); Thread rTask1 = new Thread(t1); Thread rTask2 = new Thread(t2); Thread rTask3 = new Thread(t3); rTask1.start(); rTask2.start(); rTask3.start(); while (!t1.finished() || !t2.finished() || !t3.finished()) { try { Thread.sleep(1000); } catch (InterruptedException ex) { } } assertEquals(queue1.size(), queue2.size()); assertEquals(queue1.size(), queue3.size()); checkContents(queue1.getContents(), queue2.getContents()); checkContents(queue1.getContents(), queue3.getContents()); } protected void checkContents(Vector q1, Vector q2) { for (int i = 0; i < q1.size(); i++) { Object e1 = q1.elementAt(i); Object e2 = q2.elementAt(i); boolean t = e1.equals(e2); if (!t) { logger.error("Data order differs :" + e1 + "!=" + e2); } else logger.debug("Data order ok :" + e1 + "==" + e2); assertTrue(e1.equals(e2)); } } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
// $Id: RpcDispatcherBlocking.java,v 1.3 2004/07/03 22:42:58 belaban Exp $ package org.jgroups.tests; import org.jgroups.*; import org.jgroups.blocks.GroupRequest; import org.jgroups.blocks.RpcDispatcher; import org.jgroups.util.RspList; import org.jgroups.util.Util; /** * Tests synchronous group RPCs. 2 main test cases: * <ol> * <li>Member crashes during invocation of sync group RPC: start 3 instances (A, * B,C), set the timeout to be 30 seconds. Then invoke a sync group RPC by A * (press 's' in A's window). A,B and C should receive the RPC. Now kill C. * After some time, A's method call should return and show A's and B's reply to * be valid, while showing C's response marked as suspected. * <li>Member joins group during synchronous group RPC: start A and B with * timeout=30000. Invoke a sync group RPC on A. Start C. A and B should * <em>not</em> receive the view change <em>before</em> the group RPC has * returned with A's and B's results. Therefore A and B should <em>not</em> wait * for C's response, which would never be received because C never got the RPC * in the first place. This would block A forever. * </ol> * * @author bela Dec 19, 2002 */ public class RpcDispatcherBlocking implements MembershipListener { RpcDispatcher disp; Channel channel; long timeout=30000; String props=null; int i=0; public RpcDispatcherBlocking(String props, long timeout) { this.props=props; this.timeout=timeout; } public void print(int i) throws Exception { System.out.println("<-- " + i + " [sleeping for " + timeout + " msecs"); Util.sleep(timeout); } public void viewAccepted(View new_view) { System.out.println("new view: " + new_view); } /** Called when a member is suspected */ public void suspect(Address suspected_mbr) { System.out.println(suspected_mbr + " is suspected"); } /** Block sending and receiving of messages until viewAccepted() is called */ public void block() { } public void start() throws Exception { int c; RspList rsps; channel=new JChannel(null); // default props disp=new RpcDispatcher(channel, null, this, this); channel.connect("rpc-test"); while(true) { System.out.println("[x]: exit [s]: send sync group RPC"); System.out.flush(); c=System.in.read(); switch(c) { case 'x': channel.close(); disp.stop(); return; case 's': rsps=sendGroupRpc(); System.out.println("responses:\n" + rsps); break; } System.in.skip(System.in.available()); } } RspList sendGroupRpc() throws Exception { return disp.callRemoteMethods(null, "print", new Object[]{new Integer(i++)}, new Class[] {int.class}, GroupRequest.GET_ALL, 0); } public static void main(String[] args) { long timeout=30000; String props=null; for(int i=0; i < args.length; i++) { if(args[i].equals("-props")) { props=args[++i]; continue; } if(args[i].equals("-timeout")) { timeout=Long.parseLong(args[++i]); continue; } help(); return; } try { new RpcDispatcherBlocking(props, timeout).start(); } catch(Exception ex) { System.err.println(ex); } } static void help() { System.out.println("RpcDispatcherBlocking [-help] [-props <properties>] [-timeout <timeout>]"); } }
package to.etc.domui.component.misc; import javax.annotation.*; import to.etc.domui.component.buttons.*; import to.etc.domui.component.layout.*; import to.etc.domui.component.meta.*; import to.etc.domui.dom.css.*; import to.etc.domui.dom.html.*; import to.etc.domui.trouble.*; import to.etc.domui.util.*; import to.etc.domui.util.bugs.*; public class MsgBox extends Window { public interface IAnswer { void onAnswer(MsgBoxButton result) throws Exception; } public interface IAnswer2 { void onAnswer(Object result) throws Exception; } public static enum Type { INFO, WARNING, ERROR, DIALOG } private Img m_theImage = new Img(); private String m_theText; private Div m_theButtons = new Div(); private static final int WIDTH = 500; private static final int HEIGHT = 210; private Object m_selectedChoice; private IAnswer m_onAnswer; private IAnswer2 m_onAnswer2; private MsgBoxButton m_closeButtonObject; /** * Custom dialog message text renderer. */ private INodeContentRenderer<String> m_dataRenderer; protected MsgBox() { super(true, false, WIDTH, HEIGHT, ""); setErrorFence(null); // Do not accept handling errors!! m_theButtons.setCssClass("ui-mbx-bb"); setOnClose(new IWindowClosed() { @Override public void closed(@Nonnull String closeReason) throws Exception { if(null != m_onAnswer) { m_selectedChoice = m_closeButtonObject; try { m_onAnswer.onAnswer(m_closeButtonObject); } catch(ValidationException ex) { //close message box in case of validation exception is thrown as result of answer. Other exceptions do not close. close(); throw ex; } } if(null != m_onAnswer2) { m_selectedChoice = m_closeButtonObject; try { m_onAnswer2.onAnswer(m_closeButtonObject); } catch(ValidationException ex) { //close message box in case of validation exception is thrown as result of answer. Other exceptions do not close. close(); throw ex; } } } }); } static public MsgBox create(NodeBase parent) { MsgBox w = new MsgBox(); // Create instance // //vmijic 20100326 - in case of cascading floating windows, z-index higher than one from parent floating window must be set. // FloatingWindow parentFloatingWindow = parent.getParent(FloatingWindow.class); // if(parentFloatingWindow != null) { // w.setZIndex(parentFloatingWindow.getZIndex() + 100); UrlPage body = parent.getPage().getBody(); body.add(w); return w; } protected void setType(Type type) { String ttl; String icon; switch(type){ default: throw new IllegalStateException(type + " ??"); case ERROR: ttl = Msgs.BUNDLE.getString(Msgs.UI_MBX_ERROR); icon = "mbx-error.png"; break; case WARNING: ttl = Msgs.BUNDLE.getString(Msgs.UI_MBX_WARNING); icon = "mbx-warning.png"; break; case INFO: ttl = Msgs.BUNDLE.getString(Msgs.UI_MBX_INFO); icon = "mbx-info.png"; break; case DIALOG: ttl = Msgs.BUNDLE.getString(Msgs.UI_MBX_DIALOG); icon = "mbx-question.png"; break; } m_theImage.setSrc("THEME/" + icon); setWindowTitle(ttl); setTestID("msgBox"); } protected void setMessage(String txt) { m_theText = txt; } private void setCloseButton(MsgBoxButton val) { m_closeButtonObject = val; } MsgBoxButton getCloseObject() { return m_closeButtonObject; } public static void message(NodeBase dad, Type mt, String string) { if(mt == Type.DIALOG) { throw new IllegalArgumentException("Please use one of the predefined button calls for MsgType.DIALOG type MsgBox!"); } MsgBox box = create(dad); box.setType(mt); box.setMessage(string); box.addButton(MsgBoxButton.CONTINUE); box.setCloseButton(MsgBoxButton.CONTINUE); box.construct(); } /** * Provides interface to create INFO type messages with custom icon. * @param dad * @param iconSrc * @param string */ public static void message(NodeBase dad, String iconSrc, String string) { message(dad, iconSrc, string, null); } /** * Provides interface to create INFO type messages with custom icon. * @param dad * @param iconSrc * @param string * @param onAnswer */ public static void message(NodeBase dad, String iconSrc, String string, IAnswer onAnswer) { MsgBox box = create(dad); box.setType(Type.INFO); box.m_theImage.setSrc(iconSrc); box.setMessage(string); box.addButton(MsgBoxButton.CONTINUE); box.setCloseButton(MsgBoxButton.CONTINUE); box.setOnAnswer(onAnswer); box.construct(); } /** * Provides interface to create INFO type messages with custom title, icon, data section and optional callback. * @param dad * @param iconSrc * @param title * @param message * @param onAnswer * @param msgRenderer */ public static void message(NodeBase dad, String iconSrc, String title, IAnswer onAnswer, INodeContentRenderer<String> msgRenderer) { MsgBox box = create(dad); box.setType(Type.INFO); box.m_theImage.setSrc(iconSrc); box.setWindowTitle(title); box.addButton(MsgBoxButton.CONTINUE); box.setCloseButton(MsgBoxButton.CONTINUE); box.setOnAnswer(onAnswer); box.setDataRenderer(msgRenderer); box.construct(); } public static void info(NodeBase dad, String string) { message(dad, Type.INFO, string); } public static void warning(NodeBase dad, String string) { message(dad, Type.WARNING, string); } public static void error(NodeBase dad, String string) { message(dad, Type.ERROR, string); } public static void message(NodeBase dad, Type mt, String string, IAnswer onAnswer) { if(mt == Type.DIALOG) { throw new IllegalArgumentException("Please use one of the predefined button calls for MsgType.DIALOG type MsgBox!"); } MsgBox box = create(dad); box.setType(mt); box.setMessage(string); box.addButton(MsgBoxButton.CONTINUE); box.setCloseButton(MsgBoxButton.CONTINUE); box.setOnAnswer(onAnswer); box.construct(); } public static void dialog(NodeBase dad, String title, IAnswer onAnswer, INodeContentRenderer<String> contentRenderer) { MsgBox box = create(dad); box.setType(Type.DIALOG); box.setWindowTitle(title); box.addButton(MsgBoxButton.CANCEL); box.setCloseButton(MsgBoxButton.CANCEL); box.setOnAnswer(onAnswer); box.setDataRenderer(contentRenderer); box.construct(); } public static void yesNoCancel(NodeBase dad, String string, IAnswer onAnswer) { MsgBox box = create(dad); box.setType(Type.DIALOG); box.setMessage(string); box.addButton(MsgBoxButton.YES); box.addButton(MsgBoxButton.NO); box.addButton(MsgBoxButton.CANCEL); box.setCloseButton(MsgBoxButton.CANCEL); box.setOnAnswer(onAnswer); box.construct(); } /** * Ask a yes/no confirmation, and pass either YES or NO to the onAnswer delegate. Use this if you need the NO action too, else use the IClicked variant. * @param dad * @param string * @param onAnswer */ public static void yesNo(NodeBase dad, String string, IAnswer onAnswer) { yesNo(dad, string, onAnswer, null); } /** * Ask a yes/no confirmation, and pass either YES or NO to the onAnswer delegate. Use this if you need the NO action too, else use the IClicked variant. * @param dad * @param string * @param onAnswer * @param msgRenderer Provides custom rendering of specified string message. */ public static void yesNo(NodeBase dad, String string, IAnswer onAnswer, INodeContentRenderer<String> msgRenderer) { MsgBox box = create(dad); box.setType(Type.DIALOG); box.setMessage(string); box.addButton(MsgBoxButton.YES); box.addButton(MsgBoxButton.NO); box.setCloseButton(MsgBoxButton.NO); box.setOnAnswer(onAnswer); box.setDataRenderer(msgRenderer); box.construct(); } /** * Ask a yes/no confirmation; call the onAnswer handler if YES is selected and do nothing otherwise. * @param dad * @param string * @param onAnswer */ public static void yesNo(NodeBase dad, String string, final IClicked<MsgBox> onAnswer) { yesNo(dad, MsgBox.Type.DIALOG, string, onAnswer); } /** * Ask a yes/no confirmation; call the onAnswer handler if YES is selected and do nothing otherwise. * @param dad * @param string * @param onAnswer */ public static void yesNo(NodeBase dad, Type msgtype, String string, final IClicked<MsgBox> onAnswer) { final MsgBox box = create(dad); box.setType(msgtype); box.setMessage(string); box.addButton(MsgBoxButton.YES); box.addButton(MsgBoxButton.NO); box.setCloseButton(MsgBoxButton.NO); box.setOnAnswer(new IAnswer() { @Override public void onAnswer(MsgBoxButton result) throws Exception { if(result == MsgBoxButton.YES) onAnswer.clicked(box); } }); box.construct(); } /** * Show message of specified type, and provide details (More...) button. Usually used to show some error details if user wants to see it. * @param dad * @param type * @param string * @param onAnswer */ public static void okMore(NodeBase dad, Type type, String string, IAnswer onAnswer) { final MsgBox box = create(dad); box.setType(type); box.setMessage(string); box.addButton(MsgBoxButton.OK); box.addButton(MsgBoxButton.MORE); box.setCloseButton(MsgBoxButton.OK); box.setOnAnswer(onAnswer); box.construct(); } /** * Ask a continue/cancel confirmation. This passes either choice to the handler. * @param dad * @param string * @param onAnswer */ public static void continueCancel(NodeBase dad, String string, IAnswer onAnswer) { MsgBox box = create(dad); box.setType(Type.DIALOG); box.setMessage(string); box.addButton(MsgBoxButton.CONTINUE); box.addButton(MsgBoxButton.CANCEL); box.setCloseButton(MsgBoxButton.CANCEL); box.setOnAnswer(onAnswer); box.construct(); } /** * Ask a continue/cancel confirmation, and call the IClicked handler for CONTINUE only. * @param dad * @param string * @param onAnswer */ public static void continueCancel(NodeBase dad, String string, final IClicked<MsgBox> onAnswer) { final MsgBox box = create(dad); box.setType(Type.DIALOG); box.setMessage(string); box.addButton(MsgBoxButton.CONTINUE); box.addButton(MsgBoxButton.CANCEL); box.setCloseButton(MsgBoxButton.CANCEL); box.setOnAnswer(new IAnswer() { @Override public void onAnswer(MsgBoxButton result) throws Exception { if(result == MsgBoxButton.CONTINUE) onAnswer.clicked(box); } }); box.construct(); } /** * * @param dad * @param boxType * @param message * @param onAnswer * @param buttonresultpairs */ public static void flexDialog(@Nonnull NodeBase dad, @Nonnull Type boxType, @Nonnull String message, @Nonnull IAnswer2 onAnswer, Object... buttonresultpairs) { MsgBox box = create(dad); box.setType(boxType); box.setMessage(message); int ix = 0; while(ix < buttonresultpairs.length) { Object o = buttonresultpairs[ix++]; if(o instanceof MsgBoxButton) { MsgBoxButton b = (MsgBoxButton) o; box.addButton(b); } else if(o instanceof String) { String s = (String) o; // Button title if(ix >= buttonresultpairs.length) throw new IllegalArgumentException("Illegal format: must be [button name string], [response object]."); box.addButton(s, buttonresultpairs[ix++]); } else throw new IllegalArgumentException("Unsupported 'button' type in list: " + o + ", only supporting String:Object and MsgBoxButton"); } box.setCloseButton(MsgBoxButton.NO); box.setOnAnswer2(onAnswer); box.construct(); } /** * Create a button which will show an "are you sure" yes/no dialog with a specified text. Only if the user * presses the "yes" button will the clicked handler be executed. * @param icon * @param text The button's text. * @param message The message to show in the are you sure popup * @param ch The delegate to call when the user is sure. * @return */ public static DefaultButton areYouSureButton(String text, String icon, final String message, final IClicked<DefaultButton> ch) { final DefaultButton btn = new DefaultButton(text, icon); IClicked<DefaultButton> bch = new IClicked<DefaultButton>() { @Override public void clicked(DefaultButton b) throws Exception { yesNo(b, message, new IClicked<MsgBox>() { @Override public void clicked(MsgBox bx) throws Exception { ch.clicked(btn); } }); } }; btn.setClicked(bch); return btn; } /** * Create a button which will show an "are you sure" yes/no dialog with a specified text. Only if the user * presses the "yes" button will the clicked handler be executed. * * @param text The button's text. * @param message The message to show in the are you sure popup * @param ch The delegate to call when the user is sure. * @return */ public static DefaultButton areYouSureButton(String text, final String message, final IClicked<DefaultButton> ch) { return areYouSureButton(text, null, message, ch); } /** * Create a LinkButton which will show an "are you sure" yes/no dialog with a specified text. Only if the user * presses the "yes" button will the clicked handler be executed. * @param icon * @param text The button's text. * @param message The message to show in the are you sure popup * @param ch The delegate to call when the user is sure. * @return */ public static LinkButton areYouSureLinkButton(String text, String icon, final String message, final IClicked<LinkButton> ch) { final LinkButton btn = new LinkButton(text, icon); IClicked<LinkButton> bch = new IClicked<LinkButton>() { @Override public void clicked(LinkButton b) throws Exception { yesNo(b, message, new IClicked<MsgBox>() { @Override public void clicked(MsgBox bx) throws Exception { ch.clicked(btn); } }); } }; btn.setClicked(bch); return btn; } /** * Create a button which will show an "are you sure" yes/no dialog with a specified text. Only if the user * presses the "yes" button will the clicked handler be executed. * * @param text The button's text. * @param message The message to show in the are you sure popup * @param ch The delegate to call when the user is sure. * @return */ public static LinkButton areYouSureLinkButton(String text, final String message, final IClicked<LinkButton> ch) { return areYouSureLinkButton(text, null, message, ch); } // /** // * Adjust dimensions in addition to inherited floater behavior. // * @see to.etc.domui.dom.html.NodeBase#createContent() // */ // @Override // public void createContent() throws Exception { // super.createContent(); // setDimensions(WIDTH, HEIGHT); private void construct() { Div a = new Div(); add(a); a.setCssClass("ui-mbx-top"); a.setStretchHeight(true); a.setOverflow(Overflow.AUTO); Table t = new Table(); a.add(t); TBody b = t.getBody(); TR row = b.addRow(); row.setVerticalAlign(VerticalAlignType.TOP); TD td = row.addCell(); td.add(m_theImage); m_theImage.setPosition(PositionType.ABSOLUTE); td.setNowrap(true); td.setWidth("50px"); td = row.addCell("ui-mbx-mc"); if(getDataRenderer() != null) { try { getDataRenderer().renderNodeContent(this, td, m_theText, null); } catch(Exception ex) { Bug.bug(ex); } } else { DomUtil.renderHtmlString(td, m_theText); // 20091206 Allow simple markup in message } add(m_theButtons); //FIXME: vmijic 20090911 Set initial focus to first button. However preventing of keyboard input focus on window in background has to be resolved properly. setFocusOnButton(); } private void setFocusOnButton() { if(m_theButtons.getChildCount() > 0 && m_theButtons.getChild(0) instanceof Button) { ((Button) m_theButtons.getChild(0)).setFocus(); } } @Override public void setDimensions(int width, int height) { super.setDimensions(width, height); setTop("50%"); // center floating window horizontally on screen setMarginLeft("-" + width / 2 + "px"); setMarginTop("-" + height / 2 + "px"); } void setSelectedChoice(Object selectedChoice) { m_selectedChoice = selectedChoice; } protected void answer(Object sel) throws Exception { m_selectedChoice = sel; if(m_onAnswer != null) { try { m_onAnswer.onAnswer((MsgBoxButton) m_selectedChoice); } catch(ValidationException ex) { //close message box in case of validation exception is thrown as result of answer close(); throw ex; } } if(m_onAnswer2 != null) { try { m_onAnswer2.onAnswer(m_selectedChoice); } catch(ValidationException ex) { //close message box in case of validation exception is thrown as result of answer close(); throw ex; } } close(); } /** * Add a default kind of button. * @param mbb */ protected void addButton(final MsgBoxButton mbb) { if(mbb == null) throw new NullPointerException("A message button cannot be null, dufus"); String lbl = MetaManager.findEnumLabel(mbb); if(lbl == null) lbl = mbb.name(); DefaultButton btn = new DefaultButton(lbl, new IClicked<DefaultButton>() { @Override public void clicked(DefaultButton b) throws Exception { answer(mbb); } }); btn.setTestID(mbb.name()); m_theButtons.add(btn); } protected void addButton(final String lbl, final Object selval) { m_theButtons.add(new DefaultButton(lbl, new IClicked<DefaultButton>() { @Override public void clicked(DefaultButton b) throws Exception { answer(selval); } })); } protected IAnswer getOnAnswer() { return m_onAnswer; } protected void setOnAnswer(IAnswer onAnswer) { m_onAnswer = onAnswer; } public IAnswer2 getOnAnswer2() { return m_onAnswer2; } public void setOnAnswer2(IAnswer2 onAnswer2) { m_onAnswer2 = onAnswer2; } protected INodeContentRenderer<String> getDataRenderer() { return m_dataRenderer; } protected void setDataRenderer(INodeContentRenderer<String> dataRenderer) { m_dataRenderer = dataRenderer; } }
package tech.gujin.toast; import android.app.Application; import android.content.Context; import android.os.Looper; import android.util.Log; import android.widget.Toast; public class ToastUtil { private static final String TAG = "ToastUtil"; private static boolean initialized; private static Context sContext; private static Mode sDefaultMode; private static Toast sToast; private static int sDuration; private static ToastUtilHandler sHandler; /** * Initialize the util. * * @param context The context to use. */ public static void initialize(Context context) { initialize(context, Mode.NORMAL); } /** * Initialize the util with the mode from user. * * @param context The context to use. * @param mode The default display mode tu use. Either{@link Mode#NORMAL} or {@link Mode#REPLACEABLE} */ public static void initialize(Context context, Mode mode) { if (initialized) { Log.w(TAG, "Invalid initialize, ToastUtil is already initialized"); return; } if (context == null) { throw new NullPointerException("context can not be null"); } if (context instanceof Application) { sContext = context; } else { sContext = context.getApplicationContext(); } // nullable sDefaultMode = mode; sHandler = new ToastUtilHandler(Looper.getMainLooper()); initialized = true; } /** * Display mode */ public enum Mode { /** * Show as a normal toast. This mode could be user-definable. This is the default. */ NORMAL, /** * When the toast is shown to the user , the text will be replaced if call the show() method again. This mode could be user-definable. */ REPLACEABLE } /** * Shot a toast with the text form a resource. * * @param resId The resource id of the string resource to use. */ public static void show(int resId) { show(sContext.getText(resId), false, sDefaultMode); } /** * Shot a toast. * * @param text The text to show. */ public static void show(CharSequence text) { show(text, false, sDefaultMode); } /** * Shot a toast with the text form a resource. * * @param resId The resource id of the string resource to use. * @param durationLong Whether the toast show for a long period of time? */ public static void show(int resId, boolean durationLong) { show(sContext.getText(resId), durationLong, sDefaultMode); } /** * Show a toast. * * @param text The text to show. * @param durationLong Whether the toast show for a long period of time? */ public static void show(CharSequence text, boolean durationLong) { show(text, durationLong, sDefaultMode); } /** * Shot a toast with the text form a resource. * * @param resId The resource id of the string resource to use. * @param mode The display mode to use. Either {@link Mode#NORMAL} or {@link Mode#REPLACEABLE} */ public static void show(int resId, Mode mode) { show(sContext.getText(resId), false, mode); } /** * Show a toast. * * @param text The text to show. * @param mode The display mode to use. Either {@link Mode#NORMAL} or {@link Mode#REPLACEABLE} */ public static void show(CharSequence text, Mode mode) { show(text, false, mode); } /** * Shot a toast with the text form a resource. * * @param resId resId The resource id of the string resource to use. * @param durationLong Whether the toast show for a long period of time? * @param mode The display mode to use. Either {@link Mode#NORMAL} or {@link Mode#REPLACEABLE} */ public static void show(int resId, boolean durationLong, Mode mode) { show(sContext.getText(resId), durationLong, mode); } /** * Show a toast. * * @param text The text to show. * @param durationLong Whether the toast show for a long period of time? * @param mode The display mode to use. Either {@link Mode#NORMAL} or {@link Mode#REPLACEABLE} */ public static void show(CharSequence text, boolean durationLong, Mode mode) { final int duration = durationLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT; if (mode != Mode.REPLACEABLE) { Toast.makeText(sContext, text, duration).show(); return; } if (sToast == null || sDuration != duration) { sDuration = duration; sToast = Toast.makeText(sContext, text, duration); } else { try { sToast.setText(text); } catch (RuntimeException e) { sToast = Toast.makeText(sContext, text, duration); } } sToast.show(); } /** * Shot a toast with the text form a resource. * * @param resId The resource id of the string resource to use. */ public static void postShow(int resId) { final ToastInfo info = new ToastInfo(); info.resId = resId; info.durationLong = false; sHandler.obtainMessage(ToastUtilHandler.MSG_POST_RES_ID, info).sendToTarget(); } /** * Shot a toast. * * @param text The text to show. */ public static void postShow(CharSequence text) { final ToastInfo info = new ToastInfo(); info.text = text; info.durationLong = false; sHandler.obtainMessage(ToastUtilHandler.MSG_POST_CHAR_SEQUENCE, info).sendToTarget(); } /** * Shot a toast with the text form a resource. * * @param resId The resource id of the string resource to use. * @param durationLong Whether the toast show for a long period of time? */ public static void postShow(int resId, boolean durationLong) { final ToastInfo info = new ToastInfo(); info.resId = resId; info.durationLong = durationLong; sHandler.obtainMessage(ToastUtilHandler.MSG_POST_RES_ID, info).sendToTarget(); } /** * Show a toast. * * @param text The text to show. * @param durationLong Whether the toast show for a long period of time? */ public static void postShow(CharSequence text, boolean durationLong) { final ToastInfo info = new ToastInfo(); info.text = text; info.durationLong = durationLong; sHandler.obtainMessage(ToastUtilHandler.MSG_POST_CHAR_SEQUENCE, info).sendToTarget(); } /** * Shot a toast with the text form a resource. * * @param resId The resource id of the string resource to use. * @param mode The display mode to use. Either {@link Mode#NORMAL} or {@link Mode#REPLACEABLE} */ public static void postShow(int resId, Mode mode) { final ToastInfo info = new ToastInfo(); info.resId = resId; info.mode = mode; sHandler.obtainMessage(ToastUtilHandler.MSG_POST_RES_ID, info).sendToTarget(); } /** * Show a toast. * * @param text The text to show. * @param mode The display mode to use. Either {@link Mode#NORMAL} or {@link Mode#REPLACEABLE} */ public static void postShow(CharSequence text, Mode mode) { final ToastInfo info = new ToastInfo(); info.text = text; info.mode = mode; sHandler.obtainMessage(ToastUtilHandler.MSG_POST_CHAR_SEQUENCE, info).sendToTarget(); } /** * Shot a toast with the text form a resource. * * @param resId resId The resource id of the string resource to use. * @param durationLong Whether the toast show for a long period of time? * @param mode The display mode to use. Either {@link Mode#NORMAL} or {@link Mode#REPLACEABLE} */ public static void postShow(int resId, boolean durationLong, Mode mode) { final ToastInfo info = new ToastInfo(); info.resId = resId; info.durationLong = durationLong; info.mode = mode; sHandler.obtainMessage(ToastUtilHandler.MSG_POST_RES_ID, info).sendToTarget(); } /** * Show a toast. * * @param text The text to show. * @param durationLong Whether the toast show for a long period of time? * @param mode The display mode to use. Either {@link Mode#NORMAL} or {@link Mode#REPLACEABLE} */ public static void postShow(CharSequence text, boolean durationLong, Mode mode) { final ToastInfo info = new ToastInfo(); info.text = text; info.durationLong = durationLong; info.mode = mode; sHandler.obtainMessage(ToastUtilHandler.MSG_POST_CHAR_SEQUENCE, info).sendToTarget(); } private ToastUtil() { } }
package peergos.shared.user.fs; import jsinterop.annotations.*; import peergos.shared.*; import peergos.shared.crypto.*; import peergos.shared.crypto.asymmetric.*; import peergos.shared.crypto.random.*; import peergos.shared.crypto.symmetric.*; import peergos.shared.io.ipfs.multihash.*; import peergos.shared.user.*; import peergos.shared.user.fs.cryptree.*; import peergos.shared.util.*; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.awt.Graphics2D; import java.awt.AlphaComposite; import java.awt.RenderingHints; import java.io.*; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.time.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.function.*; import java.util.stream.*; public class FileTreeNode { final static int THUMBNAIL_SIZE = 100; private final NativeJSThumbnail thumbnail; private final RetrievedFilePointer pointer; private final FileProperties props; private final String ownername; private final Optional<TrieNode> globalRoot; private final Set<String> readers; private final Set<String> writers; private final Optional<SecretSigningKey> entryWriterKey; private AtomicBoolean modified = new AtomicBoolean(); // This only used as a guard against concurrent modifications /** * * @param globalRoot This is only present for if this is the global root * @param pointer * @param ownername * @param readers * @param writers * @param entryWriterKey */ public FileTreeNode(Optional<TrieNode> globalRoot, RetrievedFilePointer pointer, String ownername, Set<String> readers, Set<String> writers, Optional<SecretSigningKey> entryWriterKey) { this.globalRoot = globalRoot; this.pointer = pointer == null ? null : pointer.withWriter(entryWriterKey); this.ownername = ownername; this.readers = readers; this.writers = writers; this.entryWriterKey = entryWriterKey; if (pointer == null) props = new FileProperties("/", "", 0, LocalDateTime.MIN, false, Optional.empty()); else { SymmetricKey parentKey = this.getParentKey(); props = pointer.fileAccess.getProperties(parentKey); } thumbnail = new NativeJSThumbnail(); } public FileTreeNode(RetrievedFilePointer pointer, String ownername, Set<String> readers, Set<String> writers, Optional<SecretSigningKey> entryWriterKey) { this(Optional.empty(), pointer, ownername, readers, writers, entryWriterKey); } public FileTreeNode withTrieNode(TrieNode trie) { return new FileTreeNode(Optional.of(trie), pointer, ownername, readers, writers, entryWriterKey); } private FileTreeNode withCryptreeNode(CryptreeNode access) { return new FileTreeNode(globalRoot, new RetrievedFilePointer(getPointer().filePointer, access), ownername, readers, writers, entryWriterKey); } @JsMethod public boolean equals(Object other) { if (other == null) return false; if (!(other instanceof FileTreeNode)) return false; return pointer.equals(((FileTreeNode) other).getPointer()); } public RetrievedFilePointer getPointer() { return pointer; } public boolean isRoot() { return props.name.equals("/"); } public CompletableFuture<String> getPath(NetworkAccess network) { return retrieveParent(network).thenCompose(parent -> { if (!parent.isPresent() || parent.get().isRoot()) return CompletableFuture.completedFuture("/" + props.name); return parent.get().getPath(network).thenApply(parentPath -> parentPath + "/" + props.name); }); } public CompletableFuture<Optional<FileTreeNode>> getDescendentByPath(String path, NetworkAccess network) { ensureUnmodified(); if (path.length() == 0) return CompletableFuture.completedFuture(Optional.of(this)); if (path.equals("/")) if (isDirectory()) return CompletableFuture.completedFuture(Optional.of(this)); else return CompletableFuture.completedFuture(Optional.empty()); if (path.startsWith("/")) path = path.substring(1); int slash = path.indexOf("/"); String prefix = slash > 0 ? path.substring(0, slash) : path; String suffix = slash > 0 ? path.substring(slash + 1) : ""; return getChildren(network).thenCompose(children -> { for (FileTreeNode child : children) if (child.getFileProperties().name.equals(prefix)) { return child.getDescendentByPath(suffix, network); } return CompletableFuture.completedFuture(Optional.empty()); }); } private void ensureUnmodified() { if (modified.get()) throw new IllegalStateException("This file has already been modified, use the returned instance"); } private void setModified() { if (modified.get()) throw new IllegalStateException("This file has already been modified, use the returned instance"); modified.set(true); } /** * Marks a file/directory and all its descendants as dirty. Directories are immediately cleaned, * but files have all their keys except the actual data key cleaned. That is cleaned lazily, the next time it is modified * * @param network * @param parent * @param readersToRemove * @return * @throws IOException */ public CompletableFuture<FileTreeNode> makeDirty(NetworkAccess network, SafeRandom random, FileTreeNode parent, Set<String> readersToRemove) { if (!isWritable()) throw new IllegalStateException("You cannot mark a file as dirty without write access!"); if (isDirectory()) { // create a new baseKey == subfoldersKey and make all descendants dirty SymmetricKey newSubfoldersKey = SymmetricKey.random(); FilePointer ourNewPointer = pointer.filePointer.withBaseKey(newSubfoldersKey); SymmetricKey newParentKey = SymmetricKey.random(); FileProperties props = getFileProperties(); DirAccess existing = (DirAccess) pointer.fileAccess; // Create new DirAccess, but don't upload it DirAccess newDirAccess = DirAccess.create(existing.committedHash(), newSubfoldersKey, props, parent.pointer.filePointer.getLocation(), parent.getParentKey(), newParentKey); // re add children List<FilePointer> subdirs = existing.getSubfolders().stream().map(link -> new FilePointer(link.targetLocation(pointer.filePointer.baseKey), Optional.empty(), link.target(pointer.filePointer.baseKey))).collect(Collectors.toList()); return newDirAccess.addSubdirsAndCommit(subdirs, newSubfoldersKey, ourNewPointer, getSigner(), network, random) .thenCompose(updatedDirAccess -> { SymmetricKey filesKey = existing.getFilesKey(pointer.filePointer.baseKey); List<FilePointer> files = existing.getFiles().stream() .map(link -> new FilePointer(link.targetLocation(filesKey), Optional.empty(), link.target(filesKey))) .collect(Collectors.toList()); return updatedDirAccess.addFilesAndCommit(files, newSubfoldersKey, ourNewPointer, getSigner(), network, random) .thenCompose(fullyUpdatedDirAccess -> { readers.removeAll(readersToRemove); RetrievedFilePointer ourNewRetrievedPointer = new RetrievedFilePointer(ourNewPointer, fullyUpdatedDirAccess); FileTreeNode theNewUs = new FileTreeNode(ourNewRetrievedPointer, ownername, readers, writers, entryWriterKey); // clean all subtree keys except file dataKeys (lazily re-key and re-encrypt them) return getChildren(network).thenCompose(children -> { for (FileTreeNode child : children) { child.makeDirty(network, random, theNewUs, readersToRemove); } // update pointer from parent to us return ((DirAccess) parent.pointer.fileAccess) .updateChildLink(parent.pointer.filePointer, this.pointer, ourNewRetrievedPointer, getSigner(), network, random) .thenApply(x -> theNewUs); }); }); }).thenApply(x -> { setModified(); return x; }); } else { // create a new baseKey == parentKey and mark the metaDataKey as dirty SymmetricKey parentKey = SymmetricKey.random(); return ((FileAccess) pointer.fileAccess).markDirty(writableFilePointer(), parentKey, network).thenCompose(newFileAccess -> { // changing readers here will only affect the returned FileTreeNode, as the readers are derived from the entry point TreeSet<String> newReaders = new TreeSet<>(readers); newReaders.removeAll(readersToRemove); RetrievedFilePointer newPointer = new RetrievedFilePointer(this.pointer.filePointer.withBaseKey(parentKey), newFileAccess); // update link from parent folder to file to have new baseKey return ((DirAccess) parent.pointer.fileAccess) .updateChildLink(parent.writableFilePointer(), pointer, newPointer, getSigner(), network, random) .thenApply(x -> new FileTreeNode(newPointer, ownername, newReaders, writers, entryWriterKey)); }).thenApply(x -> { setModified(); return x; }); } } public CompletableFuture<Boolean> hasChildWithName(String name, NetworkAccess network) { ensureUnmodified(); return getChildren(network) .thenApply(children -> children.stream().filter(c -> c.props.name.equals(name)).findAny().isPresent()); } public CompletableFuture<FileTreeNode> removeChild(FileTreeNode child, NetworkAccess network) { setModified(); return ((DirAccess) pointer.fileAccess) .removeChild(child.getPointer(), pointer.filePointer, getSigner(), network) .thenApply(updated -> new FileTreeNode(globalRoot, new RetrievedFilePointer(getPointer().filePointer, updated), ownername, readers, writers, entryWriterKey)); } public CompletableFuture<FileTreeNode> addLinkTo(FileTreeNode file, NetworkAccess network, SafeRandom random) { ensureUnmodified(); CompletableFuture<FileTreeNode> error = new CompletableFuture<>(); if (!this.isDirectory() || !this.isWritable()) { error.completeExceptionally(new IllegalArgumentException("Can only add link to a writable directory!")); return error; } String name = file.getFileProperties().name; return hasChildWithName(name, network).thenCompose(hasChild -> { if (hasChild) { error.completeExceptionally(new IllegalStateException("Child already exists with name: " + name)); return error; } DirAccess toUpdate = (DirAccess) pointer.fileAccess; return (file.isDirectory() ? toUpdate.addSubdirAndCommit(file.pointer.filePointer, this.getKey(), pointer.filePointer, getSigner(), network, random) : toUpdate.addFileAndCommit(file.pointer.filePointer, this.getKey(), pointer.filePointer, getSigner(), network, random)) .thenApply(dirAccess -> new FileTreeNode(this.pointer, ownername, readers, writers, entryWriterKey)); }); } @JsMethod public String toLink() { return pointer.filePointer.toLink(); } @JsMethod public boolean isWritable() { return entryWriterKey.isPresent(); } @JsMethod public boolean isReadable() { try { pointer.fileAccess.getMetaKey(pointer.filePointer.baseKey); return false; } catch (Exception e) {} return true; } public SymmetricKey getKey() { return pointer.filePointer.baseKey; } public Location getLocation() { return pointer.filePointer.getLocation(); } private SigningPrivateKeyAndPublicHash getSigner() { if (! isWritable()) throw new IllegalStateException("Can only get a signer for a writable directory!"); return new SigningPrivateKeyAndPublicHash(getLocation().writer, entryWriterKey.get()); } public Set<Location> getChildrenLocations() { ensureUnmodified(); if (!this.isDirectory()) return Collections.emptySet(); return ((DirAccess) pointer.fileAccess).getChildrenLocations(pointer.filePointer.baseKey); } public CompletableFuture<Optional<FileTreeNode>> retrieveParent(NetworkAccess network) { ensureUnmodified(); if (pointer == null) return CompletableFuture.completedFuture(Optional.empty()); SymmetricKey parentKey = getParentKey(); CompletableFuture<RetrievedFilePointer> parent = pointer.fileAccess.getParent(parentKey, network); return parent.thenApply(parentRFP -> { if (parentRFP == null) return Optional.empty(); return Optional.of(new FileTreeNode(parentRFP, ownername, Collections.emptySet(), Collections.emptySet(), entryWriterKey)); }); } public SymmetricKey getParentKey() { ensureUnmodified(); SymmetricKey parentKey = pointer.filePointer.baseKey; if (this.isDirectory()) try { parentKey = pointer.fileAccess.getParentKey(parentKey); } catch (Exception e) { // if we don't have read access to this folder, then we must just have the parent key already } return parentKey; } @JsMethod public CompletableFuture<Set<FileTreeNode>> getChildren(NetworkAccess network) { ensureUnmodified(); if (globalRoot.isPresent()) return globalRoot.get().getChildren("/", network); if (isReadable()) { return retrieveChildren(network).thenApply(childrenRFPs -> { Set<FileTreeNode> newChildren = childrenRFPs.stream() .map(x -> new FileTreeNode(x, ownername, readers, writers, entryWriterKey)) .collect(Collectors.toSet()); return newChildren.stream().collect(Collectors.toSet()); }); } throw new IllegalStateException("Unreadable FileTreeNode!"); } public CompletableFuture<Optional<FileTreeNode>> getChild(String name, NetworkAccess network) { return getChildren(network) .thenApply(children -> children.stream().filter(f -> f.getName().equals(name)).findAny()); } private CompletableFuture<Set<RetrievedFilePointer>> retrieveChildren(NetworkAccess network) { FilePointer filePointer = pointer.filePointer; CryptreeNode fileAccess = pointer.fileAccess; SymmetricKey rootDirKey = filePointer.baseKey; if (isReadable()) return ((DirAccess) fileAccess).getChildren(network, rootDirKey); throw new IllegalStateException("No credentials to retrieve children!"); } public CompletableFuture<FileTreeNode> cleanUnreachableChildren(NetworkAccess network) { setModified(); FilePointer filePointer = pointer.filePointer; CryptreeNode fileAccess = pointer.fileAccess; SymmetricKey rootDirKey = filePointer.baseKey; if (isReadable()) return ((DirAccess) fileAccess).cleanUnreachableChildren(network, rootDirKey, filePointer, getSigner()) .thenApply(da -> new FileTreeNode(globalRoot, new RetrievedFilePointer(filePointer, da), ownername, readers, writers, entryWriterKey)); throw new IllegalStateException("No credentials to retrieve children!"); } @JsMethod public String getOwner() { return ownername; } @JsMethod public boolean isDirectory() { boolean isNull = pointer == null; return isNull || pointer.fileAccess.isDirectory(); } public boolean isDirty() { ensureUnmodified(); return pointer.fileAccess.isDirty(pointer.filePointer.baseKey); } /** * * @param network * @param random * @param parent * @param fragmenter * @return updated parent dir */ public CompletableFuture<FileTreeNode> clean(NetworkAccess network, SafeRandom random, FileTreeNode parent, peergos.shared.user.fs.Fragmenter fragmenter) { if (!isDirty()) return CompletableFuture.completedFuture(this); if (isDirectory()) { throw new IllegalStateException("Directories are never dirty (they are cleaned immediately)!"); } else { FileProperties props = getFileProperties(); SymmetricKey baseKey = pointer.filePointer.baseKey; // stream download and re-encrypt with new metaKey return getInputStream(network, random, l -> {}).thenCompose(in -> { byte[] tmp = new byte[16]; new Random().nextBytes(tmp); String tmpFilename = ArrayOps.bytesToHex(tmp) + ".tmp"; CompletableFuture<FileTreeNode> reuploaded = parent.uploadFileSection(tmpFilename, in, 0, props.size, Optional.of(baseKey), true, network, random, l -> {}, fragmenter); return reuploaded.thenCompose(upload -> upload.getDescendentByPath(tmpFilename, network) .thenCompose(tmpChild -> tmpChild.get().rename(props.name, network, upload, true)) .thenApply(res -> { setModified(); return res; })); }); } } @JsMethod public CompletableFuture<FileTreeNode> uploadFileJS(String filename, AsyncReader fileData, int lengthHi, int lengthLow, boolean overwriteExisting, NetworkAccess network, SafeRandom random, ProgressConsumer<Long> monitor, Fragmenter fragmenter) { return uploadFileSection(filename, fileData, 0, lengthLow + ((lengthHi & 0xFFFFFFFFL) << 32), Optional.empty(), overwriteExisting, network, random, monitor, fragmenter); } public CompletableFuture<FileTreeNode> uploadFile(String filename, AsyncReader fileData, long length, NetworkAccess network, SafeRandom random, ProgressConsumer<Long> monitor, Fragmenter fragmenter) { return uploadFileSection(filename, fileData, 0, length, Optional.empty(), true, network, random, monitor, fragmenter); } public CompletableFuture<FileTreeNode> uploadFile(String filename, AsyncReader fileData, boolean isHidden, long length, boolean overwriteExisting, NetworkAccess network, SafeRandom random, ProgressConsumer<Long> monitor, Fragmenter fragmenter) { return uploadFileSection(filename, fileData, isHidden, 0, length, Optional.empty(), overwriteExisting, network, random, monitor, fragmenter); } public CompletableFuture<FileTreeNode> uploadFileSection(String filename, AsyncReader fileData, long startIndex, long endIndex, NetworkAccess network, SafeRandom random, ProgressConsumer<Long> monitor, Fragmenter fragmenter) { return uploadFileSection(filename, fileData, startIndex, endIndex, Optional.empty(), true, network, random, monitor, fragmenter); } public CompletableFuture<FileTreeNode> uploadFileSection(String filename, AsyncReader fileData, long startIndex, long endIndex, Optional<SymmetricKey> baseKey, boolean overwriteExisting, NetworkAccess network, SafeRandom random, ProgressConsumer<Long> monitor, Fragmenter fragmenter) { return uploadFileSection(filename, fileData, false, startIndex, endIndex, baseKey, overwriteExisting, network, random, monitor, fragmenter); } public CompletableFuture<FileTreeNode> uploadFileSection(String filename, AsyncReader fileData, boolean isHidden, long startIndex, long endIndex, Optional<SymmetricKey> baseKey, boolean overwriteExisting, NetworkAccess network, SafeRandom random, ProgressConsumer<Long> monitor, Fragmenter fragmenter) { if (!isLegalName(filename)) { CompletableFuture<FileTreeNode> res = new CompletableFuture<>(); res.completeExceptionally(new IllegalStateException("Illegal filename: " + filename)); return res; } if (! isDirectory()) { CompletableFuture<FileTreeNode> res = new CompletableFuture<>(); res.completeExceptionally(new IllegalStateException("Cannot upload a sub file to a file!")); return res; } return getDescendentByPath(filename, network).thenCompose(childOpt -> { if (childOpt.isPresent()) { if (! overwriteExisting) throw new IllegalStateException("File already exists with name " + filename); return updateExistingChild(childOpt.get(), fileData, startIndex, endIndex, network, random, monitor, fragmenter); } if (startIndex > 0) { // TODO if startIndex > 0 prepend with a zero section throw new IllegalStateException("Unimplemented!"); } SymmetricKey fileKey = baseKey.orElseGet(SymmetricKey::random); SymmetricKey fileMetaKey = SymmetricKey.random(); SymmetricKey rootRKey = pointer.filePointer.baseKey; DirAccess dirAccess = (DirAccess) pointer.fileAccess; SymmetricKey dirParentKey = dirAccess.getParentKey(rootRKey); Location parentLocation = getLocation(); int thumbnailSrcImageSize = startIndex == 0 && endIndex < Integer.MAX_VALUE ? (int) endIndex : 0; return generateThumbnail(network, fileData, thumbnailSrcImageSize, filename) .thenCompose(thumbData -> fileData.reset() .thenCompose(forMime -> calculateMimeType(forMime, endIndex) .thenCompose(mimeType -> fileData.reset().thenCompose(resetReader -> { FileProperties fileProps = new FileProperties(filename, mimeType, endIndex, LocalDateTime.now(), isHidden, Optional.of(thumbData)); FileUploader chunks = new FileUploader(filename, mimeType, resetReader, startIndex, endIndex, fileKey, fileMetaKey, parentLocation, dirParentKey, monitor, fileProps, fragmenter); byte[] mapKey = random.randomBytes(32); Location nextChunkLocation = new Location(getLocation().owner, getLocation().writer, mapKey); return chunks.upload(network, random, parentLocation.owner, getSigner(), nextChunkLocation) .thenCompose(fileLocation -> { FilePointer filePointer = new FilePointer(fileLocation, Optional.empty(), fileKey); return addChildPointer(filename, filePointer, network, random, 2); }); })) ) ); }); } private CompletableFuture<FileTreeNode> addChildPointer(String filename, FilePointer childPointer, NetworkAccess network, SafeRandom random, int retries) { CompletableFuture<FileTreeNode> result = new CompletableFuture<>(); ((DirAccess) pointer.fileAccess).addFileAndCommit(childPointer, pointer.filePointer.baseKey, pointer.filePointer, getSigner(), network, random) .thenAccept(uploadResult -> { setModified(); result.complete(this.withCryptreeNode(uploadResult)); }).exceptionally(e -> { if (e instanceof Btree.CasException || e.getCause() instanceof Btree.CasException) { // reload directory and try again network.getMetadata(getLocation()).thenCompose(opt -> { DirAccess updatedUs = (DirAccess) opt.get(); // Check another file of same name hasn't been added in the concurrent change RetrievedFilePointer updatedPointer = new RetrievedFilePointer(pointer.filePointer, updatedUs); FileTreeNode us = new FileTreeNode(globalRoot, updatedPointer, ownername, readers, writers, entryWriterKey); return us.getChildren(network).thenCompose(children -> { Set<String> childNames = children.stream() .map(f -> f.getName()) .collect(Collectors.toSet()); if (! childNames.contains(filename)) { return us.addChildPointer(filename, childPointer, network, random, retries) .thenAccept(res -> { result.complete(res); }); } String safeName = nextSafeReplacementFilename(filename, childNames); // rename file in place as we've already uploaded it return network.getMetadata(childPointer.location).thenCompose(renameOpt -> { CryptreeNode fileToRename = renameOpt.get(); RetrievedFilePointer updatedChildPointer = new RetrievedFilePointer(childPointer, fileToRename); FileTreeNode toRename = new FileTreeNode(Optional.empty(), updatedChildPointer, ownername, readers, writers, entryWriterKey); return toRename.rename(safeName, network, us).thenCompose(usAgain -> ((DirAccess) usAgain.pointer.fileAccess) .addFileAndCommit(childPointer, pointer.filePointer.baseKey, pointer.filePointer, getSigner(), network, random) .thenAccept(uploadResult -> { setModified(); result.complete(this.withCryptreeNode(uploadResult)); })); }); }); }).exceptionally(ex -> { if ((e instanceof Btree.CasException || e.getCause() instanceof Btree.CasException) && retries > 0) addChildPointer(filename, childPointer, network, random, retries - 1) .thenApply(f -> result.complete(f)) .exceptionally(e2 -> { result.completeExceptionally(e2); return null; }); else result.completeExceptionally(e); return null; }); } else result.completeExceptionally(e); return null; }); return result; } private static String nextSafeReplacementFilename(String desired, Set<String> existing) { if (! existing.contains(desired)) return desired; for (int counter = 1; counter < 1000; counter++) { int dot = desired.lastIndexOf("."); String candidate = dot >= 0 ? desired.substring(0, dot) + "[" + counter + "]" + desired.substring(dot) : desired + "[" + counter + "]"; if (! existing.contains(candidate)) return candidate; } throw new IllegalStateException("Too many concurrent writes trying to add a file of the same name!"); } private CompletableFuture<FileTreeNode> updateExistingChild(FileTreeNode existingChild, AsyncReader fileData, long inputStartIndex, long endIndex, NetworkAccess network, SafeRandom random, ProgressConsumer<Long> monitor, Fragmenter fragmenter) { String filename = existingChild.getFileProperties().name; System.out.println("Overwriting section [" + Long.toHexString(inputStartIndex) + ", " + Long.toHexString(endIndex) + "] of child with name: " + filename); Supplier<Location> locationSupplier = () -> new Location(getLocation().owner, getLocation().writer, random.randomBytes(32)); return (existingChild.isDirty() ? existingChild.clean(network, random, this, fragmenter) .thenCompose(us -> us.getChild(filename, network) .thenApply(cleanedChild -> new Pair<>(us, cleanedChild.get()))) : CompletableFuture.completedFuture(new Pair<>(this, existingChild)) ).thenCompose(updatedPair -> { FileTreeNode us = updatedPair.left; FileTreeNode child = updatedPair.right; FileProperties childProps = child.getFileProperties(); final AtomicLong filesSize = new AtomicLong(childProps.size); FileRetriever retriever = child.getRetriever(); SymmetricKey baseKey = child.pointer.filePointer.baseKey; FileAccess fileAccess = (FileAccess) child.pointer.fileAccess; SymmetricKey dataKey = fileAccess.getDataKey(baseKey); List<Long> startIndexes = new ArrayList<>(); for (long startIndex = inputStartIndex; startIndex < endIndex; startIndex = startIndex + Chunk.MAX_SIZE - (startIndex % Chunk.MAX_SIZE)) startIndexes.add(startIndex); boolean identity = true; BiFunction<Boolean, Long, CompletableFuture<Boolean>> composer = (id, startIndex) -> { return retriever.getChunkInputStream(network, random, dataKey, startIndex, filesSize.get(), child.getLocation(), child.pointer.fileAccess.committedHash(), monitor) .thenCompose(currentLocation -> { CompletableFuture<Optional<Location>> locationAt = retriever .getLocationAt(child.getLocation(), startIndex + Chunk.MAX_SIZE, dataKey, network); return locationAt.thenCompose(location -> CompletableFuture.completedFuture(new Pair<>(currentLocation, location))); } ).thenCompose(pair -> { if (!pair.left.isPresent()) { CompletableFuture<Boolean> result = new CompletableFuture<>(); result.completeExceptionally(new IllegalStateException("Current chunk not present")); return result; } LocatedChunk currentOriginal = pair.left.get(); Optional<Location> nextChunkLocationOpt = pair.right; Location nextChunkLocation = nextChunkLocationOpt.orElseGet(locationSupplier); System.out.println("********** Writing to chunk at mapkey: " + ArrayOps.bytesToHex(currentOriginal.location.getMapKey()) + " next: " + nextChunkLocation); // modify chunk, re-encrypt and upload int internalStart = (int) (startIndex % Chunk.MAX_SIZE); int internalEnd = endIndex - (startIndex - internalStart) > Chunk.MAX_SIZE ? Chunk.MAX_SIZE : (int) (endIndex - (startIndex - internalStart)); byte[] rawData = currentOriginal.chunk.data(); // extend data array if necessary if (rawData.length < internalEnd) rawData = Arrays.copyOfRange(rawData, 0, internalEnd); byte[] raw = rawData; return fileData.readIntoArray(raw, internalStart, internalEnd - internalStart).thenCompose(read -> { byte[] nonce = random.randomBytes(TweetNaCl.SECRETBOX_NONCE_BYTES); Chunk updated = new Chunk(raw, dataKey, currentOriginal.location.getMapKey(), nonce); LocatedChunk located = new LocatedChunk(currentOriginal.location, currentOriginal.existingHash, updated); long currentSize = filesSize.get(); FileProperties newProps = new FileProperties(childProps.name, childProps.mimeType, endIndex > currentSize ? endIndex : currentSize, LocalDateTime.now(), childProps.isHidden, childProps.thumbnail); CompletableFuture<Multihash> chunkUploaded = FileUploader.uploadChunk(getSigner(), newProps, getLocation(), us.getParentKey(), baseKey, located, fragmenter, nextChunkLocation, network, monitor); return chunkUploaded.thenCompose(isUploaded -> { //update indices to be relative to next chunk long updatedLength = startIndex + internalEnd - internalStart; if (updatedLength > filesSize.get()) { filesSize.set(updatedLength); if (updatedLength > Chunk.MAX_SIZE) { // update file size in FileProperties of first chunk CompletableFuture<Boolean> updatedSize = getChildren(network).thenCompose(children -> { Optional<FileTreeNode> updatedChild = children.stream() .filter(f -> f.getFileProperties().name.equals(filename)) .findAny(); return updatedChild.get().setProperties(child.getFileProperties().withSize(endIndex), network, this); }); } } return CompletableFuture.completedFuture(true); }); }); }); }; BiFunction<Boolean, Boolean, Boolean> combiner = (left, right) -> left && right; return Futures.reduceAll(startIndexes, identity, composer, combiner) .thenApply(b -> us); }); } static boolean isLegalName(String name) { return !name.contains("/"); } @JsMethod public CompletableFuture<FilePointer> mkdir(String newFolderName, NetworkAccess network, boolean isSystemFolder, SafeRandom random) throws IOException { return mkdir(newFolderName, network, null, isSystemFolder, random); } public CompletableFuture<FilePointer> mkdir(String newFolderName, NetworkAccess network, SymmetricKey requestedBaseSymmetricKey, boolean isSystemFolder, SafeRandom random) { CompletableFuture<FilePointer> result = new CompletableFuture<>(); if (!this.isDirectory()) { result.completeExceptionally(new IllegalStateException("Cannot mkdir in a file!")); return result; } if (!isLegalName(newFolderName)) { result.completeExceptionally(new IllegalStateException("Illegal directory name: " + newFolderName)); return result; } return hasChildWithName(newFolderName, network).thenCompose(hasChild -> { if (hasChild) { result.completeExceptionally(new IllegalStateException("Child already exists with name: " + newFolderName)); return result; } FilePointer dirPointer = pointer.filePointer; DirAccess dirAccess = (DirAccess) pointer.fileAccess; SymmetricKey rootDirKey = dirPointer.baseKey; return dirAccess.mkdir(newFolderName, network, dirPointer.location.owner, getSigner(), dirPointer.getLocation().getMapKey(), rootDirKey, requestedBaseSymmetricKey, isSystemFolder, random).thenApply(x -> { setModified(); return x; }); }); } @JsMethod public CompletableFuture<FileTreeNode> rename(String newFilename, NetworkAccess network, FileTreeNode parent) { return rename(newFilename, network, parent, false); } /** * @param newFilename * @param network * @param parent * @param overwrite * @return the updated parent */ public CompletableFuture<FileTreeNode> rename(String newFilename, NetworkAccess network, FileTreeNode parent, boolean overwrite) { setModified(); if (! isLegalName(newFilename)) return CompletableFuture.completedFuture(parent); CompletableFuture<Optional<FileTreeNode>> childExists = parent == null ? CompletableFuture.completedFuture(Optional.empty()) : parent.getDescendentByPath(newFilename, network); return childExists .thenCompose(existing -> { if (existing.isPresent() && !overwrite) return CompletableFuture.completedFuture(parent); return ((overwrite && existing.isPresent()) ? existing.get().remove(network, parent) : CompletableFuture.completedFuture(parent) ).thenCompose(res -> { //get current props FilePointer filePointer = pointer.filePointer; SymmetricKey baseKey = filePointer.baseKey; CryptreeNode fileAccess = pointer.fileAccess; SymmetricKey key = this.isDirectory() ? fileAccess.getParentKey(baseKey) : baseKey; FileProperties currentProps = fileAccess.getProperties(key); FileProperties newProps = new FileProperties(newFilename, currentProps.mimeType, currentProps.size, currentProps.modified, currentProps.isHidden, currentProps.thumbnail); return fileAccess.updateProperties(writableFilePointer(), newProps, network) .thenApply(fa -> res); }); }); } public CompletableFuture<Boolean> setProperties(FileProperties updatedProperties, NetworkAccess network, FileTreeNode parent) { setModified(); String newName = updatedProperties.name; CompletableFuture<Boolean> result = new CompletableFuture<>(); if (!isLegalName(newName)) { result.completeExceptionally(new IllegalArgumentException("Illegal file name: " + newName)); return result; } return (parent == null ? CompletableFuture.completedFuture(false) : parent.hasChildWithName(newName, network)) .thenCompose(hasChild -> { if (hasChild && parent != null && !parent.getChildrenLocations().stream() .map(l -> new ByteArrayWrapper(l.getMapKey())) .collect(Collectors.toSet()) .contains(new ByteArrayWrapper(pointer.filePointer.getLocation().getMapKey()))) { result.completeExceptionally(new IllegalStateException("Cannot rename to same name as an existing file")); return result; } CryptreeNode fileAccess = pointer.fileAccess; return fileAccess.updateProperties(writableFilePointer(), updatedProperties, network) .thenApply(fa -> true); }); } private FilePointer writableFilePointer() { FilePointer filePointer = pointer.filePointer; SymmetricKey baseKey = filePointer.baseKey; return new FilePointer(filePointer.location, entryWriterKey, baseKey); } public Optional<SecretSigningKey> getEntryWriterKey() { return entryWriterKey; } @JsMethod public CompletableFuture<FileTreeNode> copyTo(FileTreeNode target, NetworkAccess network, SafeRandom random, Fragmenter fragmenter) { ensureUnmodified(); CompletableFuture<FileTreeNode> result = new CompletableFuture<>(); if (! target.isDirectory()) { result.completeExceptionally(new IllegalStateException("CopyTo target " + target + " must be a directory")); return result; } return target.hasChildWithName(getFileProperties().name, network).thenCompose(childExists -> { if (childExists) { result.completeExceptionally(new IllegalStateException("CopyTo target " + target + " already has child with name " + getFileProperties().name)); return result; } boolean sameWriter = getLocation().writer.equals(target.getLocation().writer); //make new FileTreeNode pointing to the same file if we are the same writer, but with a different location if (sameWriter) { byte[] newMapKey = new byte[32]; random.randombytes(newMapKey, 0, 32); SymmetricKey ourBaseKey = this.getKey(); SymmetricKey newBaseKey = SymmetricKey.random(); FilePointer newRFP = new FilePointer(target.getLocation().owner, target.getLocation().writer, newMapKey, newBaseKey); Location newParentLocation = target.getLocation(); SymmetricKey newParentParentKey = target.getParentKey(); return pointer.fileAccess.copyTo(ourBaseKey, newBaseKey, newParentLocation, newParentParentKey, target.getLocation().writer, getSigner(), newMapKey, network, random) .thenCompose(newAccess -> { // upload new metadatablob RetrievedFilePointer newRetrievedFilePointer = new RetrievedFilePointer(newRFP, newAccess); FileTreeNode newFileTreeNode = new FileTreeNode(newRetrievedFilePointer, target.getOwner(), Collections.emptySet(), Collections.emptySet(), target.getEntryWriterKey()); return target.addLinkTo(newFileTreeNode, network, random); }); } else { return getInputStream(network, random, x -> {}) .thenCompose(stream -> target.uploadFileSection(getName(), stream, 0, getSize(), Optional.empty(), false, network, random, x -> {}, fragmenter) .thenApply(b -> target)); } }); } /** * @param network * @param parent * @return updated parent */ @JsMethod public CompletableFuture<FileTreeNode> remove(NetworkAccess network, FileTreeNode parent) { ensureUnmodified(); Supplier<CompletableFuture<Boolean>> supplier = () -> new RetrievedFilePointer(writableFilePointer(), pointer.fileAccess) .remove(network, null, getSigner()); if (parent != null) { return parent.removeChild(this, network) .thenCompose(updated -> supplier.get() .thenApply(x -> updated)); } return supplier.get().thenApply(x -> parent); } public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network, SafeRandom random, ProgressConsumer<Long> monitor) { return getInputStream(network, random, getFileProperties().size, monitor); } @JsMethod public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network, SafeRandom random, int fileSizeHi, int fileSizeLow, ProgressConsumer<Long> monitor) { return getInputStream(network, random, fileSizeLow + ((fileSizeHi & 0xFFFFFFFFL) << 32), monitor); } public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network, SafeRandom random, long fileSize, ProgressConsumer<Long> monitor) { ensureUnmodified(); if (pointer.fileAccess.isDirectory()) throw new IllegalStateException("Cannot get input stream for a directory!"); FileAccess fileAccess = (FileAccess) pointer.fileAccess; SymmetricKey baseKey = pointer.filePointer.baseKey; SymmetricKey dataKey = fileAccess.getDataKey(baseKey); return fileAccess.retriever().getFile(network, random, dataKey, fileSize, getLocation(), fileAccess.committedHash(), monitor); } private FileRetriever getRetriever() { if (pointer.fileAccess.isDirectory()) throw new IllegalStateException("Cannot get input stream for a directory!"); FileAccess fileAccess = (FileAccess) pointer.fileAccess; return fileAccess.retriever(); } @JsMethod public String getBase64Thumbnail() { Optional<byte[]> thumbnail = props.thumbnail; if (thumbnail.isPresent()) { String base64Data = Base64.getEncoder().encodeToString(thumbnail.get()); return "data:image/png;base64," + base64Data; } else { return ""; } } @JsMethod public FileProperties getFileProperties() { ensureUnmodified(); return props; } public String getName() { return getFileProperties().name; } public long getSize() { return getFileProperties().size; } public String toString() { return getFileProperties().name; } public static FileTreeNode createRoot(TrieNode root) { return new FileTreeNode(Optional.of(root), null, null, Collections.EMPTY_SET, Collections.EMPTY_SET, null); } public static byte[] generateThumbnail(byte[] imageBlob) { try { BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBlob)); BufferedImage thumbnailImage = new BufferedImage(THUMBNAIL_SIZE, THUMBNAIL_SIZE, image.getType()); Graphics2D g = thumbnailImage.createGraphics(); g.setComposite(AlphaComposite.Src); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.drawImage(image, 0, 0, THUMBNAIL_SIZE, THUMBNAIL_SIZE, null); g.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(thumbnailImage, "JPG", baos); baos.close(); return baos.toByteArray(); } catch (IOException ioe) { ioe.printStackTrace(); } return new byte[0]; } public static byte[] generateVideoThumbnail(byte[] videoBlob) { File tempFile = null; try { tempFile = File.createTempFile(UUID.randomUUID().toString(), ".mp4"); Files.write(tempFile.toPath(), videoBlob, StandardOpenOption.WRITE); return VideoThumbnail.create(tempFile.getAbsolutePath(), THUMBNAIL_SIZE, THUMBNAIL_SIZE); } catch (IOException ioe) { ioe.printStackTrace(); } finally { if(tempFile != null) { try { Files.delete(tempFile.toPath()); }catch(IOException ioe){ } } } return new byte[0]; } private CompletableFuture<byte[]> generateThumbnail(NetworkAccess network, AsyncReader fileData, int fileSize, String filename) { CompletableFuture<byte[]> fut = new CompletableFuture<>(); if (fileSize > MimeTypes.HEADER_BYTES_TO_IDENTIFY_MIME_TYPE) { getFileType(fileData).thenAccept(mimeType -> { if (mimeType.startsWith("image")) { if (network.isJavascript()) { thumbnail.generateThumbnail(fileData, fileSize, filename).thenAccept(base64Str -> { byte[] bytesOfData = Base64.getDecoder().decode(base64Str); fut.complete(bytesOfData); }); } else { byte[] bytes = new byte[fileSize]; fileData.readIntoArray(bytes, 0, fileSize).thenAccept(data -> { fut.complete(generateThumbnail(bytes)); }); } }else if(mimeType.startsWith("video")) { if (network.isJavascript()) { thumbnail.generateVideoThumbnail(fileData, fileSize, filename).thenAccept(base64Str -> { byte[] bytesOfData = Base64.getDecoder().decode(base64Str); fut.complete(bytesOfData); }); } else { byte[] bytes = new byte[fileSize]; fileData.readIntoArray(bytes, 0, fileSize).thenAccept(data -> { fut.complete(generateVideoThumbnail(bytes)); }); } } else { fut.complete(new byte[0]); } }); } else { fut.complete(new byte[0]); } return fut; } private CompletableFuture<String> getFileType(AsyncReader imageBlob) { CompletableFuture<String> result = new CompletableFuture<>(); byte[] data = new byte[MimeTypes.HEADER_BYTES_TO_IDENTIFY_MIME_TYPE]; imageBlob.readIntoArray(data, 0, data.length).thenAccept(numBytesRead -> { imageBlob.reset().thenAccept(resetResult -> { if (numBytesRead < data.length) { result.complete(""); } else { String mimeType = MimeTypes.calculateMimeType(data); result.complete(mimeType); } }); }); return result; } public static CompletableFuture<String> calculateMimeType(AsyncReader data, long fileSize) { byte[] header = new byte[(int) Math.min(fileSize, MimeTypes.HEADER_BYTES_TO_IDENTIFY_MIME_TYPE)]; return data.readIntoArray(header, 0, header.length) .thenApply(read -> MimeTypes.calculateMimeType(header)); } }
import java.awt.Font; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import com.senac.SimpleJava.Console; import com.senac.SimpleJava.Graphics.Canvas; import com.senac.SimpleJava.Graphics.Color; import com.senac.SimpleJava.Graphics.GraphicApplication; import com.senac.SimpleJava.Graphics.Image; import com.senac.SimpleJava.Graphics.Point; import com.senac.SimpleJava.Graphics.Resolution; import com.senac.SimpleJava.Graphics.events.KeyboardAction; public class Arkanoid extends GraphicApplication { private Tile tiles1[] = new Tile[8]; private Tile tiles2[] = new Tile[8]; private Tile tiles3[] = new Tile[8]; private Tile tiles4[] = new Tile[8]; private Tile tiles5[] = new Tile[8]; private Paddle paddle; private Ball ball; private static int deltaY = 1; private static int deltaX = 1; private static int score = 0; private static int highScore = 0; private static int playerLife = 3; private static int level = 1; private static int tiles = 0; private static boolean startGame = false; private Image backgroundImage; private Image logoImage; private JLabel lblScore = new JLabel("SCORE: " + score, SwingConstants.CENTER); private JLabel lblHighScore = new JLabel("<html><center>HIGH SCORE<br>" + highScore + "</center></html>"); private JLabel lblLife = new JLabel("LIFE: " + playerLife, SwingConstants.CENTER); private JLabel lblAcademic = new JLabel("<html><center>Laura Abitante<br>2016<center><html>", SwingConstants.CENTER); private JLabel lblGameOver = new JLabel("GAME OVER"); private JLabel lblRestart = new JLabel("Press spacebar to restart"); private JLabel lblStartGame = new JLabel("Press enter to start"); private JLabel lblLevel = new JLabel("LEVEL: " + level, SwingConstants.CENTER); private JLabel lblWinner = new JLabel("YOU WIN!"); Font fontHeader = new Font("courier", Font.BOLD, 16); Font fontGameOver = new Font("courier", Font.BOLD, 32); Font fontWinner = new Font("courier", Font.BOLD, 42); Font fontRestart = new Font("courier", Font.BOLD, 22); Font fontHighScore = new Font("courier", Font.BOLD, 20); Font fontAcademic = new Font("courier", Font.BOLD, 12); @Override protected void draw(Canvas canvas) { canvas.clear(); canvas.drawImage(backgroundImage, 0, 0); canvas.drawImage(logoImage, 190, 20); //Draw tiles drawTiles(canvas,tiles1); drawTiles(canvas,tiles2); drawTiles(canvas,tiles3); drawTiles(canvas,tiles4); drawTiles(canvas,tiles5); //Draw components ball.draw(canvas); paddle.draw(canvas); canvas.add(lblScore); canvas.add(lblHighScore); canvas.add(lblAcademic); canvas.add(lblLife); canvas.add(lblLevel); canvas.add(lblGameOver); canvas.add(lblRestart); canvas.add(lblStartGame); canvas.add(lblWinner); } @Override protected void setup() { this.setFramesPerSecond(60); this.setResolution(Resolution.MSX); this.setTitle("ARKANOID PROJECT - LAURA ABITANTE"); try { backgroundImage = new Image("images/background.png"); } catch (IOException e) { e.printStackTrace(System.err); } try { logoImage = new Image("images/logo.png"); } catch (IOException e) { e.printStackTrace(System.err); } ball = new Ball(); ball.setPosition(120, 177); paddle = new Paddle(); paddle.setPosition(100, 183); buildLevels(); setupKeyboardKeys(); setupLabels(); } @Override protected void loop() { if (startGame == false) { lblStartGame.setVisible(!lblRestart.isVisible()); Console.println("Enter to start"); setupPanel(); redraw(); return; } //Testing axis X and Y. Point pos = ball.getPosition(); if (testScreenBounds(pos.y, 10, getResolution().height)) { Console.println("Y"); Console.println(deltaY); if (deltaY == 1){ playerLife try { playSound("sounds/lost_life.wav"); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } startGame = false; } if (playerLife == 0){ lblStartGame.setVisible(false); deltaY = 0; deltaX = 0; Console.println("Game Over"); lblGameOver.setVisible(true); try { playSound("sounds/game_over.wav"); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } Console.println("Restart"); lblRestart.setVisible(true); } else { deltaY *= -1; } } if(tiles <= 0 && playerLife > 0) { if(level >= 3) { lblWinner.setVisible(true); lblStartGame.setVisible(false); lblRestart.setVisible(true); } else { lblStartGame.setVisible(true); level++; setup(); } startGame = false; } if (testScreenBounds(pos.x, 12, getResolution().width - 80)) { deltaX *= -1; Console.println("X"); } //Check collided paddle if (paddle.collided(ball)) { deltaY = -1; Console.println("Collided PADDLE!"); try { playSound("sounds/paddle.wav"); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Tiles collision check checkTilesCollision(ball, tiles1); checkTilesCollision(ball, tiles2); checkTilesCollision(ball, tiles3); checkTilesCollision(ball, tiles4); checkTilesCollision(ball, tiles5); setupPanel(); ball.move(deltaX, deltaY); redraw(); } private boolean testScreenBounds(double pos, int min, int max) { if(pos > max || pos < min) { return true; } else { return false; } } public static void buildTiles(Tile t[], int tileCount, Color c, int life, int posY) { for (int i=0; i< tileCount; i++) { Tile tile = new Tile(c, life); tile.setPosition(14 + (i*20), posY); t[i] = tile; } } public static void drawTiles(Canvas c, Tile t[]) { for(int i=0; i<t.length; i++) { Tile tile = t[i]; tile.draw(c); } } public static void checkTilesCollision(Ball ball, Tile t[]) { for (int i=0; i<t.length; i++) { Tile tile = t[i]; if (tile.collided(ball)) { if (ball.getPosition().y > tile.getPosition().y) { deltaY = 1; } else { deltaY = -1; } if (ball.getPosition().x <= tile.getPosition().x) { deltaX = -1; } else if (ball.getPosition().x >= tile.getPosition().x + tile.getWidth()) { deltaX = 1; } Console.println("Collided!"); if (tile.lifeTile == 1) { try { playSound("sounds/tile_strong.wav"); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { playSound("sounds/tile_weak.wav"); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } } score += 10; if(highScore < score){ highScore = score; } tiles } } } public void setupKeyboardKeys() { bindKeyPressed("LEFT", new KeyboardAction() { @Override public void handleEvent() { paddle.getPosition(); if(startGame == true){ if(paddle.getPosition().x > 14){ paddle.move(-6, 0); } } } }); bindKeyPressed("RIGHT", new KeyboardAction() { @Override public void handleEvent() { if(startGame == true){ if(paddle.getPosition().x + paddle.getWidth() < getResolution().width - 82){ paddle.move(6, 0); } } } }); bindKeyPressed("SPACE", new KeyboardAction() { @Override public void handleEvent() { if (playerLife == 0 || lblWinner.isVisible()) { deltaY = -1; deltaX = -1; playerLife = 3; score = 0; level = 1; tiles = 0; startGame = false; setup(); } } }); bindKeyPressed("ENTER", new KeyboardAction() { @Override public void handleEvent() { if (startGame == false && !lblRestart.isVisible()) { startGame = true; setup(); lblStartGame.setVisible(false); } } }); } static void playSound(String soundFile) throws LineUnavailableException, MalformedURLException, IOException, UnsupportedAudioFileException { File f = new File("./" + soundFile); Clip clip = AudioSystem.getClip(); clip.open(AudioSystem.getAudioInputStream(f.toURI().toURL())); clip.start(); } public void buildLevels() { if (tiles <= 0) { if(level == 1) { buildTiles(tiles1, tiles1.length, Color.GRAY, 2, 19); buildTiles(tiles2, tiles2.length, Color.BLUE, 1, 28); buildTiles(tiles3, tiles3.length, Color.MAGENTA, 1, 37); buildTiles(tiles4, tiles4.length, Color.GREEN, 1, 46); buildTiles(tiles5, tiles5.length, Color.RED, 1, 55); tiles = 48; playStartLevel(); } else if(level == 2){ buildTiles(tiles1, 1, Color.GREEN, 1, 19); buildTiles(tiles2, 3, Color.RED, 1, 28); buildTiles(tiles3, 5, Color.CYAN, 1, 37); buildTiles(tiles4, 7, Color.YELLOW, 1, 46); buildTiles(tiles5, tiles5.length, Color.GRAY, 2, 55); tiles = 32; playStartLevel(); } else if(level == 3){ buildTiles(tiles1, tiles1.length, Color.GRAY, 2, 19); buildTiles(tiles2, tiles1.length, Color.CYAN, 1, 28); buildTiles(tiles3, tiles1.length, Color.GRAY, 2, 37); buildTiles(tiles4, tiles1.length, Color.BLUE, 1, 46); buildTiles(tiles5, tiles1.length, Color.GRAY, 2, 55); tiles = 64; playStartLevel(); } } } public void playStartLevel(){ try { playSound("sounds/start_level.wav"); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void setupLabels() { //Building score lblScore.setVisible(true); lblScore.setBounds(590, 250, 200, 100); lblScore.setFont(fontHeader); lblScore.setForeground(java.awt.Color.white); //Building high score lblHighScore.setVisible(true); lblHighScore.setBounds(630, 330, 200, 100); lblHighScore.setFont(fontHighScore); lblHighScore.setForeground(java.awt.Color.red); //Life player lblLife.setVisible(true); lblLife.setBounds(590, 150, 200, 100); lblLife.setFont(fontHeader); lblLife.setForeground(java.awt.Color.white); //Level lblLevel.setVisible(true); lblLevel.setBounds(590, 200, 200, 100); lblLevel.setFont(fontHeader); lblLevel.setForeground(java.awt.Color.white); //Academic lblAcademic.setVisible(true); lblAcademic.setBounds(590, 500, 200, 100); lblAcademic.setFont(fontAcademic); lblAcademic.setForeground(java.awt.Color.white); //Game Over lblGameOver.setVisible(false); lblGameOver.setBounds(215, 150, 300, 300); lblGameOver.setFont(fontGameOver); lblGameOver.setForeground(java.awt.Color.red); //Restart lblRestart.setVisible(false); lblRestart.setBounds(140, 190, 325, 300); lblRestart.setFont(fontRestart); lblRestart.setForeground(java.awt.Color.white); //Start lblStartGame.setVisible(false); lblStartGame.setBounds(170, 190, 300, 300); lblStartGame.setFont(fontRestart); lblStartGame.setForeground(java.awt.Color.white); //Winner lblWinner.setVisible(false); lblWinner.setBounds(200, 150, 300, 300); lblWinner.setFont(fontWinner); lblWinner.setForeground(java.awt.Color.red); } public void setupPanel() { lblScore.setText("SCORE: "+ score); lblHighScore.setText("<html><center>HIGH SCORE<br>" + highScore + "</center></html>"); lblLife.setText("LIFE: "+ playerLife); lblLevel.setText("LEVEL: "+ level); } }
package org.mozilla.javascript.tools.shell; import java.io.*; import java.net.*; import java.nio.charset.Charset; import java.lang.reflect.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.Matcher; import org.mozilla.javascript.*; import org.mozilla.javascript.commonjs.module.Require; import org.mozilla.javascript.commonjs.module.RequireBuilder; import org.mozilla.javascript.commonjs.module.provider.SoftCachingModuleScriptProvider; import org.mozilla.javascript.commonjs.module.provider.UrlModuleSourceProvider; import org.mozilla.javascript.tools.ToolErrorReporter; import org.mozilla.javascript.serialize.*; /** * This class provides for sharing functions across multiple threads. * This is of particular interest to server applications. * * @author Norris Boyd */ public class Global extends ImporterTopLevel { static final long serialVersionUID = 4029130780977538005L; NativeArray history; boolean attemptedJLineLoad; private ShellConsole console; private InputStream inStream; private PrintStream outStream; private PrintStream errStream; private boolean sealedStdLib = false; boolean initialized; private QuitAction quitAction; private String[] prompts = { "js> ", " > " }; private HashMap<String,String> doctestCanonicalizations; public Global() { } public Global(Context cx) { init(cx); } public boolean isInitialized() { return initialized; } /** * Set the action to call from quit(). */ public void initQuitAction(QuitAction quitAction) { if (quitAction == null) throw new IllegalArgumentException("quitAction is null"); if (this.quitAction != null) throw new IllegalArgumentException("The method is once-call."); this.quitAction = quitAction; } public void init(ContextFactory factory) { factory.call(new ContextAction() { public Object run(Context cx) { init(cx); return null; } }); } public void init(Context cx) { // Define some global functions particular to the shell. Note // that these functions are not part of ECMA. initStandardObjects(cx, sealedStdLib); String[] names = { "defineClass", "deserialize", "doctest", "gc", "help", "load", "loadClass", "print", "quit", "readFile", "readUrl", "runCommand", "seal", "serialize", "spawn", "sync", "toint32", "version", }; defineFunctionProperties(names, Global.class, ScriptableObject.DONTENUM); // Set up "environment" in the global scope to provide access to the // System environment variables. Environment.defineClass(this); Environment environment = new Environment(this); defineProperty("environment", environment, ScriptableObject.DONTENUM); history = (NativeArray) cx.newArray(this, 0); defineProperty("history", history, ScriptableObject.DONTENUM); initialized = true; } public Require installRequire(Context cx, List<String> modulePath, boolean sandboxed) { RequireBuilder rb = new RequireBuilder(); rb.setSandboxed(sandboxed); List<URI> uris = new ArrayList<URI>(); if (modulePath != null) { for (String path : modulePath) { try { URI uri = new URI(path); if (!uri.isAbsolute()) { // call resolve("") to canonify the path uri = new File(path).toURI().resolve(""); } if (!uri.toString().endsWith("/")) { // make sure URI always terminates with slash to // avoid loading from unintended locations uri = new URI(uri + "/"); } uris.add(uri); } catch (URISyntaxException usx) { throw new RuntimeException(usx); } } } rb.setModuleScriptProvider( new SoftCachingModuleScriptProvider( new UrlModuleSourceProvider(uris, null))); Require require = rb.createRequire(cx, this); require.install(this); return require; } /** * Print a help message. * * This method is defined as a JavaScript function. */ public static void help(Context cx, Scriptable thisObj, Object[] args, Function funObj) { PrintStream out = getInstance(funObj).getOut(); out.println(ToolErrorReporter.getMessage("msg.help")); } public static void gc(Context cx, Scriptable thisObj, Object[] args, Function funObj) { System.gc(); } /** * Print the string values of its arguments. * * This method is defined as a JavaScript function. * Note that its arguments are of the "varargs" form, which * allows it to handle an arbitrary number of arguments * supplied to the JavaScript function. * */ public static Object print(Context cx, Scriptable thisObj, Object[] args, Function funObj) { PrintStream out = getInstance(funObj).getOut(); for (int i=0; i < args.length; i++) { if (i > 0) out.print(" "); // Convert the arbitrary JavaScript value into a string form. String s = Context.toString(args[i]); out.print(s); } out.println(); return Context.getUndefinedValue(); } /** * Call embedding-specific quit action passing its argument as * int32 exit code. * * This method is defined as a JavaScript function. */ public static void quit(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Global global = getInstance(funObj); if (global.quitAction != null) { int exitCode = (args.length == 0 ? 0 : ScriptRuntime.toInt32(args[0])); global.quitAction.quit(cx, exitCode); } } /** * Get and set the language version. * * This method is defined as a JavaScript function. */ public static double version(Context cx, Scriptable thisObj, Object[] args, Function funObj) { double result = cx.getLanguageVersion(); if (args.length > 0) { double d = Context.toNumber(args[0]); cx.setLanguageVersion((int) d); } return result; } /** * Load and execute a set of JavaScript source files. * * This method is defined as a JavaScript function. * */ public static void load(Context cx, Scriptable thisObj, Object[] args, Function funObj) { for (Object arg : args) { String file = Context.toString(arg); try { Main.processFile(cx, thisObj, file); } catch (IOException ioex) { String msg = ToolErrorReporter.getMessage( "msg.couldnt.read.source", file, ioex.getMessage()); throw Context.reportRuntimeError(msg); } catch (VirtualMachineError ex) { // Treat StackOverflow and OutOfMemory as runtime errors ex.printStackTrace(); String msg = ToolErrorReporter.getMessage( "msg.uncaughtJSException", ex.toString()); throw Context.reportRuntimeError(msg); } } } @SuppressWarnings({"unchecked"}) public static void defineClass(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IllegalAccessException, InstantiationException, InvocationTargetException { Class<?> clazz = getClass(args); if (!Scriptable.class.isAssignableFrom(clazz)) { throw reportRuntimeError("msg.must.implement.Scriptable"); } ScriptableObject.defineClass(thisObj, (Class<? extends Scriptable>)clazz); } public static void loadClass(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IllegalAccessException, InstantiationException { Class<?> clazz = getClass(args); if (!Script.class.isAssignableFrom(clazz)) { throw reportRuntimeError("msg.must.implement.Script"); } Script script = (Script) clazz.newInstance(); script.exec(cx, thisObj); } private static Class<?> getClass(Object[] args) { if (args.length == 0) { throw reportRuntimeError("msg.expected.string.arg"); } Object arg0 = args[0]; if (arg0 instanceof Wrapper) { Object wrapped = ((Wrapper)arg0).unwrap(); if (wrapped instanceof Class) return (Class<?>)wrapped; } String className = Context.toString(args[0]); try { return Class.forName(className); } catch (ClassNotFoundException cnfe) { throw reportRuntimeError("msg.class.not.found", className); } } public static void serialize(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { if (args.length < 2) { throw Context.reportRuntimeError( "Expected an object to serialize and a filename to write " + "the serialization to"); } Object obj = args[0]; String filename = Context.toString(args[1]); FileOutputStream fos = new FileOutputStream(filename); Scriptable scope = ScriptableObject.getTopLevelScope(thisObj); ScriptableOutputStream out = new ScriptableOutputStream(fos, scope); out.writeObject(obj); out.close(); } public static Object deserialize(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException, ClassNotFoundException { if (args.length < 1) { throw Context.reportRuntimeError( "Expected a filename to read the serialization from"); } String filename = Context.toString(args[0]); FileInputStream fis = new FileInputStream(filename); Scriptable scope = ScriptableObject.getTopLevelScope(thisObj); ObjectInputStream in = new ScriptableInputStream(fis, scope); Object deserialized = in.readObject(); in.close(); return Context.toObject(deserialized, scope); } public String[] getPrompts(Context cx) { if (ScriptableObject.hasProperty(this, "prompts")) { Object promptsJS = ScriptableObject.getProperty(this, "prompts"); if (promptsJS instanceof Scriptable) { Scriptable s = (Scriptable) promptsJS; if (ScriptableObject.hasProperty(s, 0) && ScriptableObject.hasProperty(s, 1)) { Object elem0 = ScriptableObject.getProperty(s, 0); if (elem0 instanceof Function) { elem0 = ((Function) elem0).call(cx, this, s, new Object[0]); } prompts[0] = Context.toString(elem0); Object elem1 = ScriptableObject.getProperty(s, 1); if (elem1 instanceof Function) { elem1 = ((Function) elem1).call(cx, this, s, new Object[0]); } prompts[1] = Context.toString(elem1); } } } return prompts; } /** * Example: doctest("js> function f() {\n > return 3;\n > }\njs> f();\n3\n"); returns 2 * (since 2 tests were executed). */ public static Object doctest(Context cx, Scriptable thisObj, Object[] args, Function funObj) { if (args.length == 0) { return Boolean.FALSE; } String session = Context.toString(args[0]); Global global = getInstance(funObj); return new Integer(global.runDoctest(cx, global, session, null, 0)); } public int runDoctest(Context cx, Scriptable scope, String session, String sourceName, int lineNumber) { doctestCanonicalizations = new HashMap<String,String>(); String[] lines = session.split("\r\n?|\n"); String prompt0 = this.prompts[0].trim(); String prompt1 = this.prompts[1].trim(); int testCount = 0; int i = 0; while (i < lines.length && !lines[i].trim().startsWith(prompt0)) { i++; // skip lines that don't look like shell sessions } while (i < lines.length) { String inputString = lines[i].trim().substring(prompt0.length()); inputString += "\n"; i++; while (i < lines.length && lines[i].trim().startsWith(prompt1)) { inputString += lines[i].trim().substring(prompt1.length()); inputString += "\n"; i++; } String expectedString = ""; while (i < lines.length && !lines[i].trim().startsWith(prompt0)) { expectedString += lines[i] + "\n"; i++; } PrintStream savedOut = this.getOut(); PrintStream savedErr = this.getErr(); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); this.setOut(new PrintStream(out)); this.setErr(new PrintStream(err)); String resultString = ""; ErrorReporter savedErrorReporter = cx.getErrorReporter(); cx.setErrorReporter(new ToolErrorReporter(false, this.getErr())); try { testCount++; Object result = cx.evaluateString(scope, inputString, "doctest input", 1, null); if (result != Context.getUndefinedValue() && !(result instanceof Function && inputString.trim().startsWith("function"))) { resultString = Context.toString(result); } } catch (RhinoException e) { ToolErrorReporter.reportException(cx.getErrorReporter(), e); } finally { this.setOut(savedOut); this.setErr(savedErr); cx.setErrorReporter(savedErrorReporter); resultString += err.toString() + out.toString(); } if (!doctestOutputMatches(expectedString, resultString)) { String message = "doctest failure running:\n" + inputString + "expected: " + expectedString + "actual: " + resultString + "\n"; if (sourceName != null) throw Context.reportRuntimeError(message, sourceName, lineNumber+i-1, null, 0); else throw Context.reportRuntimeError(message); } } return testCount; } /** * Compare actual result of doctest to expected, modulo some * acceptable differences. Currently just trims the strings * before comparing, but should ignore differences in line numbers * for error messages for example. * * @param expected the expected string * @param actual the actual string * @return true iff actual matches expected modulo some acceptable * differences */ private boolean doctestOutputMatches(String expected, String actual) { expected = expected.trim(); actual = actual.trim().replace("\r\n", "\n"); if (expected.equals(actual)) return true; for (Map.Entry<String,String> entry: doctestCanonicalizations.entrySet()) { expected = expected.replace(entry.getKey(), entry.getValue()); } if (expected.equals(actual)) return true; // java.lang.Object.toString() prints out a unique hex number associated // with each object. This number changes from run to run, so we want to // ignore differences between these numbers in the output. We search for a // regexp that matches the hex number preceded by '@', then enter mappings into // "doctestCanonicalizations" so that we ensure that the mappings are // consistent within a session. Pattern p = Pattern.compile("@[0-9a-fA-F]+"); Matcher expectedMatcher = p.matcher(expected); Matcher actualMatcher = p.matcher(actual); for (;;) { if (!expectedMatcher.find()) return false; if (!actualMatcher.find()) return false; if (actualMatcher.start() != expectedMatcher.start()) return false; int start = expectedMatcher.start(); if (!expected.substring(0, start).equals(actual.substring(0, start))) return false; String expectedGroup = expectedMatcher.group(); String actualGroup = actualMatcher.group(); String mapping = doctestCanonicalizations.get(expectedGroup); if (mapping == null) { doctestCanonicalizations.put(expectedGroup, actualGroup); expected = expected.replace(expectedGroup, actualGroup); } else if (!actualGroup.equals(mapping)) { return false; // wrong object! } if (expected.equals(actual)) return true; } } /** * The spawn function runs a given function or script in a different * thread. * * js> function g() { a = 7; } * js> a = 3; * 3 * js> spawn(g) * Thread[Thread-1,5,main] * js> a * 3 */ public static Object spawn(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Scriptable scope = funObj.getParentScope(); Runner runner; if (args.length != 0 && args[0] instanceof Function) { Object[] newArgs = null; if (args.length > 1 && args[1] instanceof Scriptable) { newArgs = cx.getElements((Scriptable) args[1]); } if (newArgs == null) { newArgs = ScriptRuntime.emptyArgs; } runner = new Runner(scope, (Function) args[0], newArgs); } else if (args.length != 0 && args[0] instanceof Script) { runner = new Runner(scope, (Script) args[0]); } else { throw reportRuntimeError("msg.spawn.args"); } runner.factory = cx.getFactory(); Thread thread = new Thread(runner); thread.start(); return thread; } /** * The sync function creates a synchronized function (in the sense * of a Java synchronized method) from an existing function. The * new function synchronizes on the the second argument if it is * defined, or otherwise the <code>this</code> object of * its invocation. * js> var o = { f : sync(function(x) { * print("entry"); * Packages.java.lang.Thread.sleep(x*1000); * print("exit"); * })}; * js> spawn(function() {o.f(5);}); * Thread[Thread-0,5,main] * entry * js> spawn(function() {o.f(5);}); * Thread[Thread-1,5,main] * js> * exit * entry * exit */ public static Object sync(Context cx, Scriptable thisObj, Object[] args, Function funObj) { if (args.length >= 1 && args.length <= 2 && args[0] instanceof Function) { Object syncObject = null; if (args.length == 2 && args[1] != Undefined.instance) { syncObject = args[1]; } return new Synchronizer((Function)args[0], syncObject); } else { throw reportRuntimeError("msg.sync.args"); } } /** * Execute the specified command with the given argument and options * as a separate process and return the exit status of the process. * <p> * Usage: * <pre> * runCommand(command) * runCommand(command, arg1, ..., argN) * runCommand(command, arg1, ..., argN, options) * </pre> * All except the last arguments to runCommand are converted to strings * and denote command name and its arguments. If the last argument is a * JavaScript object, it is an option object. Otherwise it is converted to * string denoting the last argument and options objects assumed to be * empty. * The following properties of the option object are processed: * <ul> * <li><tt>args</tt> - provides an array of additional command arguments * <li><tt>env</tt> - explicit environment object. All its enumerable * properties define the corresponding environment variable names. * <li><tt>input</tt> - the process input. If it is not * java.io.InputStream, it is converted to string and sent to the process * as its input. If not specified, no input is provided to the process. * <li><tt>output</tt> - the process output instead of * java.lang.System.out. If it is not instance of java.io.OutputStream, * the process output is read, converted to a string, appended to the * output property value converted to string and put as the new value of * the output property. * <li><tt>err</tt> - the process error output instead of * java.lang.System.err. If it is not instance of java.io.OutputStream, * the process error output is read, converted to a string, appended to * the err property value converted to string and put as the new * value of the err property. * <li><tt>dir</tt> - the working direcotry to run the commands. * </ul> */ public static Object runCommand(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { int L = args.length; if (L == 0 || (L == 1 && args[0] instanceof Scriptable)) { throw reportRuntimeError("msg.runCommand.bad.args"); } File wd = null; InputStream in = null; OutputStream out = null, err = null; ByteArrayOutputStream outBytes = null, errBytes = null; Object outObj = null, errObj = null; String[] environment = null; Scriptable params = null; Object[] addArgs = null; if (args[L - 1] instanceof Scriptable) { params = (Scriptable)args[L - 1]; --L; Object envObj = ScriptableObject.getProperty(params, "env"); if (envObj != Scriptable.NOT_FOUND) { if (envObj == null) { environment = new String[0]; } else { if (!(envObj instanceof Scriptable)) { throw reportRuntimeError("msg.runCommand.bad.env"); } Scriptable envHash = (Scriptable)envObj; Object[] ids = ScriptableObject.getPropertyIds(envHash); environment = new String[ids.length]; for (int i = 0; i != ids.length; ++i) { Object keyObj = ids[i], val; String key; if (keyObj instanceof String) { key = (String)keyObj; val = ScriptableObject.getProperty(envHash, key); } else { int ikey = ((Number)keyObj).intValue(); key = Integer.toString(ikey); val = ScriptableObject.getProperty(envHash, ikey); } if (val == ScriptableObject.NOT_FOUND) { val = Undefined.instance; } environment[i] = key+'='+ScriptRuntime.toString(val); } } } Object wdObj = ScriptableObject.getProperty(params, "dir"); if(wdObj != Scriptable.NOT_FOUND){ wd = new File(ScriptRuntime.toString(wdObj)); } Object inObj = ScriptableObject.getProperty(params, "input"); if (inObj != Scriptable.NOT_FOUND) { in = toInputStream(inObj); } outObj = ScriptableObject.getProperty(params, "output"); if (outObj != Scriptable.NOT_FOUND) { out = toOutputStream(outObj); if (out == null) { outBytes = new ByteArrayOutputStream(); out = outBytes; } } errObj = ScriptableObject.getProperty(params, "err"); if (errObj != Scriptable.NOT_FOUND) { err = toOutputStream(errObj); if (err == null) { errBytes = new ByteArrayOutputStream(); err = errBytes; } } Object addArgsObj = ScriptableObject.getProperty(params, "args"); if (addArgsObj != Scriptable.NOT_FOUND) { Scriptable s = Context.toObject(addArgsObj, getTopLevelScope(thisObj)); addArgs = cx.getElements(s); } } Global global = getInstance(funObj); if (out == null) { out = (global != null) ? global.getOut() : System.out; } if (err == null) { err = (global != null) ? global.getErr() : System.err; } // If no explicit input stream, do not send any input to process, // in particular, do not use System.in to avoid deadlocks // when waiting for user input to send to process which is already // terminated as it is not always possible to interrupt read method. String[] cmd = new String[(addArgs == null) ? L : L + addArgs.length]; for (int i = 0; i != L; ++i) { cmd[i] = ScriptRuntime.toString(args[i]); } if (addArgs != null) { for (int i = 0; i != addArgs.length; ++i) { cmd[L + i] = ScriptRuntime.toString(addArgs[i]); } } int exitCode = runProcess(cmd, environment, wd, in, out, err); if (outBytes != null) { String s = ScriptRuntime.toString(outObj) + outBytes.toString(); ScriptableObject.putProperty(params, "output", s); } if (errBytes != null) { String s = ScriptRuntime.toString(errObj) + errBytes.toString(); ScriptableObject.putProperty(params, "err", s); } return new Integer(exitCode); } /** * The seal function seals all supplied arguments. */ public static void seal(Context cx, Scriptable thisObj, Object[] args, Function funObj) { for (int i = 0; i != args.length; ++i) { Object arg = args[i]; if (!(arg instanceof ScriptableObject) || arg == Undefined.instance) { if (!(arg instanceof Scriptable) || arg == Undefined.instance) { throw reportRuntimeError("msg.shell.seal.not.object"); } else { throw reportRuntimeError("msg.shell.seal.not.scriptable"); } } } for (int i = 0; i != args.length; ++i) { Object arg = args[i]; ((ScriptableObject)arg).sealObject(); } } /** * The readFile reads the given file content and convert it to a string * using the specified character coding or default character coding if * explicit coding argument is not given. * <p> * Usage: * <pre> * readFile(filePath) * readFile(filePath, charCoding) * </pre> * The first form converts file's context to string using the default * character coding. */ public static Object readFile(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { if (args.length == 0) { throw reportRuntimeError("msg.shell.readFile.bad.args"); } String path = ScriptRuntime.toString(args[0]); String charCoding = null; if (args.length >= 2) { charCoding = ScriptRuntime.toString(args[1]); } return readUrl(path, charCoding, true); } /** * The readUrl opens connection to the given URL, read all its data * and converts them to a string * using the specified character coding or default character coding if * explicit coding argument is not given. * <p> * Usage: * <pre> * readUrl(url) * readUrl(url, charCoding) * </pre> * The first form converts file's context to string using the default * charCoding. */ public static Object readUrl(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { if (args.length == 0) { throw reportRuntimeError("msg.shell.readUrl.bad.args"); } String url = ScriptRuntime.toString(args[0]); String charCoding = null; if (args.length >= 2) { charCoding = ScriptRuntime.toString(args[1]); } return readUrl(url, charCoding, false); } /** * Convert the argument to int32 number. */ public static Object toint32(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Object arg = (args.length != 0 ? args[0] : Undefined.instance); if (arg instanceof Integer) return arg; return ScriptRuntime.wrapInt(ScriptRuntime.toInt32(arg)); } private boolean loadJLine(Charset cs) { if (!attemptedJLineLoad) { // Check if we can use JLine for better command line handling attemptedJLineLoad = true; console = ShellConsole.getConsole(this, cs); } return console != null; } public ShellConsole getConsole(Charset cs) { if (!loadJLine(cs)) { console = ShellConsole.getConsole(getIn(), getErr(), cs); } return console; } public InputStream getIn() { if (inStream == null && !attemptedJLineLoad) { if (loadJLine(Charset.defaultCharset())) { inStream = console.getIn(); } } return inStream == null ? System.in : inStream; } public void setIn(InputStream in) { inStream = in; } public PrintStream getOut() { return outStream == null ? System.out : outStream; } public void setOut(PrintStream out) { outStream = out; } public PrintStream getErr() { return errStream == null ? System.err : errStream; } public void setErr(PrintStream err) { errStream = err; } public void setSealedStdLib(boolean value) { sealedStdLib = value; } private static Global getInstance(Function function) { Scriptable scope = function.getParentScope(); if (!(scope instanceof Global)) throw reportRuntimeError("msg.bad.shell.function.scope", String.valueOf(scope)); return (Global)scope; } /** * Runs the given process using Runtime.exec(). * If any of in, out, err is null, the corresponding process stream will * be closed immediately, otherwise it will be closed as soon as * all data will be read from/written to process * * @return Exit value of process. * @throws IOException If there was an error executing the process. */ private static int runProcess(String[] cmd, String[] environment, File wd, InputStream in, OutputStream out, OutputStream err) throws IOException { Process p; if (environment == null) { p = Runtime.getRuntime().exec(cmd,null,wd); } else { p = Runtime.getRuntime().exec(cmd, environment,wd); } try { PipeThread inThread = null; if (in != null) { inThread = new PipeThread(false, in, p.getOutputStream()); inThread.start(); } else { p.getOutputStream().close(); } PipeThread outThread = null; if (out != null) { outThread = new PipeThread(true, p.getInputStream(), out); outThread.start(); } else { p.getInputStream().close(); } PipeThread errThread = null; if (err != null) { errThread = new PipeThread(true, p.getErrorStream(), err); errThread.start(); } else { p.getErrorStream().close(); } // wait for process completion for (;;) { try { p.waitFor(); if (outThread != null) { outThread.join(); } if (inThread != null) { inThread.join(); } if (errThread != null) { errThread.join(); } break; } catch (InterruptedException ignore) { } } return p.exitValue(); } finally { p.destroy(); } } static void pipe(boolean fromProcess, InputStream from, OutputStream to) throws IOException { try { final int SIZE = 4096; byte[] buffer = new byte[SIZE]; for (;;) { int n; if (!fromProcess) { n = from.read(buffer, 0, SIZE); } else { try { n = from.read(buffer, 0, SIZE); } catch (IOException ex) { // Ignore exception as it can be cause by closed pipe break; } } if (n < 0) { break; } if (fromProcess) { to.write(buffer, 0, n); to.flush(); } else { try { to.write(buffer, 0, n); to.flush(); } catch (IOException ex) { // Ignore exception as it can be cause by closed pipe break; } } } } finally { try { if (fromProcess) { from.close(); } else { to.close(); } } catch (IOException ex) { // Ignore errors on close. On Windows JVM may throw invalid // refrence exception if process terminates too fast. } } } private static InputStream toInputStream(Object value) throws IOException { InputStream is = null; String s = null; if (value instanceof Wrapper) { Object unwrapped = ((Wrapper)value).unwrap(); if (unwrapped instanceof InputStream) { is = (InputStream)unwrapped; } else if (unwrapped instanceof byte[]) { is = new ByteArrayInputStream((byte[])unwrapped); } else if (unwrapped instanceof Reader) { s = readReader((Reader)unwrapped); } else if (unwrapped instanceof char[]) { s = new String((char[])unwrapped); } } if (is == null) { if (s == null) { s = ScriptRuntime.toString(value); } is = new ByteArrayInputStream(s.getBytes()); } return is; } private static OutputStream toOutputStream(Object value) { OutputStream os = null; if (value instanceof Wrapper) { Object unwrapped = ((Wrapper)value).unwrap(); if (unwrapped instanceof OutputStream) { os = (OutputStream)unwrapped; } } return os; } private static String readUrl(String filePath, String charCoding, boolean urlIsFile) throws IOException { int chunkLength; InputStream is = null; try { if (!urlIsFile) { URL urlObj = new URL(filePath); URLConnection uc = urlObj.openConnection(); is = uc.getInputStream(); chunkLength = uc.getContentLength(); if (chunkLength <= 0) chunkLength = 1024; if (charCoding == null) { String type = uc.getContentType(); if (type != null) { charCoding = getCharCodingFromType(type); } } } else { File f = new File(filePath); if (!f.exists()) { throw new FileNotFoundException("File not found: " + filePath); } else if (!f.canRead()) { throw new IOException("Cannot read file: " + filePath); } long length = f.length(); chunkLength = (int)length; if (chunkLength != length) throw new IOException("Too big file size: "+length); if (chunkLength == 0) { return ""; } is = new FileInputStream(f); } Reader r; if (charCoding == null) { r = new InputStreamReader(is); } else { r = new InputStreamReader(is, charCoding); } return readReader(r, chunkLength); } finally { if (is != null) is.close(); } } private static String getCharCodingFromType(String type) { int i = type.indexOf(';'); if (i >= 0) { int end = type.length(); ++i; while (i != end && type.charAt(i) <= ' ') { ++i; } String charset = "charset"; if (charset.regionMatches(true, 0, type, i, charset.length())) { i += charset.length(); while (i != end && type.charAt(i) <= ' ') { ++i; } if (i != end && type.charAt(i) == '=') { ++i; while (i != end && type.charAt(i) <= ' ') { ++i; } if (i != end) { // i is at the start of non-empty // charCoding spec while (type.charAt(end -1) <= ' ') { --end; } return type.substring(i, end); } } } } return null; } private static String readReader(Reader reader) throws IOException { return readReader(reader, 4096); } private static String readReader(Reader reader, int initialBufferSize) throws IOException { char[] buffer = new char[initialBufferSize]; int offset = 0; for (;;) { int n = reader.read(buffer, offset, buffer.length - offset); if (n < 0) { break; } offset += n; if (offset == buffer.length) { char[] tmp = new char[buffer.length * 2]; System.arraycopy(buffer, 0, tmp, 0, offset); buffer = tmp; } } return new String(buffer, 0, offset); } static RuntimeException reportRuntimeError(String msgId) { String message = ToolErrorReporter.getMessage(msgId); return Context.reportRuntimeError(message); } static RuntimeException reportRuntimeError(String msgId, String msgArg) { String message = ToolErrorReporter.getMessage(msgId, msgArg); return Context.reportRuntimeError(message); } } class Runner implements Runnable, ContextAction { Runner(Scriptable scope, Function func, Object[] args) { this.scope = scope; f = func; this.args = args; } Runner(Scriptable scope, Script script) { this.scope = scope; s = script; } public void run() { factory.call(this); } public Object run(Context cx) { if (f != null) return f.call(cx, scope, scope, args); else return s.exec(cx, scope); } ContextFactory factory; private Scriptable scope; private Function f; private Script s; private Object[] args; } class PipeThread extends Thread { PipeThread(boolean fromProcess, InputStream from, OutputStream to) { setDaemon(true); this.fromProcess = fromProcess; this.from = from; this.to = to; } @Override public void run() { try { Global.pipe(fromProcess, from, to); } catch (IOException ex) { throw Context.throwAsScriptRuntimeEx(ex); } } private boolean fromProcess; private InputStream from; private OutputStream to; }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; class Solution { public static void main(String args[]) { Scanner in = new Scanner(System.in); Game game = new Game(); Model model = new Model(); Bot bot = new Bot(); model = game.init(in, model); String output = bot.next_action(model); game.play(output); } } class Model { int temperaturesCount; List<Integer> temperatures; } class Bot { String next_action(Model model) { if (model.temperatures.size() == 0) { return "0"; } Integer minTempPositiveOrNegative = Collections .min(model.temperatures, (p1, p2) -> Data.difference_from_0_between(p1, p2)); Integer minDiff = Data.difference_from_0(minTempPositiveOrNegative); Integer minTempPositive = model.temperatures .stream() .filter(i -> minDiff == Data.difference_from_0(i)) .max((p1, p2) -> Integer.compare(p1, p2)) .get(); Log.debug("minTempPositivOrNegative=" + minTempPositiveOrNegative); Log.debug("minDiff=" + minDiff); Log.debug("minTempPositive=" + minTempPositive); return minTempPositive.toString(); } } class Data { static int difference_from_0_between(Integer p1, Integer p2) { return Integer.compare( difference_from_0(p1), difference_from_0(p2)); } static int difference_from_0(Integer p1) { return Math.abs(0 - p1); } } class Game { Model init(Scanner in, Model model) { int n = in.nextInt(); if (in.hasNextLine()) { in.nextLine(); } String temps = in.nextLine(); Log.debug("temps=%s", temps); model.temperaturesCount = n; if (model.temperaturesCount > 0) { model.temperatures = Arrays .asList(temps .split(" ")) .stream() .map(i -> Integer.valueOf(i)) .collect(Collectors.<Integer> toList()); ; } else { model.temperatures = new ArrayList<>(); } Preconditions.check(model.temperaturesCount == model.temperatures.size()); Log.debug("temperaturesCount=%d", model.temperaturesCount); Log.debug("temperatures=" + model.temperatures); return model; } void play(String output) { System.out.println(output); } } class Log { static void debug(String pattern, Object... values) { System.err.println(String.format(pattern, values)); } } class Preconditions { static void check(boolean condition) { if (!condition) throw new RuntimeException("CONDITION FALSE"); } }
package com.mrhabibi.activityfactory; import android.content.Intent; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; public abstract class BasicActivity extends AppCompatActivity { public final static String FRAGMENT_GETTER_ID_LABEL = "fragmentGetterId"; public final static String FRAGMENT_TAG = "fragmentTag"; protected boolean mFirstCreation; protected String mFragmentGetterId; protected Fragment mCurrentFragment; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { mFirstCreation = savedInstanceState == null; extractBundleStates(getIntent().getExtras()); super.onCreate(savedInstanceState); if (mFirstCreation) { mCurrentFragment = getActiveFragment(); } else { mCurrentFragment = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG); } /* * Check if the fragment has expired */ if (mFragmentGetterId != null && mCurrentFragment == null) { Log.e(ActivityFactory.TAG, "Finishing due to Expired Session"); finish(); } } @Override public void setContentView(@LayoutRes int layoutResID) { super.setContentView(layoutResID); onAttachFragment(); } @Override public void setContentView(View view) { super.setContentView(view); onAttachFragment(); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { super.setContentView(view, params); onAttachFragment(); } protected void onAttachFragment() { /* * Bring the fragment to live */ if (mFirstCreation && mCurrentFragment != null) { if (findViewById(R.id.fragment_container) == null) { throw new IllegalStateException("Fragment container resource id not found, have you included FrameLayout with @id/fragment_container inside your activity content view?"); } FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.fragment_container, mCurrentFragment, FRAGMENT_TAG) .commit(); fragmentManager.executePendingTransactions(); } } /** * Get active fragment to be attached to container, you can override it and pass your own * fragment * * @return The fragment */ protected Fragment getActiveFragment() { return FragmentPasser.getFragment(mFragmentGetterId); } /** * Pass the activity result for nested PersistentDialog */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (mCurrentFragment != null) { mCurrentFragment.onActivityResult(requestCode, resultCode, data); } } private void extractBundleStates(Bundle bundle) { if (bundle != null) { if (bundle.containsKey(FRAGMENT_GETTER_ID_LABEL)) { mFragmentGetterId = bundle.getString(FRAGMENT_GETTER_ID_LABEL); } } } }
package im.actor.model.mvvm; import junit.framework.TestCase; import java.util.ArrayList; public class ChangeBuilderTest extends TestCase { private ArrayList<Integer> prepareList(int amount) { ArrayList<Integer> workList = new ArrayList<Integer>(); for (int i = 0; i < amount; i++) { workList.add(i); } return workList; } private void assertHasOperation(ChangeDescription<Integer> op, ArrayList<ChangeDescription<Integer>> list) { for (ChangeDescription<Integer> i : list) { if (i.getOperationType() == op.getOperationType()) { if (op.getOperationType() == ChangeDescription.OperationType.REMOVE) { if (op.getIndex() == i.getIndex()) { return; } } else if (op.getOperationType() == ChangeDescription.OperationType.ADD) { if (op.getIndex() == i.getIndex()) { return; } } } } assertTrue(false); } // public void testIOSDeletions() { // // Initial List: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 // ArrayList<Integer> workList = prepareList(10); // // Result List: 0, 1, 2, 5, 6, 7, 8, 9 // ArrayList<Integer> resultList = prepareList(10); // resultList.remove(3); // resultList.remove(4); // ArrayList<ChangeDescription<Integer>> operations = new ArrayList<ChangeDescription<Integer>>(); // operations.add(ChangeDescription.<Integer>remove(3)); // operations.add(ChangeDescription.<Integer>remove(3)); // ArrayList<ChangeDescription<Integer>> res = // ChangeBuilder.processAppleModifications(operations, workList); // assertHasOperation(ChangeDescription.<Integer>remove(3), res); // assertHasOperation(ChangeDescription.<Integer>remove(4), res); // assertEquals(res.size(), 2); // public void testIOSAdditions() { // // Initial List: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 // ArrayList<Integer> workList = prepareList(10); // // Result List: 0, 1, 2, 3, 11, 10, 4, 5, 6, 7, 8, 9 // ArrayList<Integer> resultList = prepareList(10); // resultList.add(4, 10); // resultList.add(4, 11); // ArrayList<ChangeDescription<Integer>> operations = new ArrayList<ChangeDescription<Integer>>(); // operations.add(ChangeDescription.add(4, 10)); // operations.add(ChangeDescription.add(4, 11)); // ArrayList<ChangeDescription<Integer>> res = // ChangeBuilder.processAppleModifications(operations, workList); // assertHasOperation(ChangeDescription.add(4, 10), res); // assertHasOperation(ChangeDescription.add(5, 11), res); }
package im.actor.core.js.utils; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.safehtml.shared.UriUtils; import im.actor.runtime.markdown.*; import java.util.ArrayList; public class HtmlMarkdownUtils { public static String processText(String markdown, int mode) { MDDocument doc = new MarkdownParser(mode).processDocument(markdown); ArrayList<String> renderedSections = new ArrayList<String>(); for (MDSection section : doc.getSections()) { renderedSections.add(renderSection(section)); } StringBuilder builder = new StringBuilder(); for (String section : renderedSections) { builder.append("<p>"); builder.append(section); builder.append("</p>"); } return builder.toString(); } public static String renderSection(MDSection section) { if (section.getType() == MDSection.TYPE_CODE) { return renderCode(section.getCode()); } else if (section.getType() == MDSection.TYPE_TEXT) { return renderText(section.getText()); } else { return ""; } } public static String renderCode(MDCode code) { return "<pre><code>" + SafeHtmlUtils.htmlEscape(code.getCode()) + "</pre></code>"; } public static String renderText(MDText[] texts) { StringBuilder builder = new StringBuilder(); for (MDText text : texts) { if (text instanceof MDRawText) { final MDRawText rawText = (MDRawText) text; builder.append(SafeHtmlUtils.htmlEscape(rawText.getRawText()).replace("\n", "<br/>")); } else if (text instanceof MDSpan) { final MDSpan span = (MDSpan) text; builder.append(spanElement(span.getSpanType(), renderText(span.getChild()))); } else if (text instanceof MDUrl) { final MDUrl url = (MDUrl) text; builder.append(urlElement(url)); } } return builder.toString(); } private static String spanElement(int type, String innerHTML) { if (type == MDSpan.TYPE_BOLD) { return "<b>" + innerHTML + "</b>"; } else if (type == MDSpan.TYPE_ITALIC) { return "<i>" + innerHTML + "</i>"; } else { return innerHTML; } } private static String urlElement(MDUrl url) { String href = UriUtils.sanitizeUri(url.getUrl()); if (href != "#" && !href.contains("://")) { href = "http://" + href; } return "<a " + "target=\"_blank\" " + "onClick=\"window.messenger.handleLinkClick(event)\" " + "href=\"" + href + "\">" + SafeHtmlUtils.htmlEscape(url.getUrlTitle()) + "</a>"; } }
package ru.stqa.pft.addressbook.tests; import org.openqa.selenium.remote.BrowserType; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import ru.stqa.pft.addressbook.appmanager.ApplicationManager; import ru.stqa.pft.addressbook.model.GroupData; import ru.stqa.pft.addressbook.model.Groups; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class TestBase { protected static final ApplicationManager app = new ApplicationManager(System.getProperty("browser", BrowserType.CHROME)); @BeforeSuite public void setUp() throws Exception { app.init(); } @AfterSuite public void tearDown() { app.stop(); } public void verifyGroupListInUI() { if (Boolean.getBoolean("verifyUI")) { Groups dbGroups = app.db().groups(); Groups uiGroups = app.group().all(); assertThat(uiGroups, equalTo(dbGroups .stream() .map( (g) -> new GroupData().withId(g.getId()).withName(g.getName()) ) .collect(Collectors.toSet())) ); } } }
package org.jetel.ctl; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.jetel.ctl.ASTnode.CLVFAssignment; import org.jetel.ctl.ASTnode.CLVFBlock; import org.jetel.ctl.ASTnode.CLVFCaseStatement; import org.jetel.ctl.ASTnode.CLVFDictionaryNode; import org.jetel.ctl.ASTnode.CLVFFieldAccessExpression; import org.jetel.ctl.ASTnode.CLVFForeachStatement; import org.jetel.ctl.ASTnode.CLVFFunctionDeclaration; import org.jetel.ctl.ASTnode.CLVFImportSource; import org.jetel.ctl.ASTnode.CLVFLiteral; import org.jetel.ctl.ASTnode.CLVFLookupNode; import org.jetel.ctl.ASTnode.CLVFMemberAccessExpression; import org.jetel.ctl.ASTnode.CLVFParameters; import org.jetel.ctl.ASTnode.CLVFSequenceNode; import org.jetel.ctl.ASTnode.CLVFStart; import org.jetel.ctl.ASTnode.CLVFStartExpression; import org.jetel.ctl.ASTnode.CLVFSwitchStatement; import org.jetel.ctl.ASTnode.CLVFType; import org.jetel.ctl.ASTnode.CLVFUnaryNonStatement; import org.jetel.ctl.ASTnode.CLVFVariableDeclaration; import org.jetel.ctl.ASTnode.Node; import org.jetel.ctl.ASTnode.SimpleNode; import org.jetel.ctl.data.TLType; import org.jetel.ctl.data.TLTypePrimitive; import org.jetel.ctl.data.UnknownTypeException; import org.jetel.data.Defaults; import org.jetel.data.lookup.LookupTable; import org.jetel.data.sequence.Sequence; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.NotInitializedException; import org.jetel.graph.TransformationGraph; import org.jetel.graph.dictionary.Dictionary; import org.jetel.graph.dictionary.IDictionaryType; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.string.StringUtils; /** * Implementation of semantic checking for CTL compiler. * Resolves external references, functions and records. * Performs code structure validation, mostly for correct * derivation of expression statements. * * @author Michal Tomcanyi <michal.tomcanyi@javlin.cz> * */ public class ASTBuilder extends NavigatingVisitor { /** Void metadata used by Rollup transforms when no group accumulator is used. */ private static final DataRecordMetadata VOID_METADATA = new DataRecordMetadata(Defaults.CTL.VOID_METADATA_NAME); /** Metadata for component's input ports */ private final DataRecordMetadata[] inputMetadata; // may be null /** Metadata for component's output ports */ private final DataRecordMetadata[] outputMetadata; // may be null /** Name -> position mapping for input ports */ private final Map<String, Integer> inputRecordsMap = new TreeMap<String, Integer>(); /** Name -> position mapping for output ports */ private final Map<String, Integer> outputRecordsMap = new TreeMap<String, Integer>(); /** Name/ID -> metadata mapping for record-type variables */ private final Map<String, DataRecordMetadata> graphMetadata = new TreeMap<String, DataRecordMetadata>(); /** Name/ID -> lookup mapping for lookup nodes */ private final Map<String, LookupTable> lookupMap = new TreeMap<String, LookupTable>(); /** Name/ID -> lookup mapping for sequences */ private final Map<String, Sequence> sequenceMap = new TreeMap<String, Sequence>(); /** Function declarations */ private final Map<String, List<CLVFFunctionDeclaration>> declaredFunctions; private final Dictionary dictionary; /** Set of ambiguous input metadata names. */ private final Set<String> ambiguousInputMetadata = new HashSet<String>(); /** Set of ambiguous output metadata names. */ private final Set<String> ambiguousOutputMetadata = new HashSet<String>(); /** Set of ambiguous graph metadata names. */ private final Set<String> ambiguousGraphMetadata = new HashSet<String>(); /** Set of ambiguous lookup table names. */ private final Set<String> ambiguousLookupTables = new HashSet<String>(); /** Set of ambiguous input sequence names. */ private final Set<String> ambiguousSequences = new HashSet<String>(); /** Problem collector */ private ProblemReporter problemReporter; public ASTBuilder(TransformationGraph graph, DataRecordMetadata[] inputMetadata, DataRecordMetadata[] outputMetadata, Map<String, List<CLVFFunctionDeclaration>> declaredFunctions, ProblemReporter problemReporter) { this.inputMetadata = inputMetadata; this.outputMetadata = outputMetadata; this.declaredFunctions = declaredFunctions; this.problemReporter = problemReporter; this.dictionary = graph != null ? graph.getDictionary() : null; // populate name -> position mappings // input metadata names can clash if (inputMetadata != null) { for (int i = 0; i < inputMetadata.length; i++) { DataRecordMetadata m = inputMetadata[i]; if (m != null) { if (inputRecordsMap.put(m.getName(), i) != null) { ambiguousInputMetadata.add(m.getName()); } } } } // the same for output just different error message if (outputMetadata != null) { for (int i = 0; i < outputMetadata.length; i++) { DataRecordMetadata m = outputMetadata[i]; if (m != null) { if (outputRecordsMap.put(m.getName(), i) != null) { ambiguousOutputMetadata.add(m.getName()); } } } } if (graph != null) { // all graph metadata for resolving record-type variable declarations Iterator<String> mi = graph.getDataRecordMetadata(); while (mi.hasNext()) { DataRecordMetadata m = graph.getDataRecordMetadata(mi.next()); if (graphMetadata.put(m.getName(), m) != null) { ambiguousGraphMetadata.add(m.getName()); } } // lookup tables Iterator<String> li = graph.getLookupTables(); while (li.hasNext()) { LookupTable t = graph.getLookupTable(li.next()); if (lookupMap.put(t.getName(), t) != null) { ambiguousLookupTables.add(t.getName()); } } // sequences Iterator<String> si = graph.getSequences(); while (si.hasNext()) { Sequence s = graph.getSequence(si.next()); if (sequenceMap.put(s.getName(), s) != null) { ambiguousSequences.add(s.getName()); } } } } /** * AST builder entry method for complex transformations * * @param tree * AST to resolve */ public void resolveAST(CLVFStart tree) { visit(tree, null); checkLocalFunctionsDuplicities(); } /** * AST builder entry method for simple expression (Filter) * @param tree */ public void resolveAST(CLVFStartExpression tree) { visit(tree,null); } @Override public Object visit(CLVFImportSource node, Object data) { // store current "import context" so we can restore it after parsing this import String importFileUrl = problemReporter.getImportFileUrl(); ErrorLocation errorLocation = problemReporter.getErrorLocation(); // set new "import context", propagate error location if already defined problemReporter.setImportFileUrl(node.getSourceToImport()); problemReporter.setErrorLocation((errorLocation != null) ? errorLocation : new ErrorLocation(node.getBegin(), node.getEnd())); Object result = super.visit(node, data); // restore current "import context" problemReporter.setImportFileUrl(importFileUrl); problemReporter.setErrorLocation(errorLocation); return result; } /** * Field references are context-sensitive. Field reference "$out.someField" on LHS resolves to an OUTPUT field * 'someField' in record name 'out'. The flag is sent in 'data' object. */ @Override public CLVFAssignment visit(CLVFAssignment node, Object data) { // if LHS, must send flag down the tree to inform FieldAccessExpression it is an output field node.jjtGetChild(0).jjtAccept(this, true); node.jjtGetChild(1).jjtAccept(this, false); return node; } @Override public CLVFBlock visit(CLVFBlock node, Object data) { super.visit(node,data); checkBlockParseTree(node); return node; } @Override public Object visit(CLVFStart node, Object data) { super.visit(node,data); checkBlockParseTree(node); return node; } /** * Calculates positional references according to field names. * Validates that metadata and field references are valid * in the current graph. */ @Override public CLVFFieldAccessExpression visit(CLVFFieldAccessExpression node, Object data) { if (isGlobal(node)) { error(node, "Unable to access record field in global scope"); } Object id = node.getRecordId(); Boolean isOutput; Boolean isLHS = data != null ? (Boolean)data : false; String discriminator = node.getDiscriminator(); if (discriminator != null) { if (discriminator.equals("in")) { if (isLHS) { error(node, "Input record cannot be assigned to"); } isOutput = false; } else if (discriminator.equals("out")) { isOutput = true; } else { throw new IllegalArgumentException(discriminator); } } else { // if the FieldAccessExpression appears somewhere except assignment // the 'data' will be null so we treat it as a reference to the input field isOutput = isLHS; node.setMetadata(null); } node.setOutput(isOutput); Integer recordPos = null; // resolve positional reference for record if necessary if (node.getRecordId() != null) { recordPos = node.getRecordId(); } else { // calculate positional reference recordPos = isOutput ? getOutputPosition(node.getRecordName()) : getInputPosition(node.getRecordName()); if (recordPos != null) { Set<String> ambiguousMetadata = isOutput ? ambiguousOutputMetadata : ambiguousInputMetadata; if (ambiguousMetadata.contains(node.getRecordName())) { // metadata names can clash - warn user that we will not be able to resolve them correctly warn(node, (isOutput ? "Output" : "Input") + " record name '" + node.getRecordName() + "' is ambiguous", "Use positional access or rename metadata to a unique name"); } node.setRecordId(recordPos); } else { error(node, "Unable to resolve " + (isOutput ? "output" : "input") + " metadata '" + node.getRecordName() + "'"); node.setType(TLType.ERROR); return node; // nothing else to do } } // check if we have metadata for this record DataRecordMetadata metadata = isOutput ? getOutputMetadata(recordPos) : getInputMetadata(recordPos); if (metadata != null) { node.setMetadata(metadata); } else { error(node, "Cannot " + (isOutput ? "write to output" : "read from input") + " port '" + id + "'", "Either the port has no edge connected or the operation is not permitted."); node.setType(TLType.ERROR); return node; } if (node.isWildcard()) { // this is not a record reference - but access all record fields node.setType(TLType.forRecord(node.getMetadata())); return node; // this node access record -> we do not want resolve field access } // resolve and validate field identifier using record metadata Integer fieldId; if (node.getFieldId() != null) { fieldId = node.getFieldId(); // fields are ordered from zero if (fieldId > metadata.getNumFields()-1) { error(node,"Field '" + fieldId + "' is out of range for record '" + metadata.getName() + "'"); node.setType(TLType.ERROR); return node; } } else { fieldId = metadata.getFieldPosition(node.getFieldName()); if (fieldId >= 0) { node.setFieldId(fieldId); } else { error(node, "Field '" + node.getFieldName() + "' does not exist in record '" + metadata.getName() + "'"); node.setType(TLType.ERROR); return node; } } try { node.setType(TLTypePrimitive.fromCloverType(node.getMetadata().getField(fieldId))); } catch (UnknownTypeException e) { error(node, "Field type '" + e.getType() + "' does not match any CTL type"); node.setType(TLType.ERROR); throw new IllegalArgumentException(e); } return node; } /** * @param node * @return */ private boolean isGlobal(SimpleNode node) { Node actualNode = node; boolean isLastNodeCLVFStartExpression = false; while ((actualNode = actualNode.jjtGetParent()) != null) { isLastNodeCLVFStartExpression = (actualNode instanceof CLVFStartExpression); if (actualNode instanceof CLVFFunctionDeclaration) return false; } // if root node of SimpleNode hierarchy is CLVFStartExpression // then only simple expression is compiled (for instance for ExtFilter component // see TLCompiler.validateExpression()) and record field access in global scope is allowed return !isLastNodeCLVFStartExpression; } @Override public Object visit(CLVFForeachStatement node, Object data) { super.visit(node, data); CLVFVariableDeclaration loopVar = (CLVFVariableDeclaration)node.jjtGetChild(0); if (loopVar.jjtGetNumChildren() > 1) { error(loopVar,"Foreach loop variable must not have a initializer","Delete the initializer expression"); node.setType(TLType.ERROR); } return node; } /** * Populates function return type and formal parameters type. * Sets node's type to {@link TLType#ERROR} in case of any issues. */ @Override public Object visit(CLVFFunctionDeclaration node, Object data) { // scan (return type), parameters and function body super.visit(node,data); // checkStatementOrBlock(node.jjtGetChild(2)); CLVFType retType = (CLVFType)node.jjtGetChild(0); node.setType(retType.getType()); CLVFParameters params = (CLVFParameters)node.jjtGetChild(1); TLType[] formalParm = new TLType[params.jjtGetNumChildren()]; for (int i=0; i<params.jjtGetNumChildren(); i++) { CLVFVariableDeclaration p = (CLVFVariableDeclaration)params.jjtGetChild(i); if ((formalParm[i] = p.getType()) == TLType.ERROR) { // if function accepts some metadata-typed params, we can have error resolving them node.setType(TLType.ERROR); } } node.setFormalParameters(formalParm); return data; } /** * Parses literal value to the corresponding object * May result in additional errors in parsing. * * @see #parseLiteral(CLVFLiteral) */ @Override public Object visit(CLVFLiteral node, Object data) { parseLiteral(node); return data; } /** * Resolves of identifier to the corresponding graph lookup table */ @Override public CLVFLookupNode visit(CLVFLookupNode node, Object data) { super.visit(node, data); LookupTable table = resolveLookup(node.getLookupName()); if (table == null) { error(node, "Unable to resolve lookup table '" + node.getLookupName() + "'"); node.setType(TLType.ERROR); return node; } else { if (ambiguousLookupTables.contains(table.getName())) { warn("Lookup table name '" + table.getName() + "' is ambiguous", "Rename the lookup table to a unique name"); } node.setLookupTable(table); // type will be set in composite reference node as it will build up the lookup node completely } // we need to call init() to get access to metadata, keys, etc. (e.g. for DBLookupTable) try { if (! node.getLookupTable().isInitialized()) { node.getLookupTable().init(); } } catch (Exception e) { // underlying lookup cannot be initialized error(node,"Lookup table has configuration error: " + e.getMessage()); node.setType(TLType.ERROR); return node; } TLType getOrCountReturnType = null; DataRecordMetadata ret = null; switch (node.getOperation()) { // OP_COUNT and OP_GET use a common arguments validation and only differ in return type case CLVFLookupNode.OP_COUNT: getOrCountReturnType = TLTypePrimitive.INTEGER; case CLVFLookupNode.OP_GET: try { DataRecordMetadata keyRecordMetadata = node.getLookupTable().getKeyMetadata(); LinkedList<Integer> decimalInfo = new LinkedList<Integer>(); if (keyRecordMetadata == null) { // fail safe step in case getKey() does not work properly -> exception is caught below throw new UnsupportedOperationException(); } // extract lookup parameter types TLType[] formal = new TLType[keyRecordMetadata.getNumFields()]; try { for (int i=0; i<keyRecordMetadata.getNumFields(); i++) { formal[i] = TLTypePrimitive.fromCloverType(keyRecordMetadata.getField(i)); if (formal[i].isDecimal()) { final DataFieldMetadata f = keyRecordMetadata.getField(i); decimalInfo.add(f.getFieldProperties().getIntProperty(DataFieldMetadata.LENGTH_ATTR)); decimalInfo.add(f.getFieldProperties().getIntProperty(DataFieldMetadata.SCALE_ATTR)); } } node.setFormalParameters(formal); node.setDecimalPrecisions(decimalInfo); } catch (UnknownTypeException e) { error(node,"Lookup returned an unknown parameter type: '" + e.getType() + "'"); node.setType(TLType.ERROR); return node; } } catch (UnsupportedOperationException e) { // can happen in case the JDBC driver does not provide info about SQL params warn(node, "Validation of lookup keys is not supported for this lookup table"); } catch (NotInitializedException e) { // should never happen error(node,"Lookup not initialized"); node.setType(TLType.ERROR); return node; } catch (ComponentNotReadyException e) { // underlying lookup is misconfigured error(node,"Lookup table has configuration errors: " + e.getMessage()); node.setType(TLType.ERROR); return node; } // if return type is already set to integer, we are validating a count() function - see case above // otherwise we are validating get() function and must compute return type from metadata if (getOrCountReturnType == null) { ret = node.getLookupTable().getMetadata(); if (ret == null) { error(node,"Lookup table has no metadata specified"); node.setType(TLType.ERROR); return node; } getOrCountReturnType = TLType.forRecord(ret); } node.setType(getOrCountReturnType); break; case CLVFLookupNode.OP_NEXT: // extract return type ret = node.getLookupTable().getMetadata(); if (ret == null) { error(node,"Lookup table has no metadata specified"); node.setType(TLType.ERROR); return node; } node.setType(TLType.forRecord(ret)); break; } return node; } private static final TLType[] CONTAINER_ELEMENT_TYPES = { TLTypePrimitive.INTEGER, TLTypePrimitive.LONG, TLTypePrimitive.STRING, TLTypePrimitive.BOOLEAN, TLTypePrimitive.DATETIME, TLTypePrimitive.DOUBLE, TLTypePrimitive.DECIMAL, TLTypePrimitive.BYTEARRAY, }; private static TLType getTypeByContentType(String contentType) { if (StringUtils.isEmpty(contentType)) { return null; } for (TLType t: CONTAINER_ELEMENT_TYPES) { if (t.name().equals(contentType)) { return t; } } return null; } @Override public Object visit(CLVFMemberAccessExpression node, Object data) { super.visit(node, data); //dictionary is not available, the ctl code is compiled without graph (graph == null) if (dictionary == null) { error(node, "Dictionary is not available"); node.setType(TLType.ERROR); return data; } // access to dictionary final SimpleNode prefix = (SimpleNode)node.jjtGetChild(0); if (prefix.getId() == TransformLangParserTreeConstants.JJTDICTIONARYNODE) { IDictionaryType dictType = dictionary.getType(node.getName()) ; if (dictType == null) { error(node, "Dictionary entry '" + node.getName() + "' does not exist"); node.setType(TLType.ERROR); return data; } TLType tlType = dictType.getTLType(); if( tlType == null){ error(node, "Dictionary entry '" + node.getName() + " has type "+dictType.getTypeId()+" which is not supported in CTL"); node.setType(TLType.ERROR); return node; } else if (tlType.isList()) { final String contentType = dictionary.getContentType(node.getName()); if (!StringUtils.isEmpty(contentType)) { TLType elementType = getTypeByContentType(contentType); tlType = TLType.createList(elementType); } } else if (tlType.isMap()) { final String contentType = dictionary.getContentType(node.getName()); if (!StringUtils.isEmpty(contentType)) { TLType elementType = getTypeByContentType(contentType); tlType = TLType.createMap(TLTypePrimitive.STRING, elementType); } } node.setType(tlType); } return data; } /** * Resolves of identifier to the corresponding graph sequence. * Sequence return type is defined by user in syntax. */ @Override public CLVFSequenceNode visit(CLVFSequenceNode node, Object data) { Sequence seq = resolveSequence(node.getSequenceName()); if (seq == null) { error(node, "Unable to resolve sequence '" + node.getSequenceName() + "'"); node.setType(TLType.ERROR); } else { if (ambiguousSequences.contains(seq.getName())) { warn("Sequence name '" + seq.getName() + "' is ambiguous", "Rename the sequence to a unique name"); } node.setSequence(seq); } return node; } /** * Computes case statements indices */ @Override public Object visit(CLVFSwitchStatement node, Object data) { super.visit(node,data); Map <Object, SimpleNode> map = new HashMap<Object, SimpleNode>(); Set <SimpleNode> duplicates = new HashSet<SimpleNode>(); ArrayList<Integer> caseIndices = new ArrayList<Integer>(); for (int i=0; i<node.jjtGetNumChildren(); i++) { SimpleNode child = (SimpleNode)node.jjtGetChild(i); if (child.getId() == TransformLangParserTreeConstants.JJTCASESTATEMENT) { if (((CLVFCaseStatement)child).isDefaultCase()) { node.setDefaultCaseIndex(i); } else { caseIndices.add(i); CLVFLiteral caseLiteral = (CLVFLiteral) child.jjtGetChild(0); Object value = caseLiteral.getValue(); SimpleNode otherNode; if ((otherNode = map.get(value)) != null) { duplicates.add(child); duplicates.add(otherNode); } else { map.put(value, child); } for (SimpleNode duplicateNode : duplicates) { error(duplicateNode, "Duplicate case"); } } } } node.setCaseIndices((Integer[]) caseIndices.toArray(new Integer[caseIndices.size()])); return node; } @Override public Object visit(CLVFType node, Object data) { node.setType(createType(node)); return node; } /** * Analyzes if the unary expression is not just a negative literal. * If yes, the negative literal is validated, parsed and the unary expression * is replaced by the literal. */ @Override public Object visit(CLVFUnaryNonStatement node, Object data) { if (((CLVFUnaryNonStatement)node).getOperator() == TransformLangParserConstants.MINUS && ((SimpleNode)node.jjtGetChild(0)).getId() == TransformLangParserTreeConstants.JJTLITERAL) { CLVFLiteral lit = (CLVFLiteral)node.jjtGetChild(0); int idx = 0; final SimpleNode parent = (SimpleNode)node.jjtGetParent(); // store position of the unary expression in idx for (idx = 0; idx < parent.jjtGetNumChildren(); idx++) { if (parent.jjtGetChild(idx) == node) { break; } } switch (lit.getTokenKind()) { case TransformLangParserConstants.FLOATING_POINT_LITERAL: case TransformLangParserConstants.LONG_LITERAL: case TransformLangParserConstants.INTEGER_LITERAL: case TransformLangParserConstants.DECIMAL_LITERAL: lit.setValue(lit.getTokenKind(), "-" + lit.getValueImage()); break; default: error(node,"Operator '-' is not defined for this type of literal"); return node; } // initialize literal value and fall back early on error if (!parseLiteral(lit)) { return node; } // literal was correctly initialized - replace the unary minus in AST lit.jjtSetParent(node.jjtGetParent()); parent.jjtAddChild(lit, idx); return lit; } // not a minus literal, but other unary expression, validate children super.visit(node, data); return node; } /** * Sets type of variable from type node */ @Override public CLVFVariableDeclaration visit(CLVFVariableDeclaration node, Object data) { super.visit(node, data); CLVFType typeNode = (CLVFType) node.jjtGetChild(0); // set the type of variable node.setType(typeNode.getType()); return node; } @Override public Object visit(CLVFDictionaryNode node, Object data) { super.visit(node, data); // actual type of dictionary entry is set while visiting MemberAccessExpression. // this is only a default value that is not used anywhere node.setType(TLTypePrimitive.STRING); return node; } /** * This method check that local declarations of functions do not contain any * duplicate function declaration. Types of function parameters within declarations * must have been already resolved (i.e. call this after AST pass has been completed) * * Function declaration is duplicate iff it has the same: * - return type * - function name * - parameters * as some other locally declared function */ private void checkLocalFunctionsDuplicities() { for (String name : declaredFunctions.keySet()) { final List<CLVFFunctionDeclaration> functions = declaredFunctions.get(name); final int overloadCount = functions.size(); if (overloadCount < 2) { // no duplicates possible continue; } for (int i=1; i<overloadCount; i++) { for (int j=i-i; j>=0; j CLVFFunctionDeclaration valid = functions.get(j); CLVFFunctionDeclaration candidate = functions.get(i); /* * This follows Java approach: overloading function must have different * parameters, difference only in return type is insufficient and is * treated as a duplicate */ if (Arrays.equals(valid.getFormalParameters(), candidate.getFormalParameters())) { // the same name, return type and parameter types: duplicate error(valid,"Duplicate function '" + valid.toHeaderString() + "'"); error(candidate,"Duplicate function '" + valid.toHeaderString() + "'"); } } } } } /** * Initializes literal by parsing its string representation into real type. * * @return false (and reports error) when parsing did not succeed, true otherwise */ private boolean parseLiteral(CLVFLiteral lit) { String errorMessage = null; String hint = null; try { lit.computeValue(); } catch (NumberFormatException e) { switch (lit.getTokenKind()) { case TransformLangParserConstants.FLOATING_POINT_LITERAL: errorMessage = "Literal '" + lit.getValueImage() + "' is out of range for type 'number'"; hint = "Use 'D' distincter to treat literal as 'decimal' "; break; case TransformLangParserConstants.LONG_LITERAL: errorMessage = "Literal '" + lit.getValueImage() + "' is out of range for type 'long'"; hint = "Use 'D' distincter to treat literal as 'decimal'"; break; case TransformLangParserConstants.INTEGER_LITERAL: errorMessage = "Literal '" + lit.getValueImage() + "' is out of range for type 'int'"; hint = "Use 'L' distincter to treat literal as 'long'"; break; default: // should never happen errorMessage = "Unrecognized literal type '" + lit.getTokenKind() + "' with value '" + lit.getValueImage() + "'"; hint = "Report as bug"; break; } } catch (ParseException e) { switch (lit.getTokenKind()) { case TransformLangParserConstants.DATE_LITERAL: errorMessage = e.getMessage(); hint = "Date literal must match format pattern 'YYYY-MM-dd' and has to be valid date value."; break; case TransformLangParserConstants.DATETIME_LITERAL: errorMessage = e.getMessage(); hint = "Date-time literal must match format pattern 'YYYY-MM-DD HH:MM:SS' and has to be valid date-time value."; break; default: // should never happen errorMessage = "Unrecognized literal type '" + lit.getTokenKind() + "' with value '" + lit.getValueImage() + "'"; hint = "Report as bug"; break; } } // report error and fall back early if (errorMessage != null) { error(lit,errorMessage,hint); return false; } return true; } private Integer getInputPosition(String name) { return inputRecordsMap.get(name); } private Integer getOutputPosition(String name) { return outputRecordsMap.get(name); } private DataRecordMetadata getInputMetadata(int recordId) { return getMetadata(inputMetadata, recordId); } private DataRecordMetadata getOutputMetadata(int recordId) { return getMetadata(outputMetadata, recordId); } private DataRecordMetadata getMetadata(DataRecordMetadata[] metadata, int recordId) { // no metadata specified on component, or metadata not assigned on edge corresponding to recordId if (metadata == null || recordId >= metadata.length || metadata[recordId] == null) { return null; } return metadata[recordId]; } private Sequence resolveSequence(String name) { return sequenceMap.get(name); } private LookupTable resolveLookup(String name) { return lookupMap.get(name); } private DataRecordMetadata resolveMetadata(String recordName) { return graphMetadata.get(recordName); } private TLType createType(CLVFType typeNode) { switch (typeNode.getKind()) { case TransformLangParserConstants.INT_VAR: return TLTypePrimitive.INTEGER; case TransformLangParserConstants.LONG_VAR: return TLTypePrimitive.LONG; case TransformLangParserConstants.DOUBLE_VAR: return TLTypePrimitive.DOUBLE; case TransformLangParserConstants.DECIMAL_VAR: return TLTypePrimitive.DECIMAL; case TransformLangParserConstants.STRING_VAR: return TLTypePrimitive.STRING; case TransformLangParserConstants.DATE_VAR: return TLTypePrimitive.DATETIME; case TransformLangParserConstants.BYTE_VAR: return TLTypePrimitive.BYTEARRAY; case TransformLangParserConstants.BOOLEAN_VAR: return TLTypePrimitive.BOOLEAN; case TransformLangParserConstants.IDENTIFIER: DataRecordMetadata meta = resolveMetadata(typeNode.getMetadataName()); if (meta == null) { if (voidMetadataAllowed(typeNode)) { meta = VOID_METADATA; } else { error(typeNode, "Unknown variable type or metadata name '" + typeNode.getMetadataName() + "'"); return TLType.ERROR; } } else if (ambiguousGraphMetadata.contains(meta.getName())) { warn(typeNode, "Metadata name '" + meta.getName() + "' is ambiguous", "Rename the metadata to a unique name"); } else if (voidMetadataAllowed(typeNode)) { warn(typeNode, "Reference to '" + VOID_METADATA.getName() + "' is ambiguous", "Rename metadata '" + VOID_METADATA.getName() + "'"); } return TLType.forRecord(meta); case TransformLangParserConstants.MAP_VAR: return TLType.createMap(createType((CLVFType) typeNode.jjtGetChild(0)), createType((CLVFType) typeNode.jjtGetChild(1))); case TransformLangParserConstants.LIST_VAR: return TLType.createList(createType((CLVFType)typeNode.jjtGetChild(0))); case TransformLangParserConstants.VOID_VAR: return TLType.VOID; default: error(typeNode, "Unknown variable type: '" + typeNode.getKind() + "'"); throw new IllegalArgumentException("Unknown variable type: '" + typeNode.getKind() + "'"); } } private boolean voidMetadataAllowed(CLVFType typeNode) { if (!typeNode.getMetadataName().equals(VOID_METADATA.getName())) { return false; } Node parent = typeNode.jjtGetParent(); return (parent != null && parent.jjtGetParent() instanceof CLVFParameters); } private final void checkBlockParseTree(SimpleNode node) { for (int i=0; i<node.jjtGetNumChildren(); i++) { final SimpleNode child = (SimpleNode)node.jjtGetChild(i); switch (child.getId()) { case TransformLangParserTreeConstants.JJTASSIGNMENT: case TransformLangParserTreeConstants.JJTBLOCK: case TransformLangParserTreeConstants.JJTBREAKSTATEMENT: case TransformLangParserTreeConstants.JJTCASESTATEMENT: case TransformLangParserTreeConstants.JJTCONTINUESTATEMENT: case TransformLangParserTreeConstants.JJTDOSTATEMENT: case TransformLangParserTreeConstants.JJTFOREACHSTATEMENT: case TransformLangParserTreeConstants.JJTFORSTATEMENT: case TransformLangParserTreeConstants.JJTFUNCTIONCALL: case TransformLangParserTreeConstants.JJTIFSTATEMENT: case TransformLangParserTreeConstants.JJTLOOKUPNODE: case TransformLangParserTreeConstants.JJTPOSTFIXEXPRESSION: case TransformLangParserTreeConstants.JJTISNULLNODE: case TransformLangParserTreeConstants.JJTNVLNODE: case TransformLangParserTreeConstants.JJTNVL2NODE: case TransformLangParserTreeConstants.JJTIIFNODE: case TransformLangParserTreeConstants.JJTPRINTERRNODE: case TransformLangParserTreeConstants.JJTPRINTLOGNODE: case TransformLangParserTreeConstants.JJTPRINTSTACKNODE: case TransformLangParserTreeConstants.JJTRAISEERRORNODE: case TransformLangParserTreeConstants.JJTRETURNSTATEMENT: case TransformLangParserTreeConstants.JJTSEQUENCENODE: case TransformLangParserTreeConstants.JJTSWITCHSTATEMENT: case TransformLangParserTreeConstants.JJTUNARYSTATEMENT: case TransformLangParserTreeConstants.JJTVARIABLEDECLARATION: case TransformLangParserTreeConstants.JJTWHILESTATEMENT: // all expression statements that can occur within block break; case TransformLangParserTreeConstants.JJTFUNCTIONDECLARATION: case TransformLangParserTreeConstants.JJTIMPORTSOURCE: // these two are only in for CLVFStart break; default: error(child,"Syntax error, statement expected"); break; } } } private void error(SimpleNode node, String error) { problemReporter.error(node.getBegin(), node.getEnd(),error, null); } private void error(SimpleNode node, String error, String hint) { problemReporter.error(node.getBegin(),node.getEnd(),error,hint); } private void warn(SimpleNode node, String warn) { problemReporter.warn(node.getBegin(),node.getEnd(), warn, null); } private void warn(SimpleNode node, String warn, String hint) { problemReporter.warn(node.getBegin(),node.getEnd(), warn, hint); } private void warn(String warn, String hint) { problemReporter.warn(1, 1, 1, 2, warn, hint); } }
package cornell.eickleapp; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.LayerDrawable; import android.os.Bundle; import android.os.Vibrator; import android.preference.PreferenceManager; import android.view.View; import android.widget.ImageView; import android.widget.Toast; public class DrinkCounter extends Activity { private int drink_count = 0; private DatabaseHandler db; private double hours; private double bac; private Vibrator click_vibe; private int face_color; private int face_icon; private final Double CALORIES_PER_DRINK = 120.0; private final Double CALORIES_HOT_DOG = 250.0; private final int START_COLOR = Color.rgb(112,191, 65); @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); click_vibe = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE); setContentView(R.layout.drink_tracker); db = new DatabaseHandler(this); calculateBac(); calculateColor(); SharedPreferences getPrefs = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); Boolean checkSurveyed = getPrefs.getBoolean("hints", true); if (checkSurveyed) { Intent openTutorial = new Intent(this, DrinkCounterTutorial.class); startActivity(openTutorial); } } private void update_face(){ ImageView face = (ImageView)findViewById(R.id.drink_smile); //Update the face color ((GradientDrawable)((LayerDrawable) face.getDrawable()).getDrawable(0) ).setColor(face_color); //Update the face icon ((LayerDrawable) face.getDrawable()).setDrawableByLayerId( R.id.face_icon, getResources().getDrawable(face_icon)); face.invalidate(); } @Override protected void onResume() { super.onResume(); calculateBac(); calculateColor(); update_face(); } private void calculateHours() { Date date = new Date(); ArrayList<DatabaseStore> drink_count_vals = (ArrayList<DatabaseStore>) db .getVarValuesDelay("drink_count", date); GregorianCalendar gc = new GregorianCalendar(); gc.setTime(date); gc.add(Calendar.HOUR_OF_DAY, -6); date = gc.getTime(); DatabaseStore current = new DatabaseStore("", "", date, "Integer"); face_color = START_COLOR; if (drink_count_vals != null) { drink_count = drink_count_vals.size(); drink_count_vals = DatabaseStore.sortByTime(drink_count_vals); // calculate the hours drinking if (drink_count_vals.size() > 0) { DatabaseStore start = drink_count_vals.get(0); Integer start_time = start.hour * 60 + start.minute; Integer last_time = current.hour * 60 + current.minute; hours = (last_time - start_time) / 60.0; } } } //TODO: Refactor to ask before removing and checking whether or not the // Drink was recently recorded. public void removeLast(View view) { drink_count Date date = new Date(); ArrayList<DatabaseStore> drink_count_vals = (ArrayList<DatabaseStore>) db .getVarValuesDelay("drink_count", date); drink_count_vals = DatabaseStore.sortByTime(drink_count_vals); ArrayList<String> variables = new ArrayList<String>(); variables.add(drink_count_vals.get( drink_count_vals.size() - 1).variable); variables.add("bac"); variables.add("bac_color"); variables.add("hotdog"); ArrayList<DatabaseStore> hd_val = ((ArrayList<DatabaseStore>)db .getVarValuesForDay("hotdog",date)); if(hd_val!=null){ if(hd_val.size() ==1){ if(Integer.valueOf(hd_val.get(0).value) >0){ db.updateOrAdd("hotdog", Integer.valueOf(hd_val.get(0).value) - 1); } } } if (drink_count_vals.size() == 1) { ArrayList<String> vals = new ArrayList<String>(); vals.add("drank_last_night"); vals.add("tracked"); db.deleteValuesTomorrow(vals); variables.add("drank"); } db.deleteVaribles(variables, drink_count_vals.get(drink_count_vals.size() - 1)); calculateBac(); calculateColor(); update_face(); Toast.makeText(getApplicationContext(), "Your last drink has been removed", Toast.LENGTH_SHORT).show(); } //TODO: Add icons for faces. public void calculateColor() { if (bac < 0.06) { face_color = START_COLOR; face_icon = R.drawable.ic_tracker_smile; } else if (bac < 0.15) { face_color = Color.rgb(245, 211,40); face_icon = R.drawable.ic_tracker_neutral; } else if (bac < 0.24) { face_color = Color.rgb(236, 93, 87); face_icon = R.drawable.ic_tracker_frown; } else { face_color = Color.DKGRAY; face_icon = R.drawable.ic_tracker_dead; } } private void calculateBac() { Date date = new Date(); ArrayList<DatabaseStore> drink_count_vals = (ArrayList<DatabaseStore>) db .getVarValuesDelay("drink_count", date); if (drink_count_vals != null) { calculateHours(); // get the users gender ArrayList<DatabaseStore> stored_gender = (ArrayList<DatabaseStore>) db .getAllVarValue("gender"); // If user did not set gender use "Female" as default String gender = "Female"; if (stored_gender != null) { gender = stored_gender.get(0).value; } // fetch the users weight ArrayList<DatabaseStore> stored_weight = (ArrayList<DatabaseStore>) db .getAllVarValue("weight"); Integer weight_lbs = 120; if (stored_weight != null) { weight_lbs = Integer.parseInt(stored_weight.get(0).value); } double metabolism_constant = 0; double gender_constant = 0; double weight_kilograms = weight_lbs * 0.453592; if (gender.equals("Male")) { metabolism_constant = 0.015; gender_constant = 0.58; } else { metabolism_constant = 0.017; gender_constant = 0.49; } bac = ((0.806 * drink_count * 1.2) / (gender_constant * weight_kilograms)) - (metabolism_constant * hours); } else { bac = 0; } } @SuppressLint("NewApi") public void hadDrink(View view) { drink_count++; if (drink_count == 1) { db.addValueTomorrow("drank_last_night", "True"); db.addValueTomorrow("tracked", "True"); db.updateOrAdd("drank", "True"); } db.addDelayValue("drink_count", drink_count); calculateBac(); db.addDelayValue("bac", String.valueOf(bac)); calculateColor(); db.addDelayValue("bac_color", String.valueOf(face_color)); update_face(); // calculate number of hot dogs that equate the number of calories Double drink_cals = drink_count * CALORIES_PER_DRINK; int number_hot_dogs = (int) Math.ceil(drink_cals/ CALORIES_HOT_DOG); db.updateOrAdd("hot_dogs", number_hot_dogs); } public void addDrinkHandler(View view){ click_vibe.vibrate(75); Toast t = Toast.makeText(getApplicationContext(), "Adding a drink. Count=" + drink_count, Toast.LENGTH_SHORT); t.show(); face_icon = R.drawable.ic_tracker_dead; face_color = Color.GRAY; update_face(); hadDrink(view); } /* * * TextView check = new TextView(this); * check.setText(String.valueOf(drink_count)); * check.setTextColor(Color.parseColor("#FFFFFF")); * ((FrameLayout)parent_view).addView(check); */ /* } @SuppressLint("NewApi") @Override public boolean onCreateOptionsMenu(Menu menu) { ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(false); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items Intent openPage; switch (item.getItemId()) { case R.id.tracking_menu: openPage = new Intent(this, DrinkCounter.class); startActivity(openPage); break; case R.id.assess_menu: openPage = new Intent(this, Assessment.class); startActivity(openPage); break; case R.id.visualize_menu: openPage = new Intent(this, VisualizeMenu.class); startActivity(openPage); break; case R.id.setting_menu: openPage = new Intent(this, Settings.class); startActivity(openPage); break; case android.R.id.home: openPage = new Intent(this, MainMenu.class); startActivity(openPage); break; } return true; } */ }
import java.text.MessageFormat; import java.util.*; import java.util.stream.Stream; public class ExpectationMaximization { private final static double TESTED_LAMBDA = 0.01; // check private final static double EPSILON_THRESHOLD = 0.00000001; private final static double K = 10; private final static double EM_THRESHOLD = 1; // check private Map<Integer, List<Article>> clusters; private DevelopmentSet developmentSet; private Topics topics; private int numClusters; private Map<Article, Double[]> Wti; private Map<Article, Double[]> Zti; private Map<Article, Double> Mt; private Map<String, Double[]> Pik; private double clustersProbability[]; //alpha(i) private double lambda; public void init(DevelopmentSet developmentSet, int numClusters, Topics topics, double lambda) { this.Wti = new HashMap<>(); this.Zti = new HashMap<>(); this.Mt = new HashMap<>(); this.Pik = new HashMap<>(); this.developmentSet = developmentSet; this.topics = topics; this.numClusters = numClusters; this.clustersProbability = new double[numClusters]; this.lambda = lambda; initClusters(); initEM(); MStep(); } public void run() { double lastLikelihood = Double.NEGATIVE_INFINITY; double likelihood = calcLikelihood(); List<Double> likelihoods = new ArrayList<Double>(); double perplexity = 0; List<Double> perplexities = new ArrayList<Double>(); // if in some round // we find that the Likelihood decrease - it means that we have a bug in our implementation or // that we are smoothing too aggressively. // Run EM algorithm until convergence while (Math.abs(likelihood - lastLikelihood) > EM_THRESHOLD) { EStep(); MStep(); // Save likelihoods for future graph plot if (lastLikelihood == Double.NEGATIVE_INFINITY) { lastLikelihood = calcLikelihood() - 2 * EM_THRESHOLD; } else { lastLikelihood = likelihood; } likelihood = calcLikelihood(); likelihoods.add(likelihood); // Save perplexities for future graph plot perplexity = calcPerplexity(likelihood); perplexities.add(perplexity); System.out.println(new MessageFormat("Likelihood: {0} \t Perplexity: {1}").format(new Object[]{likelihood, perplexity})); } Integer[][] confusionMatrix = buildConfusionMatrix(); double accuracy = calcAccuracy(confusionMatrix); System.out.println("Accuracy rate is: " + accuracy); } private double calcAccuracy(Integer[][] confusionMatrix) { int correctAssignments = 0; for (int i = 0; i < this.numClusters; i++) { correctAssignments += confusionMatrix[i][i]; } return correctAssignments / developmentSet.getArticles().size(); } private Integer[][] buildConfusionMatrix() { Integer[][] confusionMatrix = new Integer[this.numClusters][this.numClusters + 1]; for (Integer[] row : confusionMatrix) { Arrays.fill(row, 0); } int maxCluster; for (Article currentArticle : developmentSet.getArticles()) { Double maxWt = Wti.get(currentArticle)[0]; maxCluster = 0; for (int i = 1; i < this.numClusters; i++) { Double wti = Wti.get(currentArticle)[i]; if (wti > maxWt) { maxWt = wti; maxCluster = i; } } currentArticle.setAssignedTopic(topics.getTopics()[maxCluster]); // Build the confusion matrix based on the given topics and the max cluster topic for (String topic : currentArticle.getTopics()) { confusionMatrix[maxCluster][topics.getTopicIndex(topic)] += 1; confusionMatrix[maxCluster][this.numClusters] += 1; } } return confusionMatrix; } private double calcPerplexity(double likelihood) { return Math.pow(2, -1.0 / (developmentSet.countNumberOfWords() * likelihood)); } private void initClusters() { final int[] index = {0}; clusters = new HashMap<>(); developmentSet.getArticles().forEach(article -> { int key = index[0]++ % numClusters; if (!clusters.containsKey(key)) { clusters.put(key, new ArrayList<>()); } clusters.get(key).add(article); }); } // Set the initial Wti private void initEM() { // Going over all articles in each cluster (==all articles) and building the initial clusters probability for (int i = 0; i < numClusters; i++) { for (Article currentArticle : clusters.get(i)) { Double[] clusterProbabilityForArticle = new Double[numClusters]; for (int j = 0; j < numClusters; j++) { clusterProbabilityForArticle[j] = (i == j ? 1.0 : 0.0); } Wti.put(currentArticle, clusterProbabilityForArticle); } } } private void EStep() { for (Article currentArticle : developmentSet.getArticles()) { calcWti(currentArticle); } } // Calculate article probabilities for each cluster // Approximate Wti (4) private void calcWti(Article currentArticle) { Double sumZi = 0.0; Double[] Zi = calcZi(currentArticle); Double[] clusterProbabilityForArticle = new Double[numClusters]; Double m = calcMaxZi(Zi); for (int i = 0; i < numClusters; i++) { if (Zi[i] - m < -1 * K) { clusterProbabilityForArticle[i] = 0.0; } else { double eZiMinusM = Math.exp(Zi[i] - m); clusterProbabilityForArticle[i] = eZiMinusM; sumZi += eZiMinusM; } } for (int i = 0; i < numClusters; i++) { clusterProbabilityForArticle[i] /= sumZi; } Wti.put(currentArticle, clusterProbabilityForArticle); Zti.put(currentArticle, Zi); Mt.put(currentArticle, m); } // Calculate the Z value for each article in each cluster private Double[] calcZi(Article article) { Double[] result = new Double[numClusters]; for (int i = 0; i < numClusters; i++) { double sumFrequency = 0; // Going over k words and calculate the Z value for each article in each cluster for (String word : article.getWordsOccurrences().keySet()) { sumFrequency += article.getWordOccurrences(word) * Math.log(Pik.get(word)[i]); } result[i] = Math.log(clustersProbability[i]) + sumFrequency; } return result; } private Double calcMaxZi(Double[] Zi) { return Collections.max(Arrays.asList(Zi)); } private void MStep() { calcPik(); calcAlpha(); smoothAlpha(); } private void calcPik() { double sumWti; double wordsOccurrencesInArticles; double[] wordsInClusters = new double[numClusters]; // Calculate Pik (divisor) for (int i = 0; i < numClusters; i++) { sumWti = 0; for (Article currentArticle : developmentSet.getArticles()) { sumWti += (this.Wti.get(currentArticle)[i] * currentArticle.getNumberOfWords()); } wordsInClusters[i] = sumWti; } // Calculate Pik (dividend) // Calculate the Lidstone probability for each word to be in each topic by its Occurrences in all articles for (String word : developmentSet.getWordsOccurrences().keySet()) { Double[] lidstoneP = new Double[numClusters]; for (int i = 0; i < numClusters; i++) { wordsOccurrencesInArticles = 0; for (Article currentArticle : developmentSet.getArticles()) { int wordOccurrences = currentArticle.getWordOccurrences(word); Double Wti = this.Wti.get(currentArticle)[i]; if (wordOccurrences > 0 && Wti > 0) { wordsOccurrencesInArticles += (Wti * wordOccurrences); } } lidstoneP[i] = calcLidstonePortability(wordsOccurrencesInArticles, wordsInClusters[i]); } this.Pik.put(word, lidstoneP); } } private double calcLidstonePortability(double wordsOccurrencesInArticles, double wordsInCluster) { return (wordsOccurrencesInArticles + lambda) / (wordsInCluster + lambda * this.developmentSet.getWordsOccurrences().size()); } // Calculate alpha(i) private void calcAlpha() { double currentClusterProbability; for (int i = 0; i < numClusters; i++) { currentClusterProbability = 0; for (Article currentArticle : developmentSet.getArticles()) { currentClusterProbability += this.Wti.get(currentArticle)[i]; } this.clustersProbability[i] = currentClusterProbability / developmentSet.getArticles().size(); } } private void smoothAlpha() { double sumAlpha = 0; // Fix alpha(i) to the epsilon threshold for (int i = 0; i < numClusters; i++) { this.clustersProbability[i] = (clustersProbability[i] > EPSILON_THRESHOLD ? clustersProbability[i] : EPSILON_THRESHOLD); } // Find total clusters probability for (int i = 0; i < numClusters; i++) { sumAlpha += this.clustersProbability[i]; } // Find the probability to be in each cluster for (int i = 0; i < numClusters; i++) { this.clustersProbability[i] /= sumAlpha; } } private double calcLikelihood() { double likelihood = 0; for (Article currentArticle : Mt.keySet()) { double sumZt = 0; double Mt = this.Mt.get(currentArticle); Double[] clusters = Zti.get(currentArticle); if (clusters != null) { for (double Zti : clusters) { if (-1 * K <= Zti - Mt) { sumZt += Math.exp(Zti - Mt); } } } likelihood += Mt + Math.log(sumZt); } return likelihood; } }
package progen; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.doNothing; import static org.powermock.api.mockito.PowerMockito.mockStatic; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import progen.context.MissingContextFileException; import progen.context.ProGenContext; import progen.kernel.population.Individual; import progen.output.outputers.OutputStore; import progen.roles.ProGenFactory; import progen.roles.standalone.ClientLocal; import progen.roles.standalone.StandaloneFactory; import progen.userprogram.UserProgram; @RunWith(PowerMockRunner.class) @PrepareForTest({ ProGenContext.class, UserProgram.class, ProGenFactory.class, OutputStore.class }) public class ProGenTest { @Rule public ExpectedException exception = ExpectedException.none(); @Test public void testNoMasterFile() { String args[] = new String[0]; exception.expect(ProGenException.class); exception.expectMessage("'master-file' is mandatory to execute."); ProGen.main(args); fail("exception must be thrown"); } @Test(timeout=10000) public void testMasterFile() throws Exception { ByteArrayOutputStream systemOut = mockSystemOut(); String args[] = { "master-file.txt" }; mockStatic(ProGenContext.class, UserProgram.class, ProGenFactory.class, OutputStore.class); ProGenContext context = mock(ProGenContext.class); OutputStore outputStore = mock(OutputStore.class); StandaloneFactory factory = mock(StandaloneFactory.class); ClientLocal clientLocal = mock(ClientLocal.class); when(ProGenContext.makeInstance(any(String.class))).thenReturn(context); when(ProGenContext.getMandatoryProperty("progen.welcome")).thenReturn("ProGen exec TEST"); doNothing().when(ProGenContext.class, "loadExtraConfiguration"); when(ProGenFactory.makeInstance()).thenReturn(factory); when(factory.makeExecutionRole()).thenReturn(clientLocal); when(OutputStore.makeInstance()).thenReturn(outputStore); when(UserProgram.getUserProgram()).thenReturn(new UserProgramExample()); ProGen.main(args); String output = systemOut.toString("UTF-8"); assertTrue(output.startsWith("ProGen exec TEST\n\nEXECUTION TIME: ")); } @Test public void testMissingContextFileException() throws UnsupportedEncodingException{ ByteArrayOutputStream systemErr = mockSystemErr(); String args [] = {"master-file.txt"}; mockStatic(ProGenContext.class); when(ProGenContext.makeInstance(any(String.class))).thenThrow(new MissingContextFileException()); ProGen.main(args); assertEquals("File not found in the configuration files.(File not found.)\n", systemErr.toString("UTF-8")); } private ByteArrayOutputStream mockSystemOut() { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); System.setOut(printStream); return outputStream; } private ByteArrayOutputStream mockSystemErr() { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); System.setErr(printStream); return outputStream; } private class UserProgramExample extends UserProgram{ @Override public double fitness(Individual individual) { return 1; } } }
package ti.modules.titanium.network; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.MethodNotSupportedException; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.ProtocolException; import org.apache.http.StatusLine; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.params.ConnPerRouteBean; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.cookie.Cookie; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.DefaultHttpRequestFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultRedirectHandler; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollFunction; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.common.Log; import org.appcelerator.kroll.common.TiConfig; import org.appcelerator.kroll.util.TiTempFileHelper; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiBlob; import org.appcelerator.titanium.TiFileProxy; import org.appcelerator.titanium.io.TiBaseFile; import org.appcelerator.titanium.io.TiFile; import org.appcelerator.titanium.io.TiResourceFile; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiMimeTypeHelper; import ti.modules.titanium.xml.DocumentProxy; import ti.modules.titanium.xml.XMLModule; import android.net.Uri; public class TiHTTPClient { private static final String LCAT = "TiHttpClient"; private static final boolean DBG = TiConfig.LOGD; private static final int IS_BINARY_THRESHOLD = 30; private static final int DEFAULT_MAX_BUFFER_SIZE = 512 * 1024; private static final String PROPERTY_MAX_BUFFER_SIZE = "ti.android.httpclient.maxbuffersize"; private static final int PROTOCOL_DEFAULT_PORT = -1; private static final String ON_READY_STATE_CHANGE = "onreadystatechange"; private static final String ON_LOAD = "onload"; private static final String ON_ERROR = "onerror"; private static final String ON_DATA_STREAM = "ondatastream"; private static final String ON_SEND_STREAM = "onsendstream"; private static AtomicInteger httpClientThreadCounter; private static DefaultHttpClient nonValidatingClient; private static DefaultHttpClient validatingClient; private DefaultHttpClient client; private KrollProxy proxy; private int readyState; private String responseText; private DocumentProxy responseXml; private int status; private String statusText; private boolean connected; private HttpRequest request; private HttpResponse response; private String method; private HttpHost host; private LocalResponseHandler handler; private Credentials credentials; private TiBlob responseData; private OutputStream responseOut; private String charset; private String contentType; private long maxBufferSize; private ArrayList<NameValuePair> nvPairs; private HashMap<String, ContentBody> parts; private String data; private boolean needMultipart; private Thread clientThread; private boolean aborted; private int timeout = -1; private boolean autoEncodeUrl = true; private boolean autoRedirect = true; private Uri uri; private String url; protected HashMap<String,String> headers = new HashMap<String,String>(); public static final int READY_STATE_UNSENT = 0; // Unsent, open() has not yet been called public static final int READY_STATE_OPENED = 1; // Opened, send() has not yet been called public static final int READY_STATE_HEADERS_RECEIVED = 2; // Headers received, headers have returned and the status is available public static final int READY_STATE_LOADING = 3; // Loading, responseText is being loaded with data public static final int READY_STATE_DONE = 4; // Done, all operations have finished class RedirectHandler extends DefaultRedirectHandler { @Override public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } // get the location header to find out where to redirect to Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header throw new ProtocolException("Received redirect response " + response.getStatusLine() + " but no location header"); } // bug // in some cases we have to manually replace spaces in the URI (probably because the HTTP server isn't correctly escaping them) String location = locationHeader.getValue().replaceAll (" ", "%20"); response.setHeader("location", location); return super.getLocationURI(response, context); } @Override public boolean isRedirectRequested(HttpResponse response, HttpContext context) { if (autoRedirect) { return super.isRedirectRequested(response, context); } else { return false; } } } class LocalResponseHandler implements ResponseHandler<String> { public WeakReference<TiHTTPClient> client; public InputStream is; public HttpEntity entity; public LocalResponseHandler(TiHTTPClient client) { this.client = new WeakReference<TiHTTPClient>(client); } public String handleResponse(HttpResponse response) throws HttpResponseException, IOException { connected = true; String clientResponse = null; Header contentEncoding = null; if (client != null) { TiHTTPClient c = client.get(); if (c != null) { c.response = response; c.setReadyState(READY_STATE_HEADERS_RECEIVED); c.setStatus(response.getStatusLine().getStatusCode()); c.setStatusText(response.getStatusLine().getReasonPhrase()); c.setReadyState(READY_STATE_LOADING); } if (DBG) { try { Log.w(LCAT, "Entity Type: " + response.getEntity().getClass()); Log.w(LCAT, "Entity Content Type: " + response.getEntity().getContentType().getValue()); Log.w(LCAT, "Entity isChunked: " + response.getEntity().isChunked()); Log.w(LCAT, "Entity isStreaming: " + response.getEntity().isStreaming()); } catch (Throwable t) { // Ignore } } StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { setResponseText(response.getEntity()); throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } entity = response.getEntity(); contentEncoding = response.getFirstHeader("Content-Encoding"); if (entity != null) { if (entity.getContentType() != null) { contentType = entity.getContentType().getValue(); } if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { is = new GZIPInputStream(entity.getContent()); } else { is = entity.getContent(); } charset = EntityUtils.getContentCharSet(entity); } else { is = null; } responseData = null; if (is != null) { long contentLength = entity.getContentLength(); if (DBG) { Log.d(LCAT, "Content length: " + contentLength); } int count = 0; long totalSize = 0; byte[] buf = new byte[4096]; if (DBG) { Log.d(LCAT, "Available: " + is.available()); } if (entity != null) { charset = EntityUtils.getContentCharSet(entity); } while((count = is.read(buf)) != -1) { totalSize += count; try { handleEntityData(buf, count, totalSize, contentLength); } catch (IOException e) { Log.e(LCAT, "Error handling entity data", e); // TODO //Context.throwAsScriptRuntimeEx(e); } } if (entity != null) { try { entity.consumeContent(); } catch (IOException e) { e.printStackTrace(); } } if (totalSize > 0) { finishedReceivingEntityData(totalSize); } } } return clientResponse; } private TiFile createFileResponseData(boolean dumpResponseOut) throws IOException { File outFile; TiApplication app = TiApplication.getInstance(); if (app != null) { TiTempFileHelper helper = app.getTempFileHelper(); outFile = helper.createTempFile("tihttp", "tmp"); } else { outFile = File.createTempFile("tihttp", "tmp"); } TiFile tiFile = new TiFile(outFile, outFile.getAbsolutePath(), false); if (dumpResponseOut) { ByteArrayOutputStream byteStream = (ByteArrayOutputStream) responseOut; tiFile.write(TiBlob.blobFromData(byteStream.toByteArray()), false); } responseOut = new FileOutputStream(outFile, dumpResponseOut); responseData = TiBlob.blobFromFile(tiFile, contentType); return tiFile; } private void handleEntityData(byte[] data, int size, long totalSize, long contentLength) throws IOException { if (responseOut == null) { if (contentLength > maxBufferSize) { createFileResponseData(false); } else { long streamSize = contentLength > 0 ? contentLength : 512; responseOut = new ByteArrayOutputStream((int)streamSize); } } if (totalSize > maxBufferSize && responseOut instanceof ByteArrayOutputStream) { // Content length may not have been reported, dump the current stream // to a file and re-open as a FileOutputStream w/ append createFileResponseData(true); } responseOut.write(data, 0, size); KrollFunction onDataStreamCallback = getCallback(ON_DATA_STREAM); if (onDataStreamCallback != null) { KrollDict o = new KrollDict(); o.put("totalCount", contentLength); o.put("totalSize", totalSize); o.put("size", size); byte[] blobData = new byte[size]; System.arraycopy(data, 0, blobData, 0, size); TiBlob blob = TiBlob.blobFromData(blobData, contentType); o.put("blob", blob); o.put("progress", ((double)totalSize)/((double)contentLength)); onDataStreamCallback.callAsync(proxy.getKrollObject(), o); } } private void finishedReceivingEntityData(long contentLength) throws IOException { if (responseOut instanceof ByteArrayOutputStream) { ByteArrayOutputStream byteStream = (ByteArrayOutputStream) responseOut; responseData = TiBlob.blobFromData(byteStream.toByteArray(), contentType); } responseOut.close(); responseOut = null; } private void setResponseText(HttpEntity entity) throws IOException, ParseException { if (entity != null) { responseText = EntityUtils.toString(entity); } } } private interface ProgressListener { public void progress(int progress); } private class ProgressEntity implements HttpEntity { private HttpEntity delegate; private ProgressListener listener; public ProgressEntity(HttpEntity delegate, ProgressListener listener) { this.delegate = delegate; this.listener = listener; } public void consumeContent() throws IOException { delegate.consumeContent(); } public InputStream getContent() throws IOException, IllegalStateException { return delegate.getContent(); } public Header getContentEncoding() { return delegate.getContentEncoding(); } public long getContentLength() { return delegate.getContentLength(); } public Header getContentType() { return delegate.getContentType(); } public boolean isChunked() { return delegate.isChunked(); } public boolean isRepeatable() { return delegate.isRepeatable(); } public boolean isStreaming() { return delegate.isStreaming(); } public void writeTo(OutputStream stream) throws IOException { OutputStream progressOut = new ProgressOutputStream(stream, listener); delegate.writeTo(progressOut); } } private class ProgressOutputStream extends FilterOutputStream { private ProgressListener listener; private int transferred = 0, lastTransferred = 0; public ProgressOutputStream(OutputStream delegate, ProgressListener listener) { super(delegate); this.listener = listener; } private void fireProgress() { // filter to 512 bytes of granularity if (transferred - lastTransferred >= 512) { lastTransferred = transferred; listener.progress(transferred); } } @Override public void write(int b) throws IOException { super.write(b); transferred++; fireProgress(); } } public TiHTTPClient(KrollProxy proxy) { this.proxy = proxy; this.client = getClient(false); if (httpClientThreadCounter == null) { httpClientThreadCounter = new AtomicInteger(); } readyState = 0; responseText = ""; credentials = null; connected = false; this.nvPairs = new ArrayList<NameValuePair>(); this.parts = new HashMap<String,ContentBody>(); this.maxBufferSize = TiApplication.getInstance() .getSystemProperties().getInt(PROPERTY_MAX_BUFFER_SIZE, DEFAULT_MAX_BUFFER_SIZE); } public int getReadyState() { synchronized(this) { this.notify(); } return readyState; } public KrollFunction getCallback(String name) { Object value = proxy.getProperty(name); if (value != null && value instanceof KrollFunction) { return (KrollFunction) value; } return null; } public void fireCallback(String name) { KrollDict eventProperties = new KrollDict(); eventProperties.put("source", proxy); fireCallback(name, new Object [] {eventProperties}); } public void fireCallback(String name, Object[] args) { KrollFunction cb = getCallback(name); if (cb != null) { // TODO - implement converter method for array to hashmap? cb.callAsync(proxy.getKrollObject(), args); } } public boolean validatesSecureCertificate() { if (proxy.hasProperty("validatesSecureCertificate")) { return TiConvert.toBoolean(proxy.getProperty("validatesSecureCertificate")); } else { if (TiApplication.getInstance().getDeployType().equals( TiApplication.DEPLOY_TYPE_PRODUCTION)) { return true; } } return false; } public void setReadyState(int readyState) { Log.d(LCAT, "Setting ready state to " + readyState); this.readyState = readyState; fireCallback(ON_READY_STATE_CHANGE); if (readyState == READY_STATE_DONE) { // Fire onload callback fireCallback(ON_LOAD); } } public void sendError(String error) { Log.i(LCAT, "Sending error " + error); KrollDict event = new KrollDict(); event.put("error", error); event.put("source", proxy); fireCallback(ON_ERROR, new Object[] {event}); } public String getResponseText() { if (responseData != null && responseText == null) { byte[] data = responseData.getBytes(); if (charset == null) { // Detect binary int binaryCount = 0; int len = data.length; if (len > 0) { for (int i = 0; i < len; i++) { byte b = data[i]; if (b < 32 || b > 127 ) { if (b != '\n' && b != '\r' && b != '\t' && b != '\b') { binaryCount++; } } } if ((binaryCount * 100)/len >= IS_BINARY_THRESHOLD) { return null; } } charset = HTTP.DEFAULT_CONTENT_CHARSET; } try { responseText = new String(data, charset); } catch (UnsupportedEncodingException e) { Log.e(LCAT, "Unable to convert to String using charset: " + charset); } } return responseText; } public TiBlob getResponseData() { return responseData; } public DocumentProxy getResponseXML() { // avoid eating up tons of memory if we have a large binary data blob if (TiMimeTypeHelper.isBinaryMimeType(contentType)) { return null; } if (responseXml == null && (responseData != null || responseText != null)) { try { String text = getResponseText(); if (text == null || text.length() == 0) { return null; } if (charset != null && charset.length() > 0) { responseXml = XMLModule.parse(text, charset); } else { responseXml = XMLModule.parse(text); } } catch (Exception e) { Log.e(LCAT, "Error parsing XML", e); } } return responseXml; } public void setResponseText(String responseText) { this.responseText = responseText; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getStatusText() { return statusText; } public void setStatusText(String statusText) { this.statusText = statusText; } public void abort() { if (readyState > READY_STATE_UNSENT && readyState < READY_STATE_DONE) { aborted = true; if (client != null) { client.getConnectionManager().shutdown(); client = null; } if (validatingClient != null) validatingClient = null; if (nonValidatingClient != null) nonValidatingClient = null; } } public String getAllResponseHeaders() { String result = ""; if (readyState >= READY_STATE_HEADERS_RECEIVED && response != null) { StringBuilder sb = new StringBuilder(1024); Header[] headers = response.getAllHeaders(); int len = headers.length; for(int i = 0; i < len; i++) { Header h = headers[i]; sb.append(h.getName()).append(":").append(h.getValue()).append("\n"); } result = sb.toString(); } else { // Spec says return ""; } return result; } public void clearCookies(String url) { List<Cookie> cookies = new ArrayList(client.getCookieStore().getCookies()); client.getCookieStore().clear(); String lower_url = url.toLowerCase(); for (Cookie cookie : cookies) { if (!lower_url.contains(cookie.getDomain().toLowerCase())) { client.getCookieStore().addCookie(cookie); } } } public void setRequestHeader(String header, String value) { if (readyState == READY_STATE_OPENED) { headers.put(header, value); } else { throw new IllegalStateException("setRequestHeader can only be called before invoking send."); } } public String getResponseHeader(String headerName) { String result = ""; if (readyState > READY_STATE_OPENED) { String delimiter = ""; boolean firstPass = true; // headers will be an empty array if none can be found Header[] headers = response.getHeaders(headerName); for (Header header : headers) { if (!firstPass) { delimiter = ", "; } result += delimiter + header.getValue(); firstPass = false; } if (headers.length == 0) { Log.w(LCAT, "No value for response header: " + headerName); } } else { throw new IllegalStateException("getResponseHeader can only be called when readyState > 1"); } return result; } private static Uri getCleanUri(String uri) { Uri base = Uri.parse(uri); Uri.Builder builder = base.buildUpon(); builder.encodedQuery(Uri.encode(Uri.decode(base.getQuery()), "&=")); String encodedAuthority = Uri.encode(Uri.decode(base.getAuthority()),"/:@"); int firstAt = encodedAuthority.indexOf('@'); if (firstAt >= 0) { int lastAt = encodedAuthority.lastIndexOf('@'); if (lastAt > firstAt) { // We have a situation that might be like this: // i.e., the user name is user@domain.com, and the host // is api.mickey.com. We need all at-signs prior to the final one (which // indicates the host) to be encoded. encodedAuthority = Uri.encode(encodedAuthority.substring(0, lastAt), "/:") + encodedAuthority.substring(lastAt); } } builder.encodedAuthority(encodedAuthority); builder.encodedPath(Uri.encode(Uri.decode(base.getPath()), "/")); return builder.build(); } public void open(String method, String url) { if (DBG) { Log.d(LCAT, "open request method=" + method + " url=" + url); } if (url == null) { Log.e(LCAT, "unable to open a null URL"); throw new IllegalArgumentException("URL cannot be null"); } // if the url is not prepended with either http or // https, then default to http and prepend the protocol // to the url if (!url.startsWith("http: url = "http://" + url; } if (autoEncodeUrl) { this.uri = getCleanUri(url); } else { this.uri = Uri.parse(url); } // If the original url does not contain any // escaped query string (i.e., does not look // pre-encoded), go ahead and reset it to the // clean uri. Else keep it as is so the user's // escaping stays in effect. The users are on their own // at that point. if (autoEncodeUrl && !url.matches(".*\\?.*\\%\\d\\d.*$")) { this.url = this.uri.toString(); } else { this.url = url; } this.method = method; String hostString = uri.getHost(); int port = PROTOCOL_DEFAULT_PORT; // The Android Uri doesn't seem to handle user ids with at-signs (@) in them // properly, even if the @ is escaped. It will set the host (uri.getHost()) to // the part of the user name after the @. For example, this Uri would get // the host set to appcelerator.com when it should be mickey.com: // ... even if that first one is escaped to ... // Tests show that Java URL handles it properly, however. So revert to using Java URL.getHost() // if we see that the Uri.getUserInfo has an at-sign in it. // Also, uri.getPort() will throw an exception as it will try to parse what it thinks is the port // part of the Uri (":password....") as an int. So in this case we'll get the port number // as well from Java URL. See Lighthouse ticket 2150. if (uri.getUserInfo() != null && uri.getUserInfo().contains("@")) { URL javaUrl; try { javaUrl = new URL(uri.toString()); hostString = javaUrl.getHost(); port = javaUrl.getPort(); } catch (MalformedURLException e) { Log.e(LCAT, "Error attempting to derive Java url from uri: " + e.getMessage(), e); } } else { port = uri.getPort(); } if (DBG) { Log.d(LCAT, "Instantiating host with hostString='" + hostString + "', port='" + port + "', scheme='" + uri.getScheme() + "'"); } host = new HttpHost(hostString, port, uri.getScheme()); if (uri.getUserInfo() != null) { credentials = new UsernamePasswordCredentials(uri.getUserInfo()); } setReadyState(READY_STATE_OPENED); setRequestHeader("User-Agent", (String) proxy.getProperty("userAgent")); // Causes Auth to Fail with twitter and other size apparently block X- as well // Ticket #729, ignore twitter for now if (!hostString.contains("twitter.com")) { setRequestHeader("X-Requested-With","XMLHttpRequest"); } else { Log.i(LCAT, "Twitter: not sending X-Requested-With header"); } } public void addStringData(String data) { this.data = data; } public void addPostData(String name, String value) { if (value == null) { value = ""; } try { if (needMultipart) { // JGH NOTE: this seems to be a bug in RoR where it would puke if you // send a content-type of text/plain for key/value pairs in form-data // so we send an empty string by default instead which will cause the // StringBody to not include the content-type header. this should be // harmless for all other cases parts.put(name, new StringBody(value,"",null)); } else { nvPairs.add(new BasicNameValuePair(name, value.toString())); } } catch (UnsupportedEncodingException e) { nvPairs.add(new BasicNameValuePair(name, value.toString())); } } public int addTitaniumFileAsPostData(String name, Object value) { try { // TiResourceFile cannot use the FileBody approach directly, because it requires // a java File object, which you can't get from packaged resources. So // TiResourceFile uses the approach we use for blobs, which is write out the // contents to a temp file, then use that for the FileBody. if (value instanceof TiBaseFile && !(value instanceof TiResourceFile)) { TiBaseFile baseFile = (TiBaseFile) value; FileBody body = new FileBody(baseFile.getNativeFile(), TiMimeTypeHelper.getMimeType(baseFile.nativePath())); parts.put(name, body); return (int)baseFile.getNativeFile().length(); } else if (value instanceof TiBlob || value instanceof TiResourceFile) { TiBlob blob; if (value instanceof TiBlob) { blob = (TiBlob) value; } else { blob = ((TiResourceFile) value).read(); } String mimeType = blob.getMimeType(); File tmpFile = File.createTempFile("tixhr", "." + TiMimeTypeHelper.getFileExtensionFromMimeType(mimeType, "txt")); FileOutputStream fos = new FileOutputStream(tmpFile); fos.write(blob.getBytes()); fos.close(); FileBody body = new FileBody(tmpFile, mimeType); parts.put(name, body); return blob.getLength(); } else { if (value != null) { Log.e(LCAT, name + " is a " + value.getClass().getSimpleName()); } else { Log.e(LCAT, name + " is null"); } } } catch (IOException e) { Log.e(LCAT, "Error adding post data ("+name+"): " + e.getMessage()); } return 0; } protected DefaultHttpClient createClient() { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 5); ConnPerRouteBean connPerRoute = new ConnPerRouteBean(5); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); HttpProtocolParams.setUseExpectContinue(params, false); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); return new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params); } protected DefaultHttpClient getClient(boolean validating) { if (validating) { if (nonValidatingClient != null) { return nonValidatingClient; } nonValidatingClient = createClient(); nonValidatingClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); return nonValidatingClient; } else { if (validatingClient != null) { return validatingClient; } validatingClient = createClient(); validatingClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", new NonValidatingSSLSocketFactory(), 443)); return validatingClient; } } public void send(Object userData) throws MethodNotSupportedException { aborted = false; // TODO consider using task manager double totalLength = 0; needMultipart = false; if (userData != null) { if (userData instanceof HashMap) { HashMap<String, Object> data = (HashMap) userData; boolean isPostOrPut = method.equals("POST") || method.equals("PUT"); boolean isGet = !isPostOrPut && method.equals("GET"); // first time through check if we need multipart for POST for (String key : data.keySet()) { Object value = data.get(key); if(value != null) { // if the value is a proxy, we need to get the actual file object if (value instanceof TiFileProxy) { value = ((TiFileProxy) value).getBaseFile(); } if (value instanceof TiBaseFile || value instanceof TiBlob) { needMultipart = true; break; } } } boolean queryStringAltered = false; for (String key : data.keySet()) { Object value = data.get(key); if (isPostOrPut && (value != null)) { // if the value is a proxy, we need to get the actual file object if (value instanceof TiFileProxy) { value = ((TiFileProxy) value).getBaseFile(); } if (value instanceof TiBaseFile || value instanceof TiBlob) { totalLength += addTitaniumFileAsPostData(key, value); } else { String str = TiConvert.toString(value); addPostData(key, str); totalLength += str.length(); } } else if (isGet) { uri = uri.buildUpon().appendQueryParameter( key, TiConvert.toString(value)).build(); queryStringAltered = true; } } if (queryStringAltered) { this.url = uri.toString(); } } else { addStringData(TiConvert.toString(userData)); } } if (DBG) { Log.d(LCAT, "Instantiating http request with method='" + method + "' and this url:"); Log.d(LCAT, this.url); } request = new DefaultHttpRequestFactory().newHttpRequest(method, this.url); for (String header : headers.keySet()) { request.setHeader(header, headers.get(header)); } clientThread = new Thread(new ClientRunnable(totalLength), "TiHttpClient-" + httpClientThreadCounter.incrementAndGet()); clientThread.setPriority(Thread.MIN_PRIORITY); clientThread.start(); if (DBG) { Log.d(LCAT, "Leaving send()"); } } private class ClientRunnable implements Runnable { private double totalLength; public ClientRunnable(double totalLength) { this.totalLength = totalLength; } public void run() { try { Thread.sleep(10); if (DBG) { Log.d(LCAT, "send()"); } /* Header[] h = request.getAllHeaders(); for(int i=0; i < h.length; i++) { Header hdr = h[i]; //Log.e(LCAT, "HEADER: " + hdr.toString()); } */ handler = new LocalResponseHandler(TiHTTPClient.this); // lazy get client each time in case the validatesSecureCertificate() changes client = getClient(validatesSecureCertificate()); if (credentials != null) { client.getCredentialsProvider().setCredentials (new AuthScope(uri.getHost(), -1), credentials); credentials = null; } client.setRedirectHandler(new RedirectHandler()); if(request instanceof BasicHttpEntityEnclosingRequest) { UrlEncodedFormEntity form = null; MultipartEntity mpe = null; if (nvPairs.size() > 0) { try { form = new UrlEncodedFormEntity(nvPairs, "UTF-8"); } catch (UnsupportedEncodingException e) { Log.e(LCAT, "Unsupported encoding: ", e); } } if (parts.size() > 0 && needMultipart) { mpe = new MultipartEntity(); for(String name : parts.keySet()) { Log.d(LCAT, "adding part " + name + ", part type: " + parts.get(name).getMimeType() + ", len: " + parts.get(name).getContentLength()); mpe.addPart(name, parts.get(name)); } if (form != null) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream((int) form.getContentLength()); form.writeTo(bos); mpe.addPart("form", new StringBody(bos.toString(), "application/x-www-form-urlencoded", Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { Log.e(LCAT, "Unsupported encoding: ", e); } catch (IOException e) { Log.e(LCAT, "Error converting form to string: ", e); } } HttpEntityEnclosingRequest e = (HttpEntityEnclosingRequest) request; Log.d(LCAT, "totalLength="+totalLength); ProgressEntity progressEntity = new ProgressEntity(mpe, new ProgressListener() { public void progress(int progress) { KrollFunction cb = getCallback(ON_SEND_STREAM); if (cb != null) { KrollDict data = new KrollDict(); data.put("progress", ((double)progress)/totalLength); data.put("source", proxy); cb.callAsync(proxy.getKrollObject(), data); } } }); e.setEntity(progressEntity); e.addHeader("Length", totalLength+""); } else { handleURLEncodedData(form); } } // set request specific parameters if (timeout != -1) { HttpConnectionParams.setConnectionTimeout(request.getParams(), timeout); HttpConnectionParams.setSoTimeout(request.getParams(), timeout); } if (DBG) { Log.d(LCAT, "Preparing to execute request"); } String result = null; try { result = client.execute(host, request, handler); } catch (IOException e) { if (!aborted) { throw e; } } if(result != null) { Log.d(LCAT, "Have result back from request len=" + result.length()); } connected = false; setResponseText(result); setReadyState(READY_STATE_DONE); } catch(Throwable t) { if (client != null) { Log.d(LCAT, "clearing the expired and idle connections"); client.getConnectionManager().closeExpiredConnections(); client.getConnectionManager().closeIdleConnections(0, TimeUnit.NANOSECONDS); } else { Log.d(LCAT, "client is not valid, unable to clear expired and idle connections"); } String msg = t.getMessage(); if (msg == null && t.getCause() != null) { msg = t.getCause().getMessage(); } if (msg == null) { msg = t.getClass().getName(); } Log.e(LCAT, "HTTP Error (" + t.getClass().getName() + "): " + msg, t); sendError(msg); } } } private void handleURLEncodedData(UrlEncodedFormEntity form) { AbstractHttpEntity entity = null; if (data != null) { try { entity = new StringEntity(data, "UTF-8"); } catch(Exception ex) { //FIXME Log.e(LCAT, "Exception, implement recovery: ", ex); } } else { entity = form; } if (entity != null) { Header header = request.getFirstHeader("Content-Type"); if(header == null) { entity.setContentType("application/x-www-form-urlencoded"); } else { entity.setContentType(header.getValue()); } HttpEntityEnclosingRequest e = (HttpEntityEnclosingRequest)request; e.setEntity(entity); } } public String getLocation() { return url; } public String getConnectionType() { return method; } public boolean isConnected() { return connected; } public void setTimeout(int millis) { timeout = millis; } protected void setAutoEncodeUrl(boolean value) { autoEncodeUrl = value; } protected boolean getAutoEncodeUrl() { return autoEncodeUrl; } protected void setAutoRedirect(boolean value) { autoRedirect = value; } protected boolean getAutoRedirect() { return autoRedirect; } }
package proyectoingenieria; import java.io.IOException; /** * * Autora: Mafer Delgado */ public class ProyectoIngenieria { /** * @param args the command line arguments */ public static void main(String[] args)throws IOException{ // TODO code application logic here Menu(); } public static void Menu()throws IOException{ System.out.println("\n\n\t\t\t=============Menú================="); System.out.println("\t\t\t= ="); System.out.println("\t\t\t= 1-Universidad Laica Eloy Alfaro de Manabí ="); System.out.println("\t\t\t= 2- Hola Ing soy Mafer ="); System.out.println("\t\t\t= 3- Salir ="); System.out.println("\t\t\t======================================"); System.out.println("\t\t\tOpcion: "); } }
package org.zstack.image; import org.apache.logging.log4j.ThreadContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.zstack.core.Platform; import org.zstack.core.asyncbatch.AsyncBatchRunner; import org.zstack.core.asyncbatch.LoopAsyncBatch; import org.zstack.core.asyncbatch.While; import org.zstack.core.cloudbus.*; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.core.config.GlobalConfig; import org.zstack.core.config.GlobalConfigUpdateExtensionPoint; import org.zstack.core.db.*; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.defer.Defer; import org.zstack.core.defer.Deferred; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.core.notification.N; import org.zstack.core.thread.CancelablePeriodicTask; import org.zstack.core.thread.ThreadFacade; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.core.workflow.ShareFlow; import org.zstack.header.AbstractService; import org.zstack.header.core.AsyncLatch; import org.zstack.header.core.NoErrorCompletion; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.ErrorCodeList; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.identity.*; import org.zstack.header.image.*; import org.zstack.header.image.APICreateRootVolumeTemplateFromVolumeSnapshotEvent.Failure; import org.zstack.header.image.ImageConstant.ImageMediaType; import org.zstack.header.image.ImageDeletionPolicyManager.ImageDeletionPolicy; import org.zstack.header.managementnode.ManagementNodeReadyExtensionPoint; import org.zstack.header.message.APIMessage; import org.zstack.header.message.Message; import org.zstack.header.message.MessageReply; import org.zstack.header.message.NeedQuotaCheckMessage; import org.zstack.header.quota.QuotaConstant; import org.zstack.header.rest.RESTFacade; import org.zstack.header.search.SearchOp; import org.zstack.header.storage.backup.*; import org.zstack.header.storage.primary.PrimaryStorageVO; import org.zstack.header.storage.primary.PrimaryStorageVO_; import org.zstack.header.storage.snapshot.*; import org.zstack.header.vm.CreateTemplateFromVmRootVolumeMsg; import org.zstack.header.vm.CreateTemplateFromVmRootVolumeReply; import org.zstack.header.vm.VmInstanceConstant; import org.zstack.header.volume.*; import org.zstack.identity.AccountManager; import org.zstack.identity.QuotaUtil; import org.zstack.search.SearchQuery; import org.zstack.tag.TagManager; import org.zstack.utils.CollectionUtils; import org.zstack.utils.ObjectUtils; import org.zstack.utils.RunOnce; import org.zstack.utils.Utils; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.function.Function; import org.zstack.utils.gson.JSONObjectUtil; import org.zstack.utils.logging.CLogger; import javax.persistence.Tuple; import javax.persistence.TypedQuery; import java.sql.Timestamp; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static org.zstack.core.Platform.operr; import static org.zstack.header.Constants.THREAD_CONTEXT_API; import static org.zstack.header.Constants.THREAD_CONTEXT_TASK_NAME; import static org.zstack.utils.CollectionDSL.list; import static org.zstack.core.progress.ProgressReportService.reportProgress; public class ImageManagerImpl extends AbstractService implements ImageManager, ManagementNodeReadyExtensionPoint, ReportQuotaExtensionPoint, ResourceOwnerPreChangeExtensionPoint { private static final CLogger logger = Utils.getLogger(ImageManagerImpl.class); @Autowired private CloudBus bus; @Autowired private PluginRegistry pluginRgty; @Autowired private DatabaseFacade dbf; @Autowired private AccountManager acntMgr; @Autowired private ErrorFacade errf; @Autowired private TagManager tagMgr; @Autowired private ThreadFacade thdf; @Autowired private ResourceDestinationMaker destMaker; @Autowired private ImageDeletionPolicyManager deletionPolicyMgr; @Autowired protected RESTFacade restf; private Map<String, ImageFactory> imageFactories = Collections.synchronizedMap(new HashMap<>()); private static final Set<Class> allowedMessageAfterDeletion = new HashSet<>(); private Future<Void> expungeTask; static { allowedMessageAfterDeletion.add(ImageDeletionMsg.class); } @Override @MessageSafe public void handleMessage(Message msg) { if (msg instanceof ImageMessage) { passThrough((ImageMessage) msg); } else if (msg instanceof APIMessage) { handleApiMessage(msg); } else { handleLocalMessage(msg); } } private void handleLocalMessage(Message msg) { bus.dealWithUnknownMessage(msg); } private void handleApiMessage(Message msg) { if (msg instanceof APIAddImageMsg) { handle((APIAddImageMsg) msg); } else if (msg instanceof APIListImageMsg) { handle((APIListImageMsg) msg); } else if (msg instanceof APISearchImageMsg) { handle((APISearchImageMsg) msg); } else if (msg instanceof APIGetImageMsg) { handle((APIGetImageMsg) msg); } else if (msg instanceof APICreateRootVolumeTemplateFromRootVolumeMsg) { handle((APICreateRootVolumeTemplateFromRootVolumeMsg) msg); } else if (msg instanceof APICreateRootVolumeTemplateFromVolumeSnapshotMsg) { handle((APICreateRootVolumeTemplateFromVolumeSnapshotMsg) msg); } else if (msg instanceof APICreateDataVolumeTemplateFromVolumeMsg) { handle((APICreateDataVolumeTemplateFromVolumeMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(final APICreateDataVolumeTemplateFromVolumeMsg msg) { final APICreateDataVolumeTemplateFromVolumeEvent evt = new APICreateDataVolumeTemplateFromVolumeEvent(msg.getId()); List<ImageBackupStorageRefVO> refs = new ArrayList<>(); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("create-data-volume-template-from-volume-%s", msg.getVolumeUuid())); chain.then(new ShareFlow() { List<BackupStorageInventory> backupStorages = new ArrayList<>(); ImageVO image; long actualSize; @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "get-actual-size-of-data-volume"; @Override public void run(final FlowTrigger trigger, Map data) { SyncVolumeSizeMsg smsg = new SyncVolumeSizeMsg(); smsg.setVolumeUuid(msg.getVolumeUuid()); bus.makeTargetServiceIdByResourceUuid(smsg, VolumeConstant.SERVICE_ID, msg.getVolumeUuid()); bus.send(smsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } SyncVolumeSizeReply sr = reply.castReply(); actualSize = sr.getActualSize(); trigger.next(); } }); } }); flow(new Flow() { String __name__ = "create-image-in-database"; @Override public void run(FlowTrigger trigger, Map data) { SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class); q.select(VolumeVO_.format, VolumeVO_.size); q.add(VolumeVO_.uuid, Op.EQ, msg.getVolumeUuid()); Tuple t = q.findTuple(); String format = t.get(0, String.class); long size = t.get(1, Long.class); final ImageVO vo = new ImageVO(); vo.setUuid(msg.getResourceUuid() == null ? Platform.getUuid() : msg.getResourceUuid()); vo.setName(msg.getName()); vo.setDescription(msg.getDescription()); vo.setType(ImageConstant.ZSTACK_IMAGE_TYPE); vo.setMediaType(ImageMediaType.DataVolumeTemplate); vo.setSize(size); vo.setActualSize(actualSize); vo.setState(ImageState.Enabled); vo.setStatus(ImageStatus.Creating); vo.setSystem(false); vo.setFormat(format); vo.setUrl(String.format("volume://%s", msg.getVolumeUuid())); image = dbf.persistAndRefresh(vo); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName()); trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { if (image != null) { dbf.remove(image); } trigger.rollback(); } }); flow(new Flow() { String __name__ = "select-backup-storage"; @Override public void run(final FlowTrigger trigger, Map data) { final String zoneUuid = new Callable<String>() { @Override @Transactional(readOnly = true) public String call() { String sql = "select ps.zoneUuid" + " from PrimaryStorageVO ps, VolumeVO vol" + " where vol.primaryStorageUuid = ps.uuid" + " and vol.uuid = :volUuid"; TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class); q.setParameter("volUuid", msg.getVolumeUuid()); return q.getSingleResult(); } }.call(); if (msg.getBackupStorageUuids() == null) { AllocateBackupStorageMsg amsg = new AllocateBackupStorageMsg(); amsg.setRequiredZoneUuid(zoneUuid); amsg.setSize(actualSize); bus.makeLocalServiceId(amsg, BackupStorageConstant.SERVICE_ID); bus.send(amsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { backupStorages.add(((AllocateBackupStorageReply) reply).getInventory()); saveRefVOByBsInventorys(backupStorages, image.getUuid()); for (BackupStorageInventory bs: backupStorages) { for (CreateImageExtensionPoint ext : pluginRgty.getExtensionList(CreateImageExtensionPoint.class)) { ext.beforeCreateImage(ImageInventory.valueOf(image), bs.getUuid()); } } trigger.next(); } else { trigger.fail(errf.stringToOperationError("cannot find proper backup storage", reply.getError())); } } }); } else { List<AllocateBackupStorageMsg> amsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<AllocateBackupStorageMsg, String>() { @Override public AllocateBackupStorageMsg call(String arg) { AllocateBackupStorageMsg amsg = new AllocateBackupStorageMsg(); amsg.setRequiredZoneUuid(zoneUuid); amsg.setSize(actualSize); amsg.setBackupStorageUuid(arg); bus.makeLocalServiceId(amsg, BackupStorageConstant.SERVICE_ID); return amsg; } }); bus.send(amsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { List<ErrorCode> errs = new ArrayList<>(); for (MessageReply r : replies) { if (r.isSuccess()) { backupStorages.add(((AllocateBackupStorageReply) r).getInventory()); } else { errs.add(r.getError()); } } if (backupStorages.isEmpty()) { trigger.fail(operr("failed to allocate all backup storage[uuid:%s], a list of error: %s", msg.getBackupStorageUuids(), JSONObjectUtil.toJsonString(errs))); } else { saveRefVOByBsInventorys(backupStorages, image.getUuid()); for (BackupStorageInventory bs: backupStorages) { for (CreateImageExtensionPoint ext : pluginRgty.getExtensionList(CreateImageExtensionPoint.class)) { ext.beforeCreateImage(ImageInventory.valueOf(image), bs.getUuid()); } } trigger.next(); } } }); } } @Override public void rollback(FlowRollback trigger, Map data) { if (!backupStorages.isEmpty()) { List<ReturnBackupStorageMsg> rmsgs = CollectionUtils.transformToList(backupStorages, new Function<ReturnBackupStorageMsg, BackupStorageInventory>() { @Override public ReturnBackupStorageMsg call(BackupStorageInventory arg) { ReturnBackupStorageMsg rmsg = new ReturnBackupStorageMsg(); rmsg.setBackupStorageUuid(arg.getUuid()); rmsg.setSize(actualSize); bus.makeLocalServiceId(rmsg, BackupStorageConstant.SERVICE_ID); return rmsg; } }); bus.send(rmsgs, new CloudBusListCallBack(null) { @Override public void run(List<MessageReply> replies) { for (MessageReply r : replies) { BackupStorageInventory bs = backupStorages.get(replies.indexOf(r)); logger.warn(String.format("failed to return %s bytes to backup storage[uuid:%s]", acntMgr, bs.getUuid())); } } }); } trigger.rollback(); } }); flow(new NoRollbackFlow() { String __name__ = "create-data-volume-template-from-volume"; @Override public void run(final FlowTrigger trigger, Map data) { List<CreateDataVolumeTemplateFromDataVolumeMsg> cmsgs = CollectionUtils.transformToList(backupStorages, new Function<CreateDataVolumeTemplateFromDataVolumeMsg, BackupStorageInventory>() { @Override public CreateDataVolumeTemplateFromDataVolumeMsg call(BackupStorageInventory bs) { CreateDataVolumeTemplateFromDataVolumeMsg cmsg = new CreateDataVolumeTemplateFromDataVolumeMsg(); cmsg.setVolumeUuid(msg.getVolumeUuid()); cmsg.setBackupStorageUuid(bs.getUuid()); cmsg.setImageUuid(image.getUuid()); bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeConstant.SERVICE_ID, msg.getVolumeUuid()); return cmsg; } }); bus.send(cmsgs, new CloudBusListCallBack(msg) { @Override public void run(List<MessageReply> replies) { int fail = 0; String mdsum = null; ErrorCode err = null; String format = null; for (MessageReply r : replies) { BackupStorageInventory bs = backupStorages.get(replies.indexOf(r)); if (!r.isSuccess()) { logger.warn(String.format("failed to create data volume template from volume[uuid:%s] on backup storage[uuid:%s], %s", msg.getVolumeUuid(), bs.getUuid(), r.getError())); fail++; err = r.getError(); continue; } CreateDataVolumeTemplateFromDataVolumeReply reply = r.castReply(); ImageBackupStorageRefVO vo = Q.New(ImageBackupStorageRefVO.class) .eq(ImageBackupStorageRefVO_.backupStorageUuid, bs.getUuid()) .eq(ImageBackupStorageRefVO_.imageUuid, image.getUuid()) .find(); vo.setStatus(ImageStatus.Ready); vo.setInstallPath(reply.getInstallPath()); dbf.update(vo); if (mdsum == null) { mdsum = reply.getMd5sum(); } if (reply.getFormat() != null) { format = reply.getFormat(); } } int backupStorageNum = msg.getBackupStorageUuids() == null ? 1 : msg.getBackupStorageUuids().size(); if (fail == backupStorageNum) { ErrorCode errCode = operr("failed to create data volume template from volume[uuid:%s] on all backup storage%s. See cause for one of errors", msg.getVolumeUuid(), msg.getBackupStorageUuids()).causedBy(err); trigger.fail(errCode); } else { image = dbf.reload(image); if (format != null) { image.setFormat(format); } image.setMd5Sum(mdsum); image.setStatus(ImageStatus.Ready); image = dbf.updateAndRefresh(image); trigger.next(); } } }); } }); done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { evt.setInventory(ImageInventory.valueOf(image)); bus.publish(evt); } }); error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { evt.setError(errCode); bus.publish(evt); } }); } }).start(); } private void handle(final APICreateRootVolumeTemplateFromVolumeSnapshotMsg msg) { final APICreateRootVolumeTemplateFromVolumeSnapshotEvent evt = new APICreateRootVolumeTemplateFromVolumeSnapshotEvent(msg.getId()); SimpleQuery<VolumeSnapshotVO> q = dbf.createQuery(VolumeSnapshotVO.class); q.select(VolumeSnapshotVO_.format); q.add(VolumeSnapshotVO_.uuid, Op.EQ, msg.getSnapshotUuid()); String format = q.findValue(); final ImageVO vo = new ImageVO(); if (msg.getResourceUuid() != null) { vo.setUuid(msg.getResourceUuid()); } else { vo.setUuid(Platform.getUuid()); } vo.setName(msg.getName()); vo.setSystem(msg.isSystem()); vo.setDescription(msg.getDescription()); vo.setPlatform(ImagePlatform.valueOf(msg.getPlatform())); vo.setGuestOsType(vo.getGuestOsType()); vo.setStatus(ImageStatus.Creating); vo.setState(ImageState.Enabled); vo.setFormat(format); vo.setMediaType(ImageMediaType.RootVolumeTemplate); vo.setType(ImageConstant.ZSTACK_IMAGE_TYPE); vo.setUrl(String.format("volumeSnapshot://%s", msg.getSnapshotUuid())); dbf.persist(vo); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName()); SimpleQuery<VolumeSnapshotVO> sq = dbf.createQuery(VolumeSnapshotVO.class); sq.select(VolumeSnapshotVO_.volumeUuid, VolumeSnapshotVO_.treeUuid); sq.add(VolumeSnapshotVO_.uuid, Op.EQ, msg.getSnapshotUuid()); Tuple t = sq.findTuple(); String volumeUuid = t.get(0, String.class); String treeUuid = t.get(1, String.class); List<CreateTemplateFromVolumeSnapshotMsg> cmsgs = msg.getBackupStorageUuids().stream().map(bsUuid -> { CreateTemplateFromVolumeSnapshotMsg cmsg = new CreateTemplateFromVolumeSnapshotMsg(); cmsg.setSnapshotUuid(msg.getSnapshotUuid()); cmsg.setImageUuid(vo.getUuid()); cmsg.setVolumeUuid(volumeUuid); cmsg.setTreeUuid(treeUuid); cmsg.setBackupStorageUuid(bsUuid); String resourceUuid = volumeUuid != null ? volumeUuid : treeUuid; bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeSnapshotConstant.SERVICE_ID, resourceUuid); return cmsg; }).collect(Collectors.toList()); List<Failure> failures = new ArrayList<>(); AsyncLatch latch = new AsyncLatch(cmsgs.size(), new NoErrorCompletion(msg) { @Override public void done() { if (failures.size() == cmsgs.size()) { // failed on all ErrorCodeList error = errf.stringToOperationError(String.format("failed to create template from" + " the volume snapshot[uuid:%s] on backup storage[uuids:%s]", msg.getSnapshotUuid(), msg.getBackupStorageUuids()), failures.stream().map(f -> f.error).collect(Collectors.toList())); evt.setError(error); dbf.remove(vo); } else { ImageVO imvo = dbf.reload(vo); evt.setInventory(ImageInventory.valueOf(imvo)); logger.debug(String.format("successfully created image[uuid:%s, name:%s] from volume snapshot[uuid:%s]", imvo.getUuid(), imvo.getName(), msg.getSnapshotUuid())); } if (!failures.isEmpty()) { evt.setFailuresOnBackupStorage(failures); } bus.publish(evt); } }); RunOnce once = new RunOnce(); for (CreateTemplateFromVolumeSnapshotMsg cmsg : cmsgs) { bus.send(cmsg, new CloudBusCallBack(latch) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { synchronized (failures) { Failure failure = new Failure(); failure.error = reply.getError(); failure.backupStorageUuid = cmsg.getBackupStorageUuid(); failures.add(failure); } } else { CreateTemplateFromVolumeSnapshotReply cr = reply.castReply(); ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setBackupStorageUuid(cr.getBackupStorageUuid()); ref.setInstallPath(cr.getBackupStorageInstallPath()); ref.setStatus(ImageStatus.Ready); ref.setImageUuid(vo.getUuid()); dbf.persist(ref); once.run(() -> { vo.setSize(cr.getSize()); vo.setActualSize(cr.getActualSize()); vo.setStatus(ImageStatus.Ready); dbf.update(vo); }); } latch.ack(); } }); } } private void passThrough(ImageMessage msg) { ImageVO vo = dbf.findByUuid(msg.getImageUuid(), ImageVO.class); if (vo == null && allowedMessageAfterDeletion.contains(msg.getClass())) { ImageEO eo = dbf.findByUuid(msg.getImageUuid(), ImageEO.class); vo = ObjectUtils.newAndCopy(eo, ImageVO.class); } if (vo == null) { String err = String.format("Cannot find image[uuid:%s], it may have been deleted", msg.getImageUuid()); logger.warn(err); bus.replyErrorByMessageType((Message) msg, errf.instantiateErrorCode(SysErrors.RESOURCE_NOT_FOUND, err)); return; } ImageFactory factory = getImageFacotry(ImageType.valueOf(vo.getType())); Image img = factory.getImage(vo); img.handleMessage((Message) msg); } private void handle(final APICreateRootVolumeTemplateFromRootVolumeMsg msg) { FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("create-template-from-root-volume-%s", msg.getRootVolumeUuid())); chain.then(new ShareFlow() { ImageVO imageVO; VolumeInventory rootVolume; Long imageActualSize; List<BackupStorageInventory> targetBackupStorages = new ArrayList<>(); String zoneUuid; { VolumeVO rootvo = dbf.findByUuid(msg.getRootVolumeUuid(), VolumeVO.class); rootVolume = VolumeInventory.valueOf(rootvo); SimpleQuery<PrimaryStorageVO> q = dbf.createQuery(PrimaryStorageVO.class); q.select(PrimaryStorageVO_.zoneUuid); q.add(PrimaryStorageVO_.uuid, Op.EQ, rootVolume.getPrimaryStorageUuid()); zoneUuid = q.findValue(); } @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "get-volume-actual-size"; @Override public void run(final FlowTrigger trigger, Map data) { SyncVolumeSizeMsg msg = new SyncVolumeSizeMsg(); msg.setVolumeUuid(rootVolume.getUuid()); bus.makeTargetServiceIdByResourceUuid(msg, VolumeConstant.SERVICE_ID, rootVolume.getPrimaryStorageUuid()); bus.send(msg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } SyncVolumeSizeReply sr = reply.castReply(); imageActualSize = sr.getActualSize(); trigger.next(); } }); } }); flow(new Flow() { String __name__ = "create-image-in-database"; public void run(FlowTrigger trigger, Map data) { SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class); q.add(VolumeVO_.uuid, Op.EQ, msg.getRootVolumeUuid()); final VolumeVO volvo = q.find(); String accountUuid = acntMgr.getOwnerAccountUuidOfResource(volvo.getUuid()); final ImageVO imvo = new ImageVO(); if (msg.getResourceUuid() != null) { imvo.setUuid(msg.getResourceUuid()); } else { imvo.setUuid(Platform.getUuid()); } imvo.setDescription(msg.getDescription()); imvo.setMediaType(ImageMediaType.RootVolumeTemplate); imvo.setState(ImageState.Enabled); imvo.setGuestOsType(msg.getGuestOsType()); imvo.setFormat(volvo.getFormat()); imvo.setName(msg.getName()); imvo.setSystem(msg.isSystem()); imvo.setPlatform(ImagePlatform.valueOf(msg.getPlatform())); imvo.setStatus(ImageStatus.Downloading); imvo.setType(ImageConstant.ZSTACK_IMAGE_TYPE); imvo.setUrl(String.format("volume://%s", msg.getRootVolumeUuid())); imvo.setSize(volvo.getSize()); imvo.setActualSize(imageActualSize); dbf.persist(imvo); acntMgr.createAccountResourceRef(accountUuid, imvo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, imvo.getUuid(), ImageVO.class.getSimpleName()); imageVO = imvo; trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { if (imageVO != null) { dbf.remove(imageVO); } trigger.rollback(); } }); flow(new Flow() { String __name__ = String.format("select-backup-storage"); @Override public void run(final FlowTrigger trigger, Map data) { List<ImageBackupStorageRefVO> refs = new ArrayList<>(); if (msg.getBackupStorageUuids() == null) { AllocateBackupStorageMsg abmsg = new AllocateBackupStorageMsg(); abmsg.setRequiredZoneUuid(zoneUuid); abmsg.setSize(imageActualSize); bus.makeLocalServiceId(abmsg, BackupStorageConstant.SERVICE_ID); bus.send(abmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { targetBackupStorages.add(((AllocateBackupStorageReply) reply).getInventory()); saveRefVOByBsInventorys(targetBackupStorages, imageVO.getUuid()); trigger.next(); } else { trigger.fail(reply.getError()); } } }); } else { List<AllocateBackupStorageMsg> amsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<AllocateBackupStorageMsg, String>() { @Override public AllocateBackupStorageMsg call(String arg) { AllocateBackupStorageMsg abmsg = new AllocateBackupStorageMsg(); abmsg.setSize(imageActualSize); abmsg.setBackupStorageUuid(arg); bus.makeLocalServiceId(abmsg, BackupStorageConstant.SERVICE_ID); return abmsg; } }); bus.send(amsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { List<ErrorCode> errs = new ArrayList<>(); for (MessageReply r : replies) { if (r.isSuccess()) { targetBackupStorages.add(((AllocateBackupStorageReply) r).getInventory()); } else { errs.add(r.getError()); } } if (targetBackupStorages.isEmpty()) { trigger.fail(operr("unable to allocate backup storage specified by uuids%s, list errors are: %s", msg.getBackupStorageUuids(), JSONObjectUtil.toJsonString(errs))); } else { saveRefVOByBsInventorys(targetBackupStorages, imageVO.getUuid()); trigger.next(); } } }); } } @Override public void rollback(final FlowRollback trigger, Map data) { if (targetBackupStorages.isEmpty()) { trigger.rollback(); return; } List<ReturnBackupStorageMsg> rmsgs = CollectionUtils.transformToList(targetBackupStorages, new Function<ReturnBackupStorageMsg, BackupStorageInventory>() { @Override public ReturnBackupStorageMsg call(BackupStorageInventory arg) { ReturnBackupStorageMsg rmsg = new ReturnBackupStorageMsg(); rmsg.setBackupStorageUuid(arg.getUuid()); rmsg.setSize(imageActualSize); bus.makeLocalServiceId(rmsg, BackupStorageConstant.SERVICE_ID); return rmsg; } }); bus.send(rmsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { for (MessageReply r : replies) { if (!r.isSuccess()) { BackupStorageInventory bs = targetBackupStorages.get(replies.indexOf(r)); logger.warn(String.format("failed to return capacity[%s] to backup storage[uuid:%s], because %s", imageActualSize, bs.getUuid(), r.getError())); } } trigger.rollback(); } }); } }); flow(new NoRollbackFlow() { String __name__ = String.format("start-creating-template"); @Override public void run(final FlowTrigger trigger, Map data) { List<CreateTemplateFromVmRootVolumeMsg> cmsgs = CollectionUtils.transformToList(targetBackupStorages, new Function<CreateTemplateFromVmRootVolumeMsg, BackupStorageInventory>() { @Override public CreateTemplateFromVmRootVolumeMsg call(BackupStorageInventory arg) { CreateTemplateFromVmRootVolumeMsg cmsg = new CreateTemplateFromVmRootVolumeMsg(); cmsg.setRootVolumeInventory(rootVolume); cmsg.setBackupStorageUuid(arg.getUuid()); cmsg.setImageInventory(ImageInventory.valueOf(imageVO)); bus.makeTargetServiceIdByResourceUuid(cmsg, VmInstanceConstant.SERVICE_ID, rootVolume.getVmInstanceUuid()); return cmsg; } }); bus.send(cmsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { boolean success = false; ErrorCode err = null; for (MessageReply r : replies) { BackupStorageInventory bs = targetBackupStorages.get(replies.indexOf(r)); ImageBackupStorageRefVO ref = Q.New(ImageBackupStorageRefVO.class) .eq(ImageBackupStorageRefVO_.backupStorageUuid, bs.getUuid()) .eq(ImageBackupStorageRefVO_.imageUuid, imageVO.getUuid()) .find(); if (dbf.reload(imageVO) == null) { SQL.New("delete from ImageBackupStorageRefVO where imageUuid = :uuid") .param("uuid", imageVO.getUuid()) .execute(); trigger.fail(operr("image [uuid:%s] has been deleted", imageVO.getUuid())); return; } if (!r.isSuccess()) { logger.warn(String.format("failed to create image from root volume[uuid:%s] on backup storage[uuid:%s], because %s", msg.getRootVolumeUuid(), bs.getUuid(), r.getError())); err = r.getError(); dbf.remove(ref); continue; } CreateTemplateFromVmRootVolumeReply reply = (CreateTemplateFromVmRootVolumeReply) r; ref.setStatus(ImageStatus.Ready); ref.setInstallPath(reply.getInstallPath()); dbf.update(ref); imageVO.setStatus(ImageStatus.Ready); if (reply.getFormat() != null) { imageVO.setFormat(reply.getFormat()); } imageVO = dbf.updateAndRefresh(imageVO); success = true; logger.debug(String.format("successfully created image[uuid:%s] from root volume[uuid:%s] on backup storage[uuid:%s]", imageVO.getUuid(), msg.getRootVolumeUuid(), bs.getUuid())); } if (success) { trigger.next(); } else { trigger.fail(operr("failed to create image from root volume[uuid:%s] on all backup storage, see cause for one of errors", msg.getRootVolumeUuid()).causedBy(err)); } } }); } }); flow(new Flow() { String __name__ = "copy-system-tag-to-image"; public void run(FlowTrigger trigger, Map data) { // find the rootimage and create some systemtag if it has SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class); q.add(VolumeVO_.uuid, SimpleQuery.Op.EQ, msg.getRootVolumeUuid()); q.select(VolumeVO_.vmInstanceUuid); String vmInstanceUuid = q.findValue(); if (tagMgr.hasSystemTag(vmInstanceUuid, ImageSystemTags.IMAGE_INJECT_QEMUGA.getTagFormat())) { tagMgr.createNonInherentSystemTag(imageVO.getUuid(), ImageSystemTags.IMAGE_INJECT_QEMUGA.getTagFormat(), ImageVO.class.getSimpleName()); } trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { trigger.rollback(); } }); flow(new NoRollbackFlow() { String __name__ = String.format("sync-image-size"); @Override public void run(final FlowTrigger trigger, Map data) { new While<>(targetBackupStorages).all((arg, completion) -> { SyncImageSizeMsg smsg = new SyncImageSizeMsg(); smsg.setBackupStorageUuid(arg.getUuid()); smsg.setImageUuid(imageVO.getUuid()); bus.makeTargetServiceIdByResourceUuid(smsg, ImageConstant.SERVICE_ID, imageVO.getUuid()); bus.send(smsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { completion.done(); } }); }).run(new NoErrorCompletion(trigger) { @Override public void done() { trigger.next(); } }); } }); done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { APICreateRootVolumeTemplateFromRootVolumeEvent evt = new APICreateRootVolumeTemplateFromRootVolumeEvent(msg.getId()); imageVO = dbf.reload(imageVO); ImageInventory iinv = ImageInventory.valueOf(imageVO); evt.setInventory(iinv); logger.warn(String.format("successfully create template[uuid:%s] from root volume[uuid:%s]", iinv.getUuid(), msg.getRootVolumeUuid())); bus.publish(evt); } }); error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { APICreateRootVolumeTemplateFromRootVolumeEvent evt = new APICreateRootVolumeTemplateFromRootVolumeEvent(msg.getId()); evt.setError(errCode); logger.warn(String.format("failed to create template from root volume[uuid:%s], because %s", msg.getRootVolumeUuid(), errCode)); bus.publish(evt); } }); } }).start(); } private void handle(APIGetImageMsg msg) { SearchQuery<ImageInventory> sq = new SearchQuery(ImageInventory.class); sq.addAccountAsAnd(msg); sq.add("uuid", SearchOp.AND_EQ, msg.getUuid()); List<ImageInventory> invs = sq.list(); APIGetImageReply reply = new APIGetImageReply(); if (!invs.isEmpty()) { reply.setInventory(JSONObjectUtil.toJsonString(invs.get(0))); } bus.reply(msg, reply); } private void handle(APISearchImageMsg msg) { SearchQuery<ImageInventory> sq = SearchQuery.create(msg, ImageInventory.class); sq.addAccountAsAnd(msg); String content = sq.listAsString(); APISearchImageReply reply = new APISearchImageReply(); reply.setContent(content); bus.reply(msg, reply); } private void handle(APIListImageMsg msg) { List<ImageVO> vos = dbf.listAll(ImageVO.class); List<ImageInventory> invs = ImageInventory.valueOf(vos); APIListImageReply reply = new APIListImageReply(); reply.setInventories(invs); bus.reply(msg, reply); } @Deferred private void handle(final APIAddImageMsg msg) { String imageType = msg.getType(); imageType = imageType == null ? DefaultImageFactory.type.toString() : imageType; final APIAddImageEvent evt = new APIAddImageEvent(msg.getId()); ImageVO vo = new ImageVO(); if (msg.getResourceUuid() != null) { vo.setUuid(msg.getResourceUuid()); } else { vo.setUuid(Platform.getUuid()); } vo.setName(msg.getName()); vo.setDescription(msg.getDescription()); if (msg.getFormat().equals(ImageConstant.ISO_FORMAT_STRING)) { vo.setMediaType(ImageMediaType.ISO); } else { vo.setMediaType(ImageMediaType.valueOf(msg.getMediaType())); } vo.setType(imageType); vo.setSystem(msg.isSystem()); vo.setGuestOsType(msg.getGuestOsType()); vo.setFormat(msg.getFormat()); vo.setStatus(ImageStatus.Downloading); vo.setState(ImageState.Enabled); vo.setUrl(msg.getUrl()); vo.setDescription(msg.getDescription()); vo.setPlatform(ImagePlatform.valueOf(msg.getPlatform())); ImageFactory factory = getImageFacotry(ImageType.valueOf(imageType)); final ImageVO ivo = new SQLBatchWithReturn<ImageVO>() { @Override protected ImageVO scripts() { final ImageVO ivo = factory.createImage(vo, msg); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName()); return ivo; } }.execute(); List<ImageBackupStorageRefVO> refs = new ArrayList<>(); for (String uuid : msg.getBackupStorageUuids()) { ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setInstallPath(""); ref.setBackupStorageUuid(uuid); ref.setStatus(ImageStatus.Downloading); ref.setImageUuid(ivo.getUuid()); refs.add(ref); } dbf.persistCollection(refs); Defer.guard(() -> dbf.remove(ivo)); final ImageInventory inv = ImageInventory.valueOf(ivo); for (AddImageExtensionPoint ext : pluginRgty.getExtensionList(AddImageExtensionPoint.class)) { ext.preAddImage(inv); } final List<DownloadImageMsg> dmsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<DownloadImageMsg, String>() { @Override public DownloadImageMsg call(String arg) { DownloadImageMsg dmsg = new DownloadImageMsg(inv); dmsg.setBackupStorageUuid(arg); dmsg.setFormat(msg.getFormat()); dmsg.setSystemTags(msg.getSystemTags()); bus.makeTargetServiceIdByResourceUuid(dmsg, BackupStorageConstant.SERVICE_ID, arg); return dmsg; } }); CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), ext -> ext.beforeAddImage(inv)); new LoopAsyncBatch<DownloadImageMsg>(msg) { AtomicBoolean success = new AtomicBoolean(false); @Override protected Collection<DownloadImageMsg> collect() { return dmsgs; } @Override protected AsyncBatchRunner forEach(DownloadImageMsg dmsg) { return new AsyncBatchRunner() { @Override public void run(NoErrorCompletion completion) { ImageBackupStorageRefVO ref = Q.New(ImageBackupStorageRefVO.class) .eq(ImageBackupStorageRefVO_.imageUuid, ivo.getUuid()) .eq(ImageBackupStorageRefVO_.backupStorageUuid, dmsg.getBackupStorageUuid()) .find(); bus.send(dmsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { errors.add(reply.getError()); dbf.remove(ref); } else { DownloadImageReply re = reply.castReply(); if (msg.getUrl().startsWith("upload: trackUpload(ivo.getName(), ivo.getUuid(), ref.getBackupStorageUuid()); } else { ref.setStatus(ImageStatus.Ready); } ref.setInstallPath(re.getInstallPath()); if (dbf.reload(ref) == null) { logger.debug(String.format("image[uuid: %s] has been deleted", ref.getImageUuid())); completion.done(); return; } dbf.update(ref); if (success.compareAndSet(false, true)) { // In case 'Platform' etc. is changed. ImageVO vo = dbf.reload(ivo); vo.setMd5Sum(re.getMd5sum()); vo.setSize(re.getSize()); vo.setActualSize(re.getActualSize()); vo.setStatus(ref.getStatus()); dbf.update(vo); } logger.debug(String.format("successfully downloaded image[uuid:%s, name:%s] to backup storage[uuid:%s]", inv.getUuid(), inv.getName(), dmsg.getBackupStorageUuid())); } completion.done(); } }); } }; } @Override protected void done() { // check if the database still has the record of the image // if there is no record, that means user delete the image during the downloading, // then we need to cleanup ImageVO vo = dbf.reload(ivo); if (vo == null) { evt.setError(operr("image [uuid:%s] has been deleted", ivo.getUuid())); SQL.New("delete from ImageBackupStorageRefVO where imageUuid = :uuid") .param("uuid", ivo.getUuid()) .execute(); bus.publish(evt); return; } if (success.get()) { final ImageInventory einv = ImageInventory.valueOf(vo); CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() { @Override public void run(AddImageExtensionPoint ext) { ext.afterAddImage(einv); } }); evt.setInventory(einv); } else { final ErrorCode err = errf.instantiateErrorCode(SysErrors.CREATE_RESOURCE_ERROR, String.format("Failed to download image[name:%s] on all backup storage%s.", inv.getName(), msg.getBackupStorageUuids()), errors); CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() { @Override public void run(AddImageExtensionPoint ext) { ext.failedToAddImage(inv, err); } }); dbf.remove(ivo); evt.setError(err); } bus.publish(evt); } }.start(); } @Override public String getId() { return bus.makeLocalServiceId(ImageConstant.SERVICE_ID); } private void populateExtensions() { for (ImageFactory f : pluginRgty.getExtensionList(ImageFactory.class)) { ImageFactory old = imageFactories.get(f.getType().toString()); if (old != null) { throw new CloudRuntimeException(String.format("duplicate ImageFactory[%s, %s] for type[%s]", f.getClass().getName(), old.getClass().getName(), f.getType())); } imageFactories.put(f.getType().toString(), f); } } @Override public boolean start() { populateExtensions(); installGlobalConfigUpdater(); return true; } private void installGlobalConfigUpdater() { ImageGlobalConfig.DELETION_POLICY.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startExpungeTask(); } }); ImageGlobalConfig.EXPUNGE_INTERVAL.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startExpungeTask(); } }); ImageGlobalConfig.EXPUNGE_PERIOD.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startExpungeTask(); } }); } private void startExpungeTask() { if (expungeTask != null) { expungeTask.cancel(true); } expungeTask = thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask() { private List<Tuple> getDeletedImageManagedByUs() { int qun = 1000; SimpleQuery q = dbf.createQuery(ImageBackupStorageRefVO.class); q.add(ImageBackupStorageRefVO_.status, Op.EQ, ImageStatus.Deleted); long amount = q.count(); int times = (int) (amount / qun) + (amount % qun != 0 ? 1 : 0); int start = 0; List<Tuple> ret = new ArrayList<Tuple>(); for (int i = 0; i < times; i++) { q = dbf.createQuery(ImageBackupStorageRefVO.class); q.select(ImageBackupStorageRefVO_.imageUuid, ImageBackupStorageRefVO_.lastOpDate, ImageBackupStorageRefVO_.backupStorageUuid); q.add(ImageBackupStorageRefVO_.status, Op.EQ, ImageStatus.Deleted); q.setLimit(qun); q.setStart(start); List<Tuple> ts = q.listTuple(); start += qun; for (Tuple t : ts) { String imageUuid = t.get(0, String.class); if (!destMaker.isManagedByUs(imageUuid)) { continue; } ret.add(t); } } return ret; } @Override public boolean run() { final List<Tuple> images = getDeletedImageManagedByUs(); if (images.isEmpty()) { logger.debug("[Image Expunge Task]: no images to expunge"); return false; } for (Tuple t : images) { String imageUuid = t.get(0, String.class); Timestamp date = t.get(1, Timestamp.class); String bsUuid = t.get(2, String.class); final Timestamp current = dbf.getCurrentSqlTime(); if (current.getTime() >= date.getTime() + TimeUnit.SECONDS.toMillis(ImageGlobalConfig.EXPUNGE_PERIOD.value(Long.class))) { ImageDeletionPolicy deletionPolicy = deletionPolicyMgr.getDeletionPolicy(imageUuid); if (ImageDeletionPolicy.Never == deletionPolicy) { logger.debug(String.format("the deletion policy[Never] is set for the image[uuid:%s] on the backup storage[uuid:%s]," + "don't expunge it", images, bsUuid)); continue; } ExpungeImageMsg msg = new ExpungeImageMsg(); msg.setImageUuid(imageUuid); msg.setBackupStorageUuid(bsUuid); bus.makeTargetServiceIdByResourceUuid(msg, ImageConstant.SERVICE_ID, imageUuid); bus.send(msg, new CloudBusCallBack(null) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { N.New(ImageVO.class, imageUuid).warn_("failed to expunge the image[uuid:%s] on the backup storage[uuid:%s], will try it later. %s", imageUuid, bsUuid, reply.getError()); } } }); } } return false; } @Override public TimeUnit getTimeUnit() { return TimeUnit.SECONDS; } @Override public long getInterval() { return ImageGlobalConfig.EXPUNGE_INTERVAL.value(Long.class); } @Override public String getName() { return "expunge-image"; } }); } @Override public boolean stop() { return true; } private ImageFactory getImageFacotry(ImageType type) { ImageFactory factory = imageFactories.get(type.toString()); if (factory == null) { throw new CloudRuntimeException(String.format("Unable to find ImageFactory with type[%s]", type)); } return factory; } @Override public void managementNodeReady() { startExpungeTask(); } @Override public List<Quota> reportQuota() { Quota.QuotaOperator checker = new Quota.QuotaOperator() { @Override public void checkQuota(APIMessage msg, Map<String, Quota.QuotaPair> pairs) { if (!new QuotaUtil().isAdminAccount(msg.getSession().getAccountUuid())) { if (msg instanceof APIAddImageMsg) { check((APIAddImageMsg) msg, pairs); } else if (msg instanceof APIRecoverImageMsg) { check((APIRecoverImageMsg) msg, pairs); } else if (msg instanceof APIChangeResourceOwnerMsg) { check((APIChangeResourceOwnerMsg) msg, pairs); } } else { if (msg instanceof APIChangeResourceOwnerMsg) { check((APIChangeResourceOwnerMsg) msg, pairs); } } } @Override public void checkQuota(NeedQuotaCheckMessage msg, Map<String, Quota.QuotaPair> pairs) { } @Override public List<Quota.QuotaUsage> getQuotaUsageByAccount(String accountUuid) { List<Quota.QuotaUsage> usages = new ArrayList<>(); ImageQuotaUtil.ImageQuota imageQuota = new ImageQuotaUtil().getUsed(accountUuid); Quota.QuotaUsage usage = new Quota.QuotaUsage(); usage.setName(ImageConstant.QUOTA_IMAGE_NUM); usage.setUsed(imageQuota.imageNum); usages.add(usage); usage = new Quota.QuotaUsage(); usage.setName(ImageConstant.QUOTA_IMAGE_SIZE); usage.setUsed(imageQuota.imageSize); usages.add(usage); return usages; } @Transactional(readOnly = true) private void check(APIChangeResourceOwnerMsg msg, Map<String, Quota.QuotaPair> pairs) { String currentAccountUuid = msg.getSession().getAccountUuid(); String resourceTargetOwnerAccountUuid = msg.getAccountUuid(); if (new QuotaUtil().isAdminAccount(resourceTargetOwnerAccountUuid)) { return; } SimpleQuery<AccountResourceRefVO> q = dbf.createQuery(AccountResourceRefVO.class); q.add(AccountResourceRefVO_.resourceUuid, Op.EQ, msg.getResourceUuid()); AccountResourceRefVO accResRefVO = q.find(); if (accResRefVO.getResourceType().equals(ImageVO.class.getSimpleName())) { long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue(); long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue(); long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid); long imageSizeUsed = new ImageQuotaUtil().getUsedImageSize(resourceTargetOwnerAccountUuid); ImageVO image = dbf.getEntityManager().find(ImageVO.class, msg.getResourceUuid()); long imageNumAsked = 1; long imageSizeAsked = image.getSize(); QuotaUtil.QuotaCompareInfo quotaCompareInfo; { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM; quotaCompareInfo.quotaValue = imageNumQuota; quotaCompareInfo.currentUsed = imageNumUsed; quotaCompareInfo.request = imageNumAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_SIZE; quotaCompareInfo.quotaValue = imageSizeQuota; quotaCompareInfo.currentUsed = imageSizeUsed; quotaCompareInfo.request = imageSizeAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } } } @Transactional(readOnly = true) private void check(APIRecoverImageMsg msg, Map<String, Quota.QuotaPair> pairs) { String currentAccountUuid = msg.getSession().getAccountUuid(); String resourceTargetOwnerAccountUuid = new QuotaUtil().getResourceOwnerAccountUuid(msg.getImageUuid()); long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue(); long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue(); long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid); long imageSizeUsed = new ImageQuotaUtil().getUsedImageSize(resourceTargetOwnerAccountUuid); ImageVO image = dbf.getEntityManager().find(ImageVO.class, msg.getImageUuid()); long imageNumAsked = 1; long imageSizeAsked = image.getSize(); QuotaUtil.QuotaCompareInfo quotaCompareInfo; { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM; quotaCompareInfo.quotaValue = imageNumQuota; quotaCompareInfo.currentUsed = imageNumUsed; quotaCompareInfo.request = imageNumAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_SIZE; quotaCompareInfo.quotaValue = imageSizeQuota; quotaCompareInfo.currentUsed = imageSizeUsed; quotaCompareInfo.request = imageSizeAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } } @Transactional(readOnly = true) private void check(APIAddImageMsg msg, Map<String, Quota.QuotaPair> pairs) { String currentAccountUuid = msg.getSession().getAccountUuid(); String resourceTargetOwnerAccountUuid = msg.getSession().getAccountUuid(); long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue(); long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid); long imageNumAsked = 1; QuotaUtil.QuotaCompareInfo quotaCompareInfo; { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM; quotaCompareInfo.quotaValue = imageNumQuota; quotaCompareInfo.currentUsed = imageNumUsed; quotaCompareInfo.request = imageNumAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } new ImageQuotaUtil().checkImageSizeQuotaUseHttpHead(msg, pairs); } }; Quota quota = new Quota(); quota.setOperator(checker); quota.addMessageNeedValidation(APIAddImageMsg.class); quota.addMessageNeedValidation(APIRecoverImageMsg.class); quota.addMessageNeedValidation(APIChangeResourceOwnerMsg.class); Quota.QuotaPair p = new Quota.QuotaPair(); p.setName(ImageConstant.QUOTA_IMAGE_NUM); p.setValue(QuotaConstant.QUOTA_IMAGE_NUM); quota.addPair(p); p = new Quota.QuotaPair(); p.setName(ImageConstant.QUOTA_IMAGE_SIZE); p.setValue(QuotaConstant.QUOTA_IMAGE_SIZE); quota.addPair(p); return list(quota); } @Override @Transactional(readOnly = true) public void resourceOwnerPreChange(AccountResourceRefInventory ref, String newOwnerUuid) { } private void saveRefVOByBsInventorys(List<BackupStorageInventory> inventorys, String imageUuid) { List<ImageBackupStorageRefVO> refs = new ArrayList<>(); for (BackupStorageInventory backupStorageInventory : inventorys) { ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setBackupStorageUuid(backupStorageInventory.getUuid()); ref.setStatus(ImageStatus.Creating); ref.setImageUuid(imageUuid); ref.setInstallPath(""); refs.add(ref); } dbf.persistCollection(refs); } private void trackUpload(String name, String imageUuid, String bsUuid) { final int maxNumOfFailure = 3; final int maxIdleSecond = 180; thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask() { private long numError = 0; private int numTicks = 0; private void markCompletion(final GetImageDownloadProgressReply dr) { new SQLBatch() { @Override protected void scripts() { sql(ImageVO.class) .eq(ImageVO_.uuid, imageUuid) .set(ImageVO_.status, ImageStatus.Ready) .set(ImageVO_.size, dr.getSize()) .set(ImageVO_.actualSize, dr.getActualSize()) .update(); sql(ImageBackupStorageRefVO.class) .eq(ImageBackupStorageRefVO_.backupStorageUuid, bsUuid) .eq(ImageBackupStorageRefVO_.imageUuid, imageUuid) .set(ImageBackupStorageRefVO_.status, ImageStatus.Ready) .set(ImageBackupStorageRefVO_.installPath, dr.getInstallPath()) .update(); } }.execute(); N.New(ImageVO.class, imageUuid).info_("added image [name: %s, uuid: %s]", name, imageUuid); } private void markFailure() { N.New(ImageVO.class, imageUuid).error_("upload image [name: %s, uuid: %s] failed", name, imageUuid); ImageDeletionMsg msg = new ImageDeletionMsg(); msg.setImageUuid(imageUuid); msg.setBackupStorageUuids(Collections.singletonList(bsUuid)); msg.setDeletionPolicy(ImageDeletionPolicy.Direct.toString()); msg.setForceDelete(true); bus.makeTargetServiceIdByResourceUuid(msg, ImageConstant.SERVICE_ID, imageUuid); bus.send(msg); } @Override public boolean run() { final ImageVO ivo = dbf.findByUuid(imageUuid, ImageVO.class); if (ivo == null) { // If image VO not existed, stop tracking. return true; } numTicks += 1; if (ivo.getActualSize() == 0 && numTicks * getInterval() >= maxIdleSecond) { markFailure(); return true; } GetImageDownloadProgressMsg dmsg = new GetImageDownloadProgressMsg(); dmsg.setBackupStorageUuid(bsUuid); dmsg.setImageUuid(imageUuid); bus.makeTargetServiceIdByResourceUuid(dmsg, BackupStorageConstant.SERVICE_ID, bsUuid); MessageReply reply = bus.call(dmsg); if (reply.isSuccess()) { // reset the error counter numError = 0; GetImageDownloadProgressReply dr = reply.castReply(); if (dr.isCompleted()) { markCompletion(dr); return true; } ThreadContext.put(THREAD_CONTEXT_API, imageUuid); ThreadContext.put(THREAD_CONTEXT_TASK_NAME, "uploading image"); long progress = dr.getActualSize() == 0 ? 0 : dr.getDownloaded() * 100 / dr.getActualSize(); reportProgress(String.valueOf(progress)); if (ivo.getActualSize() == 0 && dr.getActualSize() != 0) { ivo.setActualSize(dr.getActualSize()); dbf.updateAndRefresh(ivo); } return false; } numError++; if (numError <= maxNumOfFailure) { return false; } markFailure(); return true; } @Override public TimeUnit getTimeUnit() { return TimeUnit.SECONDS; } @Override public long getInterval() { return 3; } @Override public String getName() { return String.format("tracking upload image [name: %s, uuid: %s]", name, imageUuid); } }); } }
package dataprocessing; import dics.elements.dtd.Dictionary; import dics.elements.dtd.Pardef; import dictools.utils.DictionaryReader; import es.ua.dlsi.monolingual.Candidate; import es.ua.dlsi.monolingual.Paradigm; import es.ua.dlsi.suffixtree.Dix2suffixtree; import es.ua.dlsi.suffixtree.SuffixTree; import es.ua.dlsi.utils.CmdLineParser; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.json.simple.JSONArray; import org.json.simple.JSONObject; /** * * @author mespla */ public class DataProcessing { /** * Main method that can be called to print the suffix tree * @param args the command line arguments */ public static void main(String[] args) { CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option odicpath = parser.addStringOption('d',"dictionary"); CmdLineParser.Option ovalidpos = parser.addStringOption('v',"valid-pos"); CmdLineParser.Option omultiword = parser.addBooleanOption('m',"mulriword"); CmdLineParser.Option otrainingpercent = parser.addDoubleOption('p',"trainingpercent"); CmdLineParser.Option otrainoutput = parser.addStringOption("training-output"); CmdLineParser.Option otestoutput = parser.addStringOption("test-output"); CmdLineParser.Option ocorpus = parser.addStringOption('c',"corpus"); try{ parser.parse(args); } catch(CmdLineParser.IllegalOptionValueException e){ System.err.println(e); System.exit(-1); } catch(CmdLineParser.UnknownOptionException e){ System.err.println(e); System.exit(-1); } String dicpath=(String)parser.getOptionValue(odicpath,null); String trainoutputpath=(String)parser.getOptionValue(otrainoutput,null); String testoutputpath=(String)parser.getOptionValue(otestoutput,null); String corpusdir=(String)parser.getOptionValue(ocorpus,null); Boolean multiword=(Boolean)parser.getOptionValue(omultiword,false); Set<String> validpos=new HashSet<>(); validpos.addAll(Arrays.asList(((String)parser.getOptionValue(ovalidpos,null)).split(","))); Double trainpercent=(Double)parser.getOptionValue(otrainingpercent,1.0); if(validpos==null){ System.err.println("The list of valid POS must be provided (use option -v)"); } PrintWriter trainoutput; if(trainoutputpath!=null){ try { trainoutput = new PrintWriter(trainoutputpath); } catch (FileNotFoundException ex) { System.err.println("Warning: output file could not be opened; exit will be printed on screen;"); trainoutput = new PrintWriter(System.out); } } else{ System.err.println("Warning: no output file defined; exit will be printed on screen;"); trainoutput = new PrintWriter(System.out); } PrintWriter testoutput; if(testoutputpath!=null){ try { testoutput = new PrintWriter(testoutputpath); } catch (FileNotFoundException ex) { System.err.println("Warning: output file could not be opened; exit will be printed on screen;"); testoutput = new PrintWriter(System.out); } } else{ System.err.println("Warning: no output file defined; exit will be printed on screen;"); testoutput = new PrintWriter(System.out); } DictionaryReader dicReader = new DictionaryReader(dicpath); Dictionary dic = dicReader.readDic(); Set<String> words_in_corpus=new HashSet(); try{ String line; // open input stream test.txt for reading purpose. BufferedReader br = new BufferedReader(new FileReader(corpusdir)); while ((line = br.readLine()) != null) { words_in_corpus.add(line.trim().split(" ")[1]); } }catch(Exception e){ e.printStackTrace(System.err); System.err.println("Error in the format of the corpus."); System.exit(-1); } //Building the suffix tree SuffixTree tree; tree=new Dix2suffixtree(dic).getSuffixTree(); Set<Paradigm> small_pars=new HashSet(); List<Paradigm> general_pars=new LinkedList(); int min_size_of_paradigm; if(trainpercent==1.0) min_size_of_paradigm=1; else min_size_of_paradigm=(int)Math.ceil(1/(1-trainpercent)); //Checking the paradigms that can be used for(Pardef p: dic.pardefs.elements){ Paradigm paradigm=new Paradigm(p, dic); if(paradigm.getSuffixes().size()>0){ if(paradigm.getSuffixes().iterator().next().getLexInfo().size()>0){ String category=paradigm.getSuffixes().iterator().next().getLexInfo().get(0); if(validpos.contains(category)){ if(paradigm.GetNumberOfEntries(dic,false) < min_size_of_paradigm) small_pars.add(paradigm); else general_pars.add(paradigm); } } } } //Running through the paradigms to identify the entries to be used to build the data sets int n_training_paradigms_paradigm; if(trainpercent==1.0) n_training_paradigms_paradigm=general_pars.size(); else n_training_paradigms_paradigm=(int)Math.ceil(general_pars.size()*trainpercent); System.err.print("Training portion: "); System.err.print(trainpercent*100); System.err.println("%"); System.err.print("Number of paradigms that can be used either for trianing or test: "); System.err.println(general_pars.size()); System.err.print("Number of training paradigms: "); System.err.println(n_training_paradigms_paradigm); System.err.println("PRINTING TRAINING CORPUS"); long seed = System.nanoTime(); Collections.shuffle(general_pars, new Random(seed)); List<Paradigm> trainingpars=general_pars.subList(0, n_training_paradigms_paradigm); trainingpars.addAll(small_pars); BuildDataset(dic, multiword, trainingpars, tree, words_in_corpus, trainoutput); trainoutput.close(); System.err.println("PRINTING TEST CORPUS"); List<Paradigm> testpars=general_pars.subList(n_training_paradigms_paradigm+1,general_pars.size()); BuildDataset(dic, multiword, testpars, tree, words_in_corpus, testoutput); testoutput.close(); } /** * Method that builds a dataset in JSON using a list of paradigms that * should be used in this dataset. * @param dic Dictionary to be processed * @param multiword Flag to decide if multiword entries should be taken into account * @param pars List of paradigms * @param tree Suffix tree used to detect the possible candidates for a given surface words * @param words_in_corpus Words that appear in the corpus * @param output PrintWriter where the output should be written */ public static void BuildDataset(Dictionary dic, boolean multiword, List<Paradigm> pars, SuffixTree tree, Set<String> words_in_corpus, PrintWriter output){ //Getting all the entries associated to every paradigm List<Candidate> candidates=new LinkedList(); for(Paradigm p: pars){ candidates.addAll(p.GetRelatedEntries(dic, multiword)); } //Getting all the surface forms for every entry associated to every paradigm for(Candidate c: candidates){ Set<String> surfaceforms=c.GetSurfaceForms(dic); //Building the collection of candidates for every surface form for(String sform: surfaceforms){ if(words_in_corpus.contains(sform)){ JSONObject json=new JSONObject(); JSONArray candidatelist=new JSONArray(); Set<Candidate> guessedcandidates=tree.SegmentWord(sform); for(Candidate candidate: guessedcandidates){ candidatelist.add(candidate.toJSON(dic)); } json.put("candidates",candidatelist); json.put("correct_candidate",c.toJSON(dic)); json.put("surfaceword",sform); output.println(json.toJSONString()); } } } } }
package HelperClasses; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class TextField extends JPanel { public static final int EQUATION = 300, COMPOUND = 68; private int index; private JLabel label; private String current; private Button sup, sub; public TextField(int length) { this.setLayout(new GridLayout()); this.setPreferredSize(new Dimension(length, 28)); current = "<html></html>"; index = 6; label = new JLabel(current); JTextField temp = new JTextField(); label.setBorder(temp.getBorder()); label.setOpaque(true); label.setBackground(Color.WHITE); /*JPanel panel = new JPanel(new GridLayout()); panel.setPreferredSize(new Dimension(length, 26)); panel.add(label); add(panel);*/ add(label); sup = new Button(this, "<sup>", "</sup>"); sub = new Button(this, "<sub>", "</sub>"); sup.addOther(sub); sub.addOther(sup); this.addKeyListener(new Key()); setFocusable(true); addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent arg0) { grabFocus(); } public void mouseEntered(MouseEvent arg0){} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0){} public void mouseReleased(MouseEvent arg0) {} }); addFocusListener(new FocusListener() { public void focusGained(FocusEvent arg0) { int newIndex = current.length() - 7; current = current.substring(0, newIndex) + '|' + current.substring(newIndex); index = newIndex; label.setText(current); } public void focusLost(FocusEvent arg0) { //last = index; current = current.substring(0, index) + current.substring(index + 1); //index = -1; label.setText(current); } }); } public TextField() { this(EQUATION); } public String getText() { String noLine = current; if(hasFocus()) noLine = current.substring(0, index) + current.substring(index + 1); return noLine.substring(6, noLine.length() - 7); } public void setText(String update) { current = "<html>" + update + "|</html>"; index = 6 + update.length(); label.setText(current); } private void enter(String enter) { if(index != -1) current = current.substring(0, index) + enter + current.substring(index); //else current = current.substring(0, last) + enter + current.substring(last); index += enter.length(); label.setText(current); if(label.getPreferredSize().getWidth() > getWidth()) { this.setPreferredSize(new Dimension(getWidth() + 50, 28)); } } private class Key implements KeyListener { public void keyPressed(KeyEvent arg0) { if(arg0.getKeyCode() == 8) //backspace { int goBack = checkBack(); if(goBack == 0) return; if(goBack == 5) { int end = current.indexOf("</", index); if(end != -1 && end != current.length() - 7) current = current.substring(0, end) + current.substring(end + 6); else if(current.substring(index - goBack, index).equals("<sub>")) sub.turnOff(); else sup.turnOff(); } else if(goBack != 1 && !current.substring(index - goBack, index).equals("\u2192")) { int start = current.lastIndexOf(">", index - goBack); current = current.substring(0, start - 4) + current.substring(start + 1); index -= 5; } current = current.substring(0, index - goBack) + current.substring(index); index = index - goBack; label.setText(current); } else if(arg0.getKeyCode() == 127) //delete { int goAhead = checkAhead(); if(goAhead == 0) return; if(goAhead == 5) { int end = current.indexOf("</", index); if(end != -1 && end != current.length() - 7) current = current.substring(0, end) + current.substring(end + 6); else if(current.substring(index + 1, index + 1 + goAhead).equals("<sub>")) sub.turnOff(); else sup.turnOff(); } else if(!current.substring(index + 1, index + 1 + goAhead).equals("\u2192")) { int end = current.lastIndexOf("<s", index); if(end != -1) { current = current.substring(0, end) + current.substring(end + 5); index -= 5; } } current = current.substring(0, index + 1) + current.substring(index + 1 + goAhead); label.setText(current); } else if(arg0.getKeyCode() == 39) //right arrow { int newIndex = index + checkAhead(); if(newIndex != index) { current = current.substring(0, index) + current.substring(index + 1, newIndex + 1) + '|' + current.substring(newIndex + 1); index = newIndex; label.setText(current); } else if(sub.isOn()) sub.toggle(); else if(sup.isOn()) sup.toggle(); } else if(arg0.getKeyCode() == 37) //left arrow { int newIndex = index - checkBack(); if(newIndex != index) { current = current.substring(0, newIndex ) + '|' + current.substring(newIndex, index) + current.substring(index + 1); index = newIndex; label.setText(current); } } else if(arg0.getKeyCode() == 36) //home { current = "<html>|" + current.substring(6, index) + current.substring(index + 1); index = 6; label.setText(current); } else if(arg0.getKeyCode() == 35) //end { current = current.substring(0, index) + current.substring(index + 1, current.length() - 7) + "|</html>"; index = current.length() - 8; label.setText(current); } } public void keyTyped(KeyEvent arg0) { char ch = arg0.getKeyChar(); if(ch != (char) 8 && ch != (char) 127 && ch != (char) 27 && ch != (char) 10) //backspace, delete, escape, and enter call this but shouldn't { if(ch == '^' && !sub.isOn()) sup.toggle(); else if(ch == '_' && !sup.isOn()) sub.toggle(); else if(ch == '>' && current.charAt(index - 1) == '-') { current = current.substring(0, index - 1) + current.substring(index); index enter("\u2192"); } else if(ch != '^' && ch != '_') enter(ch + ""); } } public void keyReleased(KeyEvent arg0){} private int checkAhead() { if(index == current.length() - 8) return 0; if(current.substring(index + 1, index + 7).equals("\u2192")) return 6; if(current.substring(index + 1, index + 6).equals("<sup>")) return 5; if(current.substring(index + 1, index + 6).equals("<sub>")) return 5; if(current.substring(index + 1, index + 7).equals("</sup>")) return 6; if(current.substring(index + 1, index + 7).equals("</sub>")) return 6; return 1; } private int checkBack() { if(index == 6) return 0; if(current.substring(index - 6, index).equals("\u2192")) return 6; if(current.substring(index - 5, index).equals("<sup>")) return 5; if(current.substring(index - 5, index).equals("<sub>")) return 5; if(current.substring(index - 6, index).equals("</sup>")) return 6; if(current.substring(index - 6, index).equals("</sub>")) return 6; return 1; } } private class Button { private String add1, add2; private boolean on; private TextField field; private Button other; public Button(TextField field, String add1, String add2) { this.add1 = add1; this.add2 = add2; on = false; this.field = field; } public void addOther(Button other) { this.other = other; } public void toggle() { if(!other.isOn()) { if(!on) field.enter(add1); else if(current.substring(index - 5, index).equals(add1)) { current = current.substring(0, index - 5) + current.substring(index); index -= 5; label.setText(current); } else field.enter(add2); on = !on; } field.grabFocus(); } public void turnOff() { on = false; } public boolean isOn() { return on; } } public static String getHelp() { return "<b>Help with textfields:</b><br>To add superscripts, type \"^\", and to add subscripts, type \"_\".<br>To exit, type the same character or" + " press the right arrow.<br>To add an arrow, enter \"->\".<br>Use the arrow keys to move the cursor."; } }
// File path shortening code adapted from: package imagej.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.regex.Pattern; /** * Useful methods for working with file paths. * * @author Johannes Schindelin * @author Grant Harris */ public final class FileUtils { public static final int DEFAULT_SHORTENER_THRESHOLD = 4; public static final String SHORTENER_BACKSLASH_REGEX = "\\\\"; public static final String SHORTENER_SLASH_REGEX = "/"; public static final String SHORTENER_BACKSLASH = "\\"; public static final String SHORTENER_SLASH = "/"; public static final String SHORTENER_ELLIPSE = "..."; private FileUtils() { // prevent instantiation of utility class } /** * Gets the absolute path to the given file, with the directory separator * standardized to forward slash, like most platforms use. * * @param file The file whose path will be obtained and standardized. * @return The file's standardized absolute path. */ public static String getPath(final File file) { final String path = file.getAbsolutePath(); // NB: Standardize directory separator (i.e., avoid Windows nonsense!). final String slash = System.getProperty("file.separator"); return path.replaceAll(Pattern.quote(slash), "/"); } /** * Extracts the file extension from a file. * * @param file the file object * @return the file extension (excluding the dot), or the empty string when * the file name does not contain dots */ public static String getExtension(final File file) { final String name = file.getName(); final int dot = name.lastIndexOf('.'); if (dot < 0) return ""; return name.substring(dot + 1); } /** * Extracts the file extension from a file name. * * @param path the path to the file (relative or absolute) * @return the file extension (excluding the dot), or the empty string when * the file name does not contain dots */ public static String getExtension(final String path) { return getExtension(new File(path)); } public static File urlToFile(final URL url) { return urlToFile(url.toString()); } public static File urlToFile(final String url) { String path = url; if (path.startsWith("jar:")) { // remove "jar:" prefix and "!/" suffix final int index = path.indexOf("!/"); path = path.substring(4, index); } try { return new File(new URL(path).toURI()); } catch (final MalformedURLException e) { // NB: URL is not completely well-formed. } catch (final URISyntaxException e) { // NB: URL is not completely well-formed. } if (path.startsWith("file:")) { // pass through the URL as-is, minus "file:" prefix path = path.substring(5); return new File(path); } throw new IllegalArgumentException("Invalid URL: " + url); } /** * Shortens the path to a maximum of 4 path elements. * * @param path the path to the file (relative or absolute) * @return shortened path */ public static String shortenPath(final String path) { return shortenPath(path, DEFAULT_SHORTENER_THRESHOLD); } /** * Shortens the path based on the given maximum number of path elements. E.g., * "C:/1/2/test.txt" returns "C:/1/.../test.txt" if threshold is 1. * * @param path the path to the file (relative or absolute) * @param threshold the number of directories to keep unshortened * @return shortened path */ public static String shortenPath(final String path, final int threshold) { String regex = SHORTENER_BACKSLASH_REGEX; String sep = SHORTENER_BACKSLASH; if (path.indexOf("/") > 0) { regex = SHORTENER_SLASH_REGEX; sep = SHORTENER_SLASH; } String pathtemp[] = path.split(regex); // remove empty elements int elem = 0; { final String newtemp[] = new String[pathtemp.length]; int j = 0; for (int i = 0; i < pathtemp.length; i++) { if (!pathtemp[i].equals("")) { newtemp[j++] = pathtemp[i]; elem++; } } pathtemp = newtemp; } if (elem > threshold) { final StringBuilder sb = new StringBuilder(); int index = 0; // drive or protocol final int pos2dots = path.indexOf(":"); if (pos2dots > 0) { // case c:\ c:/ etc. sb.append(path.substring(0, pos2dots + 2)); index++; if (path.indexOf(":/") > 0 && pathtemp[0].length() > 2) { sb.append(SHORTENER_SLASH); } } else { final boolean isUNC = path.substring(0, 2).equals(SHORTENER_BACKSLASH_REGEX); if (isUNC) { sb.append(SHORTENER_BACKSLASH).append(SHORTENER_BACKSLASH); } } for (; index <= threshold; index++) { sb.append(pathtemp[index]).append(sep); } if (index == (elem - 1)) { sb.append(pathtemp[elem - 1]); } else { sb.append(SHORTENER_ELLIPSE).append(sep).append(pathtemp[elem - 1]); } return sb.toString(); } return path; } /** * Compacts a path into a given number of characters. The result is similar to * the Win32 API PathCompactPathExA. * * @param path the path to the file (relative or absolute) * @param limit the number of characters to which the path should be limited * @return shortened path */ public static String limitPath(final String path, final int limit) { if (path.length() <= limit) return path; final char shortPathArray[] = new char[limit]; final char pathArray[] = path.toCharArray(); final char ellipseArray[] = SHORTENER_ELLIPSE.toCharArray(); final int pathindex = pathArray.length - 1; final int shortpathindex = limit - 1; // fill the array from the end int i = 0; for (; i < limit; i++) { if (pathArray[pathindex - i] != '/' && pathArray[pathindex - i] != '\\') { shortPathArray[shortpathindex - i] = pathArray[pathindex - i]; } else { break; } } // check how much space is left final int free = limit - i; if (free < SHORTENER_ELLIPSE.length()) { // fill the beginning with ellipse for (int j = 0; j < ellipseArray.length; j++) { shortPathArray[j] = ellipseArray[j]; } } else { // fill the beginning with path and leave room for the ellipse int j = 0; for (; j + ellipseArray.length < free; j++) { shortPathArray[j] = pathArray[j]; } // ... add the ellipse for (int k = 0; j + k < free; k++) { shortPathArray[j + k] = ellipseArray[k]; } } return new String(shortPathArray); } /** * Creates a temporary directory. * <p> * Since there is no atomic operation to do that, we create a temporary file, * delete it and create a directory in its place. To avoid race conditions, we * use the optimistic approach: if the directory cannot be created, we try to * obtain a new temporary file rather than erroring out. * </p> * <p> * It is the caller's responsibility to make sure that the directory is * deleted. * </p> * * @param prefix The prefix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @param suffix The suffix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @return An abstract pathname denoting a newly-created empty directory * @throws IOException */ public static File createTemporaryDirectory(final String prefix, final String suffix) throws IOException { return createTemporaryDirectory(prefix, suffix, null); } /** * Creates a temporary directory. * <p> * Since there is no atomic operation to do that, we create a temporary file, * delete it and create a directory in its place. To avoid race conditions, we * use the optimistic approach: if the directory cannot be created, we try to * obtain a new temporary file rather than erroring out. * </p> * <p> * It is the caller's responsibility to make sure that the directory is * deleted. * </p> * * @param prefix The prefix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @param suffix The suffix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @param directory The directory in which the file is to be created, or null * if the default temporary-file directory is to be used * @return: An abstract pathname denoting a newly-created empty directory * @throws IOException */ public static File createTemporaryDirectory(final String prefix, final String suffix, final File directory) throws IOException { for (int counter = 0; counter < 10; counter++) { final File file = File.createTempFile(prefix, suffix, directory); if (!file.delete()) { throw new IOException("Could not delete file " + file); } // in case of a race condition, just try again if (file.mkdir()) return file; } throw new IOException( "Could not create temporary directory (too many race conditions?)"); } // -- Deprecated methods -- /** @deprecated Use {@link AppUtils#getBaseDirectory()} instead. */ @Deprecated public static File getBaseDirectory() { return AppUtils.getBaseDirectory(); } /** @deprecated Use {@link AppUtils#getBaseDirectory(String)} instead. */ @Deprecated public static String getBaseDirectory(final String className) { final File baseDir = AppUtils.getBaseDirectory(className); return baseDir == null ? null : baseDir.getAbsolutePath(); } /** @deprecated Use {@link ProcessUtils#exec} instead. */ @Deprecated public static String exec(final File workingDirectory, final PrintStream err, final PrintStream out, final String... args) { return ProcessUtils.exec(workingDirectory, err, out, args); } }
package distributed.util; import distributed.dto.GroupMessage; import distributed.dto.PrivateMessage; import org.jgroups.Message; /** * Helper class to work with message objects. * * @author steffen * @version 0.1 - not tested */ public class MessageHelper { /** * Helper to create an encrypted message. This function carries about * the message building and the string encryption. * * @param post The original post object, to which should be answered. * @param msg The message as a String representation. The string will be encrypted * with the public key of the post object. * @return */ public static Message buildPrivateMessage(GroupMessage post, String msg) { byte[] encodedMessage = DistributedKrypto.getInstance().encryptString(msg, DistributedKrypto.getInstance().StringToPublicKey(post.getKey())); PrivateMessage message = new PrivateMessage(post.getSender(), encodedMessage); return new Message(null, message); } }
package com.android.mms.data; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.Context; import android.content.ContentValues; import android.content.ContentUris; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import android.provider.Telephony; import com.google.android.mms.util.SqliteWrapper; import com.android.mms.LogTag; public class RecipientIdCache { private static final String TAG = "Mms/cache"; private static Uri sAllCanonical = Uri.parse("content://mms-sms/canonical-addresses"); private static Uri sSingleCanonicalAddressUri = Uri.parse("content://mms-sms/canonical-address"); private static RecipientIdCache sInstance; static RecipientIdCache getInstance() { return sInstance; } private final Map<Long, String> mCache; private final Context mContext; public static class Entry { public long id; public String number; public Entry(long id, String number) { this.id = id; this.number = number; } }; static void init(Context context) { sInstance = new RecipientIdCache(context); new Thread(new Runnable() { public void run() { fill(); } }).start(); } RecipientIdCache(Context context) { mCache = new HashMap<Long, String>(); mContext = context; } public static void fill() { Context context = sInstance.mContext; Cursor c = SqliteWrapper.query(context, context.getContentResolver(), sAllCanonical, null, null, null, null); try { synchronized (sInstance) { // Technically we don't have to clear this because the stupid // canonical_addresses table is never GC'ed. sInstance.mCache.clear(); while (c.moveToNext()) { // TODO: don't hardcode the column indices long id = c.getLong(0); String number = c.getString(1); sInstance.mCache.put(id, number); } } } finally { c.close(); } } public static List<Entry> getAddresses(String spaceSepIds) { synchronized (sInstance) { List<Entry> numbers = new ArrayList<Entry>(); String[] ids = spaceSepIds.split(" "); for (String id : ids) { long longId; try { longId = Long.parseLong(id); } catch (NumberFormatException ex) { // skip this id continue; } String number = sInstance.mCache.get(longId); if (number == null) { Log.w(TAG, "RecipientId " + longId + " not in cache!"); dump(); fill(); number = sInstance.mCache.get(longId); } if (TextUtils.isEmpty(number)) { Log.w(TAG, "RecipientId " + longId + " has empty number!"); } else { numbers.add(new Entry(longId, number)); } } return numbers; } } public static void updateNumbers(long threadId, ContactList contacts) { long recipientId = 0; for (Contact contact : contacts) { if (contact.isNumberModified()) { contact.setIsNumberModified(false); } else { // if the contact's number wasn't modified, don't bother. continue; } recipientId = contact.getRecipientId(); if (recipientId == 0) { continue; } String number1 = contact.getNumber(); String number2 = sInstance.mCache.get(recipientId); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "[RecipientIdCache] updateNumbers: comparing " + number1 + " with " + number2); } // if the numbers don't match, let's update the RecipientIdCache's number // with the new number in the contact. if (!number1.equalsIgnoreCase(number2)) { sInstance.mCache.put(recipientId, number1); sInstance.updateCanonicalAddressInDb(recipientId, number1); } } } private void updateCanonicalAddressInDb(long id, String number) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "[RecipientIdCache] updateCanonicalAddressInDb: id=" + id + ", number=" + number); } ContentValues values = new ContentValues(); values.put(Telephony.CanonicalAddressesColumns.ADDRESS, number); StringBuilder buf = new StringBuilder(Telephony.CanonicalAddressesColumns._ID); buf.append('=').append(id); Uri uri = ContentUris.withAppendedId(sSingleCanonicalAddressUri, id); mContext.getContentResolver().update(uri, values, buf.toString(), null); } public static void dump() { synchronized (sInstance) { Log.d(TAG, "*** Recipient ID cache dump ***"); for (Long id : sInstance.mCache.keySet()) { Log.d(TAG, id + ": " + sInstance.mCache.get(id)); } } } }
package com.ceco.gm2.gravitybox; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.IBinder; import android.os.PowerManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XC_MethodHook.Unhook; import de.robv.android.xposed.XC_MethodReplacement; import de.robv.android.xposed.XSharedPreferences; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; import com.ceco.gm2.gravitybox.adapters.*; public class ModRebootMenu { private static final String TAG = "ModRebootMenu"; public static final String PACKAGE_NAME = "android"; public static final String CLASS_GLOBAL_ACTIONS = "com.android.internal.policy.impl.GlobalActions"; public static final String CLASS_ACTION = "com.android.internal.policy.impl.GlobalActions.Action"; private static Context mContext; private static String mRebootStr; private static String mRebootSoftStr; private static String mRecoveryStr; private static Drawable mRebootIcon; private static Drawable mRebootSoftIcon; private static Drawable mRecoveryIcon; private static List<IIconListAdapterItem> mRebootItemList; private static String mRebootConfirmStr; private static String mRebootConfirmRecoveryStr; private static Unhook mRebootActionHook; private static void log(String message) { XposedBridge.log(TAG + ": " + message); } public static void init(final XSharedPreferences prefs, final ClassLoader classLoader) { try { final Class<?> globalActionsClass = XposedHelpers.findClass(CLASS_GLOBAL_ACTIONS, classLoader); final Class<?> actionClass = XposedHelpers.findClass(CLASS_ACTION, classLoader); XposedBridge.hookAllConstructors(globalActionsClass, new XC_MethodHook() { @Override protected void afterHookedMethod(final MethodHookParam param) throws Throwable { mContext = (Context) param.args[0]; Context gbContext = mContext.createPackageContext( GravityBox.PACKAGE_NAME, Context.CONTEXT_IGNORE_SECURITY); Resources res = mContext.getResources(); Resources gbRes = gbContext.getResources(); int rebootStrId = res.getIdentifier("factorytest_reboot", "string", PACKAGE_NAME); int rebootSoftStrId = gbRes.getIdentifier("reboot_soft", "string", GravityBox.PACKAGE_NAME); int recoveryStrId = gbRes.getIdentifier("poweroff_recovery", "string", GravityBox.PACKAGE_NAME); mRebootStr = (rebootStrId == 0) ? "Reboot" : res.getString(rebootStrId); mRebootSoftStr = gbRes.getString(rebootSoftStrId); mRecoveryStr = gbRes.getString(recoveryStrId); mRebootIcon = gbRes.getDrawable( gbRes.getIdentifier("ic_lock_reboot", "drawable", GravityBox.PACKAGE_NAME)); mRebootSoftIcon = gbRes.getDrawable( gbRes.getIdentifier("ic_lock_reboot_soft", "drawable", GravityBox.PACKAGE_NAME)); mRecoveryIcon = gbRes.getDrawable( gbRes.getIdentifier("ic_lock_recovery", "drawable", GravityBox.PACKAGE_NAME)); mRebootItemList = new ArrayList<IIconListAdapterItem>(); mRebootItemList.add(new BasicIconListItem(mRebootStr, null, mRebootIcon, null)); mRebootItemList.add(new BasicIconListItem(mRebootSoftStr, null, mRebootSoftIcon, null)); mRebootItemList.add(new BasicIconListItem(mRecoveryStr, null, mRecoveryIcon, null)); mRebootConfirmStr = gbRes.getString(gbRes.getIdentifier( "reboot_confirm", "string", GravityBox.PACKAGE_NAME)); mRebootConfirmRecoveryStr = gbRes.getString(gbRes.getIdentifier( "reboot_confirm_recovery", "string", GravityBox.PACKAGE_NAME)); log("GlobalActions constructed, resources set."); } }); XposedHelpers.findAndHookMethod(globalActionsClass, "createDialog", new XC_MethodHook() { @Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { if (mRebootActionHook != null) { log("Unhooking previous hook of reboot action item"); mRebootActionHook.unhook(); mRebootActionHook = null; } } @Override protected void afterHookedMethod(final MethodHookParam param) throws Throwable { if (mContext == null) return; prefs.reload(); if (!prefs.getBoolean(GravityBoxSettings.PREF_KEY_POWEROFF_ADVANCED, false)) { return; } @SuppressWarnings("unchecked") List<Object> mItems = (List<Object>) XposedHelpers.getObjectField(param.thisObject, "mItems"); // try to find out if reboot action item already exists in the list of GlobalActions items // strategy: // 1) check if ic_lock_reboot drawable exists in system resources // 2) check if Action has field mIconResId that is equal to resId of ic_lock_reboot log("Searching for existing reboot action item..."); Object rebootActionItem = null; Resources res = mContext.getResources(); int rebootIconId = res.getIdentifier("ic_lock_reboot_radio", "drawable", "android"); // if zero, try once more with alternative name if (rebootIconId == 0) { log("ic_lock_reboot_radio not found, trying alternative ic_lock_reboot"); rebootIconId = res.getIdentifier("ic_lock_reboot", "drawable", "android"); } if (rebootIconId != 0) { log("Reboot icon resource found: " + rebootIconId + ". Searching for matching Action item"); // check if Action with given icon res id exists for (Object o : mItems) { try { Field f = XposedHelpers.findField(o.getClass(), "mIconResId"); if ((Integer) f.get(o) == rebootIconId) { rebootActionItem = o; break; } } catch (NoSuchFieldError nfe) { // continue } } } if (rebootActionItem != null) { log("Existing Reboot action item found! Replacing onPress()"); mRebootActionHook = XposedHelpers.findAndHookMethod(rebootActionItem.getClass(), "onPress", new XC_MethodReplacement () { @Override protected Object replaceHookedMethod(MethodHookParam param) throws Throwable { showDialog(); return null; } }); } else { log("Existing Reboot action item NOT found! Adding new RebootAction item"); Object action = Proxy.newProxyInstance(classLoader, new Class<?>[] { actionClass }, new RebootAction()); // add to the second position mItems.add(1, action); BaseAdapter mAdapter = (BaseAdapter) XposedHelpers.getObjectField(param.thisObject, "mAdapter"); mAdapter.notifyDataSetChanged(); } } }); } catch (Exception e) { XposedBridge.log(e); } } private static void showDialog() { if (mContext == null) { log("mContext is null - aborting"); return; } try { log("about to build reboot dialog"); AlertDialog.Builder builder = new AlertDialog.Builder(mContext) .setTitle(mRebootStr) .setAdapter(new IconListAdapter(mContext, mRebootItemList), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); log("onClick() item = " + which); handleReboot(mContext, mRebootStr, which); } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG); dialog.show(); } catch (Exception e) { XposedBridge.log(e); } } private static void handleReboot(Context context, String caption, final int mode) { try { final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); final String message = (mode == 0 || mode == 1) ? mRebootConfirmStr : mRebootConfirmRecoveryStr; AlertDialog.Builder builder = new AlertDialog.Builder(mContext) .setTitle(caption) .setMessage(message) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (mode == 0) { pm.reboot(null); } else if (mode == 1) { Class<?> classSm = XposedHelpers.findClass("android.os.ServiceManager", null); Class<?> classIpm = XposedHelpers.findClass("android.os.IPowerManager.Stub", null); IBinder b = (IBinder) XposedHelpers.callStaticMethod( classSm, "getService", Context.POWER_SERVICE); Object ipm = XposedHelpers.callStaticMethod(classIpm, "asInterface", b); XposedHelpers.callMethod(ipm, "crash", "Hot reboot"); } else if (mode == 2) { pm.reboot("recovery"); } } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG); dialog.show(); } catch (Exception e) { XposedBridge.log(e); } } private static class RebootAction implements InvocationHandler { private Context mContext; public RebootAction() { } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); if (methodName.equals("create")) { mContext = (Context) args[0]; Resources res = mContext.getResources(); LayoutInflater li = (LayoutInflater) args[3]; int layoutId = res.getIdentifier( "global_actions_item", "layout", "android"); View v = li.inflate(layoutId, (ViewGroup) args[2], false); ImageView icon = (ImageView) v.findViewById(res.getIdentifier( "icon", "id", "android")); icon.setImageDrawable(mRebootIcon); TextView messageView = (TextView) v.findViewById(res.getIdentifier( "message", "id", "android")); messageView.setText(mRebootStr); TextView statusView = (TextView) v.findViewById(res.getIdentifier( "status", "id", "android")); statusView.setVisibility(View.GONE); return v; } else if (methodName.equals("onPress")) { showDialog(); return null; } else if (methodName.equals("onLongPress")) { return false; } else if (methodName.equals("showDuringKeyguard")) { return true; } else if (methodName.equals("showBeforeProvisioning")) { return true; } else if (methodName.equals("isEnabled")) { return true; } else { return null; } } } }
package com.ecyrd.jspwiki.plugin; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.auth.AuthorizationManager; import com.ecyrd.jspwiki.auth.permissions.PagePermission; import com.ecyrd.jspwiki.parser.PluginContent; import com.ecyrd.jspwiki.providers.ProviderException; /** * <p>Builds a simple weblog. * The pageformat can use the following params:</p> * <p>%p - Page name</p> * <p>Parameters:</p> * <ul> * <li>page - which page is used to do the blog; default is the current page.</li> * <li>entryFormat - how to display the date on pages, using the J2SE SimpleDateFormat * syntax. Defaults to the current locale's DateFormat.LONG format * for the date, and current locale's DateFormat.SHORT for the time. * Thus, for the US locale this will print dates similar to * this: September 4, 2005 11:54 PM</li> * <li>days - how many days the weblog aggregator should show. If set to * "all", shows all pages.</li> * <li>pageformat - What the entry pages should look like.</li> * <li>startDate - Date when to start. Format is "ddMMyy."</li> * <li>maxEntries - How many entries to show at most.</li> * </ul> * <p>The "days" and "startDate" can also be sent in HTTP parameters, * and the names are "weblog.days" and "weblog.startDate", respectively.</p> * <p>The weblog plugin also adds an attribute to each page it is on: * "weblogplugin.isweblog" is set to "true". This can be used to quickly * peruse pages which have weblogs.</p> * @since 1.9.21 */ // FIXME: Add "entries" param as an alternative to "days". // FIXME: Entries arrive in wrong order. public class WeblogPlugin implements WikiPlugin, ParserStagePlugin { private static Logger log = Logger.getLogger(WeblogPlugin.class); private static final DateFormat DEFAULT_ENTRYFORMAT = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT); private static final Pattern headingPattern; /** How many days are considered by default. Default value is {@value} */ public static final int DEFAULT_DAYS = 7; public static final String DEFAULT_PAGEFORMAT = "%p_blogentry_"; public static final String DEFAULT_DATEFORMAT = "ddMMyy"; public static final String PARAM_STARTDATE = "startDate"; public static final String PARAM_ENTRYFORMAT = "entryFormat"; public static final String PARAM_DAYS = "days"; public static final String PARAM_ALLOWCOMMENTS = "allowComments"; public static final String PARAM_MAXENTRIES = "maxEntries"; public static final String PARAM_PAGE = "page"; public static final String ATTR_ISWEBLOG = "weblogplugin.isweblog"; static { // This is a pretty ugly, brute-force regex. But it will do for now... headingPattern = Pattern.compile("(<h[1-4].*>)(.*)(</h[1-4]>)", Pattern.CASE_INSENSITIVE); } public static String makeEntryPage( String pageName, String date, String entryNum ) { return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName)+date+"_"+entryNum; } public static String makeEntryPage( String pageName ) { return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName); } public static String makeEntryPage( String pageName, String date ) { return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName)+date; } public String execute( WikiContext context, Map params ) throws PluginException { Calendar startTime; Calendar stopTime; int numDays = DEFAULT_DAYS; WikiEngine engine = context.getEngine(); AuthorizationManager mgr = engine.getAuthorizationManager(); // Parse parameters. String days; DateFormat entryFormat; String startDay = null; boolean hasComments = false; int maxEntries; String weblogName; if( (weblogName = (String) params.get(PARAM_PAGE)) == null ) { weblogName = context.getPage().getName(); } if( (days = context.getHttpParameter( "weblog."+PARAM_DAYS )) == null ) { days = (String) params.get( PARAM_DAYS ); } if( ( params.get(PARAM_ENTRYFORMAT)) == null ) { entryFormat = DEFAULT_ENTRYFORMAT; } else { entryFormat = new SimpleDateFormat( (String)params.get(PARAM_ENTRYFORMAT) ); } if( days != null ) { if( days.equalsIgnoreCase("all") ) { numDays = Integer.MAX_VALUE; } else { numDays = TextUtil.parseIntParameter( days, DEFAULT_DAYS ); } } if( (startDay = (String)params.get(PARAM_STARTDATE)) == null ) { startDay = context.getHttpParameter( "weblog."+PARAM_STARTDATE ); } if( TextUtil.isPositive( (String)params.get(PARAM_ALLOWCOMMENTS) ) ) { hasComments = true; } maxEntries = TextUtil.parseIntParameter( (String)params.get(PARAM_MAXENTRIES), Integer.MAX_VALUE ); // Determine the date range which to include. startTime = Calendar.getInstance(); stopTime = Calendar.getInstance(); if( startDay != null ) { SimpleDateFormat fmt = new SimpleDateFormat( DEFAULT_DATEFORMAT ); try { Date d = fmt.parse( startDay ); startTime.setTime( d ); stopTime.setTime( d ); } catch( ParseException e ) { return "Illegal time format: "+startDay; } } // Mark this to be a weblog context.getPage().setAttribute(ATTR_ISWEBLOG, "true"); // We make a wild guess here that nobody can do millisecond // accuracy here. startTime.add( Calendar.DAY_OF_MONTH, -numDays ); startTime.set( Calendar.HOUR, 0 ); startTime.set( Calendar.MINUTE, 0 ); startTime.set( Calendar.SECOND, 0 ); stopTime.set( Calendar.HOUR, 23 ); stopTime.set( Calendar.MINUTE, 59 ); stopTime.set( Calendar.SECOND, 59 ); StringBuffer sb = new StringBuffer(); try { List blogEntries = findBlogEntries( engine.getPageManager(), weblogName, startTime.getTime(), stopTime.getTime() ); Collections.sort( blogEntries, new PageDateComparator() ); sb.append("<div class=\"weblog\">\n"); for( Iterator i = blogEntries.iterator(); i.hasNext() && maxEntries { WikiPage p = (WikiPage) i.next(); if( mgr.checkPermission( context.getWikiSession(), new PagePermission(p, PagePermission.VIEW_ACTION) ) ) { addEntryHTML(context, entryFormat, hasComments, sb, p); } } sb.append("</div>\n"); } catch( ProviderException e ) { log.error( "Could not locate blog entries", e ); throw new PluginException( "Could not locate blog entries: "+e.getMessage() ); } return sb.toString(); } /** * Generates HTML for an entry. * * @param context * @param entryFormat * @param hasComments True, if comments are enabled. * @param buffer The buffer to which we add. * @param entry * @throws ProviderException */ private void addEntryHTML(WikiContext context, DateFormat entryFormat, boolean hasComments, StringBuffer buffer, WikiPage entry) throws ProviderException { WikiEngine engine = context.getEngine(); buffer.append("<div class=\"weblogentry\">\n"); // Heading buffer.append("<div class=\"weblogentryheading\">\n"); Date entryDate = entry.getLastModified(); buffer.append( entryFormat.format(entryDate) ); buffer.append("</div>\n"); // Append the text of the latest version. Reset the // context to that page. WikiContext entryCtx = (WikiContext) context.clone(); entryCtx.setPage( entry ); String html = engine.getHTML( entryCtx, engine.getPage(entry.getName()) ); // Extract the first h1/h2/h3 as title, and replace with null buffer.append("<div class=\"weblogentrytitle\">\n"); Matcher matcher = headingPattern.matcher( html ); if ( matcher.find() ) { String title = matcher.group(2); html = matcher.replaceFirst(""); buffer.append( title ); } else { buffer.append( entry.getName() ); } buffer.append("</div>\n"); buffer.append("<div class=\"weblogentrybody\">\n"); buffer.append( html ); buffer.append("</div>\n"); // Append footer buffer.append("<div class=\"weblogentryfooter\">\n"); String author = entry.getAuthor(); if( author != null ) { if( engine.pageExists(author) ) { author = "<a href=\""+entryCtx.getURL( WikiContext.VIEW, author )+"\">"+engine.beautifyTitle(author)+"</a>"; } } else { author = "AnonymousCoward"; } buffer.append("By "+author+"&nbsp;&nbsp;"); buffer.append( "<a href=\""+entryCtx.getURL(WikiContext.VIEW, entry.getName())+"\">Permalink</a>" ); String commentPageName = TextUtil.replaceString( entry.getName(), "blogentry", "comments" ); if( hasComments ) { int numComments = guessNumberOfComments( engine, commentPageName ); // We add the number of comments to the URL so that // the user's browsers would realize that the page // has changed. buffer.append( "&nbsp;&nbsp;" ); buffer.append( "<a target=\"_blank\" href=\""+ entryCtx.getURL(WikiContext.COMMENT, commentPageName, "nc="+numComments)+ "\">Comments? ("+ numComments+ ")</a>" ); } buffer.append("</div>\n"); // Done, close buffer.append("</div>\n"); } private int guessNumberOfComments( WikiEngine engine, String commentpage ) throws ProviderException { String pagedata = engine.getPureText( commentpage, WikiProvider.LATEST_VERSION ); if( pagedata == null || pagedata.trim().length() == 0 ) { return 0; } return TextUtil.countSections( pagedata ); } /** * Attempts to locate all pages that correspond to the * blog entry pattern. Will only consider the days on the dates; not the hours and minutes. * * @param mgr A PageManager which is used to get the pages * @param baseName The basename (e.g. "Main" if you want "Main_blogentry_xxxx") * @param start The date which is the first to be considered * @param end The end date which is the last to be considered * @return a list of pages with their FIRST revisions. * @throws ProviderException If something goes wrong */ public List findBlogEntries( PageManager mgr, String baseName, Date start, Date end ) throws ProviderException { Collection everyone = mgr.getAllPages(); ArrayList result = new ArrayList(); baseName = makeEntryPage( baseName ); SimpleDateFormat fmt = new SimpleDateFormat(DEFAULT_DATEFORMAT); for( Iterator i = everyone.iterator(); i.hasNext(); ) { WikiPage p = (WikiPage)i.next(); String pageName = p.getName(); if( pageName.startsWith( baseName ) ) { // Check the creation date from the page name. // We do this because RCSFileProvider is very slow at getting a // specific page version. try { //log.debug("Checking: "+pageName); int firstScore = pageName.indexOf('_',baseName.length()-1 ); if( firstScore != -1 && firstScore+1 < pageName.length() ) { int secondScore = pageName.indexOf('_', firstScore+1); if( secondScore != -1 ) { String creationDate = pageName.substring( firstScore+1, secondScore ); Date pageDay = fmt.parse( creationDate ); // Add the first version of the page into the list. This way // the page modified date becomes the page creation date. if( pageDay != null && pageDay.after(start) && pageDay.before(end) ) { WikiPage firstVersion = mgr.getPageInfo( pageName, 1 ); result.add( firstVersion ); } } } } catch( Exception e ) { log.debug("Page name :"+pageName+" was suspected as a blog entry but it isn't because of parsing errors",e); } } } return result; } /** * Reverse comparison. */ private static class PageDateComparator implements Comparator { public int compare( Object o1, Object o2 ) { if( o1 == null || o2 == null ) { return 0; } WikiPage page1 = (WikiPage)o1; WikiPage page2 = (WikiPage)o2; return page2.getLastModified().compareTo( page1.getLastModified() ); } } /** Mark us as being a real weblog. */ public void executeParser(PluginContent element, WikiContext context, Map params) { context.getPage().setAttribute( ATTR_ISWEBLOG, "true" ); } }
package com.example.reader; import ilearnrw.textadaptation.TextAnnotationModule; import ilearnrw.textclassification.Word; import ilearnrw.user.problems.ProblemDefinition; import ilearnrw.user.problems.ProblemDefinitionIndex; import ilearnrw.user.problems.ProblemDescription; import ilearnrw.user.profile.UserProfile; import java.io.File; import java.util.ArrayList; import com.example.reader.interfaces.ColorPickerListener; import com.example.reader.interfaces.OnHttpListener; import com.example.reader.interfaces.OnProfileFetched; import com.example.reader.results.ProfileResult; import com.example.reader.tasks.ProfileTask; import com.example.reader.types.ColorPickerDialog; import com.example.reader.types.BasicListAdapter; import com.example.reader.utils.FileHelper; import com.example.reader.utils.HttpHelper; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.Spinner; public class PresentationModule extends Activity implements OnClickListener, OnCheckedChangeListener, OnHttpListener, OnProfileFetched, OnItemSelectedListener { private LinearLayout colorLayout, container; private Button btnOk, btnCancel; private RadioGroup rulesGroup; private RadioButton rbtnRule1, rbtnRule2, rbtnRule3, rbtnRule4; private Spinner spCategories, spProblems; private ImageView colorBox; private File fileHtml = null; private File fileJSON = null; private String html, json; private String name = ""; private Boolean showGUI = false; private ArrayList<Word> trickyWords; private SharedPreferences sp; private String TAG; private ProblemDefinition[] definitions; private ProblemDescription[][] descriptions; private ProblemDescription[] problemDescriptions; private ArrayList<String> categories; private ArrayList<String> problems; private final int DEFAULT_COLOR = 0xffff0000; private final int DEFAULT_RULE = 3; private int currentColor; private int currentRule; private int currentCategoryPos; private int currentProblemPos; private UserProfile userProfile; private TextAnnotationModule txModule; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TAG = getClass().getName(); Bundle bundle = getIntent().getExtras(); boolean loadFiles = true; if(bundle.containsKey("loadFiles")) loadFiles = bundle.getBoolean("loadFiles"); name = bundle.getString("title", ""); showGUI = bundle.getBoolean("showGUI", false); trickyWords = new ArrayList<Word>(); if(loadFiles){ fileHtml = (File)bundle.get("file"); fileJSON = (File)bundle.get("json"); html = FileHelper.readFromFile(fileHtml); json = FileHelper.readFromFile(fileJSON); } else { html = bundle.getString("html"); json = bundle.getString("json"); } categories = new ArrayList<String>(); problems = new ArrayList<String>(); setContentView(R.layout.activity_presentation_module); sp = PreferenceManager.getDefaultSharedPreferences(this); sp.edit().putBoolean("showGUI", showGUI).commit(); int id = sp.getInt("id",-1); String token = sp.getString("authToken", ""); if(id==-1 || token.isEmpty()) { finished(); // If you don't have an id something is terribly wrong throw new IllegalArgumentException("Missing id or token"); } init(); } private void init(){ container = (LinearLayout) findViewById(R.id.presentation_module_container); if(showGUI) container.setVisibility(View.VISIBLE); else container.setVisibility(View.GONE); spCategories = (Spinner) findViewById(R.id.categories); spProblems = (Spinner) findViewById(R.id.problems); btnOk = (Button) findViewById(R.id.pm_btn_ok); btnCancel = (Button) findViewById(R.id.pm_btn_cancel); rulesGroup = (RadioGroup) findViewById(R.id.pm_rules); rbtnRule1 = (RadioButton) findViewById(R.id.pm_rule1); rbtnRule2 = (RadioButton) findViewById(R.id.pm_rule2); rbtnRule3 = (RadioButton) findViewById(R.id.pm_rule3); rbtnRule4 = (RadioButton) findViewById(R.id.pm_rule4); colorLayout = (LinearLayout) findViewById(R.id.pm_color_layout); colorBox = (ImageView) findViewById(R.id.pm_color); btnCancel.setOnClickListener(this); btnOk.setOnClickListener(this); colorLayout.setOnClickListener(this); rulesGroup.setOnCheckedChangeListener(this); String userId = Integer.toString(sp.getInt("id", 0)); String token = sp.getString("authToken", ""); currentCategoryPos = 0; currentProblemPos = 0; updateColor(currentCategoryPos, currentProblemPos); updateRule(currentCategoryPos, currentProblemPos); spCategories.setOnItemSelectedListener(this); spProblems.setOnItemSelectedListener(this); new ProfileTask(this, showGUI, this, this).run(userId, token); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.pm_btn_ok: //int color = sp.getInt("pm_color_0_0", DEFAULT_COLOR); //int rule = sp.getInt("pm_rule_0_0", DEFAULT_RULE); /*if (rbtnRule1.isChecked() || rbtnRule2.isChecked()) { Log.i("Checked", "rbtnRule2"); Log.i("Checked", this.txModule.getBackgroundColor()); this.txModule.getPresentationRulesModule().setTextColor(category, problem, currentColor+""); } else if (rbtnRule3.isChecked() || rbtnRule4.isChecked()) { Log.i("Checked", "rbtnRule3"); }*/ for (int i = 0; i < categories.size(); i++) { for (int j = 0; j < this.problems.size(); j++) { int color = sp.getInt("pm_color_"+i+"_"+j, DEFAULT_COLOR); int rule = sp.getInt("pm_rule_"+i+"_"+j, DEFAULT_RULE); this.txModule.getPresentationRulesModule().setPresentationRule(i, j, rule); Log.i("Rule", color+""); //Log.i("Rule", this.txModule.getPresentationRulesModule().getHighlightingColor(i, j)+""); if (rbtnRule1.isChecked() || rbtnRule2.isChecked()) { this.txModule.getPresentationRulesModule().setTextColor(i, j, color); } else if (rbtnRule3.isChecked() || rbtnRule4.isChecked()) { this.txModule.getPresentationRulesModule().setHighlightingColor(i, j, color); } //Log.i("Rule", this.txModule.getPresentationRulesModule().getTextColor(i, j)+""); //Log.i("Rule", this.txModule.getPresentationRulesModule().getHighlightingColor(i, j)+""); } } finished(); break; case R.id.pm_btn_cancel: onBackPressed(); break; case R.id.pm_color_layout: int color = sp.getInt("pm_color_" + currentCategoryPos + "_" + currentProblemPos, DEFAULT_COLOR); ColorPickerDialog dialog = new ColorPickerDialog(this, color, new ColorPickerListener() { @Override public void onOk(ColorPickerDialog dialog, int color) { sp.edit().putInt("pm_color_" + currentCategoryPos + "_" + currentProblemPos, color).commit(); updateColor(currentCategoryPos, currentProblemPos); } @Override public void onCancel(ColorPickerDialog dialog) {} }); dialog.show(); break; } }; @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (group.getId()) { case R.id.pm_rules: switch(group.getCheckedRadioButtonId()){ case R.id.pm_rule1: currentRule = 1; break; case R.id.pm_rule2: currentRule = 2; break; case R.id.pm_rule3: currentRule = 3; break; case R.id.pm_rule4: currentRule = 4; break; } default: break; } sp.edit().putInt("pm_rule_"+currentCategoryPos+"_"+currentProblemPos, currentRule).commit(); updateRule(currentCategoryPos, currentProblemPos); } @Override public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) { switch(parent.getId()){ case R.id.categories: currentCategoryPos = pos; updateProblems(currentCategoryPos); updateRule(currentCategoryPos, currentProblemPos); break; case R.id.problems: currentProblemPos = pos; updateColor(currentCategoryPos, currentProblemPos); updateRule(currentCategoryPos, currentProblemPos); break; default: break; } } @Override public void onNothingSelected(AdapterView<?> parent) {} @Override public void onBackPressed() { Intent i = new Intent(this, LibraryActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(i); finish(); } private void finished(){ Intent intent = new Intent(PresentationModule.this, ReaderActivity.class); intent.putExtra("html", html); intent.putExtra("json", json); intent.putExtra("title", name); intent.putExtra("trickyWords", (ArrayList<Word>) trickyWords); startActivity(intent); } private void updateColor(int category, int problem){ currentColor = sp.getInt("pm_color_"+category+"_"+problem, DEFAULT_COLOR); colorBox.setBackgroundColor(currentColor); } private void updateRule(int category, int problem){ currentRule = sp.getInt("pm_rule_"+category+"_"+problem, DEFAULT_RULE); switch(currentRule){ case 1: rbtnRule1.setChecked(true); break; case 2: rbtnRule2.setChecked(true); break; case 3: rbtnRule3.setChecked(true); break; case 4: rbtnRule4.setChecked(true); break; } } private void updateProblems(int index){ problemDescriptions = descriptions[index]; currentProblemPos = 0; problems.clear(); for(int i=0; i<problemDescriptions.length; i++){ String[] descriptions = problemDescriptions[i].getDescriptions(); String str = ""; for(int j=0; j<descriptions.length; j++){ if(j+1<descriptions.length) str += descriptions[j] + " | "; else str += descriptions[j]; } problems.add((i+1) + ". " + str); } ArrayAdapter<String> problemAdapter = new BasicListAdapter(this, R.layout.textview_item_multiline, problems, true); problemAdapter.notifyDataSetChanged(); spProblems.setAdapter(problemAdapter); } @Override public void onTokenExpired(final String... params) { if(HttpHelper.refreshTokens(this)){ final String newToken = sp.getString("authToken", ""); runOnUiThread(new Runnable() { @Override public void run() { new ProfileTask(PresentationModule.this, showGUI, PresentationModule.this, PresentationModule.this).run(params[0], newToken); Log.d(TAG, getString(R.string.token_error_retry)); Toast.makeText(PresentationModule.this, getString(R.string.token_error_retry), Toast.LENGTH_SHORT).show(); } }); } } @Override public void onProfileFetched(ProfileResult profile) { trickyWords = (ArrayList<Word>) profile.userProblems.getTrickyWords(); if(!showGUI){ finished(); return; } ProblemDefinitionIndex index = profile.userProblems.getProblems(); definitions = index.getProblemsIndex(); descriptions = index.getProblems(); categories.clear(); for(int i=0; i<definitions.length;i++){ categories.add((i+1) + ". " + definitions[i].getType().getUrl()); } currentCategoryPos = 0; updateProblems(currentCategoryPos); ArrayAdapter<String> categoryAdapter = new BasicListAdapter(this, R.layout.textview_item_multiline, categories, true); spCategories.setAdapter(categoryAdapter); userProfile = new UserProfile(profile.language, profile.userProblems, profile.preferences); txModule = new TextAnnotationModule(html, userProfile); try{ txModule.sendPostToServer(sp.getString("authToken", "")); Log.i("Result", txModule.getJSONFile()); } catch (Exception e) { Log.i("Exception", e.toString()); } } }
package com.socialteinc.socialate; import android.support.test.espresso.intent.Intents; import android.support.test.filters.LargeTest; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.intent.Intents.intended; import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static junit.framework.Assert.assertEquals; @RunWith(AndroidJUnit4.class) public class CheckEmailActivityTest { @Rule public ActivityTestRule<CheckEmailActivity> mActivityRule = new ActivityTestRule<>( CheckEmailActivity.class); /** * This is a test for Checking if the username has already being taken or not, * if username doesn't exist, you'll be allowed to create a password **/ @Test public void EmailTest(){ assertEquals(false, CheckEmailActivity.isValidEmail("mmmmm")); assertEquals(false, CheckEmailActivity.isValidEmail("abcd.com")); assertEquals(true, CheckEmailActivity.isValidEmail("socialate@gmail.com")); assertEquals(true, CheckEmailActivity.isValidEmail("1234@gmail.com")); } @Test public void InvalidEmailTest() throws InterruptedException { onView(withId(R.id.emailEditText)).perform(typeText("invalidemail.com")); onView(withId(R.id.nextButton)).perform(click()); } @Test public void ValidEmailTest(){ onView(withId(R.id.emailEditText)).perform(typeText("musar@gmail.com")); onView(withId(R.id.nextButton)).perform(click()); } }
package io.github.droidkaigi.confsched2017.di; import com.facebook.stetho.okhttp3.StethoInterceptor; import android.content.Context; import java.io.File; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.Interceptor; import okhttp3.OkHttpClient; @Module public class HttpClientModule { static final String CACHE_FILE_NAME = "okhttp.cache"; static final long MAX_CACHE_SIZE = 4 * 1024 * 1024; @Singleton @Provides public OkHttpClient provideHttpClient(Context context, Interceptor interceptor) { File cacheDir = new File(context.getCacheDir(), CACHE_FILE_NAME); Cache cache = new Cache(cacheDir, MAX_CACHE_SIZE); OkHttpClient.Builder c = new OkHttpClient.Builder().cache(cache).addInterceptor(interceptor) .addNetworkInterceptor(new StethoInterceptor()); return c.build(); } }
package com.battlelancer.seriesguide.ui.search; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.PopupMenu; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.loader.app.LoaderManager; import androidx.loader.content.Loader; import butterknife.ButterKnife; import butterknife.Unbinder; import com.battlelancer.seriesguide.R; import com.battlelancer.seriesguide.ui.OverviewActivity; import com.battlelancer.seriesguide.ui.SearchActivity; import com.battlelancer.seriesguide.ui.shows.ShowTools; import com.battlelancer.seriesguide.util.TaskManager; import com.battlelancer.seriesguide.util.tasks.BaseShowActionTask; import com.battlelancer.seriesguide.widgets.EmptyView; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; /** * Can display either the connected trakt user's watched, collected or watchlist-ed shows and offer * to add them. */ public class TraktAddFragment extends AddFragment { /** * Which trakt list should be shown. One of {@link TraktShowsLink}. */ private final static String ARG_TYPE = "traktListType"; public static TraktAddFragment newInstance(TraktShowsLink link) { TraktAddFragment f = new TraktAddFragment(); Bundle args = new Bundle(); args.putInt(TraktAddFragment.ARG_TYPE, link.id); f.setArguments(args); return f; } private Unbinder unbinder; private TraktShowsLink listType; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); listType = TraktShowsLink.fromId(args != null ? args.getInt(ARG_TYPE) : -1); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_addshow_trakt, container, false); unbinder = ButterKnife.bind(this, v); // set initial view states setProgressVisible(true, false); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // setup adapter, enable context menu only for watchlist adapter = new AddAdapter(getActivity(), new ArrayList<>(), itemClickListener, listType == TraktShowsLink.WATCHLIST ); // load data LoaderManager.getInstance(this) .initLoader(SearchActivity.TRAKT_BASE_LOADER_ID + listType.id, null, traktAddCallbacks); // add menu options setHasOptionsMenu(true); } private final AddAdapter.OnItemClickListener itemClickListener = new AddAdapter.OnItemClickListener() { @Override public void onItemClick(SearchResult item) { if (item != null && item.getState() != SearchResult.STATE_ADDING) { if (item.getState() == SearchResult.STATE_ADDED) { // already in library, open it startActivity(OverviewActivity .intentShowByTmdbId(requireContext(), item.getTmdbId())); } else { // display more details in a dialog AddShowDialogFragment.show(getParentFragmentManager(), item); } } } @Override public void onAddClick(SearchResult item) { EventBus.getDefault().post(new OnAddingShowEvent(item.getTmdbId())); TaskManager.getInstance().performAddTask(requireContext(), item); } @Override public void onMenuWatchlistClick(View view, int showTmdbId) { PopupMenu popupMenu = new PopupMenu(view.getContext(), view); popupMenu.inflate(R.menu.add_dialog_popup_menu); // prevent adding shows to watchlist already on watchlist if (listType == TraktShowsLink.WATCHLIST) { popupMenu.getMenu().findItem(R.id.menu_action_show_watchlist_add).setVisible(false); } popupMenu.setOnMenuItemClickListener( new AddItemMenuItemClickListener(requireContext(), showTmdbId)); popupMenu.show(); } }; public static class AddItemMenuItemClickListener implements PopupMenu.OnMenuItemClickListener { private final Context context; private final int showTmdbId; public AddItemMenuItemClickListener(Context context, int showTmdbId) { this.context = context; this.showTmdbId = showTmdbId; } @Override public boolean onMenuItemClick(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_action_show_watchlist_add) { ShowTools.addToWatchlist(context, showTmdbId); return true; } if (itemId == R.id.menu_action_show_watchlist_remove) { ShowTools.removeFromWatchlist(context, showTmdbId); return true; } return false; } } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.trakt_library_menu, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_add_all) { if (searchResults != null) { List<SearchResult> showsToAdd = new LinkedList<>(); // only include shows not already added for (SearchResult result : searchResults) { if (result.getState() == SearchResult.STATE_ADD) { showsToAdd.add(result); result.setState(SearchResult.STATE_ADDING); } } EventBus.getDefault().post(new OnAddingShowEvent()); TaskManager.getInstance().performAddTask(getContext(), showsToAdd, false, false); } // disable the item so the user has to come back item.setEnabled(false); return true; } return super.onOptionsItemSelected(item); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(BaseShowActionTask.ShowChangedEvent event) { if (listType == TraktShowsLink.WATCHLIST) { // reload watchlist if a show was removed LoaderManager.getInstance(this) .restartLoader(SearchActivity.TRAKT_BASE_LOADER_ID + listType.id, null, traktAddCallbacks); } } @Override protected void setupEmptyView(EmptyView emptyView) { emptyView.setButtonClickListener(v -> { setProgressVisible(true, false); LoaderManager.getInstance(TraktAddFragment.this) .restartLoader(SearchActivity.TRAKT_BASE_LOADER_ID + listType.id, null, traktAddCallbacks); }); } private final LoaderManager.LoaderCallbacks<TraktAddLoader.Result> traktAddCallbacks = new LoaderManager.LoaderCallbacks<TraktAddLoader.Result>() { @Override public Loader<TraktAddLoader.Result> onCreateLoader(int id, Bundle args) { return new TraktAddLoader(getContext(), listType); } @Override public void onLoadFinished(@NonNull Loader<TraktAddLoader.Result> loader, TraktAddLoader.Result data) { if (!isAdded()) { return; } setSearchResults(data.results); setEmptyMessage(data.emptyText); setProgressVisible(false, true); } @Override public void onLoaderReset(@NonNull Loader<TraktAddLoader.Result> loader) { // keep currently displayed data } }; }
/* * $Log: Adapter.java,v $ * Revision 1.42 2008-06-18 12:27:43 europe\L190409 * discern between severe errors and warnings (for monitoring) * * Revision 1.41 2008/05/21 10:56:09 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * modified monitorAdapter interface * fixed NDC handling * * Revision 1.40 2008/05/14 09:33:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * simplified methodnames of StatisticsKeeperIterationHandler * now implements interface HasStatistics * * Revision 1.39 2008/03/28 14:20:42 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * simplify error messages * * Revision 1.38 2008/03/27 11:09:41 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * avoid nested non-informative NDCs * * Revision 1.37 2008/01/03 15:40:19 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * renamed start and stop threads * do not wait at end of start thread * * Revision 1.36 2007/12/28 12:01:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * log error messages in request-reply logging * * Revision 1.35 2007/12/12 09:08:41 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added message class to monitor event from error * * Revision 1.34 2007/12/10 10:00:02 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added monitoring * * Revision 1.33 2007/10/10 09:35:28 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Direct copy from Ibis-EJB: * spring enabled version * * Revision 1.32 2007/10/08 12:15:38 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected date formatting * * Revision 1.31 2007/07/24 08:05:22 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added targetDesignDocument attribute * * Revision 1.30 2007/07/10 07:11:45 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * logging improvements * * Revision 1.29 2007/06/26 12:05:34 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * tuned logging * * Revision 1.28 2007/05/02 11:23:52 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added attribute 'active' * * Revision 1.27 2007/03/14 12:22:10 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * log results in case of exception, too * * Revision 1.26 2007/02/12 13:44:09 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Logger from LogUtil * * Revision 1.25 2006/09/14 14:58:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added getPipeLine() * * Revision 1.24 2006/09/07 08:35:50 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added requestReplyLogging * * Revision 1.23 2006/08/22 12:50:17 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * moved code for userTransaction to JtaUtil * * Revision 1.22 2006/02/09 07:55:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * name, upSince and lastMessageDate in statistics-summary * * Revision 1.21 2005/12/28 08:34:46 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * introduced StatisticsKeeper-iteration * * Revision 1.20 2005/10/26 13:16:14 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added second default for UserTransactionUrl * * Revision 1.19 2005/10/17 08:51:23 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * made getMessageKeeper synchronized * * Revision 1.18 2005/08/17 08:12:45 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * NDC updated * * Revision 1.17 2005/08/16 12:33:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added NDC with correlationId * * Revision 1.16 2005/07/05 12:27:52 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added possibility to end processing with an exception * * Revision 1.15 2005/01/13 08:55:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Make threadContext-attributes available in PipeLineSession * * Revision 1.14 2004/09/08 14:14:41 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * adjusted error logging * * Revision 1.13 2004/08/19 07:16:21 unknown <unknown@ibissource.org> * Resolved problem of hanging adapter if stopRunning was called just after the * adapter was set to started * * Revision 1.12 2004/07/06 07:00:44 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * configure now throws less exceptions * * Revision 1.11 2004/06/30 10:02:23 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved error reporting * * Revision 1.10 2004/06/16 13:08:11 Johan Verrips <johan.verrips@ibissource.org> * Added configuration error when no pipeline was configured * * Revision 1.9 2004/06/16 12:34:46 Johan Verrips <johan.verrips@ibissource.org> * Added AutoStart functionality on Adapter * * Revision 1.8 2004/04/28 08:31:41 Johan Verrips <johan.verrips@ibissource.org> * Added getRunStateAsString function * * Revision 1.7 2004/04/13 11:37:13 Johan Verrips <johan.verrips@ibissource.org> * When the Adapter was in state "ERROR", it could not be stopped anymore. Fixed it. * * Revision 1.6 2004/04/06 14:52:52 Johan Verrips <johan.verrips@ibissource.org> * Updated handling of errors in receiver.configure() * * Revision 1.5 2004/03/30 07:29:53 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * * Revision 1.4 2004/03/26 10:42:45 Johan Verrips <johan.verrips@ibissource.org> * added @version tag in javadoc * */ package nl.nn.adapterframework.core; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter; import nl.nn.adapterframework.monitoring.EventTypeEnum; import nl.nn.adapterframework.monitoring.IMonitorAdapter; import nl.nn.adapterframework.monitoring.MonitorAdapterFactory; import nl.nn.adapterframework.monitoring.SeverityEnum; import nl.nn.adapterframework.receivers.ReceiverBase; import nl.nn.adapterframework.util.DateUtils; import nl.nn.adapterframework.util.HasStatistics; import nl.nn.adapterframework.util.LogUtil; import nl.nn.adapterframework.util.MessageKeeper; import nl.nn.adapterframework.util.RunStateEnum; import nl.nn.adapterframework.util.RunStateManager; import nl.nn.adapterframework.util.StatisticsKeeper; import nl.nn.adapterframework.util.StatisticsKeeperIterationHandler; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import org.springframework.beans.factory.NamedBean; import org.springframework.core.task.TaskExecutor; /** * The Adapter is the central manager in the IBIS Adapterframework, that has knowledge * and uses {@link IReceiver IReceivers} and a {@link PipeLine}. * * <b>responsibility</b><br/> * <ul> * <li>keeping and gathering statistics</li> * <li>processing messages, retrieved from IReceivers</li> * <li>starting and stoppping IReceivers</li> * <li>delivering error messages in a specified format</li> * </ul> * All messages from IReceivers pass through the adapter (multi threaded). * Multiple receivers may be attached to one adapter.<br/> * <br/> * The actual processing of messages is delegated to the {@link PipeLine} * object, which returns a {@link PipeLineResult}. If an error occurs during * the pipeline execution, the state in the <code>PipeLineResult</code> is set * to the state specified by <code>setErrorState</code>, which defaults to "ERROR". * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>className</td><td>nl.nn.adapterframework.pipes.AbstractPipe</td><td>&nbsp;</td></tr> * <tr><td>{@link #setName(String) name}</td><td>name of the Adapter</td><td>&nbsp;</td></tr> * <tr><td>{@link #setDescription(String) description}</td><td>description of the Adapter</td><td>&nbsp;</td></tr> * <tr><td>{@link #setAutoStart(boolean) autoStart}</td><td>controls whether Adapters starts when configuration loads</td><td>true</td></tr> * <tr><td>{@link #setActive(boolean) active}</td> <td>controls whether Adapter is included in configuration. When set <code>false</code> or set to something else as "true", (even set to the empty string), the receiver is not included in the configuration</td><td>true</td></tr> * <tr><td>{@link #setErrorMessageFormatter(String) errorMessageFormatter}</td><td>&nbsp;</td><td>&nbsp;</td></tr> * <tr><td>{@link #setErrorState(String) errorState}</td><td>If an error occurs during * the pipeline execution, the state in the <code>PipeLineResult</code> is set to this state</td><td>ERROR</td></tr> * <tr><td>{@link #setMessageKeeperSize(int) messageKeeperSize}</td><td>number of message displayed in IbisConsole</td><td>10</td></tr> * <tr><td>{@link #setRequestReplyLogging(boolean) requestReplyLogging}</td><td>when <code>true</code>, the request and reply messages will be logged for each request processed</td><td>false</td></tr> * </table></td><td>&nbsp;</td></tr> * </table> * * @version Id * @author Johan Verrips * @see nl.nn.adapterframework.core.IReceiver * @see nl.nn.adapterframework.core.PipeLine * @see nl.nn.adapterframework.util.StatisticsKeeper * @see nl.nn.adapterframework.util.DateUtils * @see nl.nn.adapterframework.util.MessageKeeper * @see nl.nn.adapterframework.core.PipeLineResult * */ public class Adapter implements IAdapter, NamedBean { public static final String version = "$RCSfile: Adapter.java,v $ $Revision: 1.42 $ $Date: 2008-06-18 12:27:43 $"; private Logger log = LogUtil.getLogger(this); private String name; private String targetDesignDocument; private boolean active=true; private Vector receivers = new Vector(); private long lastMessageDate = 0; private PipeLine pipeline; private long numOfMessagesProcessed = 0; private long numOfMessagesInError = 0; private StatisticsKeeper statsMessageProcessingDuration = null; private long statsUpSince = System.currentTimeMillis(); private IErrorMessageFormatter errorMessageFormatter; private RunStateManager runState = new RunStateManager(); private boolean configurationSucceeded = false; private String description; private MessageKeeper messageKeeper; //instantiated in configure() private int messageKeeperSize = 10; //default length private boolean autoStart = true; private boolean requestReplyLogging = false; // state to put in PipeLineResult when a PipeRunException occurs; private String errorState = "ERROR"; /** * The nummer of message currently in process */ private int numOfMessagesInProcess = 0; private IMonitorAdapter monitorAdapter=null; private TaskExecutor taskExecutor; /** * Indicates wether the configuration succeeded. * @return boolean */ public boolean configurationSucceeded() { return configurationSucceeded; } /* * This function is called by Configuration.registerAdapter, * to make configuration information available to the Adapter. <br/><br/> * This method also performs * a <code>Pipeline.configurePipes()</code>, as to configure the individual pipes. * @see nl.nn.adapterframework.core.Pipeline#configurePipes */ public void configure() throws ConfigurationException { configurationSucceeded = false; log.debug("configuring adapter [" + getName() + "]"); MessageKeeper messageKeeper = getMessageKeeper(); statsMessageProcessingDuration = new StatisticsKeeper(getName()); if (pipeline == null) { String msg = "No pipeline configured for adapter [" + getName() + "]"; messageKeeper.add(msg); throw new ConfigurationException(msg); } try { pipeline.setAdapter(this); pipeline.configurePipes(); messageKeeper.add("pipeline successfully configured"); Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); log.info("Adapter [" + name + "] is initializing receiver [" + receiver.getName() + "]"); receiver.setAdapter(this); try { receiver.configure(); messageKeeper.add("receiver [" + receiver.getName() + "] successfully configured"); } catch (ConfigurationException e) { error(true, "error initializing receiver [" + receiver.getName() + "]",e); } } monitorAdapter=MonitorAdapterFactory.getMonitorAdapter(); configurationSucceeded = true; } catch (ConfigurationException e) { error(true, "error initializing pipeline", e); } } /** * sends a warning to the log and to the messagekeeper of the adapter */ protected void warn(String msg) { log.warn("Adapter [" + getName() + "] "+msg); getMessageKeeper().add("WARNING: " + msg); } /** * sends a warning to the log and to the messagekeeper of the adapter */ protected void error(boolean critical, String msg, Throwable t) { log.error("Adapter [" + getName() + "] "+msg, t); getMessageKeeper().add("ERROR: " + msg+": "+t.getMessage()); String prefix=critical?"ADPTERROR ":"ADPTWARN "; fireMonitorEvent(EventTypeEnum.TECHNICAL,critical?SeverityEnum.CRITICAL:SeverityEnum.WARNING, prefix+msg,t); } protected void fireMonitorEvent(EventTypeEnum eventType, SeverityEnum severity, String message, Throwable t) { if (monitorAdapter!=null) { monitorAdapter.fireEvent(getName(), eventType, severity, message, t); } } /** * Increase the number of messages in process */ private void incNumOfMessagesInProcess(long startTime) { synchronized (statsMessageProcessingDuration) { numOfMessagesInProcess++; lastMessageDate = startTime; } } /** * Decrease the number of messages in process */ private synchronized void decNumOfMessagesInProcess(long duration) { synchronized (statsMessageProcessingDuration) { numOfMessagesInProcess numOfMessagesProcessed++; statsMessageProcessingDuration.addValue(duration); notifyAll(); } } /** * The number of messages for which processing ended unsuccessfully. */ private void incNumOfMessagesInError() { synchronized (statsMessageProcessingDuration) { numOfMessagesInError++; } } public synchronized String formatErrorMessage( String errorMessage, Throwable t, String originalMessage, String messageID, INamedObject objectInError, long receivedTime) { if (errorMessageFormatter == null) { errorMessageFormatter = new ErrorMessageFormatter(); } // you never can trust an implementation, so try/catch! try { String formattedErrorMessage= errorMessageFormatter.format( errorMessage, t, objectInError, originalMessage, messageID, receivedTime); if (isRequestReplyLogging()) { log.info("Adapter [" + getName() + "] messageId[" + messageID + "] formatted errormessage, result [" + formattedErrorMessage + "]"); } else { if (log.isDebugEnabled()) { log.info("Adapter [" + getName() + "] messageId[" + messageID + "] formatted errormessage, result [" + formattedErrorMessage + "]"); } } return formattedErrorMessage; } catch (Exception e) { String msg = "got error while formatting errormessage, original errorMessage [" + errorMessage + "]"; msg = msg + " from [" + (objectInError == null ? "unknown-null" : objectInError.getName()) + "]"; error(false, "got error while formatting errormessage", e); return errorMessage; } } /** * retrieve the date and time of the last message. */ public String getLastMessageDate() { String result = ""; if (lastMessageDate != 0) result = DateUtils.format(new Date(lastMessageDate), DateUtils.FORMAT_FULL_GENERIC); else result = "-"; return result; } /** * the MessageKeeper is for keeping the last <code>messageKeeperSize</code> * messages available, for instance for displaying it in the webcontrol * @see nl.nn.adapterframework.util.MessageKeeper */ public synchronized MessageKeeper getMessageKeeper() { if (messageKeeper == null) messageKeeper = new MessageKeeper(messageKeeperSize < 1 ? 1 : messageKeeperSize); return messageKeeper; } public void forEachStatisticsKeeper(StatisticsKeeperIterationHandler hski) { Object root=hski.start(); forEachStatisticsKeeperBody(hski,root); hski.end(root); } public void forEachStatisticsKeeperBody(StatisticsKeeperIterationHandler hski, Object data) { Object adapterData=hski.openGroup(data,getName(),"adapter"); hski.handleScalar(adapterData,"name", getName()); hski.handleScalar(adapterData,"upSince", getStatsUpSince()); hski.handleScalar(adapterData,"lastMessageDate", getLastMessageDate()); hski.handleScalar(adapterData,"messagesInProcess", getNumOfMessagesInProcess()); hski.handleScalar(adapterData,"messagesProcessed", getNumOfMessagesProcessed()); hski.handleScalar(adapterData,"messagesInError", getNumOfMessagesInError()); hski.handleStatisticsKeeper(adapterData, statsMessageProcessingDuration); Object recsData=hski.openGroup(adapterData,getName(),"receivers"); Iterator recIt=getReceiverIterator(); if (recIt.hasNext()) { while (recIt.hasNext()) { IReceiver receiver=(IReceiver) recIt.next(); Object recData=hski.openGroup(recsData,receiver.getName(),"receiver"); hski.handleScalar(recData,"messagesReceived", receiver.getMessagesReceived()); if (receiver instanceof IReceiverStatistics) { IReceiverStatistics statReceiver = (IReceiverStatistics)receiver; Iterator statsIter; statsIter = statReceiver.getProcessStatisticsIterator(); Object pstatData=hski.openGroup(recData,receiver.getName(),"procStats"); if (statsIter != null) { while(statsIter.hasNext()) { StatisticsKeeper pstat = (StatisticsKeeper) statsIter.next(); hski.handleStatisticsKeeper(pstatData,pstat); } } hski.closeGroup(pstatData); statsIter = statReceiver.getIdleStatisticsIterator(); Object istatData=hski.openGroup(recData,receiver.getName(),"idleStats"); if (statsIter != null) { while(statsIter.hasNext()) { StatisticsKeeper pstat = (StatisticsKeeper) statsIter.next(); hski.handleStatisticsKeeper(istatData,pstat); } } hski.closeGroup(istatData); } hski.closeGroup(recData); } } hski.closeGroup(recsData); Object pipelineData=hski.openGroup(adapterData,getName(),"pipeline"); Hashtable pipelineStatistics = getPipeLineStatistics(); // sort the Hashtable SortedSet sortedKeys = new TreeSet(pipelineStatistics.keySet()); Iterator pipelineStatisticsIter = sortedKeys.iterator(); Object pipestatData=hski.openGroup(pipelineData,getName(),"pipeStats"); while (pipelineStatisticsIter.hasNext()) { String pipeName = (String) pipelineStatisticsIter.next(); StatisticsKeeper pstat = (StatisticsKeeper) pipelineStatistics.get(pipeName); hski.handleStatisticsKeeper(pipestatData,pstat); IPipe pipe = pipeline.getPipe(pipeName); if (pipe instanceof HasStatistics) { ((HasStatistics) pipe).iterateOverStatistics(hski, pipestatData); } } hski.closeGroup(pipestatData); pipestatData=hski.openGroup(pipelineData,getName(),"idleStats"); pipelineStatistics = getWaitingStatistics(); if (pipelineStatistics.size()>0) { // sort the Hashtable sortedKeys = new TreeSet(pipelineStatistics.keySet()); pipelineStatisticsIter = sortedKeys.iterator(); while (pipelineStatisticsIter.hasNext()) { String pipeName = (String) pipelineStatisticsIter.next(); StatisticsKeeper pstat = (StatisticsKeeper) pipelineStatistics.get(pipeName); hski.handleStatisticsKeeper(pipestatData,pstat); } } hski.closeGroup(pipestatData); hski.closeGroup(pipelineData); hski.closeGroup(adapterData); } /** * the functional name of this adapter * @return the name of the adapter */ public String getName() { return name; } /** * The number of messages for which processing ended unsuccessfully. */ public long getNumOfMessagesInError() { synchronized (statsMessageProcessingDuration) { return numOfMessagesInError; } } public int getNumOfMessagesInProcess() { synchronized (statsMessageProcessingDuration) { return numOfMessagesInProcess; } } /** * Total of messages processed * @return long total messages processed */ public long getNumOfMessagesProcessed() { synchronized (statsMessageProcessingDuration) { return numOfMessagesProcessed; } } public Hashtable getPipeLineStatistics() { return pipeline.getPipeStatistics(); } public IReceiver getReceiverByName(String receiverName) { Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); if (receiver.getName().equalsIgnoreCase(receiverName)) { return receiver; } } return null; } public Iterator getReceiverIterator() { return receivers.iterator(); } public PipeLine getPipeLine() { return pipeline; } public RunStateEnum getRunState() { return runState.getRunState(); } public String getRunStateAsString() { return runState.getRunState().toString(); } /** * Return the total processing duration as a StatisticsKeeper * @see nl.nn.adapterframework.util.StatisticsKeeper * @return nl.nn.adapterframework.util.StatisticsKeeper */ public StatisticsKeeper getStatsMessageProcessingDuration() { return statsMessageProcessingDuration; } public String getStatsUpSince() { return DateUtils.format(new Date(statsUpSince), DateUtils.FORMAT_FULL_GENERIC); } /** * Retrieve the waiting statistics as a <code>Hashtable</code> */ public Hashtable getWaitingStatistics() { return pipeline.getPipeWaitingStatistics(); } /** * * Process the receiving of a message * After all Pipes have been run in the PipeLineProcessor, the Object.toString() function * is called. The result is returned to the Receiver. * */ public PipeLineResult processMessage(String messageId, String message) { return processMessage(messageId, message, null); } public PipeLineResult processMessage(String messageId, String message, PipeLineSession pipeLineSession) { long startTime = System.currentTimeMillis(); try { return processMessageWithExceptions(messageId, message, pipeLineSession); } catch (Throwable t) { PipeLineResult result = new PipeLineResult(); result.setState(getErrorState()); String msg = "Illegal exception ["+t.getClass().getName()+"]"; INamedObject objectInError = null; if (t instanceof ListenerException) { Throwable cause = ((ListenerException) t).getCause(); if (cause instanceof PipeRunException) { PipeRunException pre = (PipeRunException) cause; msg = "error during pipeline processing"; objectInError = pre.getPipeInError(); } else if (cause instanceof ManagedStateException) { msg = "illegal state"; objectInError = this; } } result.setResult(formatErrorMessage(msg, t, message, messageId, objectInError, startTime)); if (isRequestReplyLogging()) { log.info("Adapter [" + getName() + "] messageId [" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } else { if (log.isDebugEnabled()) { log.debug("Adapter [" + getName() + "] messageId [" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } } return result; } } public PipeLineResult processMessageWithExceptions(String messageId, String message, PipeLineSession pipeLineSession) throws ListenerException { PipeLineResult result = new PipeLineResult(); long startTime = System.currentTimeMillis(); // prevent executing a stopped adapter // the receivers should implement this, but you never now.... RunStateEnum currentRunState = getRunState(); if (!currentRunState.equals(RunStateEnum.STARTED) && !currentRunState.equals(RunStateEnum.STOPPING)) { String msgAdapterNotOpen = "Adapter [" + getName() + "] in state [" + currentRunState + "], cannot process message"; throw new ListenerException(new ManagedStateException(msgAdapterNotOpen)); } incNumOfMessagesInProcess(startTime); String lastNDC=NDC.peek(); String newNDC="cid [" + messageId + "]"; boolean ndcChanged=!newNDC.equals(lastNDC); if (ndcChanged) { NDC.push(newNDC); } if (isRequestReplyLogging()) { if (log.isInfoEnabled()) log.info("Adapter [" + name + "] received message [" + message + "] with messageId [" + messageId + "]"); } else { if (log.isDebugEnabled()) { log.debug("Adapter [" + name + "] received message [" + message + "] with messageId [" + messageId + "]"); } else { log.info("Adapter [" + name + "] received message with messageId [" + messageId + "]"); } } try { result = pipeline.process(messageId, message,pipeLineSession); if (isRequestReplyLogging()) { log.info("Adapter [" + getName() + "] messageId[" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } else { if (log.isDebugEnabled()) { log.debug("Adapter [" + getName() + "] messageId[" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } } return result; } catch (Throwable t) { ListenerException e; if (t instanceof ListenerException) { e = (ListenerException) t; } else { e = new ListenerException(t); } incNumOfMessagesInError(); error(false, "error processing message with messageId [" + messageId+"]: ",e); throw e; } finally { long endTime = System.currentTimeMillis(); long duration = endTime - startTime; //reset the InProcess fields, and increase processedMessagesCount decNumOfMessagesInProcess(duration); if (log.isDebugEnabled()) { // for performance reasons log.debug("Adapter: [" + getName() + "] STAT: Finished processing message with messageId [" + messageId + "] exit-state [" + result.getState() + "] started " + DateUtils.format(new Date(startTime), DateUtils.FORMAT_FULL_GENERIC) + " finished " + DateUtils.format(new Date(endTime), DateUtils.FORMAT_FULL_GENERIC) + " total duration: " + duration + " msecs"); } else { log.info("Adapter [" + getName() + "] completed message with messageId [" + messageId + "] with exit-state [" + result.getState() + "]"); } if (ndcChanged) { NDC.pop(); } } } /** * Register a PipeLine at this adapter. On registering, the adapter performs * a <code>Pipeline.configurePipes()</code>, as to configure the individual pipes. * @param pipeline * @throws ConfigurationException * @see PipeLine */ public void registerPipeLine(PipeLine pipeline) throws ConfigurationException { this.pipeline = pipeline; pipeline.setAdapter(this); log.debug("Adapter [" + name + "] registered pipeline [" + pipeline.toString() + "]"); } /** * Register a receiver for this Adapter * @param receiver * @see IReceiver */ public void registerReceiver(IReceiver receiver) { boolean receiverActive=true; if (receiver instanceof ReceiverBase) { receiverActive=((ReceiverBase)receiver).isActive(); } if (receiverActive) { receivers.add(receiver); log.debug("Adapter [" + name + "] registered receiver [" + receiver.getName() + "] with properties [" + receiver.toString() + "]"); } else { log.debug("Adapter [" + name + "] did not register inactive receiver [" + receiver.getName() + "] with properties [" + receiver.toString() + "]"); } } /** * some functional description of the <code>Adapter</code>/ */ public void setDescription(String description) { this.description = description; } public String getDescription() { return this.description; } /** * Register a <code>ErrorMessageFormatter</code> as the formatter * for this <code>adapter</code> * @param errorMessageFormatter * @see IErrorMessageFormatter */ public void setErrorMessageFormatter(IErrorMessageFormatter errorMessageFormatter) { this.errorMessageFormatter = errorMessageFormatter; } /** * state to put in PipeLineResult when a PipeRunException occurs * @param newErrorState java.lang.String * @see PipeLineResult */ public void setErrorState(java.lang.String newErrorState) { errorState = newErrorState; } /** * state to put in PipeLineResult when a PipeRunException occurs. */ public String getErrorState() { return errorState; } /** * Set the number of messages that are kept on the screen. * @param size * @see nl.nn.adapterframework.util.MessageKeeper */ public void setMessageKeeperSize(int size) { this.messageKeeperSize = size; } /** * the functional name of this adapter */ public void setName(String name) { this.name = name; } /** * Start the adapter. The thread-name will be set tot the adapter's name. * The run method, called by t.start(), will call the startRunning method * of the IReceiver. The Adapter will be a new thread, as this interface * extends the <code>Runnable</code> interface. The actual starting is done * in the <code>run</code> method. * @see IReceiver#startRunning() * @see Adapter#run */ public void startRunning() { taskExecutor.execute(new Runnable() { public void run() { Thread.currentThread().setName("starting Adapter "+getName()); try { if (!configurationSucceeded) { log.error( "configuration of adapter [" + getName() + "] did not succeed, therefore starting the adapter is not possible"); warn("configuration did not succeed. Starting the adapter is not possible"); runState.setRunState(RunStateEnum.ERROR); return; } synchronized (runState) { RunStateEnum currentRunState = getRunState(); if (!currentRunState.equals(RunStateEnum.STOPPED)) { String msg = "currently in state [" + currentRunState + "], ignoring start() command"; warn(msg); return; } // start the pipeline runState.setRunState(RunStateEnum.STARTING); } try { log.debug("Adapter [" + getName() + "] is starting pipeline"); pipeline.start(); } catch (PipeStartException pre) { error(true, "got error starting PipeLine", pre); runState.setRunState(RunStateEnum.ERROR); return; } // as from version 3.0 the adapter is started, // regardless of receivers are correctly started. runState.setRunState(RunStateEnum.STARTED); getMessageKeeper().add("Adapter up and running"); log.info("Adapter [" + getName() + "] up and running"); // starting receivers Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); if (receiver.getRunState() != RunStateEnum.ERROR) { log.info("Adapter [" + getName() + "] is starting receiver [" + receiver.getName() + "]"); receiver.startRunning(); } else log.warn("Adapter [" + getName() + "] will NOT start receiver [" + receiver.getName() + "] as it is in state ERROR"); } //while // // wait until the stopRunning is called // waitForRunState(RunStateEnum.STOPPING); } catch (Throwable e) { log.error("error running adapter [" + getName() + "] [" + ToStringBuilder.reflectionToString(e) + "]", e); runState.setRunState(RunStateEnum.ERROR); } } // End Runnable.run() }); // End Runnable } // End startRunning() /** * Stop the <code>Adapter</code> and close all elements like receivers, * Pipeline, pipes etc. * The adapter * will call the <code>IReceiver</code> to <code>stopListening</code> * <p>Also the <code>PipeLine.close()</code> method will be called, * closing alle registered pipes. </p> * @see IReceiver#stopRunning * @see PipeLine#stop */ public void stopRunning() { synchronized (runState) { RunStateEnum currentRunState = getRunState(); if (!currentRunState.equals(RunStateEnum.STARTED) && (!currentRunState.equals(RunStateEnum.ERROR))) { warn("in state [" + currentRunState + "] while stopAdapter() command is issued, ignoring command"); return; } if (currentRunState.equals(RunStateEnum.ERROR)) { runState.setRunState(RunStateEnum.STOPPED); return; } runState.setRunState(RunStateEnum.STOPPING); } taskExecutor.execute(new Runnable() { public void run() { Thread.currentThread().setName("stopping Adapter " +getName()); try { log.debug("Adapter [" + name + "] is stopping receivers"); Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); try { receiver.stopRunning(); log.info("Adapter [" + name + "] successfully stopped receiver [" + receiver.getName() + "]"); } catch (Exception e) { error(false, "received error while stopping receiver [" + receiver.getName() + "], ignoring this, so watch out.", e); } } // stop the adapter log.debug("***stopping adapter"); it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); receiver.waitForRunState(RunStateEnum.STOPPED); log.info("Adapter [" + getName() + "] stopped [" + receiver.getName() + "]"); } int currentNumOfMessagesInProcess = getNumOfMessagesInProcess(); if (currentNumOfMessagesInProcess > 0) { String msg = "Adapter [" + name + "] is being stopped while still processing " + currentNumOfMessagesInProcess + " messages, waiting for them to finish"; warn(msg); } waitForNoMessagesInProcess(); log.debug("Adapter [" + name + "] is stopping pipeline"); pipeline.stop(); runState.setRunState(RunStateEnum.STOPPED); getMessageKeeper().add("Adapter stopped"); } catch (Throwable e) { log.error("error running adapter [" + getName() + "] [" + ToStringBuilder.reflectionToString(e) + "]", e); runState.setRunState(RunStateEnum.ERROR); } } // End of run() }); // End of Runnable } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[name=" + name + "]"); sb.append("[version=" + version + "]"); sb.append("[targetDesignDocument=" + targetDesignDocument + "]"); Iterator it = receivers.iterator(); sb.append("[receivers="); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); sb.append(" " + receiver.getName()); } sb.append("]"); sb.append( "[pipeLine=" + ((pipeline != null) ? pipeline.toString() : "none registered") + "]" + "[started=" + getRunState() + "]"); return sb.toString(); } public void waitForNoMessagesInProcess() throws InterruptedException { synchronized (statsMessageProcessingDuration) { while (getNumOfMessagesInProcess() > 0) { wait(); } } } public void waitForRunState(RunStateEnum requestedRunState) throws InterruptedException { runState.waitForRunState(requestedRunState); } public boolean waitForRunState(RunStateEnum requestedRunState, long maxWait) throws InterruptedException { return runState.waitForRunState(requestedRunState, maxWait); } /** * AutoStart indicates that the adapter should be started when the configuration * is started. AutoStart defaults to <code>true</code> * @since 4.1.1 */ public void setAutoStart(boolean autoStart) { this.autoStart = autoStart; } public boolean isAutoStart() { return autoStart; } public void setRequestReplyLogging(boolean requestReplyLogging) { this.requestReplyLogging = requestReplyLogging; } public boolean isRequestReplyLogging() { return requestReplyLogging; } public void setActive(boolean b) { active = b; } public boolean isActive() { return active; } public void setTargetDesignDocument(String string) { targetDesignDocument = string; } public String getTargetDesignDocument() { return targetDesignDocument; } public void setTaskExecutor(TaskExecutor executor) { taskExecutor = executor; } public TaskExecutor getTaskExecutor() { return taskExecutor; } /* (non-Javadoc) * @see org.springframework.beans.factory.NamedBean#getBeanName() */ public String getBeanName() { return name; } }
package com.googlecode.jmxtrans.util; import java.io.File; import java.io.IOException; import java.lang.reflect.Array; import java.rmi.UnmarshalException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.MBeanAttributeInfo; import javax.management.MBeanInfo; import javax.management.MBeanServerConnection; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; import javax.management.openmbean.TabularDataSupport; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; import org.codehaus.jackson.map.SerializationConfig.Feature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.googlecode.jmxtrans.OutputWriter; import com.googlecode.jmxtrans.model.JmxProcess; import com.googlecode.jmxtrans.model.Query; import com.googlecode.jmxtrans.model.Result; import com.googlecode.jmxtrans.model.Server; /** * The worker code. * * @author jon */ public class JmxUtils { private static final Logger log = LoggerFactory.getLogger(JmxUtils.class); /** * Either invokes the queries multithreaded (max threads == server.getMultiThreaded()) * or invokes them one at a time. */ public static void processQueriesForServer(final MBeanServerConnection mbeanServer, Server server) throws Exception { if (server.isQueriesMultiThreaded()) { ExecutorService service = null; try { service = Executors.newFixedThreadPool(server.getNumQueryThreads()); List<Callable<Object>> threads = new ArrayList<Callable<Object>>(server.getQueries().size()); for (Query query : server.getQueries()) { query.setServer(server); ProcessQueryThread pqt = new ProcessQueryThread(mbeanServer, query); threads.add(Executors.callable(pqt)); } service.invokeAll(threads); } finally { service.shutdown(); } } else { for (Query query : server.getQueries()) { query.setServer(server); processQuery(mbeanServer, query); } } } /** * Executes either a getAttribute or getAttributes query. */ public static class ProcessQueryThread implements Runnable { private MBeanServerConnection mbeanServer; private Query query; public ProcessQueryThread(MBeanServerConnection mbeanServer, Query query) { this.mbeanServer = mbeanServer; this.query = query; } public void run() { try { processQuery(mbeanServer, query); } catch (Exception e) { log.error("Error executing query", e); throw new RuntimeException(e); } } } public static void processQuery(MBeanServerConnection mbeanServer, Query query) throws Exception { ObjectName oName = new ObjectName(query.getObj()); Set<ObjectName> queryNames = mbeanServer.queryNames(oName, null); for (ObjectName queryName : queryNames) { List<Result> resList = new ArrayList<Result>(); MBeanInfo info = mbeanServer.getMBeanInfo(queryName); ObjectInstance oi = mbeanServer.getObjectInstance(queryName); List<String> queryAttributes = query.getAttr(); if (queryAttributes == null || queryAttributes.size() == 0) { MBeanAttributeInfo[] attrs = info.getAttributes(); for (MBeanAttributeInfo attrInfo : attrs) { query.addAttr(attrInfo.getName()); } } try { if (query.getAttr() != null && query.getAttr().size() > 0) { log.debug("Started query: " + query); AttributeList al = mbeanServer.getAttributes(queryName, query.getAttr().toArray(new String[query.getAttr().size()])); for (Attribute attribute : al.asList()) { getResult(resList, info, oi, (Attribute)attribute, query); } if (log.isDebugEnabled()) { log.debug("Finished query."); } query.setResults(resList); // Now run the filters. runFiltersForQuery(query); if (log.isDebugEnabled()) { log.debug("Finished running filters: " + query); } } } catch (UnmarshalException ue) { if (ue.getCause() != null && ue.getCause() instanceof ClassNotFoundException) { log.debug("Bad unmarshall, continuing. This is probably ok and due to something like this: " + "http://ehcache.org/xref/net/sf/ehcache/distribution/RMICacheManagerPeerListener.html#52", ue.getMessage()); } } } } /** * Populates the Result objects. This is a recursive function. Query contains the * keys that we want to get the values of. */ private static void getResult(List<Result> resList, MBeanInfo info, ObjectInstance oi, String attributeName, CompositeData cds, Query query) { CompositeType t = cds.getCompositeType(); Result r = getNewResultObject(info, oi, attributeName, query); Set<String> keys = t.keySet(); for (String key : keys) { Object value = cds.get(key); if (value instanceof TabularDataSupport) { TabularDataSupport tds = (TabularDataSupport) value; processTabularDataSupport(resList, info, oi, r, attributeName + "." + key, tds, query); r.addValue(key, value.toString()); } else if (value instanceof CompositeDataSupport) { // now recursively go through everything. CompositeDataSupport cds2 = (CompositeDataSupport) value; getResult(resList, info, oi, attributeName, (CompositeDataSupport)cds2, query); return; // because we don't want to add to the list yet. } else { r.addValue(key, value.toString()); } } resList.add(r); } private static void processTabularDataSupport(List<Result> resList, MBeanInfo info, ObjectInstance oi, Result r, String attributeName, TabularDataSupport tds, Query query) { Set<Entry<Object,Object>> entries = tds.entrySet(); for (Entry<Object, Object> entry : entries) { Object entryKeys = entry.getKey(); if (entryKeys instanceof List) { // ie: attributeName=LastGcInfo.Par Survivor Space // i haven't seen this be smaller or larger than List<1>, but might as well loop it. StringBuilder sb = new StringBuilder(); for (Object entryKey : (List<?>)entryKeys) { sb.append("."); sb.append(entryKey); } String attributeName2 = sb.toString(); Object entryValue = entry.getValue(); if (entryValue instanceof CompositeDataSupport) { getResult(resList, info, oi, attributeName + attributeName2, (CompositeDataSupport)entryValue, query); } else { throw new RuntimeException("!!!!!!!!!! Please file a bug: http://code.google.com/p/jmxtrans/issues/entry entryValue is: " + entryValue.getClass().getCanonicalName()); } } else { throw new RuntimeException("!!!!!!!!!! Please file a bug: http://code.google.com/p/jmxtrans/issues/entry entryKeys is: " + entryKeys.getClass().getCanonicalName()); } } } /** * Builds up the base Result object */ private static Result getNewResultObject(MBeanInfo info, ObjectInstance oi, String attributeName, Query query) { Result r = new Result(attributeName); r.setQuery(query); r.setClassName(info.getClassName()); r.setTypeName(oi.getObjectName().getCanonicalKeyPropertyListString()); return r; } /** * Used when the object is effectively a java type */ private static void getResult(List<Result> resList, MBeanInfo info, ObjectInstance oi, Attribute attribute, Query query) { Object value = attribute.getValue(); if (value != null) { if (value instanceof CompositeDataSupport) { getResult(resList, info, oi, attribute.getName(), (CompositeData) value, query); } else if (value instanceof CompositeData[]) { for (CompositeData cd : (CompositeData[])value) { getResult(resList, info, oi, attribute.getName(), cd, query); } } else if (value instanceof ObjectName[]) { Result r = getNewResultObject(info, oi, attribute.getName(), query); for (ObjectName obj : (ObjectName[])value) { r.addValue(obj.getCanonicalName(), obj.getKeyPropertyListString()); } resList.add(r); } else if (value.getClass().isArray()) { // OMFG: this is nutty. some of the items in the array can be primitive! great interview question! Result r = getNewResultObject(info, oi, attribute.getName(), query); for (int i = 0; i < Array.getLength(value); i++) { Object val = Array.get(value, i); r.addValue(attribute.getName() + "." + i, val); } resList.add(r); } else if (value instanceof TabularDataSupport) { TabularDataSupport tds = (TabularDataSupport) value; Result r = getNewResultObject(info, oi, attribute.getName(), query); processTabularDataSupport(resList, info, oi, r, attribute.getName(), tds, query); resList.add(r); } else { Result r = getNewResultObject(info, oi, attribute.getName(), query); r.addValue(attribute.getName(), value.toString()); resList.add(r); } } } private static void runFiltersForQuery(Query query) throws Exception { List<OutputWriter> filters = query.getOutputWriters(); if (filters != null) { for (OutputWriter filter : filters) { filter.doWrite(query); } } } /** * Generates the proper username/password environment for JMX connections. */ public static Map<String, String[]> getEnvironment(Server server) { Map<String, String[]> environment = new HashMap<String, String[]>(); String username = server.getUsername(); String password = server.getPassword(); if (username != null && password != null) { String[] credentials = new String[2]; credentials[0] = username; credentials[1] = password; environment.put(JMXConnector.CREDENTIALS, credentials); } return environment; } /** * Either invokes the servers multithreaded (max threads == jmxProcess.getMultiThreaded()) * or invokes them one at a time. */ public static void execute(JmxProcess process) throws Exception { if (process.isServersMultiThreaded()) { ExecutorService service = null; try { service = Executors.newFixedThreadPool(process.getNumMultiThreadedServers()); List<Callable<Object>> threads = new ArrayList<Callable<Object>>(process.getServers().size()); for (Server server : process.getServers()) { ProcessServerThread pqt = new ProcessServerThread(server); threads.add(Executors.callable(pqt)); } service.invokeAll(threads); } finally { service.shutdown(); } } else { for (Server server : process.getServers()) { processServer(server); } } } /** * Executes either a getAttribute or getAttributes query. */ public static class ProcessServerThread implements Runnable { private Server server; public ProcessServerThread(Server server) { this.server = server; } public void run() { try { processServer(server); } catch (Exception e) { throw new RuntimeException(e); } } } /** * Helper method for connecting to a Server. You need to close the resulting connection. */ public static JMXConnector getServerConnection(Server server) throws Exception { JMXServiceURL url = new JMXServiceURL(server.getUrl()); return JMXConnectorFactory.connect(url, getEnvironment(server)); } /** * Does the work for processing a Server object. */ public static void processServer(Server server) throws Exception { JMXConnector conn = null; try { conn = getServerConnection(server); MBeanServerConnection mbeanServer = conn.getMBeanServerConnection(); JmxUtils.processQueriesForServer(mbeanServer, server); } catch (IOException e) { log.error("Problem processing queries for server: " + server.getHost() + ":" + server.getPort(), e); } finally { if (conn != null) { conn.close(); } } } /** * Utility function good for testing things. Prints out the json * tree of the JmxProcess. */ public static void printJson(JmxProcess process) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().set(Feature.WRITE_NULL_MAP_VALUES, false); System.out.println(mapper.writeValueAsString(process)); } /** * Utility function good for testing things. Prints out the json * tree of the JmxProcess. */ public static void prettyPrintJson(JmxProcess process) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().set(Feature.WRITE_NULL_MAP_VALUES, false); ObjectWriter writer = mapper.defaultPrettyPrintingWriter(); System.out.println(writer.writeValueAsString(process)); } /** * Uses jackson to load json configuration from a File into a full object * tree representation of that json. */ public static JmxProcess getJmxProcess(File file) throws Exception { ObjectMapper mapper = new ObjectMapper(); JmxProcess jmx = mapper.readValue(file, JmxProcess.class); jmx.setName(file.getName()); return jmx; } /** * Useful for figuring out if an Object is a number. */ public static boolean isNumeric(Object value) { return ((value instanceof String && isNumeric((String)value)) || value instanceof Number || value instanceof Integer || value instanceof Long || value instanceof Double || value instanceof Float); } /** * <p>Checks if the String contains only unicode digits. * A decimal point is a digit and returns true.</p> * * <p><code>null</code> will return <code>false</code>. * An empty String ("") will return <code>true</code>.</p> * * <pre> * StringUtils.isNumeric(null) = false * StringUtils.isNumeric("") = true * StringUtils.isNumeric(" ") = false * StringUtils.isNumeric("123") = true * StringUtils.isNumeric("12 3") = false * StringUtils.isNumeric("ab2c") = false * StringUtils.isNumeric("12-3") = false * StringUtils.isNumeric("12.3") = true * </pre> * * @param str the String to check, may be null * @return <code>true</code> if only contains digits, and is non-null */ public static boolean isNumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { char cat = str.charAt(i); if (cat == '.') { continue; } else if (Character.isDigit(cat) == false) { return false; } } return true; } }
package com.beepscore.android.sunshine.sync; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SyncRequest; import android.content.SyncResult; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.IntDef; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.text.format.Time; import android.util.Log; import com.beepscore.android.sunshine.MainActivity; import com.beepscore.android.sunshine.PreferenceHelper; import com.beepscore.android.sunshine.R; import com.beepscore.android.sunshine.Utility; import com.beepscore.android.sunshine.WeatherHelper; import com.beepscore.android.sunshine.data.WeatherContract; import com.beepscore.android.sunshine.data.WeatherProvider; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.net.HttpURLConnection; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.util.Vector; public class SunshineSyncAdapter extends AbstractThreadedSyncAdapter { public final String LOG_TAG = SunshineSyncAdapter.class.getSimpleName(); // Interval at which to sync with the weather, in seconds. // seconds = hours * 60 minutes/hour * 60 seconds/minute // use a short interval for manual testing. // SYNC_INTERVAL = 30 resulted in about 1 call to onPerformSync every ~ 60 seconds. // Maybe inexact timers are very lenient?? // Maybe downloading and parsing caused it to not be ready after 30 seconds?? Sounds wrong. // public static final int SYNC_INTERVAL = 30; public static final int SYNC_INTERVAL = 3 * 60 * 60; public static final int SYNC_FLEXTIME = SYNC_INTERVAL / 3; private static final String[] NOTIFY_WEATHER_PROJECTION = new String[] { WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, WeatherContract.WeatherEntry.COLUMN_SHORT_DESC }; // these indices must match the projection private static final int INDEX_WEATHER_ID = 0; private static final int INDEX_MAX_TEMP = 1; private static final int INDEX_MIN_TEMP = 2; private static final int INDEX_SHORT_DESC = 3; private static final long DAY_IN_MILLIS = 1000 * 60 * 60 * 24; private static final int WEATHER_NOTIFICATION_ID = 3004; @Retention(RetentionPolicy.SOURCE) @IntDef({LOCATION_STATUS_OK, LOCATION_STATUS_SERVER_DOWN, LOCATION_STATUS_SERVER_INVALID, LOCATION_STATUS_UNKNOWN}) public @interface LocationStatus {} public static final int LOCATION_STATUS_OK = 0; public static final int LOCATION_STATUS_SERVER_DOWN = 1; public static final int LOCATION_STATUS_SERVER_INVALID = 2; public static final int LOCATION_STATUS_UNKNOWN = 3; @LocationStatus public SunshineSyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); } public static void initializeSyncAdapter(Context context) { getSyncAccount(context); } /** * Helper method to get the fake account to be used with SyncAdapter, or make a new one * if the fake account doesn't exist yet. If we make a new account, we call the * onAccountCreated method so we can initialize things. * * @param context The context used to access the account service * @return a fake account. */ public static Account getSyncAccount(Context context) { // Get an instance of the Android account manager AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); // Create the account type and default account Account newAccount = new Account( context.getString(R.string.app_name), context.getString(R.string.sync_account_type)); // If the password doesn't exist, the account doesn't exist if ( null == accountManager.getPassword(newAccount) ) { /* * Add the account and account type, no password or user data * If successful, return the Account object, otherwise report an error. */ if (!accountManager.addAccountExplicitly(newAccount, "", null)) { return null; } /* * If you don't set android:syncable="true" in * in your <provider> element in the manifest, * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1) * here. */ onAccountCreated(newAccount, context); } return newAccount; } private static void onAccountCreated(Account newAccount, Context context) { /* * Since we've created an account */ SunshineSyncAdapter.configurePeriodicSync(context, SYNC_INTERVAL, SYNC_FLEXTIME); /* * Without calling setSyncAutomatically, our periodic sync will not be enabled. */ ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true); /* * Finally, let's do a sync to get things started */ syncImmediately(context); } /** * Helper method to schedule the sync adapter periodic execution */ public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) { Log.d("SunshineSyncAdapter", "configurePeriodicSync"); Account account = getSyncAccount(context); String authority = context.getString(R.string.content_authority); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // we can enable inexact timers in our periodic sync SyncRequest request = new SyncRequest.Builder(). syncPeriodic(syncInterval, flexTime). setSyncAdapter(account, authority). setExtras(new Bundle()).build(); ContentResolver.requestSync(request); } else { ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval); } } /** * Helper method to have the sync adapter sync immediately * @param context The context used to access the account service */ public static void syncImmediately(Context context) { Bundle bundle = new Bundle(); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle); } @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { Log.d(LOG_TAG, "onPerformSync"); String locationQuery = Utility.getPreferredLocation(getContext()); if (locationQuery == null) { return; } // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; // assume ok, then error or exception can re-set setLocationStatus(getContext(), LOCATION_STATUS_OK); try { Uri builtUri = WeatherHelper.weatherUri(locationQuery, format, units, numDays); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { setLocationStatus(getContext(), LOCATION_STATUS_UNKNOWN); return; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. setLocationStatus(getContext(), LOCATION_STATUS_SERVER_DOWN); return; } forecastJsonStr = buffer.toString(); if (forecastJsonStr.contains("Error: Not found city")) { Log.e(LOG_TAG, "Error: Not found city"); setLocationStatus(getContext(), LOCATION_STATUS_UNKNOWN); return; } getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (UnknownHostException e) { // UnknownHostException extends IOException Log.e(LOG_TAG, "UnknownHostException ", e); setLocationStatus(getContext(), LOCATION_STATUS_SERVER_DOWN); } catch (FileNotFoundException e) { // FileNotFoundException extends IOException Log.e(LOG_TAG, "FileNotFoundException ", e); setLocationStatus(getContext(), LOCATION_STATUS_SERVER_DOWN); } catch (SocketException e) { // SocketException extends IOException Log.e(LOG_TAG, "SocketException ", e); setLocationStatus(getContext(), LOCATION_STATUS_SERVER_DOWN); } catch (IOException e) { // catch any remaining IOExceptions not already caught above // for example if forecastJsonStr == null Log.e(LOG_TAG, "IOException ", e); // If the code didn't successfully get the weather data, there's no point in attempting // to parse it. setLocationStatus(getContext(), LOCATION_STATUS_SERVER_DOWN); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); setLocationStatus(getContext(), LOCATION_STATUS_SERVER_INVALID); } finally { Log.v(LOG_TAG, "location status " + getLocationStatus(getContext())); if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } } /** * Parses forecastJsonStr * This method has side effects * inserts values in content provider and calls notifyWeather * @param forecastJsonStr the complete forecast in JSON format */ public void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OpenWeatherMap OWM returns daily forecasts based upon the local time // of the city that is being asked for, // which means that we need to know the GMT offset to translate this data properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for(int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay+i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } int inserted = 0; if ( cVVector.size() > 0 ) { // add to database // evaluates to content://com.beepscore.android.sunshine/weather Uri weatherUri = WeatherContract.WeatherEntry.CONTENT_URI; ContentValues[] weatherContentValues = cVVector.toArray(new ContentValues[0]); // call bulkInsert to add the weatherEntries to the database inserted = getContext().getContentResolver().bulkInsert(weatherUri, weatherContentValues); // delete old data String[] selectionArgs = new String[]{Long.toString(dayTime.setJulianDay(julianStartDay))}; int numberOfRowsDeleted = getContext().getContentResolver().delete(weatherUri, WeatherProvider.sBeforeDateSelection, selectionArgs); Log.d(LOG_TAG, "numberOfRowsDeleted " + String.valueOf(numberOfRowsDeleted)); notifyWeather(); } Log.d(LOG_TAG, "getWeatherDataFromJson Complete. " + inserted + " Inserted"); setLocationStatus(getContext(), LOCATION_STATUS_OK); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); setLocationStatus(getContext(), LOCATION_STATUS_SERVER_INVALID); } } /** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * e.g. "Sunnydale, CA" * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city * @param lon the longitude of the city * @return the row ID of the added location. */ public long addLocation(String locationSetting, String cityName, double lat, double lon) { Cursor locationCursor = getLocationCursor(locationSetting); long locationRowId = -1; if (locationCursor != null && locationCursor.moveToFirst()) { // location with this locationSetting already exists in content provider locationRowId = locationCursor.getLong(locationCursor.getColumnIndex("_id")); } else if (locationSetting != null && cityName != null) { locationRowId = addNewLocation(locationSetting, cityName, lat, lon); } if (locationCursor != null) { locationCursor.close(); } return locationRowId; } /** * queries content provider * @param locationSetting The location string used to request updates from the server. * Note multiple locationSettings could have the same cityName. * @return a Cursor with location _IDs that match locationSetting */ private Cursor getLocationCursor(String locationSetting) { // Query content provider, not database // More flexible design, easier to change content provider to use a different underlying source // e.g. "content://com.beepscore.android.sunshine/location" Uri locationUri = WeatherContract.LocationEntry.CONTENT_URI; // we need only column _ID String[] projection = {WeatherContract.LocationEntry._ID}; String selection = WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? "; String[] selectionArgs = {locationSetting}; return getContext().getContentResolver().query( locationUri, projection, selection, selectionArgs, null // sort order ); } private long addNewLocation(String locationSetting, String cityName, double lat, double lon) { Uri locationUri = WeatherContract.LocationEntry.CONTENT_URI; ContentValues contentValues = new ContentValues(); contentValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); contentValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); // e.g. content://com.beepscore.android.sunshine/location/2 Uri locationRowUri = getContext().getContentResolver().insert(locationUri, contentValues); long locationRowId = Long.valueOf(locationRowUri.getLastPathSegment()); return locationRowId; } private void notifyWeather() { Context context = getContext(); // In Sunshine, can tap Settings / Refresh to generate a notification //check the last update and notify if it's the first of the day long lastSync = PreferenceHelper.getLastSyncPreference(context); //int TIME_BETWEEN_NOTIFICATIONS_MIN_MSEC = DAY_IN_MILLIS; // for testing use a short time int TIME_BETWEEN_NOTIFICATIONS_MIN_MSEC = 10000; if (PreferenceHelper.getEnableNotificationPreference(context) && (System.currentTimeMillis() - lastSync >= TIME_BETWEEN_NOTIFICATIONS_MIN_MSEC)) { // Last sync was more than 1 day ago, let's send a notification with the weather. String locationQuery = Utility.getPreferredLocation(context); Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationQuery, System.currentTimeMillis()); // we'll query our contentProvider, as always Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null, null, null); if (cursor.moveToFirst()) { int weatherId = cursor.getInt(INDEX_WEATHER_ID); double high = cursor.getDouble(INDEX_MAX_TEMP); double low = cursor.getDouble(INDEX_MIN_TEMP); String desc = cursor.getString(INDEX_SHORT_DESC); // fix sample code to match method class //int iconId = Utility.getIconResourceForWeatherCondition(weatherId); int iconId = WeatherHelper.getIconResourceForWeatherCondition(weatherId); String title = context.getString(R.string.app_name); // Define the text of the forecast. // String contentText = String.format(context.getString(R.string.format_notification), // desc, // Utility.formatTemperature(context, high), // Utility.formatTemperature(context, low)); // see gist comments boolean isMetric = Utility.isMetric(context); String contentText = String.format(context.getString(R.string.format_notification), desc, Utility.formatTemperature(context, high, isMetric), Utility.formatTemperature(context, low, isMetric)); // Build notification // explicit intent for what the notification should open Intent intent = new Intent(context, MainActivity.class); // Create an artificial "backstack" for user to tap Back TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); taskStackBuilder.addNextIntent(intent); // pIntent is triggered if the notification is selected // use System.currentTimeMillis() to have a unique ID for the pending intent PendingIntent pIntent = taskStackBuilder.getPendingIntent((int) System.currentTimeMillis(), PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = new NotificationCompat.Builder(context) .setContentTitle(title) .setContentText(contentText) .setSmallIcon(iconId) .setContentIntent(pIntent) .setAutoCancel(true) .build(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(WEATHER_NOTIFICATION_ID, notification); PreferenceHelper.setLastSyncPreference(context, System.currentTimeMillis()); } } } public @LocationStatus int getLocationStatus(Context context) { // In SharedPreferences get value for key SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String locationStatusKey = context.getString(R.string.pref_location_status_key); // if no key-value pair for locationStatusKey, default to LOCATION_STATUS_UNKNOWN return preferences.getInt(locationStatusKey, LOCATION_STATUS_UNKNOWN); } /** * Sets the location status into shared preferences. * This should not be called from the UI thread * because it uses commit to write to the shared preferences. * @param context * @param locationStatus */ public void setLocationStatus(Context context, @LocationStatus int locationStatus) { // In SharedPreferences set key/value pair SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = preferences.edit(); String locationStatusKey = context.getString(R.string.pref_location_status_key); editor.putInt(locationStatusKey, locationStatus); // use commit() for background thread // for foreground thread use apply() editor.commit(); } }
/* * $Log: JtaUtil.java,v $ * Revision 1.11 2007-05-08 16:01:21 europe\L190409 * removed stacktrace from debug-logging while obtaining user-transaction * * Revision 1.10 2007/02/12 14:12:03 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Logger from LogUtil * * Revision 1.9 2006/09/18 11:46:36 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * lookup UserTransaction only when necessary * * Revision 1.8 2006/09/14 11:47:10 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * optimized transactionStateCompatible() * * Revision 1.7 2006/08/21 15:14:49 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * introduction of transaction attribute handling * configuration of user transaction url in appconstants.properties * * Revision 1.6 2005/09/08 15:58:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added logging * * Revision 1.5 2004/10/05 09:57:38 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * made version public * * Revision 1.4 2004/03/31 15:03:26 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * fixed javadoc * * Revision 1.3 2004/03/26 10:42:38 Johan Verrips <johan.verrips@ibissource.org> * added @version tag in javadoc * * Revision 1.2 2004/03/26 09:50:52 Johan Verrips <johan.verrips@ibissource.org> * Updated javadoc * * Revision 1.1 2004/03/23 17:14:31 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * initial version * */ package nl.nn.adapterframework.util; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.transaction.NotSupportedException; import javax.transaction.Status; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; import nl.nn.adapterframework.core.TransactionException; import org.apache.log4j.Logger; /** * Utility functions for JTA * @version Id * @author Gerrit van Brakel * @since 4.1 */ public class JtaUtil { public static final String version="$RCSfile: JtaUtil.java,v $ $Revision: 1.11 $ $Date: 2007-05-08 16:01:21 $"; private static Logger log = LogUtil.getLogger(JtaUtil.class); private static final String USERTRANSACTION_URL1_KEY="jta.userTransactionUrl1"; private static final String USERTRANSACTION_URL2_KEY="jta.userTransactionUrl2"; public static final int TRANSACTION_ATTRIBUTE_REQUIRED=0; public static final int TRANSACTION_ATTRIBUTE_REQUIRES_NEW=1; public static final int TRANSACTION_ATTRIBUTE_MANDATORY=2; public static final int TRANSACTION_ATTRIBUTE_NOT_SUPPORTED=3; public static final int TRANSACTION_ATTRIBUTE_SUPPORTS=4; public static final int TRANSACTION_ATTRIBUTE_NEVER=5; public static final int TRANSACTION_ATTRIBUTE_DEFAULT=TRANSACTION_ATTRIBUTE_SUPPORTS; public static final String TRANSACTION_ATTRIBUTE_REQUIRED_STR="Required"; public static final String TRANSACTION_ATTRIBUTE_REQUIRES_NEW_STR="RequiresNew"; public static final String TRANSACTION_ATTRIBUTE_MANDATORY_STR="Mandatory"; public static final String TRANSACTION_ATTRIBUTE_NOT_SUPPORTED_STR="NotSupported"; public static final String TRANSACTION_ATTRIBUTE_SUPPORTS_STR="Supports"; public static final String TRANSACTION_ATTRIBUTE_NEVER_STR="Never"; public static final String transactionAttributes[]= { TRANSACTION_ATTRIBUTE_REQUIRED_STR, TRANSACTION_ATTRIBUTE_REQUIRES_NEW_STR, TRANSACTION_ATTRIBUTE_MANDATORY_STR, TRANSACTION_ATTRIBUTE_NOT_SUPPORTED_STR, TRANSACTION_ATTRIBUTE_SUPPORTS_STR, TRANSACTION_ATTRIBUTE_NEVER_STR }; private static UserTransaction utx; /** * returns a meaningful string describing the transaction status. */ public static String displayTransactionStatus(int status) { switch (status) { case Status.STATUS_ACTIVE : return status+"=STATUS_ACTIVE:"+ " A transaction is associated with the target object and it is in the active state."; case Status.STATUS_COMMITTED : return status+"=STATUS_COMMITTED:"+ " A transaction is associated with the target object and it has been committed."; case Status.STATUS_COMMITTING : return status+"=STATUS_COMMITTING:"+ " A transaction is associated with the target object and it is in the process of committing."; case Status.STATUS_MARKED_ROLLBACK : return status+"=STATUS_MARKED_ROLLBACK:"+" A transaction is associated with the target object and it has been marked for rollback, perhaps as a result of a setRollbackOnly operation."; case Status.STATUS_NO_TRANSACTION : return status+"=STATUS_NO_TRANSACTION:"+ " No transaction is currently associated with the target object."; case Status.STATUS_PREPARED : return status+"=STATUS_PREPARED:"+ " A transaction is associated with the target object and it has been prepared."; case Status.STATUS_PREPARING : return status+"=STATUS_PREPARING:"+ " A transaction is associated with the target object and it is in the process of preparing."; case Status.STATUS_ROLLEDBACK : return status+"=STATUS_ROLLEDBACK:"+ " A transaction is associated with the target object and the outcome has been determined to be rollback."; case Status.STATUS_ROLLING_BACK : return status+"=STATUS_ROLLING_BACK:"+ " A transaction is associated with the target object and it is in the process of rolling back."; case Status.STATUS_UNKNOWN : return status+"=STATUS_UNKNOWN:"+ " A transaction is associated with the target object but its current status cannot be determined."; default : return "unknown transaction status"; } } /** * Convenience function for {@link #displayTransactionStatus(int status)} */ public static String displayTransactionStatus(Transaction tx) { try { return displayTransactionStatus(tx.getStatus()); } catch (Exception e) { return "exception obtaining transaction status from transaction ["+tx+"]: "+e.getMessage(); } } /** * Convenience function for {@link #displayTransactionStatus(int status)} */ public static String displayTransactionStatus(UserTransaction utx) { try { return displayTransactionStatus(utx.getStatus()); } catch (Exception e) { return "exception obtaining transaction status from transaction ["+utx+"]: "+e.getMessage(); } } /** * Convenience function for {@link #displayTransactionStatus(int status)} */ public static String displayTransactionStatus(TransactionManager tm) { try { return displayTransactionStatus(tm.getStatus()); } catch (Exception e) { return "exception obtaining transaction status from transactionmanager ["+tm+"]: "+e.getMessage(); } } /** * Convenience function for {@link #displayTransactionStatus(int status)} */ public static String displayTransactionStatus() { UserTransaction utx; try { utx = getUserTransaction(); } catch (Exception e) { return "exception obtaining user transaction: "+e.getMessage(); } return displayTransactionStatus(utx); } /** * returns true if the current thread is associated with a transaction */ public static boolean inTransaction(UserTransaction utx) throws SystemException { return utx != null && utx.getStatus() != Status.STATUS_NO_TRANSACTION; } /** * Returns a UserTransaction object, that is used by Receivers and PipeLines to demarcate transactions. */ public static UserTransaction getUserTransaction(Context ctx, String userTransactionUrl) throws NamingException { if (utx == null) { log.debug("looking up UserTransaction ["+userTransactionUrl+"] in context ["+ctx.toString()+"]"); utx = (UserTransaction)ctx.lookup(userTransactionUrl); } return utx; } /** * Returns a UserTransaction object, that is used by Receivers and PipeLines to demarcate transactions. */ public static UserTransaction getUserTransaction() throws NamingException { if (utx == null) { Context ctx= (Context) new InitialContext(); String url = AppConstants.getInstance().getProperty(USERTRANSACTION_URL1_KEY,null); log.debug("looking up UserTransaction ["+url+"] in context ["+ctx.toString()+"]"); try { utx = (UserTransaction)ctx.lookup(url); } catch (Exception e) { log.debug("Could not lookup UserTransaction from url ["+url+"], will try alternative uri: "+e.getMessage()); url = AppConstants.getInstance().getProperty(USERTRANSACTION_URL2_KEY,null); log.debug("looking up UserTransaction ["+url+"] in context ["+ctx.toString()+"]"); utx = (UserTransaction)ctx.lookup(url); } } return utx; } public static int getTransactionAttributeNum(String transactionAttribute) { int i=transactionAttributes.length-1; while (i>=0 && !transactionAttributes[i].equalsIgnoreCase(transactionAttribute)) i--; // try next return i; } public static String getTransactionAttributeString(int transactionAttribute) { if (transactionAttribute<0 || transactionAttribute>=transactionAttributes.length) { return "UnknownTransactionAttribute:"+transactionAttribute; } return transactionAttributes[transactionAttribute]; } public static boolean transactionStateCompatible(int transactionAttribute) throws SystemException, NamingException { if (transactionAttribute==TRANSACTION_ATTRIBUTE_NEVER) { return !inTransaction(getUserTransaction()); } else if (transactionAttribute==TRANSACTION_ATTRIBUTE_MANDATORY) { return inTransaction(getUserTransaction()); } return true; } public static boolean isolationRequired(int transactionAttribute) throws SystemException, TransactionException, NamingException { if (transactionAttribute!=TRANSACTION_ATTRIBUTE_REQUIRES_NEW && transactionAttribute!=TRANSACTION_ATTRIBUTE_NOT_SUPPORTED) { return false; } if (!transactionStateCompatible(transactionAttribute)) { throw new TransactionException("transaction attribute ["+getTransactionAttributeString(transactionAttribute)+"] not compatible with state ["+displayTransactionStatus(utx)+"]"); } UserTransaction utx = getUserTransaction(); return inTransaction(utx) && (transactionAttribute==TRANSACTION_ATTRIBUTE_REQUIRES_NEW || transactionAttribute==TRANSACTION_ATTRIBUTE_NOT_SUPPORTED); } public static boolean newTransactionRequired(int transactionAttribute) throws SystemException, TransactionException, NamingException { if (!transactionStateCompatible(transactionAttribute)) { throw new TransactionException("transaction attribute ["+getTransactionAttributeString(transactionAttribute)+"] not compatible with state ["+displayTransactionStatus(utx)+"]"); } if (transactionAttribute==TRANSACTION_ATTRIBUTE_REQUIRED) { UserTransaction utx = getUserTransaction(); return !inTransaction(utx); } return transactionAttribute==TRANSACTION_ATTRIBUTE_REQUIRES_NEW; } private static boolean stateEvaluationRequired(int transactionAttribute) { return transactionAttribute>=0 && transactionAttribute!=TRANSACTION_ATTRIBUTE_REQUIRES_NEW && transactionAttribute!=TRANSACTION_ATTRIBUTE_SUPPORTS; } public static void startTransaction() throws NamingException, NotSupportedException, SystemException { log.debug("starting new transaction"); utx=getUserTransaction(); utx.begin(); } public static void finishTransaction() throws NamingException, IllegalStateException, SecurityException, SystemException { finishTransaction(false); } public static void finishTransaction(boolean rollbackonly) throws NamingException, IllegalStateException, SecurityException, SystemException { utx=getUserTransaction(); try { if (inTransaction(utx) && !rollbackonly) { log.debug("committing transaction"); utx.commit(); } else { log.debug("rolling back transaction"); utx.rollback(); } } catch (Throwable t1) { try { log.warn("trying to roll back transaction after exception",t1); utx.rollback(); } catch (Throwable t2) { log.warn("exception rolling back transaction",t2); } } } }
package com.beepscore.android.sunshine.sync; import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SyncRequest; import android.content.SyncResult; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.text.format.Time; import android.util.Log; import com.beepscore.android.sunshine.LocationStatusUtils; import com.beepscore.android.sunshine.MainActivity; import com.beepscore.android.sunshine.PreferenceHelper; import com.beepscore.android.sunshine.R; import com.beepscore.android.sunshine.Utility; import com.beepscore.android.sunshine.WeatherHelper; import com.beepscore.android.sunshine.data.WeatherContract; import com.beepscore.android.sunshine.data.WeatherProvider; import com.bumptech.glide.Glide; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.util.Vector; import java.util.concurrent.ExecutionException; public class SunshineSyncAdapter extends AbstractThreadedSyncAdapter { public final String LOG_TAG = SunshineSyncAdapter.class.getSimpleName(); // Interval at which to sync with the weather, in seconds. // seconds = hours * 60 minutes/hour * 60 seconds/minute // use a short interval for manual testing. // SYNC_INTERVAL = 30 resulted in about 1 call to onPerformSync every ~ 60 seconds. // Maybe inexact timers are very lenient?? // Maybe downloading and parsing caused it to not be ready after 30 seconds?? Sounds wrong. // public static final int SYNC_INTERVAL = 30; public static final int SYNC_INTERVAL = 3 * 60 * 60; public static final int SYNC_FLEXTIME = SYNC_INTERVAL / 3; private static final String[] NOTIFY_WEATHER_PROJECTION = new String[] { WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, WeatherContract.WeatherEntry.COLUMN_SHORT_DESC }; // these indices must match the projection private static final int INDEX_WEATHER_ID = 0; private static final int INDEX_MAX_TEMP = 1; private static final int INDEX_MIN_TEMP = 2; private static final int INDEX_SHORT_DESC = 3; private static final long DAY_IN_MILLIS = 1000 * 60 * 60 * 24; private static final int WEATHER_NOTIFICATION_ID = 3004; public SunshineSyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); } public static void initializeSyncAdapter(Context context) { getSyncAccount(context); } /** * Helper method to get the fake account to be used with SyncAdapter, or make a new one * if the fake account doesn't exist yet. If we make a new account, we call the * onAccountCreated method so we can initialize things. * * @param context The context used to access the account service * @return a fake account. */ public static Account getSyncAccount(Context context) { // Get an instance of the Android account manager AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); // Create the account type and default account Account newAccount = new Account( context.getString(R.string.app_name), context.getString(R.string.sync_account_type)); // If the password doesn't exist, the account doesn't exist if ( null == accountManager.getPassword(newAccount) ) { /* * Add the account and account type, no password or user data * If successful, return the Account object, otherwise report an error. */ if (!accountManager.addAccountExplicitly(newAccount, "", null)) { return null; } /* * If you don't set android:syncable="true" in * in your <provider> element in the manifest, * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1) * here. */ onAccountCreated(newAccount, context); } return newAccount; } private static void onAccountCreated(Account newAccount, Context context) { /* * Since we've created an account */ SunshineSyncAdapter.configurePeriodicSync(context, SYNC_INTERVAL, SYNC_FLEXTIME); /* * Without calling setSyncAutomatically, our periodic sync will not be enabled. */ ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true); /* * Finally, let's do a sync to get things started */ syncImmediately(context); } /** * Helper method to schedule the sync adapter periodic execution */ public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) { Log.d("SunshineSyncAdapter", "configurePeriodicSync"); Account account = getSyncAccount(context); String authority = context.getString(R.string.content_authority); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // we can enable inexact timers in our periodic sync SyncRequest request = new SyncRequest.Builder(). syncPeriodic(syncInterval, flexTime). setSyncAdapter(account, authority). setExtras(new Bundle()).build(); ContentResolver.requestSync(request); } else { ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval); } } /** * Helper method to have the sync adapter sync immediately * @param context The context used to access the account service */ public static void syncImmediately(Context context) { Bundle bundle = new Bundle(); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle); } @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { Log.d(LOG_TAG, "onPerformSync"); String locationQuery = Utility.getPreferredLocation(getContext()); if (locationQuery == null) { return; } // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; // set unknown until we get a response with more info LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_UNKNOWN); try { Uri builtUri = WeatherHelper.weatherUri(locationQuery, format, units, numDays); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_UNKNOWN); return; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_SERVER_DOWN); return; } forecastJsonStr = buffer.toString(); if (forecastJsonStr.contains("Error: Not found city")) { Log.e(LOG_TAG, "Error: Not found city"); LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_UNKNOWN); return; } getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (UnknownHostException e) { // UnknownHostException extends IOException Log.e(LOG_TAG, "UnknownHostException ", e); LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_SERVER_DOWN); } catch (FileNotFoundException e) { // FileNotFoundException extends IOException Log.e(LOG_TAG, "FileNotFoundException ", e); LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_SERVER_DOWN); } catch (SocketException e) { // SocketException extends IOException Log.e(LOG_TAG, "SocketException ", e); LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_SERVER_DOWN); } catch (IOException e) { // catch any remaining IOExceptions not already caught above // for example if forecastJsonStr == null Log.e(LOG_TAG, "IOException ", e); // If the code didn't successfully get the weather data, there's no point in attempting // to parse it. LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_SERVER_DOWN); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_SERVER_INVALID); } finally { Log.v(LOG_TAG, "location status " + LocationStatusUtils.getLocationStatus(getContext())); if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } } /** * Parses forecastJsonStr * This method has side effects * inserts values in content provider and calls notifyWeather * @param forecastJsonStr the complete forecast in JSON format */ public void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_MESSAGE_CODE = "cod"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); if (forecastJson.has(OWM_MESSAGE_CODE)) { int owmStatusCode = forecastJson.getInt(OWM_MESSAGE_CODE); switch (owmStatusCode) { case HttpURLConnection.HTTP_OK: { break; } case HttpURLConnection.HTTP_NOT_FOUND: { // HTTP_NOT_FOUND == status code 404 LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_INVALID); return; } default: { LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_SERVER_DOWN); return; } } } JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OpenWeatherMap OWM returns daily forecasts based upon the local time // of the city that is being asked for, // which means that we need to know the GMT offset to translate this data properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for(int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay+i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } int inserted = 0; if ( cVVector.size() > 0 ) { // add to database // evaluates to content://com.beepscore.android.sunshine/weather Uri weatherUri = WeatherContract.WeatherEntry.CONTENT_URI; ContentValues[] weatherContentValues = cVVector.toArray(new ContentValues[0]); // call bulkInsert to add the weatherEntries to the database inserted = getContext().getContentResolver().bulkInsert(weatherUri, weatherContentValues); // delete old data String[] selectionArgs = new String[]{Long.toString(dayTime.setJulianDay(julianStartDay))}; int numberOfRowsDeleted = getContext().getContentResolver().delete(weatherUri, WeatherProvider.sBeforeDateSelection, selectionArgs); Log.d(LOG_TAG, "numberOfRowsDeleted " + String.valueOf(numberOfRowsDeleted)); notifyWeather(); } Log.d(LOG_TAG, "getWeatherDataFromJson Complete. " + inserted + " Inserted"); LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_OK); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); LocationStatusUtils.setLocationStatus(getContext(), LocationStatusUtils.LOCATION_STATUS_SERVER_INVALID); } } /** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * e.g. "Sunnydale, CA" * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city * @param lon the longitude of the city * @return the row ID of the added location. */ public long addLocation(String locationSetting, String cityName, double lat, double lon) { Cursor locationCursor = getLocationCursor(locationSetting); long locationRowId = -1; if (locationCursor != null && locationCursor.moveToFirst()) { // location with this locationSetting already exists in content provider locationRowId = locationCursor.getLong(locationCursor.getColumnIndex("_id")); } else if (locationSetting != null && cityName != null) { locationRowId = addNewLocation(locationSetting, cityName, lat, lon); } if (locationCursor != null) { locationCursor.close(); } return locationRowId; } /** * queries content provider * @param locationSetting The location string used to request updates from the server. * Note multiple locationSettings could have the same cityName. * @return a Cursor with location _IDs that match locationSetting */ private Cursor getLocationCursor(String locationSetting) { // Query content provider, not database // More flexible design, easier to change content provider to use a different underlying source // e.g. "content://com.beepscore.android.sunshine/location" Uri locationUri = WeatherContract.LocationEntry.CONTENT_URI; // we need only column _ID String[] projection = {WeatherContract.LocationEntry._ID}; String selection = WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? "; String[] selectionArgs = {locationSetting}; return getContext().getContentResolver().query( locationUri, projection, selection, selectionArgs, null // sort order ); } private long addNewLocation(String locationSetting, String cityName, double lat, double lon) { Uri locationUri = WeatherContract.LocationEntry.CONTENT_URI; ContentValues contentValues = new ContentValues(); contentValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); contentValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); // e.g. content://com.beepscore.android.sunshine/location/2 Uri locationRowUri = getContext().getContentResolver().insert(locationUri, contentValues); long locationRowId = Long.valueOf(locationRowUri.getLastPathSegment()); return locationRowId; } private void notifyWeather() { Context context = getContext(); // In Sunshine, can tap Settings / Refresh to generate a notification //check the last update and notify if it's the first of the day long lastSync = PreferenceHelper.getLastSyncPreference(context); //int TIME_BETWEEN_NOTIFICATIONS_MIN_MSEC = DAY_IN_MILLIS; // for testing use a short time int TIME_BETWEEN_NOTIFICATIONS_MIN_MSEC = 10000; if (PreferenceHelper.getEnableNotificationPreference(context) && (System.currentTimeMillis() - lastSync >= TIME_BETWEEN_NOTIFICATIONS_MIN_MSEC)) { // Last sync was more than 1 day ago, let's send a notification with the weather. String locationQuery = Utility.getPreferredLocation(context); Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationQuery, System.currentTimeMillis()); // we'll query our contentProvider, as always Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null, null, null); if (cursor.moveToFirst()) { int weatherId = cursor.getInt(INDEX_WEATHER_ID); double high = cursor.getDouble(INDEX_MAX_TEMP); double low = cursor.getDouble(INDEX_MIN_TEMP); String desc = cursor.getString(INDEX_SHORT_DESC); int iconId = WeatherHelper.getIconResourceForWeatherCondition(weatherId); Resources resources = context.getResources(); int artResourceId = WeatherHelper.getArtResourceForWeatherCondition(weatherId); String artUrl = WeatherHelper.getArtUrlForWeatherCondition(context, weatherId); // On Honeycomb and higher devices, we can retrieve the size of the large icon // Prior to that, we use a fixed size @SuppressLint("InlinedApi") int largeIconWidth = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width) : resources.getDimensionPixelSize(R.dimen.notification_large_icon_default); @SuppressLint("InlinedApi") int largeIconHeight = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height) : resources.getDimensionPixelSize(R.dimen.notification_large_icon_default); // Retrieve the large icon Bitmap largeIcon; try { largeIcon = Glide.with(context) .load(artUrl) .asBitmap() .error(artResourceId) .fitCenter() .into(largeIconWidth, largeIconHeight).get(); } catch (InterruptedException | ExecutionException e) { Log.e(LOG_TAG, "Error retrieving large icon from " + artUrl, e); largeIcon = BitmapFactory.decodeResource(resources, artResourceId); } String title = context.getString(R.string.app_name); // Define the text of the forecast. // String contentText = String.format(context.getString(R.string.format_notification), // desc, // Utility.formatTemperature(context, high), // Utility.formatTemperature(context, low)); // see gist comments boolean isMetric = Utility.isMetric(context); String contentText = String.format(context.getString(R.string.format_notification), desc, Utility.formatTemperature(context, high, isMetric), Utility.formatTemperature(context, low, isMetric)); // Build notification // explicit intent for what the notification should open Intent intent = new Intent(context, MainActivity.class); // Create an artificial "backstack" for user to tap Back TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); taskStackBuilder.addNextIntent(intent); // pIntent is triggered if the notification is selected // use System.currentTimeMillis() to have a unique ID for the pending intent PendingIntent pIntent = taskStackBuilder.getPendingIntent((int) System.currentTimeMillis(), PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = new NotificationCompat.Builder(context) .setContentTitle(title) .setContentText(contentText) .setColor(resources.getColor(R.color.sunshine_light_blue)) .setSmallIcon(iconId) .setLargeIcon(largeIcon) .setContentIntent(pIntent) .setAutoCancel(true) .build(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(WEATHER_NOTIFICATION_ID, notification); PreferenceHelper.setLastSyncPreference(context, System.currentTimeMillis()); } } } }
package com.inbravo.concurrency; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * * @author amit.dixit * */ public final class BlockingArray { /* Create a new lock in Composition manner */ final private Lock lock = new ReentrantLock(); /* Array is NOT FULL */ final private Condition waitingToDeposit = lock.newCondition(); /* Array is NOT EMPTY */ final private Condition waitingToFetch = lock.newCondition(); /* Size of array */ final private int maxSize; /* Array of items */ final private Object[] items; /* Current counter */ private int currentIndex; public BlockingArray(final int size) { this.maxSize = size; this.items = new Object[size]; } /** * * @param x * @throws InterruptedException */ public final void deposit(final Object newObject) throws InterruptedException { System.out.println("[Thread: " + Thread.currentThread().getName() + "] Depositing: " + newObject); /* Acquire lock */ lock.lock(); try { /* If array is full */ while (this.currentIndex == this.maxSize) { System.out.println("[Thread: " + Thread.currentThread().getName() + "] Array is Full!"); /* Force this thread to await untill a fetch */ waitingToDeposit.await(); } /* Put the value in array after incrementing the current index */ items[currentIndex] = newObject; /* Increment the current index */ currentIndex++; /* Send signal to threads; waiting to fetch */ waitingToFetch.signal(); } finally { /* Release lock */ lock.unlock(); } } /** * * @return * @throws InterruptedException */ public final Object fetch() throws InterruptedException { System.out.println("[Thread: " + Thread.currentThread().getName() + "] Fetching"); /* Acquire lock */ lock.lock(); try { /* If array is empty */ while (this.currentIndex == 0) { System.out.println("[Thread: " + Thread.currentThread().getName() + "] Array is Empty!"); /* Force this thread to await untill a deposit */ waitingToFetch.await(); } /* Put the value in array */ final Object existingObject = items[currentIndex]; /* Decrement the current index */ currentIndex /* Send signal to threads; waiting to deposit */ waitingToDeposit.signal(); return existingObject; } finally { /* Release lock */ lock.unlock(); } } public static final void main(final String... args) { /* Create new instance of lock test */ final BlockingArray array = new BlockingArray(100); /* Start second anonymous thread */ new Thread("Fetcher") { @Override public void run() { for (int i = 0; i < 100; i++) { try { /* Fetch from array */ array.fetch(); } catch (final InterruptedException e) { e.printStackTrace(); } } } }.start(); /* Start first anonymous thread */ new Thread("Depositor") { @Override public void run() { for (int i = 0; i < 100; i++) { try { /* Put in array */ array.deposit("Object-" + i); } catch (final InterruptedException e) { e.printStackTrace(); } } } }.start(); } }
package jp.toastkid.search_widget.search.suggest; import android.support.annotation.NonNull; import android.util.Log; import java.io.IOException; import java.util.List; import java.util.Locale; import java.util.concurrent.TimeUnit; import io.reactivex.functions.Consumer; import jp.toastkid.search_widget.libs.Logger; import jp.toastkid.search_widget.libs.Utf8StringEncoder; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Suggest Web API response fetcher. * * @author toastkidjp */ public class SuggestFetcher { /** Suggest Web API. */ private static final String URL = "https: /** HTTP client. */ private OkHttpClient mClient; /** * Initialize HTTP client. */ public SuggestFetcher() { mClient = new OkHttpClient.Builder() .connectTimeout(3L, TimeUnit.SECONDS) .readTimeout(3L, TimeUnit.SECONDS) .build(); } /** * Fetch Web API result asynchronously. * * @param query * @param consumer */ public void fetchAsync(final String query, final Consumer<List<String>> consumer) { final Request request = new Request.Builder() .url(makeSuggestUrl(query)) .build(); mClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(final Call call, final IOException e) { e.printStackTrace(); } @Override public void onResponse( final Call call, @NonNull final Response response ) throws IOException { if (response.body() == null) { return; } try { consumer.accept(new SuggestParser().parse(response.body().string())); } catch (final Exception e) { e.printStackTrace(); } } }); } /** * Make suggest Web API requesting URL. * @param query Query * @return suggest Web API requesting URL */ @NonNull private String makeSuggestUrl(@NonNull final String query) { return URL + "&hl=" + Locale.getDefault().getLanguage() + "&q=" + Utf8StringEncoder.encode(query); } }
package io.github.hidroh.materialistic.data; import android.content.ContentValues; import android.content.Intent; import android.content.ShadowAsyncQueryHandler; import android.os.Parcel; import android.support.v4.content.LocalBroadcastManager; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowContentResolver; import org.robolectric.shadows.ShadowLocalBroadcastManager; import java.util.HashSet; import java.util.Set; import io.github.hidroh.materialistic.test.TestWebItem; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; import static org.assertj.android.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.robolectric.Shadows.shadowOf; import static org.robolectric.support.v4.Shadows.shadowOf; @Config(shadows = {ShadowAsyncQueryHandler.class}) @RunWith(RobolectricTestRunner.class) public class FavoriteManagerTest { private ShadowContentResolver resolver; private FavoriteManager manager; private FavoriteManager.OperationCallbacks callbacks; @Before public void setUp() { callbacks = mock(FavoriteManager.OperationCallbacks.class); resolver = shadowOf(ShadowApplication.getInstance().getContentResolver()); ContentValues cv = new ContentValues(); cv.put("itemid", "1"); cv.put("title", "title"); cv.put("url", "http://example.com"); cv.put("time", String.valueOf(System.currentTimeMillis())); resolver.insert(MaterialisticProvider.URI_FAVORITE, cv); cv = new ContentValues(); cv.put("itemid", "2"); cv.put("title", "ask HN"); cv.put("url", "http://example.com"); cv.put("time", String.valueOf(System.currentTimeMillis())); resolver.insert(MaterialisticProvider.URI_FAVORITE, cv); manager = new FavoriteManager(); } @Test public void testGetNoQuery() { manager.get(RuntimeEnvironment.application, null); Intent actual = getBroadcastIntent(); assertThat(actual).hasAction(FavoriteManager.ACTION_GET); assertThat((FavoriteManager.Favorite[]) actual.getParcelableArrayExtra(FavoriteManager.ACTION_GET_EXTRA_DATA)).hasSize(2); } @Test public void testGetEmpty() { manager.get(RuntimeEnvironment.application, "blah"); Intent actual = getBroadcastIntent(); assertThat(actual).hasAction(FavoriteManager.ACTION_GET); assertThat((FavoriteManager.Favorite[]) actual.getParcelableArrayExtra(FavoriteManager.ACTION_GET_EXTRA_DATA)).isEmpty(); } @Test public void testCheckNoId() { manager.check(RuntimeEnvironment.application, null, callbacks); verify(callbacks, never()).onCheckComplete(anyBoolean()); } @Test public void testCheckTrue() { manager.check(RuntimeEnvironment.application, "1", callbacks); verify(callbacks).onCheckComplete(eq(true)); } @Test public void testCheckFalse() { manager.check(RuntimeEnvironment.application, "-1", callbacks); verify(callbacks).onCheckComplete(eq(false)); } @Test public void testAdd() { manager.add(RuntimeEnvironment.application, new TestWebItem() { @Override public String getId() { return "3"; } @Override public String getUrl() { return "http://newitem.com"; } @Override public String getDisplayedTitle() { return "new title"; } }); Intent actual = getBroadcastIntent(); assertThat(actual).hasAction(FavoriteManager.ACTION_ADD); assertEquals("3", actual.getStringExtra(FavoriteManager.ACTION_ADD_EXTRA_DATA)); } @Test public void testClearAll() { manager.clear(RuntimeEnvironment.application, null); assertThat(getBroadcastIntent()).hasAction(FavoriteManager.ACTION_CLEAR); } @Test public void testClearQuery() { manager.clear(RuntimeEnvironment.application, "blah"); assertThat(getBroadcastIntent()).hasAction(FavoriteManager.ACTION_CLEAR); } @Test public void testRemoveNoId() { manager.remove(RuntimeEnvironment.application, (String) null); assertThat(shadowOf(LocalBroadcastManager.getInstance(RuntimeEnvironment.application)) .getSentBroadcastIntents()).isEmpty(); } @Test public void testRemoveId() { manager.remove(RuntimeEnvironment.application, "1"); Intent actual = getBroadcastIntent(); assertThat(actual).hasAction(FavoriteManager.ACTION_REMOVE); assertEquals("1", actual.getStringExtra(FavoriteManager.ACTION_REMOVE_EXTRA_DATA)); } @Test public void testRemoveMultipleNoId() { manager.remove(RuntimeEnvironment.application, (Set<String>) null); assertThat(shadowOf(LocalBroadcastManager.getInstance(RuntimeEnvironment.application)) .getSentBroadcastIntents()).isEmpty(); } @Test public void testRemoveMultiple() { manager.remove(RuntimeEnvironment.application, new HashSet<String>(){{add("1");add("2");}}); assertThat(getBroadcastIntent()).hasAction(FavoriteManager.ACTION_CLEAR); } @Test public void testFavorite() { Parcel parcel = Parcel.obtain(); parcel.writeString("1"); parcel.writeString("http://example.com"); parcel.writeString("title"); parcel.setDataPosition(0); FavoriteManager.Favorite favorite = FavoriteManager.Favorite.CREATOR.createFromParcel(parcel); assertEquals("title", favorite.getDisplayedTitle()); assertEquals("example.com", favorite.getSource()); assertEquals("http://example.com", favorite.getUrl()); assertEquals("1", favorite.getId()); assertNotNull(favorite.getDisplayedTime(RuntimeEnvironment.application)); assertEquals(ItemManager.WebItem.Type.story, favorite.getType()); assertTrue(favorite.isShareable()); assertEquals("title - http://example.com", favorite.toString()); assertEquals(0, favorite.describeContents()); Parcel output = Parcel.obtain(); favorite.writeToParcel(output, 0); output.setDataPosition(0); assertEquals("1", output.readString()); assertThat(FavoriteManager.Favorite.CREATOR.newArray(1)).hasSize(1); } private Intent getBroadcastIntent() { ShadowLocalBroadcastManager broadcastManager = shadowOf(LocalBroadcastManager.getInstance(RuntimeEnvironment.application)); return broadcastManager.getSentBroadcastIntents().get(0); } }
package com.oakesville.mythling; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.Timer; import java.util.TimerTask; import org.json.JSONException; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Messenger; import android.support.v4.app.NavUtils; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.View.OnKeyListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.oakesville.mythling.StreamVideoDialog.StreamDialogListener; import com.oakesville.mythling.app.AppData; import com.oakesville.mythling.app.AppSettings; import com.oakesville.mythling.app.BadSettingsException; import com.oakesville.mythling.app.Listable; import com.oakesville.mythling.media.Item; import com.oakesville.mythling.media.LiveStreamInfo; import com.oakesville.mythling.media.MediaList; import com.oakesville.mythling.media.MediaSettings; import com.oakesville.mythling.media.MediaSettings.MediaType; import com.oakesville.mythling.media.MediaSettings.SortType; import com.oakesville.mythling.media.MediaSettings.ViewType; import com.oakesville.mythling.media.Recording; import com.oakesville.mythling.media.SearchResults; import com.oakesville.mythling.media.StorageGroup; import com.oakesville.mythling.media.TunerInUseException; import com.oakesville.mythling.media.TvShow; import com.oakesville.mythling.prefs.PrefsActivity; import com.oakesville.mythling.util.FrontendPlayer; import com.oakesville.mythling.util.HttpHelper; import com.oakesville.mythling.util.MediaListParser; import com.oakesville.mythling.util.MythTvParser; import com.oakesville.mythling.util.Recorder; import com.oakesville.mythling.util.Reporter; import com.oakesville.mythling.util.ServiceFrontendPlayer; import com.oakesville.mythling.util.SocketFrontendPlayer; import com.oakesville.mythling.util.Transcoder; /** * Base class for the different ways to view collections of MythTV media. */ public abstract class MediaActivity extends Activity { private static final String TAG = MediaActivity.class.getSimpleName(); static final String DETAIL_FRAGMENT = "detailFragment"; static final String LIST_FRAGMENT = "listFragment"; static final String PATH = "path"; static final String SEL_ITEM_INDEX = "idx"; static final String CURRENT_TOP = "curTop"; static final String TOP_OFFSET = "topOff"; static final String DETAIL_GRAB = "grab"; private ListableListAdapter listAdapter; ListableListAdapter getListAdapter() { return listAdapter; } void setListAdapter(ListableListAdapter listAdapter) { this.listAdapter = listAdapter; getListView().setAdapter(listAdapter); } protected String getPath() { return ""; } protected List<Listable> getListables() { return mediaList.getListables(getPath()); } protected List<Listable> getListables(String path) { if (mediaList == null) // TODO: how? return new ArrayList<Listable>(); return mediaList.getListables(path); } private int currentTop = 0; // top item in the list int getCurrentTop() { return currentTop; } void setCurrentTop(int currentTop) { this.currentTop = currentTop; } private int topOffset = 0; int getTopOffset() { return topOffset; } void setTopOffset(int topOffset) { this.topOffset = topOffset; } private int selItemIndex = 0; int getSelItemIndex() { return selItemIndex; } void setSelItemIndex(int selItemIndex) { this.selItemIndex = selItemIndex; } protected MediaList mediaList; protected Map<String, StorageGroup> storageGroups; private BroadcastReceiver playbackBroadcastReceiver; private static AppData appData; public static AppData getAppData() { return appData; } public static void setAppData(AppData data) { appData = data; } private AppSettings appSettings; public AppSettings getAppSettings() { return appSettings; } private MediaType mediaType; protected MediaType getMediaType() { return mediaType; } protected void setMediaType(MediaType mt) { this.mediaType = mt; } public String getCharSet() { return "UTF-8"; } private MenuItem mediaMenuItem; private MenuItem searchMenuItem; private MenuItem viewMenuItem; private MenuItem sortMenuItem; private MenuItem moviesMenuItem; private MenuItem tvSeriesMenuItem; private MenuItem musicMenuItem; private MenuItem mythwebMenuItem; private MenuItem stopMenuItem; private ProgressBar progressBar; private ProgressDialog countdownDialog; private int count; private Timer timer; protected boolean modeSwitch; // tracking for back button protected boolean refreshing; public void refresh() { currentTop = 0; topOffset = 0; selItemIndex = 0; } public abstract ListView getListView(); private boolean active; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); appSettings = new AppSettings(getApplicationContext()); } @Override protected void onResume() { active = true; super.onResume(); if (supportsMusic()) registerPlaybackBroadcastReceiver(true); } @Override public void onPause() { active = false; registerPlaybackBroadcastReceiver(false); super.onPause(); } private void registerPlaybackBroadcastReceiver(boolean register) { if (register) { if (playbackBroadcastReceiver == null) { playbackBroadcastReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { showStopMenuItem(false); } }; } registerReceiver(playbackBroadcastReceiver, new IntentFilter(MusicPlaybackService.ACTION_PLAYBACK_STOPPED)); } else { if (playbackBroadcastReceiver != null) { unregisterReceiver(playbackBroadcastReceiver); playbackBroadcastReceiver = null; } } } protected ProgressBar createProgressBar() { progressBar = (ProgressBar) findViewById(R.id.progress); progressBar.setVisibility(View.GONE); progressBar.setIndeterminate(true); progressBar.setScaleX(0.20f); progressBar.setScaleY(0.20f); return progressBar; } @Override public boolean onPrepareOptionsMenu(Menu menu) { MediaSettings mediaSettings = appSettings.getMediaSettings(); mediaMenuItem = menu.findItem(R.id.menu_media); if (mediaMenuItem != null) { if (mediaList != null) mediaMenuItem.setTitle(mediaSettings.getTitle() + " (" + mediaList.getCount() + ")"); else mediaMenuItem.setTitle(mediaSettings.getTitle()); if (mediaSettings.isMusic()) mediaMenuItem.getSubMenu().findItem(R.id.media_music).setChecked(true); else if (mediaSettings.isLiveTv()) mediaMenuItem.getSubMenu().findItem(R.id.media_tv).setChecked(true); else if (mediaSettings.isMovies()) mediaMenuItem.getSubMenu().findItem(R.id.media_movies).setChecked(true); else if (mediaSettings.isTvSeries()) mediaMenuItem.getSubMenu().findItem(R.id.media_tv_series).setChecked(true); else if (mediaSettings.isVideos()) mediaMenuItem.getSubMenu().findItem(R.id.media_videos).setChecked(true); else mediaMenuItem.getSubMenu().findItem(R.id.media_recordings).setChecked(true); moviesMenuItem = mediaMenuItem.getSubMenu().findItem(R.id.media_movies); showMoviesMenuItem(supportsMovies()); tvSeriesMenuItem = mediaMenuItem.getSubMenu().findItem(R.id.media_tv_series); showTvSeriesMenuItem(supportsTvSeries()); musicMenuItem = mediaMenuItem.getSubMenu().findItem(R.id.media_music); showMusicMenuItem(supportsMusic()); } searchMenuItem = menu.findItem(R.id.menu_search); showSearchMenu(supportsSearch()); sortMenuItem = menu.findItem(R.id.menu_sort); showSortMenu(supportsSort()); viewMenuItem = menu.findItem(R.id.menu_view); showViewMenu(supportsViewMenu()); mythwebMenuItem = menu.findItem(R.id.menu_mythweb); showMythwebMenu(supportsMythwebMenu()); stopMenuItem = menu.findItem(R.id.menu_stop); showStopMenuItem(isPlayingMusic()); return super.onPrepareOptionsMenu(menu); } protected void showSearchMenu(boolean show) { if (searchMenuItem != null) { searchMenuItem.setEnabled(show); searchMenuItem.setVisible(show); } } protected void showMoviesMenuItem(boolean show) { if (moviesMenuItem != null) { moviesMenuItem.setEnabled(show); moviesMenuItem.setVisible(show); } } protected void showTvSeriesMenuItem(boolean show) { if (tvSeriesMenuItem != null) { tvSeriesMenuItem.setEnabled(show); tvSeriesMenuItem.setVisible(show); } } protected void showMusicMenuItem(boolean show) { if (musicMenuItem != null) { musicMenuItem.setEnabled(show); musicMenuItem.setVisible(show); } } protected void showStopMenuItem(boolean show) { if (stopMenuItem != null) { stopMenuItem.setEnabled(show); stopMenuItem.setVisible(show); } } protected void showViewMenu(boolean show) { if (viewMenuItem != null) { MediaSettings mediaSettings = appSettings.getMediaSettings(); if (show) { viewMenuItem.setIcon(mediaSettings.getViewIcon()); if (mediaSettings.getViewType() == ViewType.detail) viewMenuItem.getSubMenu().findItem(R.id.view_detail).setChecked(true); else if (mediaSettings.getViewType() == ViewType.split) viewMenuItem.getSubMenu().findItem(R.id.view_split).setChecked(true); else viewMenuItem.getSubMenu().findItem(R.id.view_list).setChecked(true); } viewMenuItem.setEnabled(show); viewMenuItem.setVisible(show); } } protected void showMythwebMenu(boolean show) { if (mythwebMenuItem != null) { mythwebMenuItem.setEnabled(show); mythwebMenuItem.setVisible(show); } } protected void showSortMenu(boolean show) { if (sortMenuItem != null) { if (show) { MediaSettings mediaSettings = appSettings.getMediaSettings(); sortMenuItem.setTitle(mediaSettings.getSortTypeTitle()); if (mediaSettings.getSortType() == SortType.byDate) sortMenuItem.getSubMenu().findItem(R.id.sort_byDate).setChecked(true); else if (mediaSettings.getSortType() == SortType.byRating) sortMenuItem.getSubMenu().findItem(R.id.sort_byRating).setChecked(true); else sortMenuItem.getSubMenu().findItem(R.id.sort_byTitle).setChecked(true); } sortMenuItem.setEnabled(show); sortMenuItem.setVisible(show); } } protected boolean supportsSearch() { return getAppSettings().isMythlingMediaServices(); } protected boolean supportsSort() { if (mediaList == null) return false; if (getAppSettings().isMythlingMediaServices() && mediaList.getMediaType() == MediaType.videos) return false; // temporarily until issue #29 is fixed return mediaList != null && mediaList.supportsSort(); } protected boolean supportsViewMenu() { return mediaList != null && mediaList.canHaveArtwork(); } protected boolean supportsMovies() { return getAppSettings().isVideosCategorization(); } protected boolean supportsTvSeries() { return getAppSettings().isVideosCategorization(); } protected boolean supportsMusic() { return getAppSettings().isMythlingMediaServices(); } protected boolean supportsMythwebMenu() { return getAppSettings().isMythWebAccessEnabled(); } protected boolean isListView() { return appSettings.getMediaSettings().getViewType() == ViewType.list; } protected boolean isDetailView() { return appSettings.getMediaSettings().getViewType() == ViewType.detail; } protected boolean isSplitView() { return appSettings.getMediaSettings().getViewType() == ViewType.split; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { NavUtils.navigateUpFromSameTask(this); return true; } try { if (sortMenuItem != null) sortMenuItem.setTitle(appSettings.getMediaSettings().getSortTypeTitle()); if (viewMenuItem != null) viewMenuItem.setIcon(appSettings.getMediaSettings().getViewIcon()); if (item.getItemId() == R.id.media_music) { ViewType oldView = appSettings.getMediaSettings().getViewType(); appSettings.setMediaType(MediaType.music); item.setChecked(true); mediaMenuItem.setTitle(MediaSettings.getMediaTitle(MediaType.music)); showViewMenu(supportsViewMenu()); showSortMenu(supportsSort()); ViewType newView = appSettings.getMediaSettings().getViewType(); if (oldView != newView) applyViewChange(oldView, newView); else refresh(); return true; } else if (item.getItemId() == R.id.media_videos) { ViewType oldView = appSettings.getMediaSettings().getViewType(); appSettings.setMediaType(MediaType.videos); item.setChecked(true); mediaMenuItem.setTitle(MediaSettings.getMediaTitle(MediaType.videos)); showViewMenu(supportsViewMenu()); showSortMenu(supportsSort()); ViewType newView = appSettings.getMediaSettings().getViewType(); if (oldView != newView) applyViewChange(oldView, newView); else refresh(); return true; } else if (item.getItemId() == R.id.media_recordings) { ViewType oldView = appSettings.getMediaSettings().getViewType(); appSettings.setMediaType(MediaType.recordings); // clears view type item.setChecked(true); mediaMenuItem.setTitle(MediaSettings.getMediaTitle(MediaType.recordings)); showViewMenu(supportsViewMenu()); showSortMenu(supportsSort()); ViewType newView = appSettings.getMediaSettings().getViewType(); if (oldView != newView) applyViewChange(oldView, newView); else refresh(); return true; } else if (item.getItemId() == R.id.media_tv) { ViewType oldView = appSettings.getMediaSettings().getViewType(); appSettings.setMediaType(MediaType.liveTv); // clears view type item.setChecked(true); mediaMenuItem.setTitle(MediaSettings.getMediaTitle(MediaType.liveTv)); showViewMenu(supportsViewMenu()); showSortMenu(supportsSort()); ViewType newView = appSettings.getMediaSettings().getViewType(); if (oldView != newView) applyViewChange(oldView, newView); else refresh(); return true; } else if (item.getItemId() == R.id.media_movies) { ViewType oldView = appSettings.getMediaSettings().getViewType(); appSettings.setMediaType(MediaType.movies); item.setChecked(true); mediaMenuItem.setTitle(MediaSettings.getMediaTitle(MediaType.movies)); showViewMenu(supportsViewMenu()); showSortMenu(supportsSort()); ViewType newView = appSettings.getMediaSettings().getViewType(); if (oldView != newView) applyViewChange(oldView, newView); else refresh(); return true; } else if (item.getItemId() == R.id.media_tv_series) { ViewType oldView = appSettings.getMediaSettings().getViewType(); appSettings.setMediaType(MediaType.tvSeries); item.setChecked(true); mediaMenuItem.setTitle(MediaSettings.getMediaTitle(MediaType.tvSeries)); showViewMenu(supportsViewMenu()); showSortMenu(supportsSort()); ViewType newView = appSettings.getMediaSettings().getViewType(); if (oldView != newView) applyViewChange(oldView, newView); else refresh(); return true; } else if (item.getItemId() == R.id.sort_byTitle) { appSettings.setSortType(SortType.byTitle); item.setChecked(true); sortMenuItem.setTitle(R.string.menu_byTitle); sort(); return true; } else if (item.getItemId() == R.id.sort_byDate) { appSettings.setSortType(SortType.byDate); item.setChecked(true); sortMenuItem.setTitle(R.string.menu_byDate); sort(); return true; } else if (item.getItemId() == R.id.sort_byRating) { appSettings.setSortType(SortType.byRating); item.setChecked(true); sortMenuItem.setTitle(R.string.menu_byRating); sort(); return true; } else if (item.getItemId() == R.id.view_list) { appSettings.setViewType(ViewType.list); item.setChecked(true); viewMenuItem.setIcon(R.drawable.ic_menu_list); goListView(); return true; } else if (item.getItemId() == R.id.view_detail) { appSettings.setViewType(ViewType.detail); item.setChecked(true); viewMenuItem.setIcon(R.drawable.ic_menu_detail); goDetailView(); return true; } else if (item.getItemId() == R.id.view_split) { appSettings.setViewType(ViewType.split); item.setChecked(true); viewMenuItem.setIcon(R.drawable.ic_menu_split); goSplitView(); return true; } else if (item.getItemId() == R.id.menu_refresh) { refresh(); return true; } else if (item.getItemId() == R.id.menu_settings) { startActivity(new Intent(this, PrefsActivity.class)); return true; } else if (item.getItemId() == R.id.menu_search) { return onSearchRequested(); } else if (item.getItemId() == R.id.menu_mythweb) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(appSettings.getMythWebUrl()))); return true; } else if (item.getItemId() == R.id.menu_help) { String url = getResources().getString(R.string.url_help); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url), getApplicationContext(), WebViewActivity.class)); return true; } else if (item.getItemId() == R.id.menu_stop) { Intent stopMusic = new Intent(this, MusicPlaybackService.class); stopMusic.setAction(MusicPlaybackService.ACTION_STOP); startService(stopMusic); return true; } } catch (BadSettingsException ex) { stopProgress(); Toast.makeText(getApplicationContext(), "Bad or missing setting:\n" + ex.getMessage(), Toast.LENGTH_LONG).show(); } catch (Exception ex) { if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled()) new Reporter(ex).send(); stopProgress(); Toast.makeText(getApplicationContext(), "Error: " + ex.toString(), Toast.LENGTH_LONG).show(); } return super.onOptionsItemSelected(item); } protected void applyViewChange(ViewType oldView, ViewType newView) { if (newView == ViewType.detail && oldView != ViewType.detail) { getAppSettings().clearCache(); // refresh after nav goDetailView(); } else if (oldView == ViewType.detail && newView != ViewType.detail) { getAppSettings().clearCache(); // refresh after nav if (newView == ViewType.split) goSplitView(); else goListView(); } else if (oldView != newView) { if (newView == ViewType.split) goSplitView(); else goListView(); refresh(); } } protected void showItemInDetailPane(int position) { showItemInDetailPane(position, false); } protected void showItemInDetailPane(int position, boolean grabFocus) { ItemDetailFragment detailFragment = new ItemDetailFragment(); Bundle arguments = new Bundle(); arguments.putInt(SEL_ITEM_INDEX, position); arguments.putBoolean(DETAIL_GRAB, grabFocus); detailFragment.setArguments(arguments); getFragmentManager().beginTransaction().replace(R.id.detail_container, detailFragment, DETAIL_FRAGMENT).commit(); } protected void showSubListPane(String path) { showSubListPane(path, -1); } protected void showSubListPane(String path, int selIdx) { ItemListFragment listFragment = new ItemListFragment(); Bundle arguments = new Bundle(); arguments.putString(PATH, path); arguments.putInt(SEL_ITEM_INDEX, selIdx); listFragment.setArguments(arguments); getFragmentManager().beginTransaction().replace(R.id.detail_container, listFragment, LIST_FRAGMENT).commit(); } protected void playItem(final Item item) { try { AppSettings appSettings = getAppSettings(); if (appSettings.isDevicePlayback()) { if (getListView() != null) { String msg = (item.isMusic() ? "Playing: '" : "Loading: '") + item.getTitle() + "'"; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, new String[]{msg}); getListView().setAdapter(adapter); } if (item.isMusic()) { String musicUrl = appSettings.getMythTvServicesBaseUrlWithCredentials() + "/Content/GetMusic?Id=" + item.getId(); if (appSettings.isExternalMusicPlayer()) { Intent intent = new Intent(android.content.Intent.ACTION_VIEW); /** * Starts a transcode without immediately watching. * TODO: how should this be called? */ protected void transcodeItem(final Item item) { item.setPath(""); new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Transcode") .setMessage("Begin transcoding " + item.getTitle() + "?") .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { // TODO: if TV, schedule recording and start transcode if (item.isRecording()) new TranscodeVideoTask(item).execute(getAppSettings().getMythTvServicesBaseUrl()); } catch (MalformedURLException ex) { stopProgress(); if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled()) new Reporter(ex).send(); Toast.makeText(getApplicationContext(), "Error: " + ex.toString(), Toast.LENGTH_LONG).show(); } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { stopProgress(); onResume(); } }) .show(); } protected void goListView() { findViewById(R.id.detail_container).setVisibility(View.GONE); } protected void goDetailView() { if (mediaList.getMediaType() == MediaType.recordings && getAppSettings().getMediaSettings().getSortType() == SortType.byTitle) getAppSettings().clearCache(); // refresh since we're switching to flattened hierarchy Uri.Builder builder = new Uri.Builder(); builder.path(getPath()); Uri uri = builder.build(); Intent intent = new Intent(Intent.ACTION_VIEW, uri, getApplicationContext(), MediaPagerActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } protected void goSplitView() { findViewById(R.id.detail_container).setVisibility(View.VISIBLE); } public void sort() throws IOException, JSONException, ParseException { startProgress(); refreshMediaList(); } private void startFrontendPlayback(Item item, final FrontendPlayer player) { if (item.isLiveTv()) { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(item.getTitle()) .setMessage("TODO: Frontend Live TV playback not yet supported.") .setPositiveButton("OK", null) .show(); } else { try { player.play(); // reset progress count = 0; // prepare for a progress bar dialog countdownDialog = new ProgressDialog(this); countdownDialog.setCancelable(true); countdownDialog.setMessage("Playing " + MediaSettings.getMediaLabel(item.getType()) + ": " + item.getLabel()); countdownDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); countdownDialog.setProgressPercentFormat(null); countdownDialog.setProgressNumberFormat(null); countdownDialog.setMax(10); countdownDialog.setCancelable(true); countdownDialog.setButton(Dialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); stopTimer(); } }); countdownDialog.setButton(Dialog.BUTTON_NEGATIVE, "Stop", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { player.stop(); dialog.dismiss(); stopTimer(); } }); countdownDialog.setCanceledOnTouchOutside(true); // countdownDialog.setProgressDrawable(getResources().getDrawable(R.drawable.countdown_bar)); countdownDialog.show(); countdownDialog.setProgress(10); tick(); } catch (Exception ex) { if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled()) new Reporter(ex).send(); stopTimer(); } } } @Override protected void onStop() { if (countdownDialog != null && countdownDialog.isShowing()) countdownDialog.dismiss(); stopTimer(); super.onStop(); } private void stopTimer() { if (timer != null) timer.cancel(); count = 0; } private void tick() { if (timer != null) timer.cancel(); timer = new Timer(); timer.schedule(new TimerTask() { public void run() { countdownDialog.setProgress(10 - count); if (count == 10) { countdownDialog.dismiss(); stopTimer(); } else { count++; tick(); } } }, 1000); } protected void refreshMediaList() { try { getAppSettings().clearMediaSettings(); // in case prefs changed if (getAppSettings().getMediaSettings().getType() == MediaType.movies && !supportsMovies()) getAppSettings().setMediaType(MediaType.valueOf(AppSettings.DEFAULT_MEDIA_TYPE)); if (getAppSettings().getMediaSettings().getType() == MediaType.tvSeries && !supportsTvSeries()) getAppSettings().setMediaType(MediaType.valueOf(AppSettings.DEFAULT_MEDIA_TYPE)); if (getAppSettings().getMediaSettings().getType() == MediaType.music && !supportsMusic()) getAppSettings().setMediaType(MediaType.valueOf(AppSettings.DEFAULT_MEDIA_TYPE)); refreshing = true; new RefreshTask().execute(getAppSettings().getUrls(getAppSettings().getMediaListUrl())); } catch (Exception ex) { throw new RuntimeException(ex.getMessage(), ex); } } protected void updateActionMenu() { showMoviesMenuItem(supportsMovies()); showTvSeriesMenuItem(supportsTvSeries()); showMusicMenuItem(supportsMusic()); showSortMenu(supportsSort()); showViewMenu(supportsViewMenu()); showSearchMenu(supportsSearch()); if (mediaMenuItem != null) mediaMenuItem.setTitle(MediaSettings.getMediaTitle(getAppSettings().getMediaSettings().getType()) + " (" + mediaList.getCount() + ")"); showStopMenuItem(isPlayingMusic()); } protected void populate() throws IOException, JSONException, ParseException { // default does nothing } private boolean isPlayingMusic() { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (MusicPlaybackService.class.getName().equals(service.service.getClassName())) return true; } return false; } protected Transcoder getTranscoder(Item item) { if (item.getStorageGroup() == null) return new Transcoder(getAppSettings(), mediaList.getBasePath()); else return new Transcoder(getAppSettings(), item.getStorageGroup()); } private class RefreshTask extends AsyncTask<URL, Integer, Long> { private String mediaListJson; private String storageGroupsJson; private Exception ex; protected Long doInBackground(URL... urls) { try { MediaSettings mediaSettings = getAppSettings().getMediaSettings(); HttpHelper downloader = getAppSettings().getMediaListDownloader(urls); byte[] bytes = downloader.get(); mediaListJson = new String(bytes, downloader.getCharSet()); if (mediaListJson.startsWith("<")) { // just display html ex = new IOException(mediaListJson); return -1L; } URL sgUrl = new URL(getAppSettings().getMythTvServicesBaseUrl() + "/Myth/GetStorageGroupDirs"); HttpHelper sgDownloader = getAppSettings().getMediaListDownloader(getAppSettings().getUrls(sgUrl)); storageGroupsJson = new String(sgDownloader.get()); storageGroups = new MythTvParser(getAppSettings(), storageGroupsJson).parseStorageGroups(); MediaListParser mediaListParser = getAppSettings().getMediaListParser(mediaListJson); if (getAppSettings().isMythlingMediaServices()) { mediaList = mediaListParser.parseMediaList(mediaSettings.getType(), storageGroups); } else { boolean hasMediaStorageGroup = mediaSettings.getType() == MediaType.recordings || mediaSettings.getType() == MediaType.liveTv || (mediaSettings.getType() != MediaType.music && storageGroups.get(appSettings.getVideoStorageGroup()) != null); if (hasMediaStorageGroup) { mediaList = ((MythTvParser) mediaListParser).parseMediaList(mediaSettings.getType(), storageGroups); } else { // no storage group for media type URL baseUrl = getAppSettings().getMythTvServicesBaseUrl(); String basePath = null; if (mediaSettings.getType() == MediaType.videos || mediaSettings.getType() == MediaType.movies || mediaSettings.getType() == MediaType.tvSeries) { // handle videos by getting the base path setting downloader = getAppSettings().getMediaListDownloader(getAppSettings().getUrls(new URL(baseUrl + "/Myth/GetHostName"))); String hostName = new MythTvParser(getAppSettings(), new String(downloader.get())).parseString(); String key = "VideoStartupDir"; downloader = getAppSettings().getMediaListDownloader(getAppSettings().getUrls(new URL(baseUrl + "/Myth/GetSetting?Key=" + key + "&HostName=" + hostName))); basePath = new MythTvParser(getAppSettings(), new String(downloader.get())).parseMythTvSetting(key); if (basePath == null) { // try without host name downloader = getAppSettings().getMediaListDownloader(getAppSettings().getUrls(new URL(baseUrl + "/Myth/GetSetting?Key=" + key))); basePath = new MythTvParser(getAppSettings(), new String(downloader.get())).parseMythTvSetting(key); } } mediaList = ((MythTvParser) mediaListParser).parseMediaList(mediaSettings.getType(), storageGroups, basePath); } } mediaList.setCharSet(downloader.getCharSet()); getAppSettings().clearPagerCurrentPosition(mediaList.getMediaType(), ""); return 0L; } catch (Exception ex) { this.ex = ex; if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled()) new Reporter(ex).send(); return -1L; } } protected void onPostExecute(Long result) { refreshing = false; if (result != 0L) { stopProgress(); if (ex != null) Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); } else { AppData appData = new AppData(getApplicationContext()); appData.setMediaList(mediaList); appData.setStorageGroups(storageGroups); setAppData(appData); setMediaType(appData.getMediaList().getMediaType()); getAppSettings().setLastLoad(System.currentTimeMillis()); try { appData.writeStorageGroups(storageGroupsJson); appData.writeMediaList(mediaListJson); stopProgress(); populate(); } catch (Exception ex) { stopProgress(); if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled()) new Reporter(ex).send(); } } } } private class StreamHlsTask extends AsyncTask<URL, Integer, Long> { private Item item; private LiveStreamInfo streamInfo; private Exception ex; public StreamHlsTask(Item item) { this.item = item; } protected Long doInBackground(URL... urls) { try { Transcoder transcoder = getTranscoder(item); // TODO: do this retry for tv playback int ct = 0; int maxTries = 3; // empty relative url i think means myth has not started transcoding while ((streamInfo == null || streamInfo.getRelativeUrl().isEmpty()) && ct < maxTries) { transcoder.beginTranscode(item); streamInfo = transcoder.getStreamInfo(); ct++; Thread.sleep(1000); } if (streamInfo == null || streamInfo.getRelativeUrl().isEmpty()) throw new IOException("Transcoding does not seem to have started"); transcoder.waitAvailable(); return 0L; } catch (Exception ex) { this.ex = ex; if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled()) new Reporter(ex).send(); return -1L; } } protected void onPostExecute(Long result) { if (result != 0L) { stopProgress(); if (ex != null) Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); onResume(); } else { try { playLiveStream(streamInfo); } catch (Exception ex) { if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled()) new Reporter(ex).send(); Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); } } } } protected class TranscodeVideoTask extends AsyncTask<URL, Integer, Long> { private Item item; private Exception ex; public TranscodeVideoTask(Item item) { this.item = item; } protected Long doInBackground(URL... urls) { try { Transcoder transcoder = getTranscoder(item); transcoder.beginTranscode(item); return 0L; } catch (Exception ex) { this.ex = ex; if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled()) new Reporter(ex).send(); return -1L; } } protected void onPostExecute(Long result) { stopProgress(); if (result != 0L) { if (ex != null) Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); onResume(); } } } protected class StreamTvTask extends AsyncTask<URL, Integer, Long> { private TvShow tvShow; private Recording recording; private Recording recordingToDelete; private LiveStreamInfo streamInfo; private boolean raw; private Exception ex; public StreamTvTask(TvShow tvShow, boolean raw) { this.tvShow = tvShow; this.raw = raw; } public StreamTvTask(TvShow tvShow, boolean raw, Recording recordingToDelete) { this(tvShow, raw); this.recordingToDelete = recordingToDelete; } protected Long doInBackground(URL... urls) { try { Recorder recorder = new Recorder(getAppSettings(), storageGroups); if (recordingToDelete != null) recorder.deleteRecording(recordingToDelete); boolean recordAvail = recorder.scheduleRecording(tvShow); if (!recordAvail) recorder.waitAvailable(); recording = recorder.getRecording(); if (!raw) { tvShow.setStorageGroup(recorder.getRecording().getStorageGroup()); Transcoder transcoder = getTranscoder(tvShow); boolean streamAvail = transcoder.beginTranscode(recorder.getRecording()); streamInfo = transcoder.getStreamInfo(); if (!streamAvail) transcoder.waitAvailable(); // this is the long pole } return 0L; } catch (Exception ex) { this.ex = ex; if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled()) new Reporter(ex).send(); return -1L; } } protected void onPostExecute(Long result) { stopProgress(); if (result != 0L) { if (ex instanceof TunerInUseException) { new AlertDialog.Builder(MediaActivity.this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Recording Conflict") .setMessage("Tuner already in use recording:\n" + ex.getMessage() + "\nDelete this recording and proceed?") .setPositiveButton("Delete", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { final Recording inProgressRecording = ((TunerInUseException) ex).getRecording(); new AlertDialog.Builder(MediaActivity.this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Confirm Delete") .setMessage("Delete in-progress recording?\n" + inProgressRecording) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startProgress(); new StreamTvTask(tvShow, raw, inProgressRecording).execute(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { stopProgress(); onResume(); } }) .show(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { stopProgress(); onResume(); } }) .show(); } else { if (ex != null) Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); onResume(); } } else { try { if (raw) playRawVideoStream(recording); else playLiveStream(streamInfo); } catch (Exception ex) { if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled()) new Reporter(ex).send(); Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); } } } } /** * Requires MythTV content.cpp patch to work without storage groups (or maybe create * a bogus SG called None that points to your backend videos base location). */ private void playRawVideoStream(Item item) { try { final URL baseUrl = getAppSettings().getMythTvServicesBaseUrlWithCredentials(); String itemPath = item.isRecording() || item.getPath().isEmpty() ? item.getFileName() : item.getPath() + "/" + item.getFileName(); String fileUrl = baseUrl + "/Content/GetFile?FileName=" + URLEncoder.encode(itemPath, "UTF-8"); if (item.getStorageGroup() == null) fileUrl += "&StorageGroup=None"; else fileUrl += "&StorageGroup=" + item.getStorageGroup().getName(); stopProgress(); if (appSettings.isExternalVideoPlayer()) { Intent toStart = new Intent(Intent.ACTION_VIEW);
package com.simplenote.android.ui; import java.util.HashMap; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.EditText; import com.simplenote.android.Constants; import com.simplenote.android.Preferences; import com.simplenote.android.R; import com.simplenote.android.net.Api.Response; import com.simplenote.android.net.HttpCallback; import com.simplenote.android.widget.LoginActionListener; /** * Activity to get credentials from user * @author bryanjswift */ public class LoginDialog extends Activity { private static final String LOGGING_TAG = Constants.TAG + LoginDialog.class.getName(); /** * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set view and a couple flags setContentView(R.layout.login); getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND); // Get credentials HashMap<String,String> credentials = Preferences.getLoginPreferences(this); // Get fields final EditText email = (EditText) findViewById(R.id.email); final EditText password = (EditText) findViewById(R.id.password); // Set values to what is stored in preferences email.setText(credentials.get(Preferences.EMAIL)); password.setText(credentials.get(Preferences.PASSWORD)); // When user presses an action button when in the password field authenticate the user password.setOnEditorActionListener(new LoginActionListener(this, email, password, new HttpCallback() { /** * @see com.simplenote.android.net.HttpCallback#on200(com.simplenote.android.net.Api.Response) */ @Override public void on200(final Response response) { Log.d(LOGGING_TAG, "Authentication successful, closing dialog"); Intent intent = getIntent(); intent.putExtra(Preferences.EMAIL, email.getText().toString()); intent.putExtra(Preferences.TOKEN, response.body); LoginDialog.this.setResult(Activity.RESULT_OK, intent); LoginDialog.this.finish(); } })); } }