answer
stringlengths
17
10.2M
// Diana Cheung, CS333 Class of 2013 package catsrabbits; import game.Building; import game.PlayerMotion; import game.PlayerMotionWatcher; import game.PlayerStats; import javax.media.opengl.GL2; import javax.media.opengl.glu.GLU; public class Cat extends Critter implements PlayerMotionWatcher{ private static final float BODY_LENGTH=1.8f,HEAD_HEIGHT=.56f,HEAD_DIST=BODY_LENGTH*.7f, EYE_CENTER_DIST=.52f,EYE_HEIGHT=.35f,WHISKER_COLOR=.82f,SWIM_ANGLE=26.74f,TAIL_LENGTH=1.83f,TAIL_DIAM=.15f; private int furColor; private float eyeGreen=0; private boolean steppedOn=false; public Cat(float x,float y,float z,float a,float s,float tR, GL2 gl,GLU glu){ super(x,y,z,a,s,tR,gl,glu); tRate=.025f; furColor=(int)(Math.random()*5); if(furColor==3)eyeGreen=1; // green eyes for black fur cats texture=Building.setupTexture(gl,"cheungcatfur"+furColor+".jpg", FUR_DIRECTORY); PlayerMotion.registerPlayerWatcher(this); } public void drawWholeBody(GL2 gl, GLU glu){ gl.glPushMatrix(); gl.glEnable(GL2.GL_TEXTURE_2D); texture.bind(gl); drawBody(gl,glu); gl.glDisable(GL2.GL_TEXTURE_2D); gl.glTranslatef(0,HEAD_HEIGHT,-HEAD_DIST); drawHead(gl,glu); gl.glTranslatef(0,-.4f,HEAD_DIST+1.62f); gl.glEnable(GL2.GL_TEXTURE_2D); drawTail(gl,glu); drawLegs(gl,glu); gl.glDisable(GL2.GL_TEXTURE_2D); gl.glPopMatrix(); } protected void drawBody(GL2 gl, GLU glu){ gl.glPushMatrix(); gl.glScalef(1, 1, BODY_LENGTH); drawTexturedUnitSphere(glu); gl.glPopMatrix(); } protected void drawHead(GL2 gl, GLU glu){ gl.glEnable(GL2.GL_TEXTURE_2D); gl.glPushMatrix(); gl.glScalef(1.1f,1,.9f); drawSphere(textureQuadric,.8f,glu); gl.glPopMatrix(); gl.glDisable(GL2.GL_TEXTURE_2D); gl.glPushMatrix(); // draw eyes gl.glColor3f(0,eyeGreen,0); gl.glTranslatef(0,EYE_HEIGHT,-EYE_CENTER_DIST); drawEyes(gl, glu, .27f, .16f); // draw nose gl.glTranslatef(0, -EYE_HEIGHT, -.74f+EYE_CENTER_DIST); drawNose(gl,glu); // draw ears gl.glTranslatef(0, .5f, .64f); gl.glEnable(GL2.GL_TEXTURE_2D); drawEars(gl,glu); gl.glDisable(GL2.GL_TEXTURE_2D); gl.glPopMatrix(); } protected void drawNose(GL2 gl,GLU glu){ // draw nose gl.glColor3f(1, .77f, 1); drawSphere(quadric, .14f, glu); // draw whiskers gl.glColor3f(WHISKER_COLOR,WHISKER_COLOR,WHISKER_COLOR); draw6Whiskers(gl,glu); } protected void drawOneEar(GL2 gl, GLU glu){ gl.glPushMatrix(); gl.glTranslatef(.3f, 0, 0); gl.glRotatef(90, -1, .59f, 0); glu.gluCylinder(textureQuadric, .4, 0, .5, 10, 10); gl.glPopMatrix(); } private void drawOneLeg(GL2 gl,GLU glu,float rotate){ gl.glPushMatrix(); gl.glRotatef(rotate, 0, 1, 0); gl.glTranslatef(1, 0, 0); gl.glScalef(3, 1, 1); drawSphere(textureQuadric,.2f,glu); gl.glPopMatrix(); } protected void drawLegs(GL2 gl, GLU glu){ int rotate=(int)(SWIM_ANGLE*Math.sin(Math.toRadians(t*360-45))); gl.glPushMatrix(); // front legs gl.glTranslatef(0,-.43f,-2.47f); drawOneLeg(gl,glu,rotate); gl.glScalef(-1, 1, 1); drawOneLeg(gl,glu,rotate); // back legs gl.glTranslatef(0, 0, 1.88f); drawOneLeg(gl,glu,-rotate); gl.glScalef(-1, 1, 1); drawOneLeg(gl,glu,-rotate); gl.glPopMatrix(); } protected void drawTail(GL2 gl, GLU glu){ gl.glPushMatrix(); gl.glRotatef(86,-1,0,0); glu.gluCylinder(textureQuadric, TAIL_DIAM, TAIL_DIAM, TAIL_LENGTH, 10, 10); gl.glTranslatef(0, 0, TAIL_LENGTH); drawSphere(textureQuadric,TAIL_DIAM,glu); gl.glPopMatrix(); } public float size(){return BODY_LENGTH*2f;} public void playerMoved(float x, float y, float z, float angle, float y_angle,PlayerStats s){ float dist=(float)Math.sqrt(Math.pow(x-this.x, 2)+Math.pow(z-this.z, 2)); // will NOT happen if you're just standing still. you have to move to trigger this if(dist<size()&&!steppedOn){ // stepped on cat steppedOn=true; //System.out.println("Stepped on a cat!"); // TODO meow s.changeHealth(-1);s.changeHonor(-1); new Thread(new Runnable(){ public void run(){ try{ Thread.sleep(2000); }catch(InterruptedException e){}; //System.out.println("Cat recovered"); steppedOn=false; } }).start(); } } }
package com.tinkerpop.gremlin.groovy.engine; import com.tinkerpop.gremlin.AbstractGremlinTest; import com.tinkerpop.gremlin.LoadGraphWith; import com.tinkerpop.gremlin.TestHelper; import com.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineTest; import com.tinkerpop.gremlin.structure.Graph; import org.junit.Test; import org.kohsuke.groovy.sandbox.GroovyInterceptor; import javax.script.Bindings; import javax.script.SimpleBindings; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import static org.junit.Assert.*; public class GremlinExecutorTest extends AbstractGremlinTest { public static Map<String, String> PATHS = new HashMap<>(); static { try { final List<String> groovyScriptResources = Arrays.asList("GremlinExecutorInit.groovy"); for (final String fileName : groovyScriptResources) { PATHS.put(fileName, TestHelper.generateTempFileFromResource(GremlinExecutorTest.class, fileName, "").getAbsolutePath()); } } catch (Exception e) { e.printStackTrace(); } } @Test public void shouldEvalScript() throws Exception { final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create(); assertEquals(2, gremlinExecutor.eval("1+1").get()); } @Test public void shouldEvalMultipleScripts() throws Exception { final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create(); assertEquals(2, gremlinExecutor.eval("1+1").get()); assertEquals(3, gremlinExecutor.eval("1+2").get()); assertEquals(4, gremlinExecutor.eval("1+3").get()); assertEquals(5, gremlinExecutor.eval("1+4").get()); assertEquals(6, gremlinExecutor.eval("1+5").get()); assertEquals(7, gremlinExecutor.eval("1+6").get()); } @Test public void shouldEvalScriptWithBindings() throws Exception { final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create(); final Bindings b = new SimpleBindings(); b.put("x", 1); assertEquals(2, gremlinExecutor.eval("1+x", b).get()); } @Test public void shouldEvalScriptWithGlobalBindings() throws Exception { final Bindings b = new SimpleBindings(); b.put("x", 1); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(b).create(); assertEquals(2, gremlinExecutor.eval("1+x").get()); } @Test public void shouldEvalScriptWithGlobalAndLocalBindings() throws Exception { final Bindings g = new SimpleBindings(); g.put("x", 1); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(g).create(); final Bindings b = new SimpleBindings(); b.put("y", 1); assertEquals(2, gremlinExecutor.eval("y+x", b).get()); } @Test public void shouldEvalScriptWithLocalOverridingGlobalBindings() throws Exception { final Bindings g = new SimpleBindings(); g.put("x", 1); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(g).create(); final Bindings b = new SimpleBindings(); b.put("x", 10); assertEquals(11, gremlinExecutor.eval("x+1", b).get()); } @Test public void shouldTimeoutScript() throws Exception { final AtomicBoolean successCalled = new AtomicBoolean(false); final AtomicBoolean failureCalled = new AtomicBoolean(false); final CountDownLatch timeOutCount = new CountDownLatch(1); final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .scriptEvaluationTimeout(250) .afterFailure((b, e) -> failureCalled.set(true)) .afterSuccess((b) -> successCalled.set(true)) .afterTimeout((b) -> timeOutCount.countDown()).create(); try { gremlinExecutor.eval("Thread.sleep(1000);10").get(); fail("This script should have timed out with an exception"); } catch (Exception ex) { assertEquals(TimeoutException.class, ex.getCause().getClass()); } timeOutCount.await(2000, TimeUnit.MILLISECONDS); assertFalse(successCalled.get()); assertFalse(failureCalled.get()); assertEquals(0, timeOutCount.getCount()); } @Test public void shouldCallFail() throws Exception { final AtomicBoolean timeoutCalled = new AtomicBoolean(false); final AtomicBoolean successCalled = new AtomicBoolean(false); final AtomicBoolean failureCalled = new AtomicBoolean(false); final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .afterFailure((b, e) -> failureCalled.set(true)) .afterSuccess((b) -> successCalled.set(true)) .afterTimeout((b) -> timeoutCalled.set(true)).create(); try { gremlinExecutor.eval("10/0").get(); fail(); } catch (Exception ex) { } // need to wait long enough for the script to complete Thread.sleep(750); assertFalse(timeoutCalled.get()); assertFalse(successCalled.get()); assertTrue(failureCalled.get()); } @Test public void shouldCallSuccess() throws Exception { final AtomicBoolean timeoutCalled = new AtomicBoolean(false); final AtomicBoolean successCalled = new AtomicBoolean(false); final AtomicBoolean failureCalled = new AtomicBoolean(false); final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .afterFailure((b, e) -> failureCalled.set(true)) .afterSuccess((b) -> successCalled.set(true)) .afterTimeout((b) -> timeoutCalled.set(true)).create(); assertEquals(2, gremlinExecutor.eval("1+1").get()); // need to wait long enough for the script to complete Thread.sleep(750); assertFalse(timeoutCalled.get()); assertTrue(successCalled.get()); assertFalse(failureCalled.get()); } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldAllowTraversalToIterateInDifferentThreadThanOriginallyEvaluated() { // this test sort of simulates Gremlin Server interaction where a Traversal is eval'd in one Thread, but // then iterated in another. note that Gremlin Server configures the script engine to auto-commit // after evaluation. gremlin server assumes graphs are configured to use auto-transactions when in // sessionless mode. final ExecutorService evalExecutor = Executors.newSingleThreadExecutor(); final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .afterSuccess(b -> { final Graph graph = (Graph) b.get("g"); if (graph.features().graph().supportsTransactions()) graph.tx().commit(); }) .executorService(evalExecutor).create(); final Map<String,Object> bindings = new HashMap<>(); bindings.put("g", g); final AtomicInteger vertexCount = new AtomicInteger(0); final ExecutorService iterationExecutor = Executors.newSingleThreadExecutor(); gremlinExecutor.eval("g.V().out()", bindings).thenAcceptAsync(o -> { final Iterator itty = (Iterator) o; itty.forEachRemaining(v -> vertexCount.incrementAndGet()); }, iterationExecutor).join(); assertEquals(6, vertexCount.get()); } @Test public void shouldEvalInMultipleThreads() throws Exception { final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create(); final CyclicBarrier barrier = new CyclicBarrier(2); final AtomicInteger i1 = new AtomicInteger(0); final AtomicBoolean b1 = new AtomicBoolean(false); final Thread t1 = new Thread(() -> { try { barrier.await(); i1.set((Integer) gremlinExecutor.eval("1+1").get()); } catch (Exception ex) { b1.set(true); } }); final AtomicInteger i2 = new AtomicInteger(0); final AtomicBoolean b2 = new AtomicBoolean(false); final Thread t2 = new Thread(() -> { try { barrier.await(); i2.set((Integer) gremlinExecutor.eval("1+1").get()); } catch (Exception ex) { b2.set(true); } }); t1.start(); t2.start(); t1.join(); t2.join(); assertEquals(2, i1.get()); assertEquals(2, i2.get()); assertFalse(b1.get()); assertFalse(b2.get()); } @Test public void shouldNotExhaustThreads() throws Exception { // this is not representative of how the GremlinExecutor should be configured. A single thread executor // shared will create odd behaviors, but it's good for this test. final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .executorService(executorService) .scheduledExecutorService(executorService).create(); final AtomicInteger count = new AtomicInteger(0); assertTrue(IntStream.range(0, 1000).mapToObj(i -> gremlinExecutor.eval("1+1")).allMatch(f -> { try { return (Integer) f.get() == 2; } catch (Exception ex) { throw new RuntimeException(ex); } finally { count.incrementAndGet(); } })); assertEquals(1000, count.intValue()); } @Test public void shouldFailUntilImportExecutes() throws Exception { final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create(); final Set<String> imports = new HashSet<String>() {{ add("import java.awt.Color"); }}; final AtomicInteger successes = new AtomicInteger(0); final AtomicInteger failures = new AtomicInteger(0); // issue 1000 scripts in one thread using a class that isn't imported. this will result in failure. // while that thread is running start a new thread that issues an addImports to include that class. // this should block further evals in the first thread until the import is complete at which point // evals in the first thread will resume and start to succeed final Thread t1 = new Thread(() -> IntStream.range(0, 1000).mapToObj(i -> gremlinExecutor.eval("Color.BLACK")) .forEach(f -> { f.exceptionally(t -> failures.incrementAndGet()).join(); if (!f.isCompletedExceptionally()) successes.incrementAndGet(); }) ); final Thread t2 = new Thread(() -> { while (failures.get() < 500) { } gremlinExecutor.getScriptEngines().addImports(imports); }); t1.start(); t2.start(); t1.join(); t2.join(); assertTrue(successes.intValue() > 0); assertTrue(failures.intValue() >= 500); } @Test public void shouldInitializeWithScript() throws Exception { final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .addEngineSettings("gremlin-groovy", Collections.emptyList(), Collections.emptyList(), Arrays.asList(PATHS.get("GremlinExecutorInit.groovy")), Collections.emptyMap()) .create(); assertEquals(2, gremlinExecutor.eval("add(1,1)").get()); } @Test public void shouldSecureAll() throws Exception { GroovyInterceptor.getApplicableInterceptors().forEach(GroovyInterceptor::unregister); final Map<String, Object> config = new HashMap<>(); config.put("sandbox", GremlinGroovyScriptEngineTest.DenyAll.class.getName()); final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .addEngineSettings("gremlin-groovy", Collections.emptyList(), Collections.emptyList(), Arrays.asList(PATHS.get("GremlinExecutorInit.groovy")), config) .create(); try { gremlinExecutor.eval("c = new java.awt.Color(255, 255, 255)").get(); fail("Should have failed security"); } catch (Exception se) { assertEquals(SecurityException.class, se.getCause().getCause().getCause().getCause().getClass()); } finally { gremlinExecutor.close(); } } @Test public void shouldSecureSome() throws Exception { GroovyInterceptor.getApplicableInterceptors().forEach(GroovyInterceptor::unregister); final Map<String, Object> config = new HashMap<>(); config.put("sandbox", GremlinGroovyScriptEngineTest.AllowSome.class.getName()); final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .addEngineSettings("gremlin-groovy", Collections.emptyList(), Collections.emptyList(), Arrays.asList(PATHS.get("GremlinExecutorInit.groovy")), config) .create(); try { gremlinExecutor.eval("c = 'new java.awt.Color(255, 255, 255)'").get(); fail("Should have failed security"); } catch (Exception se) { assertEquals(SecurityException.class, se.getCause().getCause().getCause().getCause().getClass()); } try { final java.awt.Color c = (java.awt.Color) gremlinExecutor.eval("g = new java.awt.Color(255, 255, 255)").get(); assertEquals(java.awt.Color.class, c.getClass()); } catch (Exception ignored) { fail("Should not have tossed an exception"); } finally { gremlinExecutor.close(); } } @Test public void shouldInitializeWithScriptAndWorkAfterReset() throws Exception { final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .addEngineSettings("gremlin-groovy", Collections.emptyList(), Collections.emptyList(), Arrays.asList(PATHS.get("GremlinExecutorInit.groovy")), Collections.emptyMap()) .create(); assertEquals(2, gremlinExecutor.eval("add(1,1)").get()); gremlinExecutor.getScriptEngines().reset(); assertEquals(2, gremlinExecutor.eval("add(1,1)").get()); } }
package com.netflix.conductor.contribs.http; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.conductor.auth.AuthManager; import com.netflix.conductor.auth.AuthResponse; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.contribs.correlation.Correlator; import com.netflix.conductor.core.DNSLookup; import com.netflix.conductor.core.config.Configuration; import com.netflix.conductor.core.execution.WorkflowExecutor; import com.netflix.conductor.core.execution.tasks.WorkflowSystemTask; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.sun.jersey.oauth.client.OAuthClientFilter; import com.sun.jersey.oauth.signature.OAuthParameters; import com.sun.jersey.oauth.signature.OAuthSecrets; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; class GenericHttpTask extends WorkflowSystemTask { private static final Logger logger = LoggerFactory.getLogger(HttpTask.class); static final String REQUEST_PARAMETER_NAME = "http_request"; static final String RESPONSE_PARAMETER_NAME = "http_response"; static final String STATUS_MAPPING_PARAMETER_NAME = "status_mapping"; protected Configuration config; protected ObjectMapper om; private AuthManager auth; private RestClientManager rcm; private TypeReference<Map<String, Object>> mapOfObj = new TypeReference<Map<String, Object>>() { }; private TypeReference<List<Object>> listOfObj = new TypeReference<List<Object>>() { }; GenericHttpTask(String name, Configuration config, RestClientManager rcm, ObjectMapper om, AuthManager auth) { super(name); this.config = config; this.rcm = rcm; this.om = om; this.auth = auth; } String lookup(String service) { DNSLookup lookup = new DNSLookup(); DNSLookup.DNSResponses responses = lookup.lookupService(service); if (responses != null && ArrayUtils.isNotEmpty(responses.getResponses())) { String address = responses.getResponses()[0].getAddress(); int port = responses.getResponses()[0].getPort(); return "http://" + address + ":" + port; } return null; } @SuppressWarnings("unchecked") HttpResponse httpCallUrlEncoded(Input input, String body) throws Exception { Client client = rcm.getClient(input); MultivaluedMap formData = new MultivaluedMapImpl(); Map<String, String> bodyparam = new ObjectMapper().readValue(body, HashMap.class); Iterator it = bodyparam.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); formData.add(pair.getKey(), pair.getValue()); it.remove(); } WebResource webResource = client.resource(input.getUri()); ClientResponse response = webResource .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE) .post(ClientResponse.class, formData); if (response.getStatus() != 201 && response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + response.getEntity(String.class)); } HttpResponse responsehttp = new HttpResponse(); responsehttp.body = extractBody(response); responsehttp.statusCode = response.getStatus(); responsehttp.headers = response.getHeaders(); return responsehttp; } /** * @param input HTTP Request * @return Response of the http call * @throws Exception If there was an error making http call */ HttpResponse httpCall(Input input, Task task, Workflow workflow, WorkflowExecutor executor) throws Exception { Client client = rcm.getClient(input); if (input.getOauthConsumerKey() != null) { logger.debug("Configuring OAuth filter"); OAuthParameters params = new OAuthParameters().consumerKey(input.getOauthConsumerKey()).signatureMethod("HMAC-SHA1").version("1.0"); OAuthSecrets secrets = new OAuthSecrets().consumerSecret(input.getOauthConsumerSecret()); client.addFilter(new OAuthClientFilter(client.getProviders(), params, secrets)); } WebResource.Builder builder = client.resource(input.getUri()).type(MediaType.APPLICATION_JSON); if (input.getBody() != null) { builder.entity(input.getBody()); } // Attach the Authorization header by adding entry to the input's headers if (input.isAuthorize()) { setAuthorization(input); setAuthorizationContext(input,workflow.getAuthorizationContext()); } // Attach Deluxe Owf Context header if (input.isCorrelation()) { setCorrelation(input, workflow); } // Attach headers to the builder input.getHeaders().entrySet().forEach(e -> { builder.header(e.getKey(), e.getValue()); }); // Log the headers Map<String, Object> headers = new HashMap<>(input.getHeaders()); // We need to mask auth header value if (headers.containsKey(HttpHeaders.AUTHORIZATION)) { headers.put(HttpHeaders.AUTHORIZATION, "xxxxxxxxxxxxxxxxxxx"); } if (headers.containsKey("Authorization-Context")) { headers.put("Authorization-Context", "xxxxxxxxxxxxxxxxxxx"); } logger.debug("http task headers " + headers); // Store input headers back to the input request if (MapUtils.isNotEmpty(input.getHeaders())) { // Escaping the auth if (input.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) { input.getHeaders().put(HttpHeaders.AUTHORIZATION, "xxxxxxxxxxxxxxxxxxx"); } if (input.getHeaders().containsKey("Authorization-Context")) { input.getHeaders().put("Authorization-Context", "xxxxxxxxxxxxxxxxxxx"); } task.getInputData().put(REQUEST_PARAMETER_NAME, input); executor.updateTask(task); } HttpResponse response = new HttpResponse(); try { ClientResponse cr = builder.accept(input.getAccept()).method(input.getMethod(), ClientResponse.class); Response.Status.Family family = cr.getStatusInfo().getFamily(); if (cr.getStatus() != 204 && cr.hasEntity() && !family.equals(Response.Status.Family.REDIRECTION)) { response.body = extractBody(cr); } response.statusCode = cr.getStatus(); response.headers = cr.getHeaders(); return response; } catch (UniformInterfaceException ex) { logger.error(ex.getMessage(), ex); ClientResponse cr = ex.getResponse(); logger.error("Status Code: {}", cr.getStatus()); if (cr.getStatus() > 199 && cr.getStatus() < 300) { if (cr.getStatus() != 204 && cr.hasEntity()) { response.body = extractBody(cr); } response.error = ex.getMessage(); response.headers = cr.getHeaders(); response.statusCode = cr.getStatus(); return response; } else { String reason = cr.getEntity(String.class); logger.error(reason, ex); throw new Exception(reason); } } catch (Exception ex) { logger.error(ex.getMessage(), ex); response.body = null; response.headers = null; response.statusCode = 0; response.error = ex.getMessage(); return response; } } private Object extractBody(ClientResponse cr) { String json = cr.getEntity(String.class); try { JsonNode node = om.readTree(json); if (node.isArray()) { return om.convertValue(node, listOfObj); } else if (node.isObject()) { return om.convertValue(node, mapOfObj); } else if (node.isNumber()) { return om.convertValue(node, Double.class); } else { return node.asText(); } } catch (IOException jpe) { logger.error(jpe.getMessage(), jpe); return json; } } @SuppressWarnings("unchecked") private void setCorrelation(Input input, Workflow workflow) throws JsonProcessingException { if (workflow.getCorrelationId() != null) { Correlator correlator = new Correlator(logger, workflow.getCorrelationId()); correlator.attach(input.getHeaders()); } } private void setAuthorization(Input input) throws Exception { AuthResponse response = auth.authorize(); input.getHeaders().put(HttpHeaders.AUTHORIZATION, "Bearer " + response.getAccessToken()); } private void setAuthorizationContext(Input input,Map<String, Object> authorizationContext) throws Exception { input.getHeaders().put("Authorization-Context", authorizationContext.get("Authorization-Context")); } void setReasonForIncompletion(HttpResponse response, Task task) { if (response.body != null) { task.setReasonForIncompletion(response.body.toString()); } else if (StringUtils.isNotEmpty(response.error)) { task.setReasonForIncompletion(response.error); } else { task.setReasonForIncompletion("No response from the remote service"); } } @SuppressWarnings("unchecked") boolean handleStatusMapping(Task task, HttpResponse response) { Object param = task.getInputData().get(STATUS_MAPPING_PARAMETER_NAME); if (param == null) { return false; } if (!(param instanceof Map)) { throw new RuntimeException("The " + STATUS_MAPPING_PARAMETER_NAME + " is not an object"); } Map<Integer, Task.Status> statusMapping = om.convertValue(param, new TypeReference<Map<Integer, Task.Status>>() { }); if (statusMapping.isEmpty()) { return false; } Task.Status taskStatus = statusMapping.get(response.statusCode); if (taskStatus == null) { return false; } task.setStatus(taskStatus); return true; } }
package com.netflix.conductor.contribs.http; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.core.DNSLookup; import com.netflix.conductor.core.config.Configuration; import com.netflix.conductor.core.execution.WorkflowExecutor; import com.netflix.conductor.core.execution.tasks.WorkflowSystemTask; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.sun.jersey.oauth.client.OAuthClientFilter; import com.sun.jersey.oauth.signature.OAuthParameters; import com.sun.jersey.oauth.signature.OAuthSecrets; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; class GenericHttpTask extends WorkflowSystemTask { private static final Logger logger = LoggerFactory.getLogger(HttpTask.class); private static final String DELUXE_OWF_CORRELATION = "Deluxe-Owf-Correlation"; private static final String SEQUENCE_NO = "sequence-no"; protected RestClientManager rcm; protected Configuration config; protected ObjectMapper om; private TypeReference<Map<String, Object>> mapOfObj = new TypeReference<Map<String, Object>>() { }; private TypeReference<List<Object>> listOfObj = new TypeReference<List<Object>>() { }; GenericHttpTask(String name, Configuration config, RestClientManager rcm, ObjectMapper om) { super(name); this.config = config; this.rcm = rcm; this.om = om; } String lookup(String service) { DNSLookup lookup = new DNSLookup(); DNSLookup.DNSResponses responses = lookup.lookupService(service); if (responses != null && ArrayUtils.isNotEmpty(responses.getResponses())) { String address = responses.getResponses()[0].getAddress(); int port = responses.getResponses()[0].getPort(); return "http://" + address + ":" + port; } return null; } @SuppressWarnings("unchecked") HttpResponse httpCallUrlEncoded(Input input, String body) throws Exception { Client client = Client.create(); MultivaluedMap formData = new MultivaluedMapImpl(); Map<String, String> bodyparam = new ObjectMapper().readValue(body, HashMap.class); Iterator it = bodyparam.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); formData.add(pair.getKey(), pair.getValue()); it.remove(); } WebResource webResource = client.resource(input.getUri()); ClientResponse response = webResource .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE) .post(ClientResponse.class, formData); if (response.getStatus() != 201 && response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + response.getEntity(String.class)); } HttpResponse responsehttp = new HttpResponse(); responsehttp.body = extractBody(response); responsehttp.statusCode = response.getStatus(); responsehttp.headers = response.getHeaders(); return responsehttp; } /** * @param input HTTP Request * @return Response of the http call * @throws Exception If there was an error making http call */ HttpResponse httpCall(Input input, Workflow workflow, WorkflowExecutor executor) throws Exception { Client client = rcm.getClient(input); if (input.getOauthConsumerKey() != null) { logger.info("Configuring OAuth filter"); OAuthParameters params = new OAuthParameters().consumerKey(input.getOauthConsumerKey()).signatureMethod("HMAC-SHA1").version("1.0"); OAuthSecrets secrets = new OAuthSecrets().consumerSecret(input.getOauthConsumerSecret()); client.addFilter(new OAuthClientFilter(client.getProviders(), params, secrets)); } WebResource.Builder builder = client.resource(input.getUri()).type(MediaType.APPLICATION_JSON); if (input.getBody() != null) { builder.entity(input.getBody()); } input.getHeaders().entrySet().forEach(e -> { builder.header(e.getKey(), e.getValue()); }); // Attach Deluxe Owf Correlation header if (input.isCorrelation()) { setCorrelation(builder, workflow, executor); } HttpResponse response = new HttpResponse(); try { ClientResponse cr = builder.accept(input.getAccept()).method(input.getMethod(), ClientResponse.class); if (cr.getStatus() != 204 && cr.hasEntity()) { response.body = extractBody(cr); } response.statusCode = cr.getStatus(); response.headers = cr.getHeaders(); return response; } catch (UniformInterfaceException ex) { logger.error(ex.getMessage(), ex); ClientResponse cr = ex.getResponse(); logger.error("Status Code: {}", cr.getStatus()); if (cr.getStatus() > 199 && cr.getStatus() < 300) { if (cr.getStatus() != 204 && cr.hasEntity()) { response.body = extractBody(cr); } response.headers = cr.getHeaders(); response.statusCode = cr.getStatus(); return response; } else { String reason = cr.getEntity(String.class); logger.error(reason, ex); throw new Exception(reason); } } } private Object extractBody(ClientResponse cr) { String json = cr.getEntity(String.class); try { JsonNode node = om.readTree(json); if (node.isArray()) { return om.convertValue(node, listOfObj); } else if (node.isObject()) { return om.convertValue(node, mapOfObj); } else if (node.isNumber()) { return om.convertValue(node, Double.class); } else { return node.asText(); } } catch (IOException jpe) { logger.error(jpe.getMessage(), jpe); return json; } } @SuppressWarnings("unchecked") private void setCorrelation(WebResource.Builder builder, Workflow workflow, WorkflowExecutor executor) throws JsonProcessingException { // Exit if no headers at all if (workflow.getHeaders() == null) { return; } // Exit if no required header if (!workflow.getHeaders().containsKey(DELUXE_OWF_CORRELATION)) { return; } Map<String, Object> header = (Map<String, Object>)workflow.getHeaders().get(DELUXE_OWF_CORRELATION); int sequence = (int)header.get(SEQUENCE_NO); header.put(SEQUENCE_NO, sequence + 1); // Update workflow to save new sequence no executor.updateWorkflow(workflow); String json = om.writeValueAsString(header); logger.info("Setting " + DELUXE_OWF_CORRELATION + " header with " + json); // Set the header with json value builder.header(DELUXE_OWF_CORRELATION, json); } }
package fi.nls.oskari.control.data; import fi.mml.portti.service.search.SearchService; import fi.nls.oskari.annotation.OskariActionRoute; import fi.nls.oskari.control.ActionException; import fi.nls.oskari.control.ActionHandler; import fi.nls.oskari.control.ActionParameters; import fi.nls.oskari.search.channel.SearchableChannel; import fi.nls.oskari.service.OskariComponentManager; import fi.nls.oskari.util.JSONHelper; import fi.nls.oskari.util.ResponseHelper; import org.json.JSONArray; import org.json.JSONObject; import java.util.Map; @OskariActionRoute("SearchOptions") public class SearchOptionsHandler extends ActionHandler { private SearchService searchService; @Override public void init() { super.init(); searchService = OskariComponentManager.getComponentOfType(SearchService.class); } public void handleAction(final ActionParameters params) throws ActionException { Map<String, SearchableChannel> channels = searchService.getAvailableChannels(); JSONArray channelsJSONArray = new JSONArray(); for(SearchableChannel channel : channels.values()) { if(!channel.hasPermission(params.getUser()) || !channel.getCapabilities().canTextSearch()) { continue; } JSONObject json = new JSONObject(); JSONHelper.putValue(json, "id", channel.getId()); JSONHelper.putValue(json, "isDefault", channel.isDefaultChannel()); JSONHelper.putValue(json, "locale", channel.getUILabels().optJSONObject(params.getLocale().getLanguage())); channelsJSONArray.put(json); } JSONObject response = new JSONObject(); JSONHelper.putValue(response, "channels", channelsJSONArray); try { ResponseHelper.writeResponse(params, response); } catch (Exception ex) { throw new ActionException("Couldn't get WFS search channels", ex); } } }
package fi.nls.oskari.control.layer; import fi.nls.oskari.annotation.OskariActionRoute; import fi.nls.oskari.control.ActionException; import fi.nls.oskari.control.ActionHandler; import fi.nls.oskari.control.ActionParameters; import fi.nls.oskari.control.ActionParamsException; import fi.nls.oskari.control.view.GetAppSetupHandler; import fi.nls.oskari.domain.map.stats.StatsVisualization; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.map.stats.VisualizationService; import fi.nls.oskari.map.stats.VisualizationServiceIbatisImpl; import fi.nls.oskari.util.ConversionHelper; import fi.nls.oskari.util.IOHelper; import fi.nls.oskari.util.PropertyUtil; import org.apache.axiom.om.OMElement; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URLEncoder; import java.util.Enumeration; @OskariActionRoute("GetStatsTile") public class GetStatsTileHandler extends ActionHandler { private static final Logger log = LogFactory.getLogger(GetStatsTileHandler.class); private final VisualizationService service = new VisualizationServiceIbatisImpl(); final private static String PARAM_VISUALIZATION_ID = "VIS_ID"; final private static String PARAM_VISUALIZATION_NAME = "VIS_NAME"; // name=ows:Kunnat2013 final private static String PARAM_VISUALIZATION_FILTER_PROPERTY = "VIS_ATTR"; // attr=Kuntakoodi final private static String PARAM_VISUALIZATION_CLASSES = "VIS_CLASSES"; // classes=020,091|186,086,982|111,139,740 final private static String PARAM_VISUALIZATION_VIS = "VIS_COLORS"; // vis=choro:ccffcc|99cc99|669966 private String geoserverUrl = null; private String geoserverUser = null; private String geoserverPass = null; private String sldServerUrl = null; @Override public void init() { super.init(); geoserverUrl = PropertyUtil.getOptional("statistics.geoserver.wms.url"); geoserverUser = PropertyUtil.get("statistics.user"); geoserverPass = PropertyUtil.get("statistics.password"); sldServerUrl = PropertyUtil.getOptional("statistics.sld.server"); } public void handleAction(final ActionParameters params) throws ActionException { if (log.isDebugEnabled()) { printParameters(params); } /* // GetMap with post is horrible broken with hard coded GetMap xml. // never use it before it's fixed!! if (sldServerUrl == null) { // if SLD server is not configured, use POSTing a GetMap XML-request proxyWithGetMapPost(params); } else { */ final HttpURLConnection con = getConnection(params); try { // we should post complete GetMap XML with the custom SLD to geoserver so it doesn't need to fetch it again con.setRequestMethod("GET"); con.setDoOutput(false); con.setDoInput(true); HttpURLConnection.setFollowRedirects(false); con.setUseCaches(false); con.connect(); //IOHelper.writeToConnection(con, SLD_HANDLER.getSLD(params)); // read the image tile final byte[] presponse = IOHelper.readBytes(con.getInputStream()); final HttpServletResponse response = params.getResponse(); response.setContentType("image/png"); response.getOutputStream().write(presponse, 0, presponse.length); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { throw new ActionException("Couldn't proxy request to geoserver", e); } finally { if (con != null) { con.disconnect(); } } } private void proxyWithGetMapPost(final ActionParameters params) throws ActionException { try { String xml = buildXML(params); HttpURLConnection con = IOHelper.getConnection(geoserverUrl, geoserverUser, geoserverPass); IOHelper.writeHeader(con, "Content-type", "text/xml"); IOHelper.writeToConnection(con, xml); byte[] presponse = IOHelper.readBytes(con); log.debug("Image response length: " + presponse.length); final HttpServletResponse response = params.getResponse(); response.setContentType("image/png"); response.getOutputStream().write(presponse, 0, presponse.length); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { throw new ActionException("Couldn't post proxy request to geoserver", e); } } private HttpURLConnection getConnection(final ActionParameters params) throws ActionException { // copy parameters final HttpServletRequest httpRequest = params.getRequest(); final StringBuilder ajaxUrl = new StringBuilder(sldServerUrl); ajaxUrl.append(PropertyUtil.get("statistics.sld.server.path", PropertyUtil.get(params.getLocale(), GetAppSetupHandler.PROPERTY_AJAXURL))); ajaxUrl.append("&action_route=GetStatsLayerSLD"); StatsVisualization vis = getVisualization(params); if (vis == null) { log.info("Visualization couldn't be generated - parameters/db data missing", params); } else { // using prefetched values so we don't need to get them from db again on SLD action ajaxUrl.append("&"); ajaxUrl.append(GetStatsLayerSLDHandler.PARAM_VISUALIZATION_NAME); ajaxUrl.append("="); ajaxUrl.append(vis.getLayername()); ajaxUrl.append("&"); ajaxUrl.append(GetStatsLayerSLDHandler.PARAM_VISUALIZATION_FILTER_PROPERTY); ajaxUrl.append("="); ajaxUrl.append(vis.getFilterproperty()); ajaxUrl.append("&"); ajaxUrl.append(GetStatsLayerSLDHandler.PARAM_VISUALIZATION_CLASSES); ajaxUrl.append("="); ajaxUrl.append(vis.getClasses()); ajaxUrl.append("&"); ajaxUrl.append(GetStatsLayerSLDHandler.PARAM_VISUALIZATION_VIS); ajaxUrl.append("="); ajaxUrl.append(vis.getVisualization()); ajaxUrl.append(":"); ajaxUrl.append(vis.getColors()); } final StringBuffer queryString = new StringBuffer(); for (Object key : httpRequest.getParameterMap().keySet()) { String keyStr = (String) key; if(keyStr.equals(GetStatsLayerSLDHandler.PARAM_VISUALIZATION_NAME) || keyStr.equals(GetStatsLayerSLDHandler.PARAM_VISUALIZATION_FILTER_PROPERTY) || keyStr.equals(GetStatsLayerSLDHandler.PARAM_VISUALIZATION_CLASSES) || keyStr.equals(GetStatsLayerSLDHandler.PARAM_VISUALIZATION_VIS)) { // ignore SLD-paremeters continue; } queryString.append("&"); queryString.append(keyStr); queryString.append("="); queryString.append(params.getHttpParam(keyStr)); } try { final String url = geoserverUrl + queryString + "&SLD=" + URLEncoder.encode(ajaxUrl.toString(), "UTF-8"); log.debug("Getting stats tile from url:", url); return IOHelper.getConnection(url, geoserverUser, geoserverPass); } catch (Exception e) { throw new ActionException( "Couldnt get connection to geoserver", e); } } private StatsVisualization getVisualization(final ActionParameters params) { final int visId = ConversionHelper.getInt( params.getHttpParam(PARAM_VISUALIZATION_ID), -1); log.debug("visid: " + visId); log.debug("PARAM_VISUALIZATION_CLASSES: " + params.getHttpParam(PARAM_VISUALIZATION_CLASSES)); log.debug("PARAM_VISUALIZATION_NAME: " + params.getHttpParam(PARAM_VISUALIZATION_NAME)); log.debug("PARAM_VISUALIZATION_FILTER_PROPERTY: " + params.getHttpParam(PARAM_VISUALIZATION_FILTER_PROPERTY)); log.debug("PARAM_VISUALIZATION_VIS: " + params.getHttpParam(PARAM_VISUALIZATION_VIS, "")); return service.getVisualization( visId, params.getHttpParam(PARAM_VISUALIZATION_CLASSES), params.getHttpParam(PARAM_VISUALIZATION_NAME), params.getHttpParam(PARAM_VISUALIZATION_FILTER_PROPERTY), params.getHttpParam(PARAM_VISUALIZATION_VIS, "") ); } private String buildXML(final ActionParameters params) { // TODO: maybe create GetMap XML somewhere on service level and inject the SLD part here? Element getMapElement = null; try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); getMapElement = doc.createElement("ogc:GetMap"); Attr xmlns_ogc_attr = doc.createAttribute("xmlns:ogc"); xmlns_ogc_attr.setValue("http: getMapElement.setAttributeNode(xmlns_ogc_attr); Attr xmlns_gml_attr = doc.createAttribute("xmlns:gml"); xmlns_gml_attr.setValue("http: getMapElement.setAttributeNode(xmlns_gml_attr); Attr xversion_attr = doc.createAttribute("version"); xversion_attr.setValue(params.getHttpParam("VERSION", "1.1.1")); getMapElement.setAttributeNode(xversion_attr); Attr service_attr = doc.createAttribute("service"); service_attr.setValue(params.getHttpParam("SERVICE", "WMS")); getMapElement.setAttributeNode(service_attr); doc.appendChild(getMapElement); // styledLayerDescription elements // FIXME: use code from GetStatsLayerSLD/getSLD(params) to create!! Element styledLayerDescription = doc.createElement("StyledLayerDescriptor"); Attr version_attr = doc.createAttribute("version"); version_attr.setValue("1.0.0"); styledLayerDescription.setAttributeNode(version_attr); getMapElement.appendChild(styledLayerDescription); // NamedLayer elements Element namedLayer = doc.createElement("NamedLayer"); styledLayerDescription.appendChild(namedLayer); // Name element Element name = doc.createElement("Name"); name.appendChild(doc.createTextNode(params.getRequiredParam("LAYERS"))); namedLayer.appendChild(name); Element namedStyle = doc.createElement("NamedStyle"); Element name2 = doc.createElement("Name"); name2.appendChild(doc.createTextNode("polygon")); namedStyle.appendChild(name2); namedLayer.appendChild(namedStyle); Element boundingBox = doc.createElement("BoundingBox"); Attr srsName_attr = doc.createAttribute("srsName"); // FIXME: setup SRS correctly!! // SRS:EPSG:3067 srsName_attr.setValue("http://www.opengis.net/gml/srs/epsg.xml#3067"); boundingBox.setAttributeNode(srsName_attr); getMapElement.appendChild(boundingBox); // FIXME: setup bbox correctly!! // BBOX:-621248,6045776,1661248,8454224 Element gml_coord = doc.createElement("gml:coord"); boundingBox.appendChild(gml_coord); Element gml_x = doc.createElement("gml:x"); gml_x.appendChild(doc.createTextNode("-2132672")); gml_coord.appendChild(gml_x); Element gml_y = doc.createElement("gml:y"); gml_y.appendChild(doc.createTextNode("5721680")); gml_coord.appendChild(gml_y); Element gml_coord2 = doc.createElement("gml:coord"); boundingBox.appendChild(gml_coord2); Element gml_x2 = doc.createElement("gml:x"); gml_x2.appendChild(doc.createTextNode("3172672")); gml_coord2.appendChild(gml_x2); Element gml_y2 = doc.createElement("gml:y"); gml_y2.appendChild(doc.createTextNode("8778320")); gml_coord2.appendChild(gml_y2); Element output = doc.createElement("Output"); getMapElement.appendChild(output); Element format = doc.createElement("Format"); format.appendChild(doc.createTextNode(params.getHttpParam("FORMAT", "image/png"))); output.appendChild(format); Element size = doc.createElement("Size"); output.appendChild(size); Element width = doc.createElement("Width"); width.appendChild(doc.createTextNode(params.getRequiredParam("WIDTH"))); size.appendChild(width); Element height = doc.createElement("height"); height.appendChild(doc.createTextNode(params.getRequiredParam("HEIGHT"))); size.appendChild(height); final Transformer transformer = TransformerFactory.newInstance() .newTransformer(); final DOMSource source = new DOMSource(doc); final StringWriter outWriter = new StringWriter(); final StreamResult result = new StreamResult(outWriter); transformer.transform(source, result); String transformedResponse = outWriter.toString(); log.debug("GetMap.xml: ", transformedResponse); return transformedResponse; } catch (Exception e) { log.error(e, "Couldn't create GetMap XML-request"); } return null; } private String getSLD(final ActionParameters params) throws ActionException { final String PARAM_LANGUAGE = "lang"; final String PARAM_MODE = "mode"; final String MODE_XML = "XML"; printParameters(params); final String lang = params.getHttpParam(PARAM_LANGUAGE, params .getLocale().getLanguage()); final boolean modeXML = MODE_XML.equals(params.getHttpParam(PARAM_MODE, "").toUpperCase()); final StatsVisualization vis = getVisualization(params); if (vis == null) { throw new ActionParamsException("Couldn't get requested visualization"); } log.debug("Found visualization:", vis); final OMElement xml = service.getXML(vis, lang); try { if (modeXML) { return xml.toString(); } else { String xmlString = service.transform(xml, service.getDefaultXSLT()); log.debug("xmlString: " + xmlString); return xmlString; } } catch (Exception e) { throw new ActionException("Unable to create SLD", e); } } private void printParameters(ActionParameters params) { Enumeration e = params.getRequest().getParameterNames(); log.debug("GetStatsTile parameters:"); while (e.hasMoreElements()) { String key = (String) e.nextElement(); log.debug("Key: " + key); String[] values = params.getRequest().getParameterValues(key); for (String value : values) { log.debug(" value: " + value); } } } }
package org.spine3.server.storage.filesystem; import com.google.protobuf.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spine3.server.storage.CommandStoreRecord; import org.spine3.server.storage.EventStoreRecord; import javax.annotation.Nullable; import java.io.*; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.base.Throwables.propagate; import static java.nio.file.Files.copy; import static org.apache.commons.io.FileUtils.deleteDirectory; /** * TODO:2015-09-22:mikhail.mikhaylov: * This class should replace {@code org.spine3.sample.server.FileSystemHelper}. * Also, the old mechanism of working * with files should also be removed as soon as this is ready. * * @author Mikhail Mikhaylov * @author Alexander Litus */ @SuppressWarnings("UtilityClass") class Helper { private static final Logger LOG = LoggerFactory.getLogger(Helper.class); @SuppressWarnings("StaticNonFinalField") private static String fileStoragePath = null; private static final String COMMAND_STORE_FILE_NAME = "/command-store"; private static final String EVENT_STORE_FILE_NAME = "/event-store"; private static final String AGGREGATE_FILE_NAME_PREFIX = "/aggregate/"; private static final String PATH_DELIMITER = "/"; public static final String STORAGE_PATH_IS_NOT_SET = "Storage path is not set."; @SuppressWarnings("StaticNonFinalField") private static File backup = null; private Helper() { } /** * Configures helper with file storage path. * * @param executorClass execution context class. Is used to choose target directory. */ public static void configure(Class executorClass) { final String tempDir = getTempDir().getAbsolutePath(); fileStoragePath = tempDir + PATH_DELIMITER + executorClass.getSimpleName(); } /** * Removes all previous existing data from file system storage. */ public static void cleanTestData() { final File folder = new File(fileStoragePath); if (!folder.exists() || !folder.isDirectory()) { return; } try { deleteDirectory(folder); } catch (IOException e) { propagate(e); } } /** * Returns path for aggregate storage file. * * @param aggregateType the type of an aggregate * @param aggregateIdString String representation of aggregate id * @return absolute path string */ public static String getAggregateFilePath(String aggregateType, String aggregateIdString) { checkConfigured(); final String filePath = fileStoragePath + AGGREGATE_FILE_NAME_PREFIX + aggregateType + PATH_DELIMITER + aggregateIdString; return filePath; } /** * Returns common event store file path. * * @return absolute path string */ public static String getEventStoreFilePath() { checkConfigured(); final String filePath = fileStoragePath + EVENT_STORE_FILE_NAME; return filePath; } /** * Writes the {@code CommandStoreRecord} to common command store. * * @param record {@code CommandStoreRecord} instance */ @SuppressWarnings("TypeMayBeWeakened") public static void write(CommandStoreRecord record) { checkConfigured(); final String filePath = fileStoragePath + COMMAND_STORE_FILE_NAME; File file = new File(filePath); writeMessage(file, record); } /** * Writes the {@code EventStoreRecord} to common event store. * * @param record {@code EventStoreRecord} instance */ @SuppressWarnings("TypeMayBeWeakened") public static void write(EventStoreRecord record) { checkConfigured(); final String filePath = getEventStoreFilePath(); File file = new File(filePath); writeMessage(file, record); } /* * Closes streams in turn. */ @SuppressWarnings("ConstantConditions") public static void closeSilently(@Nullable Closeable... closeables) { if (closeables == null) { return; } try { for (Closeable c : closeables) { if (c != null) { c.close(); } } } catch (IOException e) { if (LOG.isWarnEnabled()) { LOG.warn("Exception while closing stream", e); } } } /* * Flushes streams in turn. */ @SuppressWarnings("ConstantConditions") public static void flushSilently(@Nullable Flushable... flushables) { if (flushables == null) { return; } try { for (Flushable f : flushables) { if (f != null) { f.flush(); } } } catch (IOException e) { if (LOG.isWarnEnabled()) { LOG.warn("Exception while flushing stream", e); } } } /* * Flushes and closes output streams in turn. */ @SuppressWarnings("ConstantConditions") public static void flushAndCloseSilently(@Nullable OutputStream... streams) { if (streams == null) { return; } flushSilently(streams); closeSilently(streams); } /** * Writes {@code Message} into {@code File} using {@code Message.writeDelimitedTo}. * * @param file a {@code File} to write data in * @param message data to extract */ @SuppressWarnings({"TypeMayBeWeakened", "ResultOfMethodCallIgnored", "OverlyBroadCatchBlock"}) private static void writeMessage(File file, Message message) { FileOutputStream fileOutputStream = null; OutputStream bufferedOutputStream = null; try { if (file.exists()) { backup = makeBackupCopy(file); } else { file.getParentFile().mkdirs(); file.createNewFile(); } fileOutputStream = new FileOutputStream(file, true); bufferedOutputStream = new BufferedOutputStream(fileOutputStream); message.writeDelimitedTo(bufferedOutputStream); if (backup != null) { backup.delete(); } } catch (IOException ignored) { restoreFromBackup(file); } finally { flushAndCloseSilently(fileOutputStream, bufferedOutputStream); } } private static void restoreFromBackup(File file) { boolean isDeleted = file.delete(); if (isDeleted && backup != null) { //noinspection ResultOfMethodCallIgnored backup.renameTo(file); } } private static File makeBackupCopy(File sourceFile) throws IOException { File backupFile = new File(sourceFile.toPath() + "_backup"); copy(sourceFile.toPath(), backupFile.toPath()); return backupFile; } @SuppressWarnings("StaticVariableUsedBeforeInitialization") private static void checkConfigured() { if (isNullOrEmpty(fileStoragePath)) { throw new IllegalStateException(STORAGE_PATH_IS_NOT_SET); } } private static File getTempDir() { try { File tmpFile = File.createTempFile("temp-dir-check", ".tmp"); File result = new File(tmpFile.getParent()); if (tmpFile.exists()) { //noinspection ResultOfMethodCallIgnored tmpFile.delete(); } return result; } catch (IOException e) { propagate(e); } throw new IllegalStateException("Unable to get temporary directory for storage"); } }
package org.song.http.framework; import android.util.Log; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import java.io.File; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public class RequestParams { private String charset; private String url; private List<String> pathParams;//path private Map<String, String> headers; private Map<String, Object> params; private RequestBody requestBody;//post/put private Map<String, RequestBody> multipartBody; private String multipartType; private Object tag; private String qsClient; private HttpEnum.RequestMethod requestMethod;// GET/P_FORM/... private HttpEnum.ResultType resultType; private HttpEnum.ParserMode parserMode;// string private HttpEnum.CacheMode cacheMode; private String downloadPath; private Class<?> _class; private Parser parser; private int cacheTime; private int timeOut; private RequestParams() { } public String charset() { return charset; } public String url() { return url; } public HttpEnum.RequestMethod requestMethod() { return requestMethod; } public HttpEnum.ResultType resultType() { return resultType; } public HttpEnum.CacheMode cacheMode() { return cacheMode; } public RequestBody requestBody() { return requestBody; } public Map<String, Object> params() { return params; } public Map<String, RequestBody> multipartBody() { return multipartBody; } public String multipartType() { return multipartType; } public Map<String, String> headers() { return headers; } public HttpEnum.ParserMode parserMode() { return parserMode; } public Class<?> get_class() { return _class; } public Parser parser() { return parser; } public Object tag() { return tag; } public int timeOut() { return timeOut; } public int cacheTime() { return cacheTime; } public String downloadPath() { return downloadPath; } /** * url */ public String urlEncode() { StringBuilder sbUrl = new StringBuilder(); sbUrl.append(urlAndPath()); if (params != null) { sbUrl.append('?'); for (String name : params.keySet()) { String value = String.valueOf(params.get(name)); sbUrl.append(Utils.URLEncoder(name, charset)) .append('=') .append(Utils.URLEncoder(value, charset)) .append('&'); } sbUrl.deleteCharAt(sbUrl.length() - 1); } return sbUrl.toString(); } /** * url */ public String urlAndPath() { StringBuilder sbUrl = new StringBuilder(url); if (pathParams != null) { for (String value : pathParams) { value = Utils.URLEncoder(value, charset); sbUrl.append("/").append(value); } } return sbUrl.toString(); } public Builder newBuild() { return newBuild(url); } public Builder newBuild(String url) { Builder builder = new Builder(url); builder.charset = charset; builder.url = url; builder.requestBody = requestBody; builder.pathParams = pathParams; builder.params = params; builder.multipartBody = multipartBody; builder.multipartType = multipartType; builder.headers = headers; builder.tag = tag; builder.qsClient = qsClient; builder.requestMethod = requestMethod; builder.resultType = resultType; builder.parserMode = parserMode; builder.cacheMode = cacheMode; builder._class = _class; builder.parser = parser; builder.downloadPath = downloadPath; builder.cacheTime = cacheTime; builder.timeOut = timeOut; return builder; } public static Builder Build(String url) { return new Builder(url); } public static final class Builder { private String charset = HttpEnum.CHARSET_UTF8; private String url; private RequestBody requestBody; private Map<String, String> headers; private Map<String, Object> params; private List<String> pathParams; private Map<String, RequestBody> multipartBody; private String multipartType; private Object tag; private HttpEnum.RequestMethod requestMethod = HttpEnum.RequestMethod.GET;// GET/P_FORM/... private HttpEnum.ResultType resultType = HttpEnum.ResultType.STRING; private HttpEnum.ParserMode parserMode = HttpEnum.ParserMode.NOTHING; private HttpEnum.CacheMode cacheMode = HttpEnum.CacheMode.NO_STORE; private Class<?> _class; private Parser parser; private String downloadPath; private String qsClient; private int cacheTime; private int timeOut; private boolean toJsonBodyFlag; private boolean toMultiBodyFlag; public Builder(String url) { this.url = url; } public RequestParams build() { if (toJsonBodyFlag & requestBody == null) { jsonBody(params); } else if (toMultiBodyFlag) { multipartBody(params); } RequestParams requestParams = new RequestParams(); requestParams.charset = charset; requestParams.url = url; requestParams.pathParams = pathParams; requestParams.requestBody = requestBody; requestParams.params = params; requestParams.multipartBody = multipartBody; requestParams.multipartType = multipartType; requestParams.headers = headers; requestParams.tag = tag; requestParams.qsClient = qsClient; requestParams.requestMethod = requestMethod; requestParams.resultType = resultType; requestParams.parserMode = parserMode; requestParams.cacheMode = cacheMode; requestParams._class = _class; requestParams.parser = parser; requestParams.cacheTime = cacheTime; requestParams.downloadPath = downloadPath; requestParams.timeOut = timeOut; return requestParams; } public RequestParams.Builder charset(String charset) { if (Charset.isSupported(charset)) this.charset = charset; else Log.e("RequestParams.Builder", charset + "is not support"); return this; } /** * * get/post/.. */ public RequestParams.Builder requestMethod(HttpEnum.RequestMethod requestMethod) { if (requestMethod != null) this.requestMethod = requestMethod; return this; } /** * string byte file */ public RequestParams.Builder resultType(HttpEnum.ResultType resultType) { if (resultType != null) this.resultType = resultType; return this; } public RequestParams.Builder resultByBytes() { return resultType(HttpEnum.ResultType.BYTES); } public RequestParams.Builder resultByFile(String downloadPath) { this.downloadPath = downloadPath; return resultType(HttpEnum.ResultType.FILE); } /** * json// * resultTypestring */ public RequestParams.Builder parserMode(HttpEnum.ParserMode parserMode) { if (parserMode != null) this.parserMode = parserMode; return this; } public RequestParams.Builder cacheMode(HttpEnum.CacheMode cacheMode) { if (cacheMode != null) this.cacheMode = cacheMode; return this; } public RequestParams.Builder noCache() { return cacheMode(HttpEnum.CacheMode.NO_CACHE); } public RequestParams.Builder noStore() { return cacheMode(HttpEnum.CacheMode.NO_STORE); } public RequestParams.Builder onlyIfCached() { return cacheMode(HttpEnum.CacheMode.ONLY_CACHE); } public RequestParams.Builder openServerCache() { return cacheMode(HttpEnum.CacheMode.SERVER_CACHE); } public RequestParams.Builder errCache() { return cacheMode(HttpEnum.CacheMode.ERR_CACHE); } public RequestParams.Builder clientCache(int timeout) { cacheTime(timeout); return cacheMode(HttpEnum.CacheMode.CLIENT_CACHE); } /** * http * Content-Type */ public RequestParams.Builder header(String key, String value) { if (headers == null) headers = new HashMap<>(); if (value != null) headers.put(key, value); else headers.remove(key); return this; } /** * get/xx/xxx */ public RequestParams.Builder path(Object... value) { if (pathParams == null) pathParams = new ArrayList<>(); if (value != null) for (Object o : value) if (o != null) pathParams.add(String.valueOf(o)); return this; } /** * (string file byte[]) */ public RequestParams.Builder param(String key, Object value) { if (params == null) params = new HashMap<>(); if (value != null) params.put(key, value); else params.remove(key); return this; } public RequestParams.Builder param(Object object) { if (object != null) { if (object.getClass().isArray() || object instanceof Collection) throw new IllegalArgumentException("param can not array"); if (object instanceof org.json.JSONObject) { object = object.toString(); } JSONObject jsonObject = (JSONObject) JSON.toJSON(object); for (String key : jsonObject.keySet()) param(key, jsonObject.get(key)); } return this; } public RequestParams.Builder param(Map<String, ?> params) { if (params != null) { for (String key : params.keySet()) param(key, params.get(key)); } return this; } /** * params json */ public RequestParams.Builder toJsonBody() { toJsonBodyFlag = true; return this; } /** * post/put json body */ public RequestParams.Builder jsonBody(Object object) { if (object instanceof org.json.JSONObject) { object = object.toString(); } requestBody(HttpEnum.CONTENT_TYPE_JSON_ + charset, JSON.toJSONString(object)); return this; } /** * post/put (file byte[] string */ public RequestParams.Builder requestBody(String contentType, Object content) { requestBody = new RequestBody(contentType, content); return this; } /** * params multipartBody */ public RequestParams.Builder toMultiBody() { return toMultiBody(HttpEnum.CONTENT_TYPE_FORM); } /** * params multipartBody */ public RequestParams.Builder toMultiBody(String multipartType) { if (toMultiBodyFlag) return this; toMultiBodyFlag = true; this.multipartType = multipartType; if (multipartBody == null) multipartBody = new HashMap<>(); return this; } public RequestParams.Builder multipartBody(String key, String contentType, String filename, Object value) { toMultiBody(); multipartBody.put(key, new RequestBody(contentType, filename, value)); return this; } private RequestParams.Builder multipartBody(Map<String, ?> params) { if (params != null) { for (String key : params.keySet()) { Object value = params.get(key); if (value instanceof File) { multipartBody(key, HttpEnum.CONTENT_TYPE_FORM, ((File) value).getName(), value); } else if (value instanceof byte[]) { multipartBody(key, HttpEnum.CONTENT_TYPE_FORM, "bytes", value); } else if (value != null) { multipartBody(key, HttpEnum.CONTENT_TYPE_TEXT_ + charset, null, value.toString()); } } } return this; } /** * * json */ public RequestParams.Builder jsonModel(Class<?> _class) { this._class = _class; parserMode(HttpEnum.ParserMode.JSON); return this; } public RequestParams.Builder parser(Parser parser) { this.parser = parser; parserMode(HttpEnum.ParserMode.COSTOM); return this; } /** * * QSHttpManage.addClient() */ public RequestParams.Builder qsClient(String qsClient) { this.qsClient = qsClient; return this; } public RequestParams.Builder tag(Object tag) { this.tag = tag; return this; } public RequestParams.Builder timeOut(int timeOut) { this.timeOut = timeOut; return this; } private RequestParams.Builder cacheTime(int cacheTime) { this.cacheTime = cacheTime; return this; } public int buildAndExecute(HttpCallback cb) { return build().execute(cb); } public int buildAndExecute() { return buildAndExecute(null); } } public static class RequestBody { private String contentType; private Object content;//byte file string ouputstream private String filename; public RequestBody(String contentType, Object content) { this(contentType, Long.toString(System.currentTimeMillis()), content); } public RequestBody(String contentType, String filename, Object content) { this.contentType = contentType; this.content = content; this.filename = filename; } public Object getContent() { return content; } public void setContent(Object content) { this.content = content; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getCharset() { return Utils.charsetName(contentType); } @Override public String toString() { return "{ " + "ContentType:" + contentType + "; filename:" + filename + "; Content:" + content + " }"; } } public int execute(HttpCallback cb) { if (qsClient == null) return QSHttpManage.getQSHttpClient().execute(this, cb); else return QSHttpManage.getQSHttpClient(qsClient).execute(this, cb); } }
package org.dataportal; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.dataportal.controllers.JPADownloadController; import org.dataportal.controllers.JPAUserController; import org.dataportal.csw.GetRecordById; import org.dataportal.model.Download; import org.dataportal.model.DownloadItem; import org.dataportal.model.User; import org.dataportal.utils.DataPortalException; import org.dataportal.utils.Utils; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Class to control the files download. Use a Cached Thread Pool to download * files concurrently * * @author Micho Garcia * */ public class DownloadController extends DataPortalController { private static Logger logger = Logger.getLogger(DownloadController.class); private static final String IDS = "//id/child::node()"; //$NON-NLS-1$ private static final String IDENTIFIERS = "//BriefRecord/identifier/child::node()"; //$NON-NLS-1$ private static final String ITEMS = "//item"; //$NON-NLS-1$ private static final String UNDERSCORE = "_"; //$NON-NLS-1$ private static final String SLASH = "/"; //$NON-NLS-1$ private static final int IDSNODELIST = 0; private static final int ITEMSSNODELIST = 1; private static final int IDENTIFIERSNODELIST = 0; private static final String ZIP = ".zip"; //$NON-NLS-1$ private static final ExecutorService threadsPool = Executors .newCachedThreadPool(); private String tempDir; private String id = null; /** * Constructor. Reads tempDir from properties file. * @throws MalformedURLException */ public DownloadController(String lang) throws MalformedURLException { super(); Messages.setLang(lang); this.tempDir = Config.get("temp.dir"); //$NON-NLS-1$ } /** * Create the pathfile with the information extracted from properties and * create the directory if not exists * * @param userName * User name from session (String) */ public String createPathFile(String userName) { String pathFile = this.tempDir + SLASH + userName; File personalDirectory = new File(pathFile); boolean exists = personalDirectory.exists(); if (!exists) { boolean createDir = personalDirectory.mkdir(); if (!createDir) pathFile = null; } return pathFile; } /** * Extract id's from client XML request. Checks whether id's are in the * server using a GetRecordById request. If checking is OK, extract the * URL's from client XML request and sends to DownloadController to download * files * * @param InputStream * with the XML sends by client * @param userName * String with user name * @return * @throws Exception */ public String askgn2download(InputStream isRequestXML) throws Exception { StringBuffer response = new StringBuffer(); String[] expresions = { IDS, ITEMS }; ArrayList<NodeList> nodes = new ArrayList<NodeList>(); nodes = extractNodeList(isRequestXML, expresions); ArrayList<String> requestIdes = Utils.nodeList2ArrayList(nodes .get(IDSNODELIST)); GetRecordById getRecordById = new GetRecordById("brief"); //$NON-NLS-1$ String getRecordByIdQuery = getRecordById.createQuery(requestIdes); InputStream isGetRecordByIdResponse = catalogo .sendCatalogRequest(getRecordByIdQuery); String[] identifiers = { IDENTIFIERS }; ArrayList<NodeList> identifierArrayList = extractNodeList( isGetRecordByIdResponse, identifiers); ArrayList<String> responseIdes = Utils .nodeList2ArrayList(identifierArrayList .get(IDENTIFIERSNODELIST)); ArrayList<String> noIdsResponse = Utils.compare2Arraylist(requestIdes, responseIdes); if (noIdsResponse.size() != 0) { logger.info("ID'S NO ENCONTRADOS: " //$NON-NLS-1$ + String.valueOf(noIdsResponse.size()) + " -> " //$NON-NLS-1$ + StringUtils.join(noIdsResponse, " : ")); //$NON-NLS-1$ dtException = new DataPortalException( Messages.getString("downloadcontroller.ids_not_found") //$NON-NLS-1$ + StringUtils.join(noIdsResponse, ", ")); //$NON-NLS-1$ dtException.setCode(IDNOTFOUND); throw dtException; } else { NodeList itemsNodeList = nodes.get(ITEMSSNODELIST); int nItems = itemsNodeList.getLength(); ArrayList<DownloadItem> items = new ArrayList<DownloadItem>(nItems); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(dataPortalCtx); for (int i = 0; i < nItems; i++) { DownloadItem item = new DownloadItem(); Node itemDom = itemsNodeList.item(i); item.setItemId(xpath.evaluate("id", itemDom)); //$NON-NLS-1$ item.setUrl(xpath.evaluate("data_link", itemDom)); //$NON-NLS-1$ item.setInstitution(xpath.evaluate("institution", itemDom)); //$NON-NLS-1$ item.setIcosDomain(xpath.evaluate("icos_domain", itemDom)); //$NON-NLS-1$ items.add(item); } String resultDownload = downloadDatasets(items, user.getId()); response.append(resultDownload); } logger.debug("RESPONSE CONTROLLER: " + response.toString()); //$NON-NLS-1$ return response.toString(); } public String getId() { return this.id; } /** * * Insert download into RDBMS * * @param user * User * @param fileName * String with filename * @param urlsRequest * url request array * @throws Exception */ private void insertDownload(User user, String uid, String fileName, ArrayList<DownloadItem> downloadItems) throws Exception { Timestamp timeStamp = Utils.extractDateSystemTimeStamp(); Download download = new Download(uid, fileName, timeStamp, user); downloadJPAController = new JPADownloadController(); downloadJPAController.insertItems(download, downloadItems); } /** * * Method to obtain DOI * * @return String with DOI */ private String generateId() { this.id = UUID.randomUUID().toString(); return this.id; } /** * @param Document * @param expresions * array * @return * @throws Exception */ private ArrayList<NodeList> extractNodeList(InputStream inputStream, String[] expresions) throws Exception { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document documentXML = (Document) dBuilder.parse(inputStream); NodeList nodelist; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(dataPortalCtx); ArrayList<NodeList> nodos = new ArrayList<NodeList>(); for (int n = 0; n < expresions.length; n++) { nodelist = (NodeList) xpath.evaluate(expresions[n], documentXML, XPathConstants.NODESET); nodos.add(nodelist); } return nodos; } /** * Method to download files from a url's array and make some necessary * operations like create readme file, compress files and save to rdbms the * download information * * @param urlsRequest * ArrayList with url's (ArrayList) * @return String with file name * @throws Exception */ private String downloadDatasets(ArrayList<DownloadItem> downloadItems, String userName) throws Exception { User anUser = new User(userName); userJPAController = new JPAUserController(); User user = userJPAController.existsInto(anUser); if (user == null) { dtException = new DataPortalException( Messages.getString("downloadcontroller.user_not_found") + userName); //$NON-NLS-1$ dtException.setCode(USERNOTFOUND); throw dtException; } StringBuffer response = new StringBuffer(); String pathFile = createPathFile(userName); String nameFile = userName + UNDERSCORE + Utils.extractDateSystem(); if (pathFile == null) { dtException = new DataPortalException(Messages.getString("downloadcontroller.failed_create_dir")); //$NON-NLS-1$ dtException.setCode(FAILECREATEDIRECTORY); throw dtException; } else { String[] files = createDownloadThreads(downloadItems, pathFile); String uid = this.generateId(); Map<String, String> params = new HashMap<String, String>(); params.put("ddi", uid); //$NON-NLS-1$ File readmeFile = createReadmeFile(params, pathFile); compressFiles(pathFile, readmeFile, files, nameFile); insertDownload(user, uid, nameFile + ZIP, downloadItems); logger.debug("FILE to download: " + nameFile + ZIP); //$NON-NLS-1$ response.append(nameFile + ZIP); } return response.toString(); } /** * Create README file in user folder with download information * * @param vars * @param pathFile * @return Returns the readme file ready to compress * @throws IOException */ private File createReadmeFile(Map<String, String> vars, String pathFile) throws IOException { InputStream is = DownloadController.class .getResourceAsStream("/README.txt"); //$NON-NLS-1$ String readmeString = IOUtils.toString(is, "UTF-8"); //$NON-NLS-1$ for (Map.Entry<String, String> var : vars.entrySet()) { readmeString = readmeString.replaceAll( "\\{" + var.getKey() + "\\}", var.getValue()); //$NON-NLS-1$ //$NON-NLS-2$ } File readmeFile = new File(pathFile + "/README.txt" + "_" + System.currentTimeMillis()); //$NON-NLS-1$ FileUtils.writeStringToFile(readmeFile, readmeString); return readmeFile; } /** * * Create all Threads to download files * * @param urlsRequest * URL's ArrayList * @param pathFile * path to save files * @throws MalformedURLException * @throws InterruptedException * @throws ExecutionException */ private String[] createDownloadThreads( ArrayList<DownloadItem> downloadItems, String pathFile) throws MalformedURLException, InterruptedException, ExecutionException { int nItems = downloadItems.size(); @SuppressWarnings("unchecked") Future<String> futures[] = new Future[nItems]; for (int i = 0; i < nItems; i++) { String url = downloadItems.get(i).getUrl(); String name = StringUtils.substringAfterLast(url, SLASH); DownloadCallable hiloDescarga = new DownloadCallable(url, name, pathFile); futures[i] = threadsPool.submit(hiloDescarga); } String[] files = new String[futures.length]; for (int i = 0; i < nItems; i++) { String tarea = futures[i].get(); files[i] = tarea; logger.info("DOWNLOADING FINISH: " + tarea); //$NON-NLS-1$ } return files; } /** * Returns an inputStream to download the compressed file * * @param fileName * Name of compressed file * @param userName * User name that generated the file * @return * @throws FileNotFoundException */ public InputStream getFileContents(String fileName) throws FileNotFoundException { File file = new File(this.tempDir + SLASH + user.getId() + SLASH + fileName); return new FileInputStream(file); } /** * Returns the downloadable file size * * @param fileName * Name of compressed file * @param userName * User name that generated the file * @return * @throws FileNotFoundException */ public long getFileSize(String fileName) throws FileNotFoundException { File file = new File(this.tempDir + SLASH + user.getId() + SLASH + fileName); if (file.exists() && file.isFile()) return file.length(); else return 0; } /** * * Compress in tar format files in directory * * @param pathDir * directory path (String) * @param readmeFile * The file containing the instructions * @param files * The files in pathDir to add to the zip file * @param nameFile * archive name (String) * @throws IOException */ private void compressFiles(String pathDir, File readmeFile, String[] files, String nameFile) throws IOException { String filePathName = pathDir + SLASH + nameFile + ".zip"; //$NON-NLS-1$ OutputStream os = new FileOutputStream(filePathName); ZipArchiveOutputStream zipOs = new ZipArchiveOutputStream(os); addToZip(zipOs, readmeFile); for (String filePath : files) { File fl = new File(filePath); addToZip(zipOs, fl); } zipOs.finish(); zipOs.close(); os.close(); } private void addToZip(ZipArchiveOutputStream zipOs, File fl) throws IOException { ArchiveEntry archFl = zipOs.createArchiveEntry(fl, getName(fl)); zipOs.putArchiveEntry(archFl); zipOs.write(FileUtils.readFileToByteArray(fl)); zipOs.flush(); zipOs.closeArchiveEntry(); FileUtils.forceDelete(fl); } private String getName(File fl) { String name = fl.getName(); return name.substring(0, name.lastIndexOf('_')); } }
package com.gentics.mesh.graphdb; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringEscapeUtils; import com.gentics.mesh.etc.GraphStorageOptions; import com.gentics.mesh.graphdb.ferma.AbstractDelegatingFramedOrientGraph; import com.gentics.mesh.graphdb.model.MeshElement; import com.gentics.mesh.graphdb.spi.AbstractDatabase; import com.gentics.mesh.graphdb.spi.Database; import com.gentics.mesh.graphdb.spi.TrxHandler; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.command.OCommandOutputListener; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.db.tool.ODatabaseExport; import com.orientechnologies.orient.core.db.tool.ODatabaseImport; import com.orientechnologies.orient.core.exception.OConcurrentModificationException; import com.orientechnologies.orient.core.exception.OSchemaException; import com.orientechnologies.orient.core.index.OCompositeKey; import com.orientechnologies.orient.core.index.OIndex; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.server.OServer; import com.orientechnologies.orient.server.OServerMain; import com.orientechnologies.orient.server.plugin.OServerPluginManager; import com.syncleus.ferma.FramedGraph; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.TransactionalGraph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; import com.tinkerpop.blueprints.impls.orient.OrientEdgeType; import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory; import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; import com.tinkerpop.blueprints.impls.orient.OrientVertex; import com.tinkerpop.blueprints.impls.orient.OrientVertexType; import com.tinkerpop.blueprints.util.wrappers.wrapped.WrappedVertex; import io.vertx.core.Vertx; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * OrientDB specific mesh graph database implementation. */ public class OrientDBDatabase extends AbstractDatabase { private static final Logger log = LoggerFactory.getLogger(OrientDBDatabase.class); private OrientGraphFactory factory; private DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy_HH-mm-ss-SSS"); private int maxRetry = 25; @Override public void stop() { factory.close(); Orient.instance().shutdown(); Database.setThreadLocalGraph(null); } @Override public void init(GraphStorageOptions options, Vertx vertx) throws Exception { super.init(options, vertx); if (options != null && options.getParameters() != null && options.getParameters().get("maxTransactionRetry") != null) { this.maxRetry = options.getParameters().get("maxTransactionRetry").getAsInt(); log.info("Using {" + this.maxRetry + "} transaction retries before failing"); } } // Code is broken and cause NPE and stuck tests: // @Override // public void clear() { // OrientGraphNoTx noTx = factory.getNoTx(); // try { // noTx.drop(); // } finally { // noTx.shutdown(); @Override public TransactionalGraph rawTx() { return factory.getTx(); } @Override public void start() throws Exception { Orient.instance().startup(); if (options == null || options.getDirectory() == null) { log.info("No graph database settings found. Fallback to in memory mode."); factory = new OrientGraphFactory("memory:tinkerpop").setupPool(5, 100); } else { factory = new OrientGraphFactory("plocal:" + options.getDirectory()).setupPool(5, 100); } if (options != null && options.getStartServer()) { startOrientServer(); } configureGraphDB(); } private InputStream getOrientServerConfig() throws IOException { InputStream configIns = getClass().getResourceAsStream("/config/orientdb-server-config.xml"); StringWriter writer = new StringWriter(); IOUtils.copy(configIns, writer, StandardCharsets.UTF_8); String configString = writer.toString(); configString = configString.replaceAll("%PLUGIN_DIRECTORY%", "orient-plugins"); configString = configString.replaceAll("%CONSOLE_LOG_LEVEL%", "finest"); configString = configString.replaceAll("%FILE_LOG_LEVEL%", "fine"); String safePath = StringEscapeUtils.escapeJava(StringEscapeUtils.escapeXml11(new File(options.getDirectory()).getAbsolutePath())); configString = configString.replaceAll("%MESH_DB_PATH%", "plocal:" + safePath); if (log.isDebugEnabled()) { log.debug("Effective orientdb server configuration:" + configString); } String safeParentDirPath = StringEscapeUtils .escapeJava(StringEscapeUtils.escapeXml11(new File(options.getDirectory()).getParentFile().getAbsolutePath())); configString = configString.replaceAll("%MESH_DB_PARENT_PATH%", safeParentDirPath); System.out.println(configString); InputStream stream = new ByteArrayInputStream(configString.getBytes(StandardCharsets.UTF_8)); return stream; } private void startOrientServer() throws Exception { String orientdbHome = new File("").getAbsolutePath(); System.setProperty("ORIENTDB_HOME", orientdbHome); System.out.println(orientdbHome); OServer server = OServerMain.create(); log.info("Extracting OrientDB Studio"); InputStream ins = getClass().getResourceAsStream("/plugins/studio-2.2.zip"); File pluginDirectory = new File("orient-plugins"); pluginDirectory.mkdirs(); IOUtils.copy(ins, new FileOutputStream(new File(pluginDirectory, "studio-2.2.zip"))); server.startup(getOrientServerConfig()); OServerPluginManager manager = new OServerPluginManager(); manager.config(server); server.activate(); manager.startup(); } private void configureGraphDB() { log.info("Configuring orientdb..."); OrientGraphNoTx tx = factory.getNoTx(); try { tx.setUseLightweightEdges(false); tx.setUseVertexFieldsForEdgeLabels(false); } finally { tx.shutdown(); } } @Override public void addEdgeIndex(String label, String... extraFields) { OrientGraphNoTx tx = factory.getNoTx(); try { OrientEdgeType e = tx.getEdgeType(label); if (e == null) { e = tx.createEdgeType(label); } if (e.getProperty("in") == null) { e.createProperty("in", OType.LINK); } if (e.getProperty("out") == null) { e.createProperty("out", OType.LINK); } for (String key : extraFields) { if (e.getProperty(key) == null) { e.createProperty(key, OType.STRING); } } String indexName = "e." + label.toLowerCase(); List<String> fields = new ArrayList<>(Arrays.asList("out", "in")); fields.addAll(Arrays.asList(extraFields)); if (e.getClassIndex(indexName) == null) { e.createIndex(indexName, OClass.INDEX_TYPE.UNIQUE_HASH_INDEX, fields.toArray(new String[fields.size()])); } } finally { tx.shutdown(); } } @Override public Iterator<Vertex> getVertices(Class<?> classOfVertex, String[] fieldNames, Object[] fieldValues) { FramedGraph graph = Database.getThreadLocalGraph(); Graph baseGraph = ((AbstractDelegatingFramedOrientGraph) graph).getBaseGraph(); OrientBaseGraph orientBaseGraph = ((OrientBaseGraph) baseGraph); return orientBaseGraph.getVertices(classOfVertex.getSimpleName(), fieldNames, fieldValues).iterator(); } /** * Unwrap the current thread local graph. * * @return */ private OrientBaseGraph unwrapCurrentGraph() { FramedGraph graph = Database.getThreadLocalGraph(); Graph baseGraph = ((AbstractDelegatingFramedOrientGraph) graph).getBaseGraph(); OrientBaseGraph tx = ((OrientBaseGraph) baseGraph); return tx; } @Override public void addEdgeType(String label, String... stringPropertyKeys) { if (log.isDebugEnabled()) { log.debug("Adding edge type for label {" + label + "}"); } OrientBaseGraph tx = unwrapCurrentGraph(); OrientEdgeType e = tx.getEdgeType(label); if (e == null) { e = tx.createEdgeType(label); } for (String key : stringPropertyKeys) { if (e.getProperty(key) == null) { e.createProperty(key, OType.STRING); } } } @Override public void addVertexType(Class<?> clazzOfVertex, Class<?> superClazzOfVertex) { if (log.isDebugEnabled()) { log.debug("Adding vertex type for class {" + clazzOfVertex.getName() + "}"); } OrientGraphNoTx tx = factory.getNoTx(); try { OrientVertexType e = tx.getVertexType(clazzOfVertex.getSimpleName()); if (e == null) { String superClazz = "V"; if (superClazzOfVertex != null) { superClazz = superClazzOfVertex.getSimpleName(); } e = tx.createVertexType(clazzOfVertex.getSimpleName(), superClazz); } else { if (superClazzOfVertex != null) { OrientVertexType superType = tx.getVertexType(superClazzOfVertex.getSimpleName()); if (superType == null) { throw new RuntimeException("The supertype for vertices of type {" + clazzOfVertex + "} can't be set since the supertype {" + superClazzOfVertex.getSimpleName() + "} was not yet added to orientdb."); } e.setSuperClass(superType); } } } finally { tx.shutdown(); } } @Override public void addEdgeIndexSource(String label) { if (log.isDebugEnabled()) { log.debug("Adding source edge index for label {" + label + "}"); } OrientGraphNoTx tx = factory.getNoTx(); try { OrientEdgeType e = tx.getEdgeType(label); if (e == null) { e = tx.createEdgeType(label); } if (e.getProperty("out") == null) { e.createProperty("out", OType.LINK); } String indexName = "e." + label.toLowerCase(); String[] fields = { "out" }; if (e.getClassIndex(indexName) == null) { e.createIndex(indexName, OClass.INDEX_TYPE.NOTUNIQUE_HASH_INDEX, fields); } } finally { tx.shutdown(); } } @Override public void addVertexIndex(String indexName, Class<?> clazzOfVertices, boolean unique, String... fields) { if (log.isDebugEnabled()) { log.debug("Adding vertex index for class {" + clazzOfVertices.getName() + "}"); } OrientGraphNoTx tx = factory.getNoTx(); try { String name = clazzOfVertices.getSimpleName(); OrientVertexType v = tx.getVertexType(name); if (v == null) { throw new RuntimeException("Vertex type {" + name + "} is unknown. Can't create index {" + indexName + "}"); } for (String field : fields) { if (v.getProperty(field) == null) { v.createProperty(field, OType.STRING); } } if (v.getClassIndex(indexName) == null) { v.createIndex(indexName, unique ? OClass.INDEX_TYPE.UNIQUE_HASH_INDEX.toString() : OClass.INDEX_TYPE.NOTUNIQUE_HASH_INDEX.toString(), null, new ODocument().fields("ignoreNullValues", true), fields); } } finally { tx.shutdown(); } } @Override public <T extends MeshElement> T checkIndexUniqueness(String indexName, T element, Object key) { FramedGraph graph = Database.getThreadLocalGraph(); OrientBaseGraph orientBaseGraph = unwrapCurrentGraph(); OrientVertexType vertexType = orientBaseGraph.getVertexType(element.getClass().getSimpleName()); if (vertexType != null) { OIndex<?> index = vertexType.getClassIndex(indexName); if (index != null) { Object recordId = index.get(key); if (recordId != null) { if (recordId.equals(element.getElement().getId())) { return null; } else { return (T) graph.getFramedVertexExplicit(element.getClass(), recordId); } } } } return null; } @Override public <T extends MeshElement> T checkIndexUniqueness(String indexName, Class<T> classOfT, Object key) { FramedGraph graph = Database.getThreadLocalGraph(); Graph baseGraph = ((AbstractDelegatingFramedOrientGraph) graph).getBaseGraph(); OrientBaseGraph orientBaseGraph = ((OrientBaseGraph) baseGraph); OrientVertexType vertexType = orientBaseGraph.getVertexType(classOfT.getSimpleName()); if (vertexType != null) { OIndex<?> index = vertexType.getClassIndex(indexName); if (index != null) { Object recordId = index.get(key); if (recordId != null) { return (T) graph.getFramedVertexExplicit(classOfT, recordId); } } } return null; } @Override public void reload(MeshElement element) { ((OrientVertex) element.getElement()).reload(); } @Override public Trx trx() { return new OrientDBTrx(factory); } @Override public <T> T trx(TrxHandler<T> txHandler) { /** * OrientDB uses the MVCC pattern which requires a retry of the code that manipulates the graph in cases where for example an * {@link OConcurrentModificationException} is thrown. */ T handlerResult = null; boolean handlerFinished = false; for (int retry = 0; retry < maxRetry; retry++) { try (Trx tx = trx()) { handlerResult = txHandler.call(); handlerFinished = true; tx.success(); } catch (OSchemaException e) { log.error("OrientDB schema exception detected."); // TODO maybe we should invoke a metadata getschema reload? // factory.getTx().getRawGraph().getMetadata().getSchema().reload(); // Database.getThreadLocalGraph().getMetadata().getSchema().reload(); } catch (OConcurrentModificationException e) { if (log.isTraceEnabled()) { log.trace("Error while handling transaction. Retrying " + retry, e); } try { // Delay the retry by 50ms to give the other transaction a chance to finish Thread.sleep(50); } catch (InterruptedException e1) { e1.printStackTrace(); } // Reset previous result handlerFinished = false; handlerResult = null; } catch (RuntimeException e) { log.error("Error handling transaction", e); throw e; } catch (Exception e) { log.error("Error handling transaction", e); throw new RuntimeException("Transaction error", e); } if (log.isDebugEnabled()) { log.debug("Retrying .. {" + retry + "}"); } if (handlerFinished) { return handlerResult; } } throw new RuntimeException("Retry limit for trx exceeded"); } @Override public NoTrx noTrx() { return new OrientDBNoTrx(factory); } @Override public void backupGraph(String backupDirectory) throws IOException { ODatabaseDocumentTx db = factory.getDatabase(); try { OCommandOutputListener listener = new OCommandOutputListener() { @Override public void onMessage(String iText) { System.out.println(iText); } }; String dateString = formatter.format(new Date()); String backupFile = "backup_" + dateString + ".zip"; OutputStream out = new FileOutputStream(new File(backupDirectory, backupFile).getAbsolutePath()); db.backup(out, null, null, listener, 9, 2048); } finally { db.close(); } } @Override public void restoreGraph(String backupFile) throws IOException { ODatabaseDocumentTx db = factory.getDatabase(); try { OCommandOutputListener listener = new OCommandOutputListener() { @Override public void onMessage(String iText) { System.out.println(iText); } }; InputStream in = new FileInputStream(backupFile); db.restore(in, null, null, listener); } finally { db.close(); } } @Override public void exportGraph(String outputDirectory) throws IOException { ODatabaseDocumentTx db = factory.getDatabase(); try { OCommandOutputListener listener = new OCommandOutputListener() { @Override public void onMessage(String iText) { System.out.println(iText); } }; String dateString = formatter.format(new Date()); String exportFile = "export_" + dateString; ODatabaseExport export = new ODatabaseExport(db, new File(outputDirectory, exportFile).getAbsolutePath(), listener); export.exportDatabase(); export.close(); } finally { db.close(); } } @Override public void importGraph(String importFile) throws IOException { ODatabaseDocumentTx db = factory.getDatabase(); try { OCommandOutputListener listener = new OCommandOutputListener() { @Override public void onMessage(String iText) { System.out.println(iText); } }; ODatabaseImport databaseImport = new ODatabaseImport(db, importFile, listener); databaseImport.importDatabase(); databaseImport.close(); } finally { db.close(); } } @Override public Object createComposedIndexKey(Object... keys) { return new OCompositeKey(keys); } @Override public void setVertexType(Element element, Class<?> classOfVertex) { if (element instanceof WrappedVertex) { element = ((WrappedVertex) element).getBaseElement(); } ((OrientVertex) element).moveToClass(classOfVertex.getSimpleName()); } }
package io.spine.server.storage.datastore; import com.google.cloud.datastore.Datastore; import com.google.cloud.datastore.DatastoreException; import com.google.cloud.datastore.DatastoreOptions; import com.google.cloud.datastore.DatastoreReader; import com.google.cloud.datastore.DatastoreReaderWriter; import com.google.cloud.datastore.DatastoreWriter; import com.google.cloud.datastore.Entity; import com.google.cloud.datastore.EntityQuery; import com.google.cloud.datastore.FullEntity; import com.google.cloud.datastore.Key; import com.google.cloud.datastore.KeyFactory; import com.google.cloud.datastore.KeyQuery; import com.google.cloud.datastore.ProjectionEntityQuery; import com.google.cloud.datastore.Query; import com.google.cloud.datastore.StructuredQuery; import com.google.cloud.datastore.Transaction; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.common.collect.Collections2; import com.google.common.collect.Iterators; import io.spine.server.storage.datastore.tenant.DsNamespaceValidator; import io.spine.server.storage.datastore.tenant.Namespace; import io.spine.server.storage.datastore.tenant.NamespaceSupplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.newLinkedList; import static java.lang.Math.min; /** * Represents a wrapper above GAE {@link Datastore}. * * <p>Provides API for Datastore to be used in storages. * * @author Dmytro Dashenkov */ public class DatastoreWrapper { private static final String ACTIVE_TRANSACTION_CONDITION_MESSAGE = "Transaction should be active."; private static final String NOT_ACTIVE_TRANSACTION_CONDITION_MESSAGE = "Transaction should NOT be active."; private static final int MAX_KEYS_PER_READ_REQUEST = 1000; private static final int MAX_ENTITIES_PER_WRITE_REQUEST = 500; private static final Map<Kind, KeyFactory> keyFactories = new HashMap<>(); private final NamespaceSupplier namespaceSupplier; private final Datastore datastore; private Transaction activeTransaction; private DatastoreReaderWriter actor; private DsNamespaceValidator namespaceValidator; /** * Creates a new instance of {@code DatastoreWrapper}. * * @param datastore {@link Datastore} to wrap * @param namespaceSupplier the instance of {@link Supplier Namespace Supplier}, providing * the namespaces for Datastore queries */ protected DatastoreWrapper(Datastore datastore, NamespaceSupplier namespaceSupplier) { this.namespaceSupplier = checkNotNull(namespaceSupplier); this.datastore = checkNotNull(datastore); this.actor = datastore; } /** * Wraps {@link Datastore} into an instance of {@code DatastoreWrapper} and returns * the instance. * * @param datastore {@link Datastore} to wrap * @param namespaceSupplier an instance of {@link Supplier Supplier&lt;Namespace&gt;} to get the * namespaces for the queries from * @return new instance of {@code DatastoreWrapper} */ @SuppressWarnings("WeakerAccess") // Part of API protected static DatastoreWrapper wrap(Datastore datastore, NamespaceSupplier namespaceSupplier) { return new DatastoreWrapper(datastore, namespaceSupplier); } /** * Writes new {@link Entity} into the Datastore. * * @param entity new {@link Entity} to put into the Datastore * @throws DatastoreException upon failure * @see DatastoreWriter#put(FullEntity) */ @SuppressWarnings("WeakerAccess") public void create(Entity entity) throws DatastoreException { actor.add(entity); } /** * Modifies an {@link Entity} in the Datastore. * * @param entity the {@link Entity} to update * @throws DatastoreException if the {@link Entity} with such {@link Key} does not exist * @see DatastoreWriter#update(Entity...) */ @SuppressWarnings("WeakerAccess") public void update(Entity entity) throws DatastoreException { actor.update(entity); } /** * Writes an {@link Entity} to the Datastore or modifies an existing one. * * @param entity the {@link Entity} to write or update * @see DatastoreWrapper#create(Entity) * @see DatastoreWrapper#update(Entity) */ public void createOrUpdate(Entity entity) { actor.put(entity); } /** * Writes the {@link Entity entities} to the Datastore or modifies the existing ones. * * @param entities the {@link Entity Entities} to write or update * @see DatastoreWrapper#createOrUpdate(Entity) */ public void createOrUpdate(Entity... entities) { if (entities.length <= MAX_ENTITIES_PER_WRITE_REQUEST) { writeSmallBulk(entities); } else { writeBulk(entities); } } /** * Writes the {@link Entity entities} to the Datastore or modifies the existing ones. * * @param entities a {@link Collection} of {@link Entity Entities} to write or update * @see DatastoreWrapper#createOrUpdate(Entity) */ public void createOrUpdate(Collection<Entity> entities) { final Entity[] array = new Entity[entities.size()]; entities.toArray(array); createOrUpdate(array); } /** * Retrieves an {@link Entity} with the given key from the Datastore. * * @param key {@link Key} to search for * @return the {@link Entity} or {@code null} in case of no results for the key given * @see DatastoreReader#get(Key) */ public Entity read(Key key) { return actor.get(key); } /** * Retrieves an {@link Entity} for each of the given keys. * * @param keys {@link Key Keys} to search for * @return A list of found entities in the order of keys (including {@code null} values for * nonexistent keys) * @see DatastoreReader#get(Key...) */ public Iterator<Entity> read(Iterable<Key> keys) { final List<Key> keysList = newLinkedList(keys); final Iterator<Entity> result; if (keysList.size() <= MAX_KEYS_PER_READ_REQUEST) { result = datastore.get(keys); // TODO:2017-06-30:dmytro.dashenkov: Use `actor`? } else { result = readBulk(keysList); } return result; } /** * Queries the Datastore with the given arguments. * * <p>As the Datastore may return a partial result set for {@link EntityQuery}, * {@link KeyQuery} and {@link ProjectionEntityQuery}, it is required to repeat a query with * the adjusted cursor position. * * <p>Therefore, an execution of this method may in fact result in several queries to * the Datastore instance. * * @param query {@link Query} to execute upon the Datastore * @return results fo the query packed in a {@link List} * @see DatastoreReader#run(Query) */ @SuppressWarnings("LoopConditionNotUpdatedInsideLoop") // Implicit call to Iterator.next() in Iterators.addAll public Iterator<Entity> read(StructuredQuery<Entity> query) { final Namespace namespace = getNamespace(); final StructuredQuery<Entity> queryWithNamespace = query.toBuilder() .setNamespace(namespace.getValue()) .build(); final Iterator<Entity> result = new DsQueryIterator(queryWithNamespace, actor); return result; } /** * Deletes all existing {@link Entity Entities} with the given keys. * * @param keys {@link Key Keys} of the {@link Entity Entities} to delete. May be nonexistent */ public void delete(Key... keys) { actor.delete(keys); } /** * Deletes all existing {@link Entities} of a kind given. * * @param table kind (a.k.a. type, table, etc.) of the records to delete */ void dropTable(String table) { final Namespace namespace = getNamespace(); final StructuredQuery<Entity> query = Query.newEntityQueryBuilder() .setNamespace(namespace.getValue()) .setKind(table) .build(); final Iterator<Entity> queryResult = read(query); final List<Entity> entities = newArrayList(queryResult); final Collection<Key> keys = Collections2.transform(entities, new Function<Entity, Key>() { @Nullable @Override public Key apply(@Nullable Entity input) { if (input == null) { return null; } return input.getKey(); } }); final Key[] keysArray = new Key[keys.size()]; keys.toArray(keysArray); dropTableInternal(keysArray); } void dropTableInternal(Key[] keysArray) { if (keysArray.length > MAX_ENTITIES_PER_WRITE_REQUEST) { int start = 0; int end = MAX_ENTITIES_PER_WRITE_REQUEST; while (true) { final int length = end - start; if (length <= 0) { return; } final Key[] keysSubarray = new Key[length]; System.arraycopy(keysArray, start, keysSubarray, 0, keysSubarray.length); delete(keysSubarray); start = end; end = min(MAX_ENTITIES_PER_WRITE_REQUEST, keysArray.length - end); } } else { delete(keysArray); } } @SuppressWarnings("WeakerAccess") // Part of API public void startTransaction() throws IllegalStateException { checkState(!isTransactionActive(), NOT_ACTIVE_TRANSACTION_CONDITION_MESSAGE); activeTransaction = datastore.newTransaction(); actor = activeTransaction; } @SuppressWarnings("WeakerAccess") // Part of API public void commitTransaction() throws IllegalStateException { checkState(isTransactionActive(), ACTIVE_TRANSACTION_CONDITION_MESSAGE); activeTransaction.commit(); this.actor = datastore; } @SuppressWarnings("WeakerAccess") // Part of API public void rollbackTransaction() throws IllegalStateException { checkState(isTransactionActive(), ACTIVE_TRANSACTION_CONDITION_MESSAGE); activeTransaction.rollback(); this.actor = datastore; } /** * Checks whether there is an active transaction on this instance of {@code DatastoreWrapper}. * * @return {@code true} if there is an active transaction, {@code false} otherwise */ @SuppressWarnings("WeakerAccess") // Part of API public boolean isTransactionActive() { return activeTransaction != null && activeTransaction.isActive(); } /** * Retrieves an instance of {@link KeyFactory} unique for given Kind of data regarding the current namespace. * * @param kind kind of {@link Entity} to generate keys for * @return an instance of {@link KeyFactory} for given kind */ public KeyFactory getKeyFactory(Kind kind) { KeyFactory keyFactory = keyFactories.get(kind); if (keyFactory == null) { keyFactory = initKeyFactory(kind); } final Namespace namespace = getNamespace(); keyFactory.setNamespace(namespace.getValue()); return keyFactory; } public DatastoreOptions getDatastoreOptions() { final DatastoreOptions options = datastore.getOptions() .toBuilder() .build(); return options; } @VisibleForTesting Datastore getDatastore() { return datastore; } private KeyFactory initKeyFactory(Kind kind) { final KeyFactory keyFactory = datastore.newKeyFactory() .setKind(kind.getValue()); keyFactories.put(kind, keyFactory); return keyFactory; } private Iterator<Entity> readBulk(List<Key> keys) { final int pageCount = keys.size() / MAX_KEYS_PER_READ_REQUEST + 1; log().debug("Reading a big bulk of entities synchronously. The data is read as {} pages.", pageCount); int lowerBound = 0; int higherBound = MAX_KEYS_PER_READ_REQUEST; int keysLeft = keys.size(); Iterator<Entity> result = null; for (int i = 0; i < pageCount; i++) { final List<Key> keysPage = keys.subList(lowerBound, higherBound); final Iterator<Entity> page = datastore.get(keysPage); result = concat(result, page); keysLeft -= keysPage.size(); lowerBound = higherBound; higherBound += min(keysLeft, MAX_KEYS_PER_READ_REQUEST); } return result; } private void writeBulk(Entity[] entities) { final int partsCount = entities.length / MAX_ENTITIES_PER_WRITE_REQUEST + 1; for (int i = 0; i < partsCount; i++) { final int partHead = i * MAX_ENTITIES_PER_WRITE_REQUEST; final int partTail = min(partHead + MAX_ENTITIES_PER_WRITE_REQUEST, entities.length); final Entity[] part = Arrays.copyOfRange(entities, partHead, partTail); writeSmallBulk(part); } } private Namespace getNamespace() { final Namespace namespace = namespaceSupplier.get(); namespaceValidator().validate(namespace); return namespace; } private DsNamespaceValidator namespaceValidator() { if (namespaceValidator == null) { namespaceValidator = new DsNamespaceValidator(getDatastore(), namespaceSupplier.isMultitenant()); } return namespaceValidator; } private void writeSmallBulk(Entity[] entities) { actor.put(entities); } private static Iterator<Entity> concat(@Nullable Iterator<Entity> first, Iterator<Entity> second) { if (first == null) { return second; } return Iterators.concat(first, second); } private static Logger log() { return LoggerSingleton.INSTANCE.logger; } private enum LoggerSingleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Logger logger = LoggerFactory.getLogger(DatastoreWrapper.class); } }
package de.dentrassi.pm.importer.aether; import java.nio.file.Path; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.eclipse.aether.ConfigurationProperties; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory; import org.eclipse.aether.impl.DefaultServiceLocator; import org.eclipse.aether.impl.DefaultServiceLocator.ErrorHandler; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.spi.connector.RepositoryConnectorFactory; import org.eclipse.aether.spi.connector.transport.TransporterFactory; import org.eclipse.aether.transport.file.FileTransporterFactory; import org.eclipse.aether.transport.http.HttpTransporterFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.dentrassi.pm.VersionInformation; public class Helper { public static RepositorySystem newRepositorySystem () { final DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator (); locator.addService ( RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class ); locator.addService ( TransporterFactory.class, FileTransporterFactory.class ); locator.addService ( TransporterFactory.class, HttpTransporterFactory.class ); locator.setErrorHandler ( new ErrorHandler () { @Override public void serviceCreationFailed ( final Class<?> type, final Class<?> impl, final Throwable exception ) { final Logger logger = LoggerFactory.getLogger ( impl ); logger.warn ( "Service creation failed: " + type.getName (), exception ); } } ); return locator.getService ( RepositorySystem.class ); } public static RepositorySystemSession newRepositorySystemSession ( final Path tempDir, final RepositorySystem system ) { final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession (); final LocalRepository localRepo = new LocalRepository ( tempDir.toFile () ); session.setLocalRepositoryManager ( system.newLocalRepositoryManager ( session, localRepo ) ); session.setTransferListener ( new LoggerTransferListener () ); // session.setRepositoryListener ( new ConsoleRepositoryListener () ); // uncomment to generate dirty trees // session.setDependencyGraphTransformer( null ); session.setConfigProperty ( ConfigurationProperties.USER_AGENT, String.format ( "PackageDrone/%s (+http://packagedrone.org)", VersionInformation.VERSION_UNQUALIFIED ) ); return session; } public static RemoteRepository newCentralRepository () { return newRemoteRepository ( "http://central.maven.org/maven2/" ); } public static RemoteRepository newRemoteRepository ( final String url ) { return new RemoteRepository.Builder ( "central", "default", url ).build (); } }
package bisq.desktop.main.offer.offerbook; import bisq.desktop.Navigation; import bisq.desktop.common.model.ActivatableViewModel; import bisq.desktop.main.MainView; import bisq.desktop.main.settings.SettingsView; import bisq.desktop.main.settings.preferences.PreferencesView; import bisq.desktop.util.DisplayUtils; import bisq.desktop.util.GUIUtil; import bisq.core.account.witness.AccountAgeWitnessService; import bisq.core.filter.FilterManager; import bisq.core.locale.BankUtil; import bisq.core.locale.CountryUtil; import bisq.core.locale.CryptoCurrency; import bisq.core.locale.CurrencyUtil; import bisq.core.locale.GlobalSettings; import bisq.core.locale.Res; import bisq.core.locale.TradeCurrency; import bisq.core.monetary.Price; import bisq.core.monetary.Volume; import bisq.core.offer.Offer; import bisq.core.offer.OfferPayload; import bisq.core.offer.OpenOfferManager; import bisq.core.payment.PaymentAccount; import bisq.core.payment.PaymentAccountUtil; import bisq.core.payment.payload.PaymentMethod; import bisq.core.provider.price.PriceFeedService; import bisq.core.trade.Trade; import bisq.core.trade.closed.ClosedTradableManager; import bisq.core.user.Preferences; import bisq.core.user.User; import bisq.core.util.BSFormatter; import bisq.core.util.BsqFormatter; import bisq.network.p2p.NodeAddress; import bisq.network.p2p.P2PService; import bisq.common.app.Version; import bisq.common.handlers.ErrorMessageHandler; import bisq.common.handlers.ResultHandler; import org.bitcoinj.core.Coin; import com.google.inject.Inject; import com.google.common.base.Joiner; import javafx.scene.control.TableColumn; import javafx.beans.property.BooleanProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import java.text.DecimalFormat; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; @Slf4j class OfferBookViewModel extends ActivatableViewModel { private final OpenOfferManager openOfferManager; private final User user; private final OfferBook offerBook; final Preferences preferences; private final P2PService p2PService; final PriceFeedService priceFeedService; private final ClosedTradableManager closedTradableManager; private final FilterManager filterManager; final AccountAgeWitnessService accountAgeWitnessService; private final Navigation navigation; private final BSFormatter btcFormatter; private final BsqFormatter bsqFormatter; final ObjectProperty<TableColumn.SortType> priceSortTypeProperty = new SimpleObjectProperty<>(); private final FilteredList<OfferBookListItem> filteredItems; private final SortedList<OfferBookListItem> sortedItems; private final ListChangeListener<TradeCurrency> tradeCurrencyListChangeListener; private final ListChangeListener<OfferBookListItem> filterItemsListener; private TradeCurrency selectedTradeCurrency; private final ObservableList<TradeCurrency> allTradeCurrencies = FXCollections.observableArrayList(); private OfferPayload.Direction direction; final StringProperty tradeCurrencyCode = new SimpleStringProperty(); // If id is empty string we ignore filter (display all methods) PaymentMethod selectedPaymentMethod = PaymentMethod.getDummyPaymentMethod(GUIUtil.SHOW_ALL_FLAG); private boolean isTabSelected; final BooleanProperty showAllTradeCurrenciesProperty = new SimpleBooleanProperty(true); final IntegerProperty maxPlacesForAmount = new SimpleIntegerProperty(); final IntegerProperty maxPlacesForVolume = new SimpleIntegerProperty(); final IntegerProperty maxPlacesForPrice = new SimpleIntegerProperty(); final IntegerProperty maxPlacesForMarketPriceMargin = new SimpleIntegerProperty(); boolean showAllPaymentMethods = true; // Constructor, lifecycle @Inject public OfferBookViewModel(User user, OpenOfferManager openOfferManager, OfferBook offerBook, Preferences preferences, P2PService p2PService, PriceFeedService priceFeedService, ClosedTradableManager closedTradableManager, FilterManager filterManager, AccountAgeWitnessService accountAgeWitnessService, Navigation navigation, BSFormatter btcFormatter, BsqFormatter bsqFormatter) { super(); this.openOfferManager = openOfferManager; this.user = user; this.offerBook = offerBook; this.preferences = preferences; this.p2PService = p2PService; this.priceFeedService = priceFeedService; this.closedTradableManager = closedTradableManager; this.filterManager = filterManager; this.accountAgeWitnessService = accountAgeWitnessService; this.navigation = navigation; this.btcFormatter = btcFormatter; this.bsqFormatter = bsqFormatter; this.filteredItems = new FilteredList<>(offerBook.getOfferBookListItems()); this.sortedItems = new SortedList<>(filteredItems); tradeCurrencyListChangeListener = c -> { fillAllTradeCurrencies(); }; filterItemsListener = c -> { final Optional<OfferBookListItem> highestAmountOffer = filteredItems.stream() .max(Comparator.comparingLong(o -> o.getOffer().getAmount().getValue())); final boolean containsRangeAmount = filteredItems.stream().anyMatch(o -> o.getOffer().isRange()); if (highestAmountOffer.isPresent()) { final OfferBookListItem item = highestAmountOffer.get(); if (!item.getOffer().isRange() && containsRangeAmount) { maxPlacesForAmount.set(formatAmount(item.getOffer(), false) .length() * 2 + BSFormatter.RANGE_SEPARATOR.length()); maxPlacesForVolume.set(formatVolume(item.getOffer(), false) .length() * 2 + BSFormatter.RANGE_SEPARATOR.length()); } else { maxPlacesForAmount.set(formatAmount(item.getOffer(), false).length()); maxPlacesForVolume.set(formatVolume(item.getOffer(), false).length()); } } final Optional<OfferBookListItem> highestPriceOffer = filteredItems.stream() .filter(o -> o.getOffer().getPrice() != null) .max(Comparator.comparingLong(o -> o.getOffer().getPrice() != null ? o.getOffer().getPrice().getValue() : 0)); highestPriceOffer.ifPresent(offerBookListItem -> maxPlacesForPrice.set(formatPrice(offerBookListItem.getOffer(), false).length())); final Optional<OfferBookListItem> highestMarketPriceMarginOffer = filteredItems.stream() .filter(o -> o.getOffer().isUseMarketBasedPrice()) .max(Comparator.comparing(o -> new DecimalFormat("#0.00").format(o.getOffer().getMarketPriceMargin() * 100).length())); highestMarketPriceMarginOffer.ifPresent(offerBookListItem -> maxPlacesForMarketPriceMargin.set(formatMarketPriceMargin(offerBookListItem.getOffer(), false).length())); }; } @Override protected void activate() { filteredItems.addListener(filterItemsListener); String code = direction == OfferPayload.Direction.BUY ? preferences.getBuyScreenCurrencyCode() : preferences.getSellScreenCurrencyCode(); if (code != null && !code.equals(GUIUtil.SHOW_ALL_FLAG) && !code.isEmpty() && CurrencyUtil.getTradeCurrency(code).isPresent()) { showAllTradeCurrenciesProperty.set(false); selectedTradeCurrency = CurrencyUtil.getTradeCurrency(code).get(); } else { showAllTradeCurrenciesProperty.set(true); selectedTradeCurrency = GlobalSettings.getDefaultTradeCurrency(); } tradeCurrencyCode.set(selectedTradeCurrency.getCode()); applyPriceSortTypeProperty(code); fillAllTradeCurrencies(); preferences.getTradeCurrenciesAsObservable().addListener(tradeCurrencyListChangeListener); offerBook.fillOfferBookListItems(); applyFilterPredicate(); setMarketPriceFeedCurrency(); } @Override protected void deactivate() { filteredItems.removeListener(filterItemsListener); preferences.getTradeCurrenciesAsObservable().removeListener(tradeCurrencyListChangeListener); } // API void initWithDirection(OfferPayload.Direction direction) { this.direction = direction; } void onTabSelected(boolean isSelected) { this.isTabSelected = isSelected; setMarketPriceFeedCurrency(); } // UI actions void onSetTradeCurrency(TradeCurrency tradeCurrency) { if (tradeCurrency != null) { String code = tradeCurrency.getCode(); boolean showAllEntry = isShowAllEntry(code); showAllTradeCurrenciesProperty.set(showAllEntry); if (isEditEntry(code)) navigation.navigateTo(MainView.class, SettingsView.class, PreferencesView.class); else if (!showAllEntry) { this.selectedTradeCurrency = tradeCurrency; tradeCurrencyCode.set(code); } applyPriceSortTypeProperty(code); setMarketPriceFeedCurrency(); applyFilterPredicate(); if (direction == OfferPayload.Direction.BUY) preferences.setBuyScreenCurrencyCode(code); else preferences.setSellScreenCurrencyCode(code); } } private void applyPriceSortTypeProperty(String code) { final OfferPayload.Direction compareDirection = CurrencyUtil.isCryptoCurrency(code) ? OfferPayload.Direction.SELL : OfferPayload.Direction.BUY; priceSortTypeProperty.set(getDirection() == compareDirection ? TableColumn.SortType.ASCENDING : TableColumn.SortType.DESCENDING); } void onSetPaymentMethod(PaymentMethod paymentMethod) { if (paymentMethod == null) return; showAllPaymentMethods = isShowAllEntry(paymentMethod.getId()); if (!showAllPaymentMethods) this.selectedPaymentMethod = paymentMethod; else this.selectedPaymentMethod = PaymentMethod.getDummyPaymentMethod(GUIUtil.SHOW_ALL_FLAG); applyFilterPredicate(); } void onRemoveOpenOffer(Offer offer, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) { openOfferManager.removeOffer(offer, resultHandler, errorMessageHandler); } // Getters SortedList<OfferBookListItem> getOfferList() { return sortedItems; } Map<String, Integer> getBuyOfferCounts() { return offerBook.getBuyOfferCountMap(); } Map<String, Integer> getSellOfferCounts() { return offerBook.getSellOfferCountMap(); } boolean isMyOffer(Offer offer) { return openOfferManager.isMyOffer(offer); } OfferPayload.Direction getDirection() { return direction; } public ObservableList<TradeCurrency> getTradeCurrencies() { return allTradeCurrencies; } boolean isBootstrappedOrShowPopup() { return GUIUtil.isBootstrappedOrShowPopup(p2PService); } TradeCurrency getSelectedTradeCurrency() { return selectedTradeCurrency; } ObservableList<PaymentMethod> getPaymentMethods() { ObservableList<PaymentMethod> list = FXCollections.observableArrayList(PaymentMethod.getPaymentMethods()); list.add(0, PaymentMethod.getDummyPaymentMethod(GUIUtil.SHOW_ALL_FLAG)); return list; } String getAmount(OfferBookListItem item) { return formatAmount(item.getOffer(), true); } private String formatAmount(Offer offer, boolean decimalAligned) { return DisplayUtils.formatAmount(offer, GUIUtil.AMOUNT_DECIMALS, decimalAligned, maxPlacesForAmount.get(), btcFormatter); } String getPrice(OfferBookListItem item) { if ((item == null)) return ""; final Offer offer = item.getOffer(); final Price price = offer.getPrice(); if (price != null) { return formatPrice(offer, true) + formatMarketPriceMargin(offer, true); } else { return Res.get("shared.na"); } } String getAbsolutePriceMargin(Offer offer) { return BSFormatter.formatPercentagePrice(Math.abs(offer.getMarketPriceMargin())); } private String formatPrice(Offer offer, boolean decimalAligned) { return DisplayUtils.formatPrice(offer.getPrice(), decimalAligned, maxPlacesForPrice.get()); } private String formatMarketPriceMargin(Offer offer, boolean decimalAligned) { String postFix = ""; if (offer.isUseMarketBasedPrice()) { postFix = " (" + BSFormatter.formatPercentagePrice(offer.getMarketPriceMargin()) + ")"; } if (decimalAligned) { postFix = BSFormatter.fillUpPlacesWithEmptyStrings(postFix, maxPlacesForMarketPriceMargin.get()); } return postFix; } String getVolume(OfferBookListItem item) { return formatVolume(item.getOffer(), true); } private String formatVolume(Offer offer, boolean decimalAligned) { Volume offerVolume = offer.getVolume(); Volume minOfferVolume = offer.getMinVolume(); if (offerVolume != null && minOfferVolume != null) { String postFix = showAllTradeCurrenciesProperty.get() ? " " + offer.getCurrencyCode() : ""; decimalAligned = decimalAligned && !showAllTradeCurrenciesProperty.get(); return DisplayUtils.formatVolume(offer, decimalAligned, maxPlacesForVolume.get()) + postFix; } else { return Res.get("shared.na"); } } int getNumberOfDecimalsForVolume(OfferBookListItem item) { return CurrencyUtil.isFiatCurrency(item.getOffer().getCurrencyCode()) ? GUIUtil.FIAT_DECIMALS_WITH_ZEROS : GUIUtil.ALTCOINS_DECIMALS_WITH_ZEROS; } String getPaymentMethod(OfferBookListItem item) { String result = ""; if (item != null) { Offer offer = item.getOffer(); String method = Res.get(offer.getPaymentMethod().getId() + "_SHORT"); String methodCountryCode = offer.getCountryCode(); if (isF2F(offer)) { result = method + " (" + methodCountryCode + ", " + offer.getF2FCity() + ")"; } else { if (methodCountryCode != null) result = method + " (" + methodCountryCode + ")"; else result = method; } } return result; } String getPaymentMethodToolTip(OfferBookListItem item) { String result = ""; if (item != null) { Offer offer = item.getOffer(); result = Res.getWithCol("shared.paymentMethod") + " " + Res.get(offer.getPaymentMethod().getId()); result += "\n" + Res.getWithCol("shared.currency") + " " + CurrencyUtil.getNameAndCode(offer.getCurrencyCode()); String countryCode = offer.getCountryCode(); if (isF2F(offer)) { if (countryCode != null) { result += "\n" + Res.get("payment.f2f.offerbook.tooltip.countryAndCity", CountryUtil.getNameByCode(countryCode), offer.getF2FCity()); result += "\n" + Res.get("payment.f2f.offerbook.tooltip.extra", offer.getF2FExtraInfo()); } } else { if (countryCode != null) { String bankId = offer.getBankId(); if (bankId != null && !bankId.equals("null")) { if (BankUtil.isBankIdRequired(countryCode)) result += "\n" + Res.get("offerbook.offerersBankId", bankId); else if (BankUtil.isBankNameRequired(countryCode)) result += "\n" + Res.get("offerbook.offerersBankName", bankId); } } if (countryCode != null) result += "\n" + Res.get("offerbook.offerersBankSeat", CountryUtil.getNameByCode(countryCode)); List<String> acceptedCountryCodes = offer.getAcceptedCountryCodes(); List<String> acceptedBanks = offer.getAcceptedBankIds(); if (acceptedCountryCodes != null && !acceptedCountryCodes.isEmpty()) { if (CountryUtil.containsAllSepaEuroCountries(acceptedCountryCodes)) result += "\n" + Res.get("offerbook.offerersAcceptedBankSeatsEuro"); else result += "\n" + Res.get("offerbook.offerersAcceptedBankSeats", CountryUtil.getNamesByCodesString(acceptedCountryCodes)); } else if (acceptedBanks != null && !acceptedBanks.isEmpty()) { if (offer.getPaymentMethod().equals(PaymentMethod.SAME_BANK)) result += "\n" + Res.getWithCol("shared.bankName") + " " + acceptedBanks.get(0); else if (offer.getPaymentMethod().equals(PaymentMethod.SPECIFIC_BANKS)) result += "\n" + Res.getWithCol("shared.acceptedBanks") + " " + Joiner.on(", ").join(acceptedBanks); } } } return result; } private boolean isF2F(Offer offer) { return offer.getPaymentMethod().equals(PaymentMethod.F2F); } String getDirectionLabelTooltip(Offer offer) { return BSFormatter.getDirectionWithCodeDetailed(offer.getMirroredDirection(), offer.getCurrencyCode()); } Optional<PaymentAccount> getMostMaturePaymentAccountForOffer(Offer offer) { return PaymentAccountUtil.getMostMaturePaymentAccountForOffer(offer, user.getPaymentAccounts(), accountAgeWitnessService); } // Private private void setMarketPriceFeedCurrency() { if (isTabSelected) { if (showAllTradeCurrenciesProperty.get()) priceFeedService.setCurrencyCode(GlobalSettings.getDefaultTradeCurrency().getCode()); else priceFeedService.setCurrencyCode(tradeCurrencyCode.get()); } } private void fillAllTradeCurrencies() { allTradeCurrencies.clear(); // Used for ignoring filter (show all) allTradeCurrencies.add(new CryptoCurrency(GUIUtil.SHOW_ALL_FLAG, "")); allTradeCurrencies.addAll(preferences.getTradeCurrenciesAsObservable()); allTradeCurrencies.add(new CryptoCurrency(GUIUtil.EDIT_FLAG, "")); } // Checks boolean isAnyPaymentAccountValidForOffer(Offer offer) { return user.getPaymentAccounts() != null && PaymentAccountUtil.isAnyTakerPaymentAccountValidForOffer(offer, user.getPaymentAccounts()); } boolean hasPaymentAccountForCurrency() { return (showAllTradeCurrenciesProperty.get() && user.getPaymentAccounts() != null && !user.getPaymentAccounts().isEmpty()) || user.hasPaymentAccountForCurrency(selectedTradeCurrency); } boolean canCreateOrTakeOffer() { return GUIUtil.canCreateOrTakeOfferOrShowPopup(user, navigation) && GUIUtil.isBootstrappedOrShowPopup(p2PService); } // Filters private void applyFilterPredicate() { filteredItems.setPredicate(offerBookListItem -> { Offer offer = offerBookListItem.getOffer(); boolean directionResult = offer.getDirection() != direction; boolean currencyResult = (showAllTradeCurrenciesProperty.get()) || offer.getCurrencyCode().equals(selectedTradeCurrency.getCode()); boolean paymentMethodResult = showAllPaymentMethods || offer.getPaymentMethod().equals(selectedPaymentMethod); boolean notMyOfferOrShowMyOffersActivated = !isMyOffer(offerBookListItem.getOffer()) || preferences.isShowOwnOffersInOfferBook(); return directionResult && currencyResult && paymentMethodResult && notMyOfferOrShowMyOffersActivated; }); } boolean isIgnored(Offer offer) { return preferences.getIgnoreTradersList().stream() .anyMatch(i -> i.equals(offer.getMakerNodeAddress().getFullAddress())); } boolean isOfferBanned(Offer offer) { return filterManager.isOfferIdBanned(offer.getId()); } boolean isCurrencyBanned(Offer offer) { return filterManager.isCurrencyBanned(offer.getCurrencyCode()); } boolean isPaymentMethodBanned(Offer offer) { return filterManager.isPaymentMethodBanned(offer.getPaymentMethod()); } boolean isNodeAddressBanned(Offer offer) { return filterManager.isNodeAddressBanned(offer.getMakerNodeAddress()); } boolean requireUpdateToNewVersion() { return filterManager.requireUpdateToNewVersionForTrading(); } boolean isInsufficientCounterpartyTradeLimit(Offer offer) { return CurrencyUtil.isFiatCurrency(offer.getCurrencyCode()) && !accountAgeWitnessService.verifyPeersTradeAmount(offer, offer.getAmount(), errorMessage -> { }); } boolean isMyInsufficientTradeLimit(Offer offer) { Optional<PaymentAccount> accountOptional = getMostMaturePaymentAccountForOffer(offer); final long myTradeLimit = accountOptional .map(paymentAccount -> accountAgeWitnessService.getMyTradeLimit(paymentAccount, offer.getCurrencyCode(), offer.getMirroredDirection())) .orElse(0L); final long offerMinAmount = offer.getMinAmount().value; log.debug("isInsufficientTradeLimit accountOptional={}, myTradeLimit={}, offerMinAmount={}, ", accountOptional.isPresent() ? accountOptional.get().getAccountName() : "null", Coin.valueOf(myTradeLimit).toFriendlyString(), Coin.valueOf(offerMinAmount).toFriendlyString()); return CurrencyUtil.isFiatCurrency(offer.getCurrencyCode()) && accountOptional.isPresent() && myTradeLimit < offerMinAmount; } boolean hasSameProtocolVersion(Offer offer) { return offer.getProtocolVersion() == Version.TRADE_PROTOCOL_VERSION; } private boolean isShowAllEntry(String id) { return id.equals(GUIUtil.SHOW_ALL_FLAG); } private boolean isEditEntry(String id) { return id.equals(GUIUtil.EDIT_FLAG); } int getNumTrades(Offer offer) { return closedTradableManager.getClosedTradables().stream() .filter(e -> { final NodeAddress tradingPeerNodeAddress = e instanceof Trade ? ((Trade) e).getTradingPeerNodeAddress() : null; return tradingPeerNodeAddress != null && tradingPeerNodeAddress.getFullAddress().equals(offer.getMakerNodeAddress().getFullAddress()); }) .collect(Collectors.toSet()) .size(); } public boolean hasSelectionAccountSigning() { if (showAllTradeCurrenciesProperty.get()) { if (!selectedPaymentMethod.getId().equals(GUIUtil.SHOW_ALL_FLAG)) { return PaymentMethod.hasChargebackRisk(selectedPaymentMethod); } } else { if (selectedPaymentMethod.getId().equals(GUIUtil.SHOW_ALL_FLAG)) return CurrencyUtil.getMatureMarketCurrencies().stream() .anyMatch(c -> c.getCode().equals(selectedTradeCurrency.getCode())); else return PaymentMethod.hasChargebackRisk(selectedPaymentMethod, tradeCurrencyCode.get()); } return true; } public String getMakerFeeAsString(Offer offer) { return offer.isCurrencyForMakerFeeBtc() ? btcFormatter.formatCoinWithCode(offer.getMakerFee()) : bsqFormatter.formatCoinWithCode(offer.getMakerFee()); } }
package net.runelite.client; import com.google.common.eventbus.EventBus; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import java.applet.Applet; import java.io.File; import java.util.Optional; import java.util.concurrent.ScheduledExecutorService; import javax.inject.Singleton; import javax.swing.SwingUtilities; import joptsimple.OptionParser; import joptsimple.OptionSet; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Client; import net.runelite.client.account.SessionManager; import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.config.ConfigManager; import net.runelite.client.menus.MenuManager; import net.runelite.client.plugins.PluginManager; import net.runelite.client.ui.ClientUI; import net.runelite.client.ui.overlay.OverlayRenderer; @Singleton @Slf4j public class RuneLite { public static final File RUNELITE_DIR = new File(System.getProperty("user.home"), ".runelite"); public static final File PROFILES_DIR = new File(RUNELITE_DIR, "profiles"); public static final File PLUGIN_DIR = new File(RUNELITE_DIR, "plugins"); private static Injector injector; private static OptionSet options; @Inject private RuneLiteProperties properties; @Inject private PluginManager pluginManager; @Inject private MenuManager menuManager; @Inject private EventBus eventBus; @Inject private ConfigManager configManager; @Inject private ChatMessageManager chatMessageManager; @Inject private ScheduledExecutorService executor; @Inject private OverlayRenderer overlayRenderer; @Inject private SessionManager sessionManager; Client client; ClientUI gui; Notifier notifier; public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser(); parser.accepts("developer-mode"); parser.accepts("no-rs"); setOptions(parser.parse(args)); PROFILES_DIR.mkdirs(); setInjector(Guice.createInjector(new RuneLiteModule())); injector.getInstance(RuneLite.class).start(); } public void start() throws Exception { // Load RuneLite or Vanilla client final boolean hasRs = !getOptions().has("no-rs"); final Optional<Applet> optionalClient = hasRs ? new ClientLoader().loadRs() : Optional.empty(); if (!optionalClient.isPresent() && hasRs) { System.exit(-1); return; } final Applet client = optionalClient.orElse(null); final boolean isOutdated = client == null || !(client instanceof Client); if (!isOutdated) { this.client = (Client) client; } // Load swing UI SwingUtilities.invokeAndWait(() -> setGui(ClientUI.create(properties, client))); // Load default configuration configManager.load(); // Register event listeners eventBus.register(overlayRenderer); eventBus.register(menuManager); eventBus.register(chatMessageManager); // Setup the notifier notifier = new Notifier(properties.getTitle(), gui.getTrayIcon()); // Tell the plugin manager if client is outdated or not pluginManager.setOutdated(isOutdated); // Load the plugins, but does not start them yet. // This will initialize configuration pluginManager.loadCorePlugins(); // Plugins have provided their config, so set default config // to main settings configManager.loadDefault(); // Start plugins pluginManager.startCorePlugins(); // Load the session, including saved configuration sessionManager.loadSession(); // Begin watching for new plugins pluginManager.watch(); } public void setGui(ClientUI gui) { this.gui = gui; } public static Injector getInjector() { return injector; } public static void setInjector(Injector injector) { RuneLite.injector = injector; } public static OptionSet getOptions() { return options; } public static void setOptions(OptionSet options) { RuneLite.options = options; } }
package rx.operators; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.CountDownLatch; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.logic.BlackHole; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Observable.Operator; import rx.Observer; import rx.Subscriber; import rx.functions.Func1; public class ObservableBenchmark { @GenerateMicroBenchmark public void measureBaseline(BlackHole bh, Input input) { for (Integer value : input.values) { bh.consume(IDENTITY_FUNCTION.call(value)); } } @GenerateMicroBenchmark public void measureMap(Input input) throws InterruptedException { input.observable.lift(MAP_OPERATOR).subscribe(input.observer); input.awaitCompletion(); } private static final Func1<Integer, Integer> IDENTITY_FUNCTION = new Func1<Integer, Integer>() { @Override public Integer call(Integer value) { return value; } }; private static final Operator<Integer, Integer> MAP_OPERATOR = new OperatorMap<Integer, Integer>(IDENTITY_FUNCTION); @State(Scope.Thread) public static class Input { @Param({"1", "1024", "1048576"}) public int size; public Collection<Integer> values; public Observable<Integer> observable; public Observer<Integer> observer; private CountDownLatch latch; @Setup public void setup() { values = new ArrayList<Integer>(); for(int i = 0; i < size; i ++) { values.add(i); } observable = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> o) { for (Integer value : values) { if (o.isUnsubscribed()) return; o.onNext(value); } o.onCompleted(); } }); final BlackHole bh = new BlackHole(); latch = new CountDownLatch(1); observer = new Observer<Integer>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { throw new RuntimeException(e); } @Override public void onNext(Integer value) { bh.consume(value); } }; } public void awaitCompletion() throws InterruptedException { latch.await(); } } }
package org.hisp.dhis.dataapproval; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import org.hisp.dhis.common.BaseIdentifiableObject; import org.hisp.dhis.common.DxfNamespaces; import org.hisp.dhis.common.IdentifiableObject; import org.hisp.dhis.common.MergeMode; import org.hisp.dhis.dataelement.CategoryOptionGroupSet; import org.hisp.dhis.schema.PropertyType; import org.hisp.dhis.schema.annotation.Property; /** * Records the approval of DataSet values for a given OrganisationUnit and * Period. * * @author Jim Grace */ @JacksonXmlRootElement( localName = "dataApprovalLevel", namespace = DxfNamespaces.DXF_2_0 ) public class DataApprovalLevel extends BaseIdentifiableObject { /** * The data approval level, 1=highest level, max=lowest level. */ private int level; /** * The organisation unit level for this data approval level. */ private int orgUnitLevel; /** * The category option group set (optional) for this data approval level. */ private CategoryOptionGroupSet categoryOptionGroupSet; /** * The name of the organisation unit level (derived through the service.) */ private transient String orgUnitLevelName; // Constructors public DataApprovalLevel() { } public DataApprovalLevel( String name, int orgUnitLevel, CategoryOptionGroupSet categoryOptionGroupSet ) { this.name = name; this.orgUnitLevel = orgUnitLevel; this.categoryOptionGroupSet = categoryOptionGroupSet; } public DataApprovalLevel( DataApprovalLevel level ) { this.name = level.name; this.level = level.level; this.orgUnitLevel = level.orgUnitLevel; this.categoryOptionGroupSet = level.categoryOptionGroupSet; this.created = level.created; this.lastUpdated = level.lastUpdated; } // Logic /** * Returns the name of the category option group set for this data approval * level, or an empty string if there is no category option group set. * * @return name of this approval level's category option group set. */ public String getCategoryOptionGroupSetName() { return categoryOptionGroupSet == null ? "" : categoryOptionGroupSet.getName(); } /** * Indicates whether this approval level specified a category option group set. */ public boolean hasCategoryOptionGroupSet() { return categoryOptionGroupSet != null; } /** * Indicates whether the given approval level represents the same level as this. */ public boolean levelEquals( DataApprovalLevel other ) { if ( other == null ) { return false; } if ( level != other.getLevel() ) { return false; } if ( categoryOptionGroupSet != null ? !categoryOptionGroupSet.equals( other.getCategoryOptionGroupSet() ) : other.getCategoryOptionGroupSet() != null ) { return false; } return true; } // toString @Override public String toString() { return "DataApprovalLevel{" + "name=" + name + ", level=" + level + ", orgUnitLevel=" + orgUnitLevel + ", categoryOptionGroupSet='" + (categoryOptionGroupSet == null ? "(null)" : categoryOptionGroupSet.getName()) + "'" + ", created=" + created + ", lastUpdated=" + lastUpdated + '}'; } // Getters and Setters @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public int getLevel() { return level; } public void setLevel( int level ) { this.level = level; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public int getOrgUnitLevel() { return orgUnitLevel; } public void setOrgUnitLevel( int orgUnitLevel ) { this.orgUnitLevel = orgUnitLevel; } @JsonProperty @JsonSerialize( as = BaseIdentifiableObject.class ) @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) @Property( value = PropertyType.REFERENCE, required = Property.Value.DEFAULT, persisted = Property.Value.TRUE, owner = Property.Value.TRUE ) public CategoryOptionGroupSet getCategoryOptionGroupSet() { return categoryOptionGroupSet; } public void setCategoryOptionGroupSet( CategoryOptionGroupSet categoryOptionGroupSet ) { this.categoryOptionGroupSet = categoryOptionGroupSet; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public String getOrgUnitLevelName() { return orgUnitLevelName; } public void setOrgUnitLevelName( String orgUnitLevelName ) { this.orgUnitLevelName = orgUnitLevelName; } @Override public void mergeWith( IdentifiableObject other, MergeMode mergeMode ) { super.mergeWith( other, mergeMode ); if ( other.getClass().isInstance( this ) ) { DataApprovalLevel dataApprovalLevel = (DataApprovalLevel) other; level = dataApprovalLevel.getLevel(); orgUnitLevel = dataApprovalLevel.getOrgUnitLevel(); if ( mergeMode.isReplace() ) { categoryOptionGroupSet = dataApprovalLevel.getCategoryOptionGroupSet(); } else if ( mergeMode.isMerge() ) { categoryOptionGroupSet = dataApprovalLevel.getCategoryOptionGroupSet() == null ? categoryOptionGroupSet : dataApprovalLevel.getCategoryOptionGroupSet(); } } } }
package io.digdag.core.log; import io.digdag.client.DigdagClient; import io.digdag.client.config.Config; import io.digdag.client.config.ConfigFactory; import io.digdag.core.agent.AgentId; import io.digdag.core.config.PropertyUtils; import io.digdag.spi.LogFilePrefix; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.time.Instant; import java.time.ZoneId; import com.google.common.base.Optional; import java.util.Properties; import static java.nio.charset.StandardCharsets.UTF_8; import io.digdag.core.log.LocalFileLogServerFactory.LocalFileLogServer.LocalFileDirectTaskLogger; public class LocalFileLogServerFactoryTest { private static final ConfigFactory CONFIG_FACTORY = new ConfigFactory(DigdagClient.objectMapper()); @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); Path taskLogPath; Properties props; Config systemConfig; LocalFileLogServerFactory logServerFactory; LocalFileLogServerFactory.LocalFileLogServer localServer; LogFilePrefix prefix = LogFilePrefix.builder() .createdAt(Instant.now()) .retryAttemptName(Optional.absent()) .projectId(1) .sessionTime(Instant.now()) .siteId(1) .timeZone(ZoneId.systemDefault()) .workflowName("test1") .build(); LocalFileDirectTaskLogger taskLogger; @Before public void setUp() throws IOException { taskLogPath = tempFolder.newFolder("task_logs").toPath(); } private void setUpTaskLogger(Optional<String> size) { props = new Properties(); props.setProperty("log-server.local.path", taskLogPath.toString()); if (size.isPresent()) { props.setProperty("log-server.local.split_size", size.get()); } else { } systemConfig = PropertyUtils.toConfigElement(props).toConfig(CONFIG_FACTORY); System.out.println(systemConfig); logServerFactory = new LocalFileLogServerFactory(systemConfig, AgentId.of("agentA")); localServer = (LocalFileLogServerFactory.LocalFileLogServer) logServerFactory.getLogServer(); taskLogger = localServer.newDirectTaskLogger(prefix, "+task1"); } @Test public void checkSplitSize() { setUpTaskLogger(Optional.of("100")); String msg = repeatedString("a", 51); for (int i = 0; i < 100; i++) { taskLogger.log(msg.getBytes(UTF_8), 0, msg.length()); } taskLogger.close(); for (File f : taskLogPath.toFile().listFiles()) { for (File f2: f.listFiles()) { File[] taskLogs = f2.listFiles(); for (File f3: taskLogs) { System.out.println(f3); } assertThat("log file should be splitted", f2.listFiles().length > 1, is(true)); } } } @Test public void checkSplitSizeIsZero() { setUpTaskLogger(Optional.of("0")); String msg = repeatedString("a", 51); for (int i = 0; i < 100; i++) { taskLogger.log(msg.getBytes(UTF_8), 0, msg.length()); } taskLogger.close(); for (File f : taskLogPath.toFile().listFiles()) { for (File f2: f.listFiles()) { File[] taskLogs = f2.listFiles(); for (File f3: taskLogs) { System.out.println(f3); } assertThat("log file should be a file", f2.listFiles().length, is(1)); } } } @Test public void checkNoSplitSize() { setUpTaskLogger(Optional.absent()); String msg = repeatedString("a", 51); for (int i = 0; i < 100; i++) { taskLogger.log(msg.getBytes(UTF_8), 0, msg.length()); } taskLogger.close(); for (File f : taskLogPath.toFile().listFiles()) { for (File f2: f.listFiles()) { File[] taskLogs = f2.listFiles(); for (File f3: taskLogs) { System.out.println(f3); } assertThat("log file should be a file", f2.listFiles().length, is(1)); } } } private String repeatedString(String v, int num) { StringBuilder b = new StringBuilder(); for (int i = 0; i < num; i++) { b.append(v); } return b.toString(); } }
package fi.iot.iiframework.databasetestingconsole; import fi.iot.iiframework.errors.dao.ErrorDAO; import java.util.Scanner; import org.springframework.beans.factory.annotation.Autowired; public class DBConsole { @Autowired ErrorDAO eDAO; public String response; private final Scanner scan; private String input; public DBConsole() { response = "What do you want to enter to the database?"; scan = new Scanner(System.in); input = " "; } public void run() { while (input.equals("exit") == false) { System.out.println(response); input = scan.nextLine(); input = input.trim().toLowerCase(); if (input.equals("error")) { response = "Lets create an error!"; } else if (input.equals("source")) { response = "Not implemented :("; } else { response = "Not a valid command!"; } } System.out.println(response = "Console stopped!"); } }
package org.broadinstitute.sting.playground.gatk.walkers.varianteval; import org.broadinstitute.sting.gatk.refdata.*; import org.broadinstitute.sting.gatk.LocusContext; import org.broadinstitute.sting.utils.StingException; import org.broadinstitute.sting.utils.Utils; import java.util.List; import java.util.ArrayList; public class GenotypeConcordance extends BasicVariantAnalysis implements GenotypeAnalysis { private String dbName; private static final int TRUTH_REF = 0; private static final int TRUTH_VAR_HET = 1; private static final int TRUTH_VAR_HOM = 2; private static final int TRUTH_UNKNOWN = 3; private static final String[] TRUTH_NAMES = {"IS_REF", "IS_VAR_HET", "IS_VAR_HOM", "UNKNOWN"}; private static final int CALL_REF = 0; private static final int CALL_VAR_HET = 1; private static final int CALL_VAR_HOM = 2; private static final int NO_CALL = 3; private static final String[] CALL_NAMES = {"CALLED_REF", "CALLED_VAR_HET", "CALLED_VAR_HOM", "NO_CALL"}; private int[][] table = new int[4][4]; private int[] truth_totals = new int[4]; private int[] calls_totals = new int[4]; public GenotypeConcordance(final String name) { super("genotype_concordance"); dbName = name; for ( int i = 0; i < 4; i++ ) { truth_totals[i] = 0; calls_totals[i] = 0; for ( int j = 0; j < 4; j++ ) table[i][j] = 0; } } public void inc(AllelicVariant chip, AllelicVariant eval, char ref) { if ( (chip != null && !chip.isGenotype()) || (eval != null && !eval.isGenotype()) ) throw new StingException("Failure: trying to analyze genotypes of non-genotype data"); int truthIndex, callIndex; if ( chip == null ) truthIndex = TRUTH_UNKNOWN; else if ( chip.isReference() && Utils.countOccurrences(ref, chip.getGenotype().get(0)) == chip.getGenotype().get(0).length() ) truthIndex = TRUTH_REF; else if ( isHet(chip) ) truthIndex = TRUTH_VAR_HET; else truthIndex = TRUTH_VAR_HOM; // todo -- FIXME on countOccurences if ( eval == null ) callIndex = NO_CALL; else if ( eval.isReference() && Utils.countOccurrences(ref, eval.getGenotype().get(0)) == eval.getGenotype().get(0).length() ) callIndex = CALL_REF; else if ( isHet(eval) ) callIndex = CALL_VAR_HET; else callIndex = CALL_VAR_HOM; if ( chip != null || eval != null ) { //System.out.printf("TEST: %d/%d %s vs. %s%n", truthIndex, callIndex, chip, eval); table[truthIndex][callIndex]++; truth_totals[truthIndex]++; calls_totals[callIndex]++; } } public String update(AllelicVariant eval, RefMetaDataTracker tracker, char ref, LocusContext context) { AllelicVariant chip = (AllelicVariant)tracker.lookup(dbName, null); inc(chip, eval, ref); return null; } public List<String> done() { List<String> s = new ArrayList<String>(); s.add(String.format("name %s", dbName)); s.add(String.format("\t\tCALLED_REF\tCALLED_VAR_HET\tCALLED_VAR_HOM\tNO_CALL\t\t\tTOTALS\tDISCOVERY_ACCURACY\tGENOTYPE_ACCURACY")); for (int i=0; i < 4; i++) { StringBuffer sb = new StringBuffer(); sb.append(TRUTH_NAMES[i] + "\t"); for (int j=0; j < 4; j++) sb.append(table[i][j] +" (" + cellPercent(table[i][j], truth_totals[i]) + ")\t\t"); sb.append(truth_totals[i]); if ( i == TRUTH_VAR_HET || i == TRUTH_VAR_HOM ) sb.append("\t"+cellPercent(table[i][CALL_VAR_HET]+table[i][CALL_VAR_HOM], truth_totals[i]) + "\t\t\t" + cellPercent(table[i][i], truth_totals[i])); s.add(sb.toString()); } s.add("\n"); s.add(String.format("\t\tCALLED_REF\tCALLED_VAR_HET\tCALLED_VAR_HOM\tNO_CALL")); for (int i=0; i < 4; i++) { StringBuffer sb = new StringBuffer(); sb.append(TRUTH_NAMES[i] + "\t"); for (int j=0; j < 4; j++) sb.append(table[i][j] + " (" + cellPercent(table[i][j], calls_totals[j]) + ")\t\t"); s.add(sb.toString()); } s.add(String.format("TOTALS\t%d\t\t%d\t\t%d\t\t%d", calls_totals[CALL_REF], calls_totals[CALL_VAR_HET], calls_totals[CALL_VAR_HOM], calls_totals[NO_CALL])); s.add("\n"); for (int i=0; i < 4; i++) { for (int j=0; j < 4; j++) { s.add(TRUTH_NAMES[i]+"_"+CALL_NAMES[j]+"_COUNT "+table[i][j]); s.add(TRUTH_NAMES[i]+"_"+CALL_NAMES[j]+"_PERCENT_OF_TRUTH "+cellPercent(table[i][j], truth_totals[i])); s.add(TRUTH_NAMES[i]+"_"+CALL_NAMES[j]+"_PERCENT_OF_CALLS "+cellPercent(table[i][j], calls_totals[j])); } if ( i == TRUTH_VAR_HET || i == TRUTH_VAR_HOM ) { s.add(TRUTH_NAMES[i]+"_DISCOVERY_ACCURACY "+cellPercent(table[i][CALL_VAR_HET]+table[i][CALL_VAR_HOM], truth_totals[i])); s.add(TRUTH_NAMES[i]+"_GENOTYPE_ACCURACY "+cellPercent(table[i][i], truth_totals[i])); } } return s; } private static String cellPercent(int count, int total) { StringBuffer sb = new StringBuffer(); if ( total == 0 ) sb.append(0); else sb.append(100*count/total); sb.append("%"); return sb.toString(); } private static boolean isHet(AllelicVariant var) { if ( var instanceof Genotype ) return ((Genotype)var).isHet(); List<String> genotype = var.getGenotype(); if ( genotype.size() < 1 ) return false; return genotype.get(0).charAt(0) != genotype.get(0).charAt(1); } }
package org.dspace.curate; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.content.DCDate; import org.dspace.content.DCValue; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.content.ItemIterator; import org.dspace.content.crosswalk.StreamIngestionCrosswalk; import org.dspace.core.ConfigurationManager; import org.dspace.doi.CDLDataCiteService; import org.dspace.embargo.EmbargoManager; import org.dspace.identifier.DOIIdentifierProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; /** * Curation task to report embargoed items without publication date * * @author pmidford * created Dec 9, 2011 * */ @Suspendable public class EmbargoedWithoutPubDate extends AbstractCurationTask { private int total; private int unpublishedCount; private List<DatedEmbargo> embargoes; private DatedEmbargo[] dummy = new DatedEmbargo[1]; private static Logger LOGGER = LoggerFactory.getLogger(EmbargoedWithoutPubDate.class); @Override public void init(Curator curator, String taskID) throws IOException{ super.init(curator, taskID); } @Override public int perform(DSpaceObject dso) throws IOException { if (dso instanceof Collection){ total = 0; unpublishedCount = 0; embargoes = new ArrayList<DatedEmbargo>(); distribute(dso); if (!embargoes.isEmpty()){ DatedEmbargo[] s = embargoes.toArray(dummy); Arrays.sort(s); this.report("Collection: " + dso.getName() + "; Total items = " + total + "; unpublished items = " + unpublishedCount); for(DatedEmbargo d : s) this.report(d.toString()); } else if (total > 0) this.report("Collection: " + dso.getName() + "; Total items = " + total + "; no unpublished items"); } return Curator.CURATE_SUCCESS; } @Override protected void performItem(Item item){ total++; boolean unpublished = false; DCDate itemPubDate; DCValue values[] = item.getMetadata("dc", "date", "available", Item.ANY); if (values== null || values.length==0){ //no available date - save and report unpublished = true; } DCDate itemEmbargoDate = null; if (unpublished){ unpublishedCount++; try { //want to continue if a problem comes up itemEmbargoDate = EmbargoManager.getEmbargoDate(null, item); if (itemEmbargoDate != null){ DatedEmbargo de = new DatedEmbargo(itemEmbargoDate.toDate(),item); embargoes.add(de); } } catch (Exception e) { this.report("Exception " + e + " encountered while processing " + item); } } } private static class DatedEmbargo implements Comparable<DatedEmbargo>{ private Date embargoDate; private Item embargoedItem; public DatedEmbargo(Date date, Item item) { embargoDate = date; embargoedItem = item; } @Override public int compareTo(DatedEmbargo o) { return embargoDate.compareTo(o.embargoDate); } @Override public String toString(){ return embargoedItem.getName() + " " + embargoDate.toString(); } } }
package org.neo4j.kernel.impl.transaction; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.RollbackException; import javax.transaction.Status; import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; class TransactionImpl implements Transaction { private static Logger log = Logger.getLogger( TransactionImpl.class .getName() ); private static final int RS_ENLISTED = 0; private static final int RS_SUSPENDED = 1; private static final int RS_DELISTED = 2; private static final int RS_READONLY = 3; // set in prepare private final byte globalId[]; private int status = Status.STATUS_ACTIVE; private boolean active = true; private boolean globalStartRecordWritten = false; private final LinkedList<ResourceElement> resourceList = new LinkedList<ResourceElement>(); private List<Synchronization> syncHooks = new ArrayList<Synchronization>(); private final int eventIdentifier; private final TxManager txManager; TransactionImpl( TxManager txManager ) { this.txManager = txManager; globalId = XidImpl.getNewGlobalId(); eventIdentifier = txManager.getNextEventIdentifier(); } Integer getEventIdentifier() { return eventIdentifier; } byte[] getGlobalId() { return globalId; } public synchronized String toString() { StringBuffer txString = new StringBuffer( "Transaction(" + eventIdentifier + ")[" + txManager.getTxStatusAsString( status ) + ",Resources=" + resourceList.size() + "]" ); // Iterator<ResourceElement> itr = resourceList.iterator(); // while ( itr.hasNext() ) // txString.append( itr.next().toString() ); // if ( itr.hasNext() ) // txString.append( "," ); return txString.toString(); } public synchronized void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException { // make sure tx not suspended txManager.commit(); } boolean isGlobalStartRecordWritten() { return globalStartRecordWritten; } public synchronized void rollback() throws IllegalStateException, SystemException { // make sure tx not suspended txManager.rollback(); } public synchronized boolean enlistResource( XAResource xaRes ) throws RollbackException, IllegalStateException, SystemException { if ( xaRes == null ) { throw new IllegalArgumentException( "Null xa resource" ); } if ( status == Status.STATUS_ACTIVE || status == Status.STATUS_PREPARING ) { try { if ( resourceList.size() == 0 ) { if ( !globalStartRecordWritten ) { txManager.writeStartRecord( globalId ); globalStartRecordWritten = true; } byte branchId[] = txManager.getBranchId( xaRes ); Xid xid = new XidImpl( globalId, branchId ); resourceList.add( new ResourceElement( xid, xaRes ) ); xaRes.start( xid, XAResource.TMNOFLAGS ); try { txManager.getTxLog().addBranch( globalId, branchId ); } catch ( IOException e ) { e.printStackTrace(); log.severe( "Error writing transaction log" ); txManager.setTmNotOk(); throw new SystemException( "TM encountered a problem, " + " error writing transaction log," + e ); } return true; } Xid sameRmXid = null; Iterator<ResourceElement> itr = resourceList.iterator(); while ( itr.hasNext() ) { ResourceElement re = itr.next(); if ( sameRmXid == null && re.getResource().isSameRM( xaRes ) ) { sameRmXid = re.getXid(); } if ( xaRes == re.getResource() ) { if ( re.getStatus() == RS_SUSPENDED ) { xaRes.start( re.getXid(), XAResource.TMRESUME ); } else { // either enlisted or delisted // is TMJOIN correct then? xaRes.start( re.getXid(), XAResource.TMJOIN ); } re.setStatus( RS_ENLISTED ); return true; } } if ( sameRmXid != null ) // should we join? { resourceList.add( new ResourceElement( sameRmXid, xaRes ) ); xaRes.start( sameRmXid, XAResource.TMJOIN ); } else // new branch { // ResourceElement re = resourceList.getFirst(); byte branchId[] = txManager.getBranchId( xaRes ); Xid xid = new XidImpl( globalId, branchId ); resourceList.add( new ResourceElement( xid, xaRes ) ); xaRes.start( xid, XAResource.TMNOFLAGS ); try { txManager.getTxLog().addBranch( globalId, branchId ); } catch ( IOException e ) { e.printStackTrace(); log.severe( "Error writing transaction log" ); txManager.setTmNotOk(); throw new SystemException( "TM encountered a problem, " + " error writing transaction log," + e ); } } return true; } catch ( XAException e ) { e.printStackTrace(); log.severe( "Unable to enlist resource[" + xaRes + "]" ); status = Status.STATUS_MARKED_ROLLBACK; return false; } } else if ( status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_ROLLEDBACK || status == Status.STATUS_MARKED_ROLLBACK ) { throw new RollbackException( "Tx status is: " + txManager.getTxStatusAsString( status ) ); } throw new IllegalStateException( "Tx status is: " + txManager.getTxStatusAsString( status ) ); } public synchronized boolean delistResource( XAResource xaRes, int flag ) throws IllegalStateException { if ( xaRes == null ) { throw new IllegalArgumentException( "Null xa resource" ); } if ( flag != XAResource.TMSUCCESS && flag != XAResource.TMSUSPEND && flag != XAResource.TMFAIL ) { throw new IllegalArgumentException( "Illegal flag: " + flag ); } ResourceElement re = null; Iterator<ResourceElement> itr = resourceList.iterator(); while ( itr.hasNext() ) { ResourceElement reMatch = itr.next(); if ( reMatch.getResource() == xaRes ) { re = reMatch; break; } } if ( re == null ) { return false; } if ( status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK ) { try { xaRes.end( re.getXid(), flag ); if ( flag == XAResource.TMSUSPEND || flag == XAResource.TMFAIL ) { re.setStatus( RS_SUSPENDED ); } else { re.setStatus( RS_DELISTED ); } return true; } catch ( XAException e ) { e.printStackTrace(); log.severe( "Unable to delist resource[" + xaRes + "]" ); status = Status.STATUS_MARKED_ROLLBACK; return false; } } throw new IllegalStateException( "Tx status is: " + txManager.getTxStatusAsString( status ) ); } // TODO: figure out if this needs syncrhonization or make status volatile public int getStatus() // throws SystemException { return status; } void setStatus( int status ) { this.status = status; } private boolean beforeCompletionRunning = false; private List<Synchronization> syncHooksAdded = new ArrayList<Synchronization>(); public synchronized void registerSynchronization( Synchronization s ) throws RollbackException, IllegalStateException { if ( s == null ) { throw new IllegalArgumentException( "Null parameter" ); } if ( status == Status.STATUS_ACTIVE || status == Status.STATUS_PREPARING || status == Status.STATUS_MARKED_ROLLBACK ) { if ( !beforeCompletionRunning ) { syncHooks.add( s ); } else { // avoid CME if synchronization is added in before completion syncHooksAdded.add( s ); } } else if ( status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_ROLLEDBACK ) { throw new RollbackException( "Tx status is: " + txManager.getTxStatusAsString( status ) ); } else { throw new IllegalStateException( "Tx status is: " + txManager.getTxStatusAsString( status ) ); } } synchronized void doBeforeCompletion() { beforeCompletionRunning = true; try { for ( Synchronization s : syncHooks ) { try { s.beforeCompletion(); } catch ( Throwable t ) { log.log( Level.WARNING, "Caught exception from tx syncronization[" + s + "] beforeCompletion()", t ); } } // execute any hooks added since we entered doBeforeCompletion while ( !syncHooksAdded.isEmpty() ) { List<Synchronization> addedHooks = syncHooksAdded; syncHooksAdded = new ArrayList<Synchronization>(); for ( Synchronization s : addedHooks ) { s.beforeCompletion(); syncHooks.add( s ); } } } finally { beforeCompletionRunning = false; } } synchronized void doAfterCompletion() { for ( Synchronization s : syncHooks ) { try { s.afterCompletion( status ); } catch ( Throwable t ) { log.log( Level.WARNING, "Caught exception from tx syncronization[" + s + "] afterCompletion()", t ); } } syncHooks = null; // help gc } public void setRollbackOnly() throws IllegalStateException { if ( status == Status.STATUS_ACTIVE || status == Status.STATUS_PREPARING || status == Status.STATUS_PREPARED || status == Status.STATUS_MARKED_ROLLBACK || status == Status.STATUS_ROLLING_BACK ) { status = Status.STATUS_MARKED_ROLLBACK; } else { throw new IllegalStateException( "Tx status is: " + txManager.getTxStatusAsString( status ) ); } } public boolean equals( Object o ) { if ( !(o instanceof TransactionImpl) ) { return false; } TransactionImpl other = (TransactionImpl) o; return this.eventIdentifier == other.eventIdentifier; } private volatile int hashCode = 0; public int hashCode() { if ( hashCode == 0 ) { hashCode = 3217 * eventIdentifier; } return hashCode; } int getResourceCount() { return resourceList.size(); } private boolean isOnePhase() { if ( resourceList.size() == 0 ) { log.severe( "Detected zero resources in resourceList" ); return true; } // check for more than one unique xid Iterator<ResourceElement> itr = resourceList.iterator(); Xid xid = itr.next().getXid(); while ( itr.hasNext() ) { if ( !xid.equals( itr.next().getXid() ) ) { return false; } } return true; } void doCommit() throws XAException, SystemException { try { boolean onePhase = isOnePhase(); boolean readOnly = true; if ( !onePhase ) { // prepare status = Status.STATUS_PREPARING; LinkedList<Xid> preparedXids = new LinkedList<Xid>(); Iterator<ResourceElement> itr = resourceList.iterator(); while ( itr.hasNext() ) { ResourceElement re = itr.next(); if ( !preparedXids.contains( re.getXid() ) ) { preparedXids.add( re.getXid() ); int vote = re.getResource().prepare( re.getXid() ); if ( vote == XAResource.XA_OK ) { readOnly = false; } else if ( vote == XAResource.XA_RDONLY ) { re.setStatus( RS_READONLY ); } else { // rollback tx status = Status.STATUS_MARKED_ROLLBACK; return; } } else { // set it to readonly, only need to commit once re.setStatus( RS_READONLY ); } } status = Status.STATUS_PREPARED; } // commit if ( !onePhase && readOnly ) { status = Status.STATUS_COMMITTED; return; } if ( !onePhase ) { try { txManager.getTxLog().markAsCommitting( getGlobalId() ); } catch ( IOException e ) { e.printStackTrace(); log.severe( "Error writing transaction log" ); txManager.setTmNotOk(); throw new SystemException( "TM encountered a problem, " + " error writing transaction log," + e ); } } status = Status.STATUS_COMMITTING; Iterator<ResourceElement> itr = resourceList.iterator(); while ( itr.hasNext() ) { ResourceElement re = itr.next(); if ( re.getStatus() != RS_READONLY ) { re.getResource().commit( re.getXid(), onePhase ); } } status = Status.STATUS_COMMITTED; } finally { this.txManager.rollbackHook.doneCommitting( eventIdentifier ); } } void doRollback() throws XAException { try { status = Status.STATUS_ROLLING_BACK; LinkedList<Xid> rolledbackXids = new LinkedList<Xid>(); Iterator<ResourceElement> itr = resourceList.iterator(); while ( itr.hasNext() ) { ResourceElement re = itr.next(); if ( !rolledbackXids.contains( re.getXid() ) ) { rolledbackXids.add( re.getXid() ); re.getResource().rollback( re.getXid() ); } } status = Status.STATUS_ROLLEDBACK; } finally { this.txManager.rollbackHook.doneCommitting( eventIdentifier ); } } private static class ResourceElement { private Xid xid = null; private XAResource resource = null; private int status; ResourceElement( Xid xid, XAResource resource ) { this.xid = xid; this.resource = resource; status = RS_ENLISTED; } Xid getXid() { return xid; } XAResource getResource() { return resource; } int getStatus() { return status; } void setStatus( int status ) { this.status = status; } public String toString() { String statusString = null; switch ( status ) { case RS_ENLISTED: statusString = "ENLISTED"; break; case RS_DELISTED: statusString = "DELISTED"; break; case RS_SUSPENDED: statusString = "SUSPENDED"; break; case RS_READONLY: statusString = "READONLY"; break; default: statusString = "UNKNOWN"; } return "Xid[" + xid + "] XAResource[" + resource + "] Status[" + statusString + "]"; } } synchronized void markAsActive() { if ( active ) { throw new IllegalStateException( "Transaction[" + this + "] already active" ); } active = true; } synchronized void markAsSuspended() { if ( !active ) { throw new IllegalStateException( "Transaction[" + this + "] already suspended" ); } active = false; } }
package chatroom; import java.awt.BorderLayout; import java.awt.Panel; import java.awt.TextArea; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; /** * @author $cotty $haw * * The Client class has a text entry field that lets us type messages * and a text display window that shows messages from other users. We * also have a background thread for receiving messages. Our infinite * loop here has the same purpose as the one in our Server: read in a * message from another user, process it, and perhaps write something * back to the server as a response. Most importantly, the GUI visual * is created in this class. * */ public class Client extends Panel implements Runnable { // String constants private static final String MY_TEXT_FIELD_MESSAGE = "Type..."; private static final String MY_TEXT_AREA_MESSAGE = "Chat..."; private static final String EMPTY_STRING = ""; private static final String NEWLINE = "\n"; private static final String ERROR_CONNECTING_MESSAGE = "Error connecting"; private static final String ERROR_SENDING_TO_SERVER = "Error communicating with server"; private static final String ERROR_DISPLAYING_MESSAGE = "Error displaying chat message"; /** * Generated serial version ID */ private static final long serialVersionUID = -1649877892361198998L; // Components for the visual display of the chat windows private TextField myTextField = new TextField(); private TextArea myTextArea = new TextArea(); // Socket connected to the server private Socket mySocket; // Streams from the socket that communicate to the server private DataOutputStream myDataOut; private DataInputStream myDataIn; protected Client (String host, int port) { setLayout(new BorderLayout()); add(MY_TEXT_FIELD_MESSAGE, myTextField); add(MY_TEXT_AREA_MESSAGE, myTextArea); // Receives messages when a user types a line and hits return myTextField.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { sendUserMessageToServer(e.getActionCommand()); } }); // Connects to the server try { mySocket = new Socket(host, port); myDataIn = new DataInputStream(mySocket.getInputStream()); myDataOut = new DataOutputStream(mySocket.getOutputStream()); // Starts background threads for receiving messages new Thread(this).start(); } catch (IOException ex) { System.out.println(ERROR_CONNECTING_MESSAGE); } } // Sends user messages to the server private void sendUserMessageToServer (String message) { try { myDataOut.writeUTF(message); myTextField.setText(EMPTY_STRING); } catch (IOException ex) { System.out.println(ERROR_SENDING_TO_SERVER); } } // Runs on background threads to display messages from other windows public void run () { try { while (true) { String message = myDataIn.readUTF(); myTextArea.append(message + NEWLINE); } } catch (IOException ex) { System.out.println(ERROR_DISPLAYING_MESSAGE); } } }
package com.vincent.filepicker.activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.vincent.filepicker.Constant; import com.vincent.filepicker.DividerGridItemDecoration; import com.vincent.filepicker.R; import com.vincent.filepicker.adapter.ImagePickAdapter; import com.vincent.filepicker.adapter.OnSelectStateListener; import com.vincent.filepicker.filter.FileFilter; import com.vincent.filepicker.filter.callback.FilterResultCallback; import com.vincent.filepicker.filter.entity.Directory; import com.vincent.filepicker.filter.entity.ImageFile; import java.io.File; import java.util.ArrayList; import java.util.List; import static com.vincent.filepicker.activity.ImageBrowserActivity.IMAGE_BROWSER_SELECTED_NUMBER; public class ImagePickActivity extends BaseActivity { public static final String IS_NEED_CAMERA = "IsNeedCamera"; public static final int DEFAULT_MAX_NUMBER = 9; public static final int COLUMN_NUMBER = 3; private int mMaxNumber; private int mCurrentNumber = 0; private Toolbar mTbImagePick; private RecyclerView mRecyclerView; private ImagePickAdapter mAdapter; private boolean isNeedCamera; private ArrayList<ImageFile> mSelectedList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_image_pick); mMaxNumber = getIntent().getIntExtra(Constant.MAX_NUMBER, DEFAULT_MAX_NUMBER); isNeedCamera = getIntent().getBooleanExtra(IS_NEED_CAMERA, false); initView(); super.onCreate(savedInstanceState); } @Override void permissionGranted() { loadData(); } private void initView() { mTbImagePick = (Toolbar) findViewById(R.id.tb_image_pick); mTbImagePick.setTitle(mCurrentNumber + "/" + mMaxNumber); setSupportActionBar(mTbImagePick); mTbImagePick.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); mRecyclerView = (RecyclerView) findViewById(R.id.rv_image_pick); GridLayoutManager layoutManager = new GridLayoutManager(this, COLUMN_NUMBER); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this)); mAdapter = new ImagePickAdapter(this, isNeedCamera, mMaxNumber); mRecyclerView.setAdapter(mAdapter); mAdapter.setOnSelectStateListener(new OnSelectStateListener<ImageFile>() { @Override public void OnSelectStateChanged(boolean state, ImageFile file) { if (state) { mSelectedList.add(file); mCurrentNumber++; } else { mSelectedList.remove(file); mCurrentNumber } mTbImagePick.setTitle(mCurrentNumber + "/" + mMaxNumber); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case Constant.REQUEST_CODE_TAKE_IMAGE: if (resultCode == RESULT_OK) { Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); File file = new File(mAdapter.mImagePath); Uri contentUri = Uri.fromFile(file); mediaScanIntent.setData(contentUri); sendBroadcast(mediaScanIntent); loadData(); } break; case Constant.REQUEST_CODE_BROWSER_IMAGE: if (resultCode == RESULT_OK) { ArrayList<ImageFile> list = data.getParcelableArrayListExtra(Constant.RESULT_BROWSER_IMAGE); mCurrentNumber = data.getIntExtra(IMAGE_BROWSER_SELECTED_NUMBER, 0); mAdapter.setCurrentNumber(mCurrentNumber); mTbImagePick.setTitle(mCurrentNumber + "/" + mMaxNumber); refreshSelectedList(list); mAdapter.refresh(list); } break; } } private void loadData() { FileFilter.getImages(this, new FilterResultCallback<ImageFile>() { @Override public void onResult(List<Directory<ImageFile>> directories) { List<ImageFile> list = new ArrayList<>(); for (Directory<ImageFile> directory : directories) { list.addAll(directory.getFiles()); } for (ImageFile file : mSelectedList) { int index = list.indexOf(file); if (index != -1) { list.get(index).setSelected(true); } } mAdapter.refresh(list); } }); } private void refreshSelectedList(List<ImageFile> list) { for (ImageFile file : list) { if(file.isSelected() && !mSelectedList.contains(file)) { mSelectedList.add(file); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_image_pick, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_done) { Intent intent = new Intent(); intent.putParcelableArrayListExtra(Constant.RESULT_PICK_IMAGE, mSelectedList); setResult(RESULT_OK, intent); finish(); return true; } return super.onOptionsItemSelected(item); } }
package com.google.api.gax.httpjson; import com.google.api.core.BetaApi; import com.google.auth.Credentials; import com.google.auto.value.AutoValue; import javax.annotation.Nullable; import org.threeten.bp.Instant; /** Options for an http-json call, including deadline and credentials. */ @BetaApi @AutoValue public abstract class HttpJsonCallOptions { @Nullable public abstract Instant getDeadline(); @Nullable public abstract Credentials getCredentials(); public static Builder newBuilder() { return new AutoValue_HttpJsonCallOptions.Builder(); } @AutoValue.Builder public abstract static class Builder { public abstract Builder setDeadline(Instant value); public abstract Builder setCredentials(Credentials value); public abstract HttpJsonCallOptions build(); } }
package org.jboss.as.console.client.v3.stores.domain; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.view.client.ProvidesKey; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.domain.model.HostInformationStore; import org.jboss.as.console.client.domain.model.Server; import org.jboss.as.console.client.domain.model.ServerInstance; import org.jboss.as.console.client.domain.model.SimpleCallback; import org.jboss.as.console.client.shared.model.ModelAdapter; import org.jboss.as.console.client.shared.util.DMRUtil; import org.jboss.as.console.client.v3.stores.domain.actions.AddServer; import org.jboss.as.console.client.v3.stores.domain.actions.CopyServer; import org.jboss.as.console.client.v3.stores.domain.actions.HostSelection; import org.jboss.as.console.client.v3.stores.domain.actions.RefreshServer; import org.jboss.as.console.client.v3.stores.domain.actions.RemoveServer; import org.jboss.as.console.client.v3.stores.domain.actions.SelectServerInstance; import org.jboss.as.console.client.v3.stores.domain.actions.UpdateServer; import org.jboss.as.console.client.widgets.forms.ApplicationMetaData; import org.jboss.as.console.client.widgets.forms.PropertyBinding; import org.jboss.dmr.client.ModelDescriptionConstants; import org.jboss.dmr.client.ModelNode; import org.jboss.dmr.client.dispatch.DispatchAsync; import org.jboss.dmr.client.dispatch.impl.DMRAction; import org.jboss.dmr.client.dispatch.impl.DMRResponse; import org.jboss.gwt.circuit.ChangeSupport; import org.jboss.gwt.circuit.Dispatcher; import org.jboss.gwt.circuit.meta.Process; import org.jboss.gwt.circuit.meta.Store; import org.jboss.gwt.flow.client.Async; import org.jboss.gwt.flow.client.Control; import org.jboss.gwt.flow.client.Function; import org.jboss.gwt.flow.client.Outcome; import javax.inject.Inject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.jboss.dmr.client.ModelDescriptionConstants.*; /** * @author Heiko Braun * @since 15/07/14 */ @Store public class ServerStore extends ChangeSupport { private final DispatchAsync dispatcher; private final ApplicationMetaData propertyMetaData; private final HostInformationStore hostInfo; private final HostStore hostStore; private Map<String, List<Server>> serverModel = new HashMap<>(); private Map<String, List<ServerInstance>> instanceModel = new HashMap<>(); private ServerInstance selectedServerInstance; @Inject public ServerStore(HostStore hostStore, HostInformationStore hostInfo, DispatchAsync dispatcher, ApplicationMetaData propertyMetaData) { this.hostStore = hostStore; this.hostInfo = hostInfo; this.dispatcher = dispatcher; this.propertyMetaData = propertyMetaData; } // init public void init(final String hostName, final AsyncCallback<List<Server>> callback) { synchronizeServerModel(hostName, new AsyncCallback<Boolean>() { @Override public void onFailure(Throwable throwable) { callback.onFailure(throwable); } @Override public void onSuccess(Boolean aBoolean) { callback.onSuccess(serverModel.get(hostName)); } }); } // action processing @Process(actionType = HostSelection.class, dependencies = {HostStore.class}) public void onSelectHost(String hostName, final Dispatcher.Channel channel) { // if the data has not been loaded we force a refresh if(!serverModel.containsKey(hostName)) onRefresh(channel); else { // if the host changes, we do select another instance by default defaultSelection(); channel.ack(); fireChanged(ServerStore.class); } } class RefreshValues { List<Server> servers; List<ServerInstance> instances; } @Process(actionType = RefreshServer.class, dependencies = {HostStore.class}) public void onRefresh(final Dispatcher.Channel channel) { final String hostName = hostStore.getSelectedHost(); synchronizeServerModel(hostName, new AsyncCallback<Boolean>() { @Override public void onFailure(Throwable throwable) { channel.nack(throwable); } @Override public void onSuccess(Boolean aBoolean) { channel.ack(); fireChanged(ServerStore.class); } }); } private void synchronizeServerModel(final String hostName, final AsyncCallback<Boolean> callback) { Function<RefreshValues> fetchServers = new Function<RefreshValues>() { @Override public void execute(final Control<RefreshValues> control) { hostInfo.getServerConfigurations(hostName, new SimpleCallback<List<Server>>() { @Override public void onSuccess(List<Server> servers) { control.getContext().servers = servers; control.proceed(); } @Override public void onFailure(Throwable caught) { control.abort(); Console.error("Failed to load servers", caught.getMessage()); } }); } }; Function<RefreshValues> fetchInstances = new Function<RefreshValues>() { @Override public void execute(final Control<RefreshValues> control) { hostInfo.getServerInstances(hostName, new SimpleCallback<List<ServerInstance>>() { @Override public void onSuccess(List<ServerInstance> servers) { control.getContext().instances = servers; control.proceed(); } @Override public void onFailure(Throwable caught) { control.abort(); Console.error("Failed to load server instances", caught.getMessage()); } }); } }; Outcome<RefreshValues> outcome = new Outcome<RefreshValues>() { @Override public void onFailure(RefreshValues context) { callback.onFailure(new RuntimeException("Failed to synchronize server model")); } @Override public void onSuccess(RefreshValues context) { serverModel.put(hostName, context.servers); instanceModel.put(hostName, context.instances); defaultSelection(); callback.onSuccess(true); } }; new Async().waterfall(new RefreshValues(), outcome, fetchServers, fetchInstances); } private void defaultSelection() { List<ServerInstance> instancesOnHost = instanceModel.get(hostStore.getSelectedHost()); if(instancesOnHost.size()>0) { selectedServerInstance = instancesOnHost.get(0); } else if(instancesOnHost.isEmpty()) { // no selection possible selectedServerInstance =null; } } @Process(actionType = AddServer.class) public void onAddServer(final Server server, final Dispatcher.Channel channel) { hostInfo.createServerConfig(hostStore.getSelectedHost(), server, new SimpleCallback<Boolean>() { @Override public void onSuccess(Boolean success) { onRefresh(channel); } @Override public void onFailure(Throwable caught) { Console.error("Failed to add server", caught.getMessage()); channel.nack(caught); } }); } @Process(actionType = RemoveServer.class) public void onRemoveServer(final Server server, final Dispatcher.Channel channel) { hostInfo.deleteServerConfig(hostStore.getSelectedHost(), server, new SimpleCallback<Boolean>() { @Override public void onSuccess(Boolean success) { onRefresh(channel); } @Override public void onFailure(Throwable caught) { Console.error("Failed to remove server", caught.getMessage()); channel.nack(caught); } }); } @Process(actionType = SelectServerInstance.class) public void onSelectedServerInstance(final ServerInstance serverInstance, final Dispatcher.Channel channel) { this.selectedServerInstance = serverInstance; channel.ack(); fireChanged(ServerStore.class); } @Process(actionType = UpdateServer.class) public void onUpdateServer(final UpdateServer.Values update, final Dispatcher.Channel channel) { final Map<String, Object> changedValues = update.getChangedValues(); Server entity = update.getServer(); if (changedValues.containsKey("portOffset")) { changedValues.put("socketBinding", entity.getSocketBinding()); } if (changedValues.containsKey("socketBinding")) { changedValues.put("portOffset", entity.getPortOffset()); } final String name = entity.getName(); ModelNode proto = new ModelNode(); proto.get(OP).set(WRITE_ATTRIBUTE_OPERATION); proto.get(ADDRESS).add("host", hostStore.getSelectedHost()); proto.get(ADDRESS).add(ModelDescriptionConstants.SERVER_CONFIG, name); List<PropertyBinding> bindings = propertyMetaData.getBindingsForType(Server.class); ModelNode operation = ModelAdapter.detypedFromChangeset(proto, changedValues, bindings); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if (response.isFailure()) { Console.error(Console.MESSAGES.modificationFailed("Server Configuration ") + name, response.getFailureDescription()); } else { Console.info(Console.MESSAGES.modified("Server Configuration ") + name); } onRefresh(channel); } @Override public void onFailure(Throwable caught) { channel.nack(caught); } }); } @Process(actionType = CopyServer.class) public void onSaveCopy(CopyServer.Values copyValues, final Dispatcher.Channel channel) { final Server original = copyValues.getOriginal(); final Server newServer = copyValues.getNewServer(); final String targetHost = copyValues.getTargetHost(); final ModelNode operation = new ModelNode(); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(ADDRESS).setEmptyList(); operation.get(ADDRESS).add("host", hostStore.getSelectedHost()); operation.get(ADDRESS).add("server-config", original.getName()); operation.get(RECURSIVE).set(true); dispatcher.execute(new DMRAction(operation, false), new AsyncCallback<DMRResponse>() { @Override public void onFailure(Throwable caught) { Console.error("Failed to read server-config: " + original.getName(), caught.getMessage()); channel.nack(caught); } @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if (response.isFailure()) { Console.error("Failed to read server-config: " + original.getName(), response.getFailureDescription()); } else { ModelNode model = response.get("result").asObject(); // required attribute changes: portOffset & serverGroup model.get("socket-binding-port-offset").set(newServer.getPortOffset()); model.remove("name"); // re-create node ModelNode compositeOp = new ModelNode(); compositeOp.get(OP).set(COMPOSITE); compositeOp.get(ADDRESS).setEmptyList(); List<ModelNode> steps = new ArrayList<ModelNode>(); final ModelNode rootResourceOp = new ModelNode(); rootResourceOp.get(OP).set(ADD); rootResourceOp.get(ADDRESS).add("host", targetHost); rootResourceOp.get(ADDRESS).add("server-config", newServer.getName()); steps.add(rootResourceOp); DMRUtil.copyResourceValues(model, rootResourceOp, steps); compositeOp.get(STEPS).set(steps); dispatcher.execute(new DMRAction(compositeOp), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse dmrResponse) { ModelNode response = dmrResponse.get(); if (response.isFailure()) { Console.error("Failed to copy server-config", response.getFailureDescription()); } else { Console.info("Successfully copied server-config '" + newServer.getName() + "'"); } onRefresh(channel); } }); } } }); } // data access public List<Server> getServerModel(String host) { List<Server> servers = serverModel.get(host); return servers != null ? servers : new ArrayList<Server>(); } public boolean hasSelectedServer() { return selectedServerInstance!=null; } public String getSelectedServer() { if(null==selectedServerInstance) throw new IllegalStateException("No server instance selected"); return selectedServerInstance.getName(); } public List<ServerInstance> getServerInstances(String host) { List<ServerInstance> serverInstances = instanceModel.get(host); return serverInstances != null ? serverInstances : new ArrayList<ServerInstance>(); } public ServerInstance getSelectedServerInstance() { if(null==selectedServerInstance) throw new IllegalStateException("No server instance selected"); return selectedServerInstance; } // utility private final static ProvidesKey<Server> SERVER_KEY = new ProvidesKey<Server>() { @Override public Object getKey(Server server) { return server.getName()+"_"+server.getGroup(); } }; private final static ProvidesKey<ServerInstance> SERVER_INSTANCE_KEY = new ProvidesKey<ServerInstance>() { @Override public Object getKey(ServerInstance server) { return server.getName()+"_"+server.getGroup(); } }; }
package ru.assisttech.sdk.engine; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.text.TextUtils; import android.util.Log; import java.net.MalformedURLException; import java.net.URL; import java.security.cert.Certificate; import ru.assisttech.sdk.AssistAddress; import ru.assisttech.sdk.AssistMerchant; import ru.assisttech.sdk.AssistPaymentData; import ru.assisttech.sdk.AssistResult; import ru.assisttech.sdk.FieldName; import ru.assisttech.sdk.R; import ru.assisttech.sdk.identification.InstallationInfo; import ru.assisttech.sdk.identification.SystemInfo; import ru.assisttech.sdk.network.AssistNetworkEngine; import ru.assisttech.sdk.processor.AssistCancelProcessor; import ru.assisttech.sdk.processor.AssistRecurrentPayProcessor; import ru.assisttech.sdk.processor.AssistTokenPayProcessor; import ru.assisttech.sdk.registration.AssistRegistrationData; import ru.assisttech.sdk.registration.AssistRegistrationProvider; import ru.assisttech.sdk.registration.RegistrationRequestBuilder; import ru.assisttech.sdk.processor.AssistBaseProcessor; import ru.assisttech.sdk.processor.AssistResultProcessor; import ru.assisttech.sdk.processor.AssistProcessorEnvironment; import ru.assisttech.sdk.processor.AssistProcessorListener; import ru.assisttech.sdk.processor.AssistWebProcessor; import ru.assisttech.sdk.storage.AssistTransaction; import ru.assisttech.sdk.storage.AssistTransactionStorage; import ru.assisttech.sdk.storage.AssistTransactionStorageImpl; import static ru.assisttech.sdk.storage.AssistTransaction.PaymentMethod.CARD_TERMINAL; /** * Initiates payment process, checks connection and registration */ public class AssistPayEngine { private static final String TAG = "AssistPayEngine"; private String ServerUrl = AssistAddress.DEFAULT_SERVER; private Context appContext; private Activity callerActivity; private InstallationInfo instInfo; private AssistNetworkEngine netEngine; protected AssistBaseProcessor processor; private AssistTransactionStorage storage; private PayEngineListener engineListener; private ProgressDialog pd; private boolean connectionChecked; private boolean finished; private String deviceUniqueId; private static AssistPayEngine instance; public static synchronized AssistPayEngine getInstance(Context context) { if (instance == null) { instance = new AssistPayEngine(context); } return instance; } private AssistPayEngine(Context c) { appContext = c.getApplicationContext(); netEngine = new AssistNetworkEngine(appContext); storage = new AssistTransactionStorageImpl(appContext, "c"); instInfo = InstallationInfo.getInstance(appContext); SystemInfo sysInfo = SystemInfo.getInstance(); deviceUniqueId = sysInfo.uniqueId(); } public AssistProcessorEnvironment buildServiceEnvironment(AssistPaymentData data) { AssistMerchant m = new AssistMerchant(data.getMerchantID(), data.getLogin(), data.getPassword()); return new AssistProcessorEnvironment(this, m, data); } public void setEngineListener(PayEngineListener listener) { engineListener = listener; } public PayEngineListener getEngineListener() { return engineListener; } public void addNetworkCertificate(Certificate cert) { netEngine.addCertificate(cert); } public void setServerURL(String url) { if (!TextUtils.isEmpty(url)) { try { String protocol = new URL(url).getProtocol(); if (TextUtils.isEmpty(protocol)) { ServerUrl = "https://" + url; } else { ServerUrl = url; } } catch (MalformedURLException e) { e.printStackTrace(); } } } public AssistTransactionStorage transactionStorage() { return storage; } public InstallationInfo getInstInfo() { return instInfo; } public void payWeb(Activity caller, AssistPaymentData data, boolean useCamera) { payWeb(caller, buildServiceEnvironment(data), useCamera); } /** * Web based payment process * Uses device camera for card data input */ public void payWeb(Activity caller, AssistProcessorEnvironment environment, boolean useCamera) { if (isEngineReady()) { saveCallerActivity(caller); setFinished(false); AssistPaymentData data = environment.getData(); data.setMobileDevice("5"); // Tells Assist server what web pages to show AssistTransaction t = createTransaction( data.getMerchantID(), data, useCamera ? AssistTransaction.PaymentMethod.CARD_PHOTO_SCAN : AssistTransaction.PaymentMethod.CARD_MANUAL ); processor = new AssistWebProcessor(getContext(), environment, useCamera); processor.setNetEngine(netEngine); processor.setURL(getWebServiceUrl()); processor.setListener(new WebProcessorListener()); processor.setTransaction(t); checkRegistration(); } } public void payToken(Activity caller, AssistPaymentData data, String type) { payToken(caller, buildServiceEnvironment(data), type); } public void payToken(Activity caller, AssistProcessorEnvironment environment, String type) { if (isEngineReady()) { saveCallerActivity(caller); setFinished(false); AssistPaymentData data = environment.getData(); AssistTransaction t = createTransaction( data.getMerchantID(), data, CARD_TERMINAL ); processor = new AssistTokenPayProcessor(getContext(), environment, type); processor.setNetEngine(netEngine); processor.setURL(getTokenPayeServiceUrl()); processor.setListener(new TokenPayProcessorListener()); processor.setTransaction(t); checkRegistration(); } } /** * Recurrent Pay */ public void payRecurrent(Activity caller, AssistProcessorEnvironment environment) { if (isEngineReady()) { saveCallerActivity(caller); setFinished(false); AssistPaymentData data = environment.getData(); AssistTransaction t = createTransaction( data.getMerchantID(), data, CARD_TERMINAL ); processor = new AssistRecurrentPayProcessor(getContext(), environment); processor.setNetEngine(netEngine); processor.setURL(getRecurrentUrl()); processor.setListener(new RecurrentPayProcessorListener()); processor.setTransaction(t); checkRegistration(); } } public void cancelPayment(Activity caller, AssistTransaction t, String mid, String login, String password) { if (isEngineReady()) { saveCallerActivity(caller); setFinished(false); AssistMerchant m = new AssistMerchant(mid, login, password); AssistProcessorEnvironment env = new AssistProcessorEnvironment(this, m, null); processor = new AssistCancelProcessor(getContext(), env); processor.setNetEngine(netEngine); processor.setURL(getCancelUrl()); processor.setListener(new CancelProcessorListener()); processor.setTransaction(t); checkRegistration(); } } /** * Gets result for certain payment * @param id transaction ID {@link AssistTransaction#getId()} */ public void getOrderResult(Activity caller, long id) { if (isEngineReady()) { saveCallerActivity(caller); setFinished(false); processor = initResultProcessor(id); checkRegistration(); } } public void stopPayment(Activity caller) { setFinished(true); if ((processor != null) && (processor.isRunning())) { processor.stop(); getEngineListener().onCanceled(caller, processor.getTransaction()); processor = null; } } public String getRegistrationId() { return getInstInfo().getAppRegId(); } public String getDeviceId() { return getInstInfo().getDeiceUniqueId(); } /** * Checks application registration in Assist Payment System */ private void checkRegistration() { /* Check network connection first */ if (!connectionChecked) { checkNetworkConnection(); return; } if (getRegistrationId() == null) { startRegistration(); } else { deviceUniqueId = getDeviceId(); startPayment(); } } private void startRegistration() { AssistRegistrationData regData = new AssistRegistrationData(); regData.setApplicationName(instInfo.appName()); regData.setAppVersion(instInfo.versionName()); regData.setDerviceID(deviceUniqueId); AssistRegistrationProvider rp = new AssistRegistrationProvider(getContext()); rp.setNetworkEngine(netEngine); rp.setURL(getRegistrationUrl()); rp.setResultListener(new RegistrationResultListener()); rp.register(new RegistrationRequestBuilder(regData)); } private void onRegistrationSuccess(String deviceId, String registrationID) { getInstInfo().setAppRegID(deviceId, registrationID); } /** * HTTPS connection's certificate check procedure */ private void checkNetworkConnection() { Log.d(TAG, "Check URL: " + ServerUrl); try { URL u = new URL(ServerUrl + AssistAddress.WEB_SERVICE); showProgressDialog(getCallerActivity(), R.string.connection_check); netEngine.checkHTTPSConnection(u, new ConnectionCheckListener()); } catch (MalformedURLException e) { e.printStackTrace(); } } public AssistTransaction createTransaction(String merchantID, AssistPaymentData data, AssistTransaction.PaymentMethod method) { AssistTransaction t = new AssistTransaction(); t.setMerchantID(merchantID); t.setOrderAmount(data.getFields().get(FieldName.OrderAmount)); t.setOrderComment(data.getFields().get(FieldName.OrderComment)); t.setOrderCurrency(AssistPaymentData.Currency.valueOf(data.getFields().get(FieldName.OrderCurrency))); t.setOrderNumber(data.getFields().get(FieldName.OrderNumber)); if (data.getOrderItems() != null) { t.setOrderItems(data.getOrderItems()); } t.setPaymentMethod(method); /* Check if transaction requires user signature */ if (data.getFields().containsKey(FieldName.PaymentMode)) { String mode = data.getFields().get(FieldName.PaymentMode); t.setRequireUserSignature(AssistPaymentData.PaymentMode.POSKeyEntry.equals(mode)); } return t; } private void startProcessor() { processor.start(getCallerActivity()); } /** * Transaction saving and payment beginning */ private void startPayment() { Log.d(TAG, "startPayment()"); if (!processor.getTransaction().isStored()) { storage.add(processor.getTransaction()); // TODO: Check return value (whether transaction added successfully or not) } startProcessor(); } /** * Internal method to get payment result after payment process completion. * Does not check application registration * @param id transaction id {@link AssistTransaction#getId()} */ private void getResult(long id) { processor = initResultProcessor(id); startProcessor(); } private AssistResultProcessor getResultProcessor() { AssistProcessorEnvironment env = new AssistProcessorEnvironment(this, null, null); env.setDeviceId(getDeviceId()); return new AssistResultProcessor(getContext(), env); } /** * @param id transaction id {@link AssistTransaction#getId()} * @return {@link AssistResultProcessor} */ private AssistResultProcessor initResultProcessor(long id) { AssistResultProcessor rp = getResultProcessor(); rp.setNetEngine(netEngine); rp.setURL(getGetOrderStatusUrl()); rp.setListener(new ResultProcessorListener()); rp.setTransaction(getTransaction(id)); return rp; } /** * Obtain transaction form DB * @param id transaction id {@link AssistTransaction#getId()} */ protected AssistTransaction getTransaction(long id) { return storage.getTransaction(id); } /** * Update transaction in DB with new {@link AssistResult} * @param id ID of transaction to cancel {@link AssistTransaction#getId()} * @param result result of transaction {@link AssistResult} */ private void updateTransaction(long id, AssistResult result) { storage.updateTransactionResult(id, result); } private void engineInitializationFailed(String info) { processor = null; if (!isFinished()) { getEngineListener().onFailure(getCallerActivity(), info); } } protected Context getContext() { return appContext; } private String getServerUrl() { return ServerUrl; } private String getRegistrationUrl() { return getServerUrl() + AssistAddress.REGISTRATION_SERVICE; } private String getWebServiceUrl() { return getServerUrl() + AssistAddress.WEB_SERVICE; } private String getTokenPayeServiceUrl() { return getServerUrl() + AssistAddress.TOKENPAY_SERVICE; } private String getRecurrentUrl() { return getServerUrl() + AssistAddress.RECURRENT_URL; } private String getGetOrderStatusUrl() { return getServerUrl() + AssistAddress.GET_ORDER_STATUS_SERVICE; } private String getCancelUrl() { return getServerUrl() + AssistAddress.CANCEL_SERVICE; } private boolean isEngineReady() { return processor == null || !processor.isRunning(); } private void saveCallerActivity(Activity caller) { callerActivity = caller; } private Activity getCallerActivity() { return callerActivity; } private boolean isFinished() { return finished; } private void setFinished(boolean value) { this.finished = value; } private void showProgressDialog(Activity activity, int messageResId) { if (pd != null) { return; } pd = new ProgressDialog(activity); pd.setCanceledOnTouchOutside(false); pd.setMessage(appContext.getString(messageResId)); pd.show(); } private void closeProgressDialog() { if (pd != null) { pd.dismiss(); pd = null; } } public AssistWebProcessor getWebProcessor() { return (AssistWebProcessor) processor; } /** * Connection check result processing */ private class ConnectionCheckListener implements AssistNetworkEngine.ConnectionCheckListener { @Override public void onConnectionSuccess() { Log.d(TAG, "Connection check success"); closeProgressDialog(); connectionChecked = true; checkRegistration(); } @Override public void onConnectionFailure(String info) { Log.d(TAG, "Connection check error. " + info); closeProgressDialog(); connectionChecked = false; engineInitializationFailed(getContext().getString(R.string.connection_error)); } } private class RegistrationResultListener implements AssistRegistrationProvider.RegistrationResultListener { @Override public void onRegistrationOk(String registrationID) { Log.d(TAG, "onRegistrationOk(): " + registrationID); onRegistrationSuccess(deviceUniqueId, registrationID); startPayment(); } @Override public void onRegistrationError(String faultCode, String faultString) { Log.d(TAG, "onRegistrationError(): " + faultCode + ": " + faultString); engineInitializationFailed(getContext().getString(R.string.registration_error)); } } private abstract class BaseProcessorListener implements AssistProcessorListener { @Override public void onNetworkError(long id, String message) { Log.d(TAG, "onNetworkError() " + message); getEngineListener().onNetworkError(getCallerActivity(), message); } @Override public void onTerminated(long id) { Log.d(TAG, "onTerminated()"); getEngineListener().onCanceled(getCallerActivity(), getTransaction(id)); } @Override public void onActivityCreated(Activity newActivity) { Log.d(TAG, "onActivityCreated()"); if (newActivity != null) { saveCallerActivity(newActivity); } } } private class WebProcessorListener extends BaseProcessorListener { @Override public void onFinished(long id, AssistResult result) { Log.d(TAG, "WebProcessorListener.onFinished() id = : " + String.valueOf(id) + "; " + result.getExtra()); if (!TextUtils.isEmpty(result.getOrderNumber())) { transactionStorage().updateTransactionOrderNumber(id, result.getOrderNumber()); } if (!isFinished()) { getResult(id); } } @Override public void onError(long id, String message) { Log.d(TAG, "WebProcessorListener.onError() " + message); transactionStorage().deleteTransaction(id); getEngineListener().onFailure(getCallerActivity(), message); } } private class ResultProcessorListener extends BaseProcessorListener { @Override public void onFinished(long id, AssistResult result) { Log.d(TAG, "ResultProcessorListener.onFinished() " + result.getOrderState()); updateTransaction(id, result); getEngineListener().onFinished(getCallerActivity(), getTransaction(id)); } @Override public void onError(long id, String message) { Log.d(TAG, "ResultProcessorListener.onError() " + message); getEngineListener().onFailure(getCallerActivity(), message); } } private class CancelProcessorListener extends BaseProcessorListener { @Override public void onFinished(long id, AssistResult result) { Log.d(TAG, "CancelProcessorListener.onFinished() " + result.getOrderState()); updateTransaction(id, result); getEngineListener().onFinished(getCallerActivity(), getTransaction(id)); } @Override public void onError(long id, String message) { Log.d(TAG, "CancelProcessorListener.onError() " + message); getEngineListener().onFailure(getCallerActivity(), message); } } private class TokenPayProcessorListener extends BaseProcessorListener { @Override public void onFinished(long id, AssistResult result) { Log.d(TAG, "TokenPayProcessorListener.onFinished() " + result.getOrderState()); updateTransaction(id, result); getEngineListener().onFinished(getCallerActivity(), getTransaction(id)); } @Override public void onError(long id, String message) { Log.d(TAG, "TokenPayProcessorListener.onError() " + message); getEngineListener().onFailure(getCallerActivity(), message); } } private class RecurrentPayProcessorListener extends BaseProcessorListener { @Override public void onFinished(long id, AssistResult result) { Log.d(TAG, "RecurrentPayProcessorListener.onFinished() " + result.getOrderState()); updateTransaction(id, result); getEngineListener().onFinished(getCallerActivity(), getTransaction(id)); } @Override public void onError(long id, String message) { Log.d(TAG, "RecurrentPayProcessorListener.onError() " + message); getEngineListener().onFailure(getCallerActivity(), message); } } }
package com.splicemachine.orc.predicate; import com.splicemachine.db.iapi.error.StandardException; import com.splicemachine.db.iapi.services.io.ArrayUtil; import com.splicemachine.db.iapi.store.access.Qualifier; import com.splicemachine.db.iapi.types.*; import com.splicemachine.orc.OrcPredicate; import com.splicemachine.orc.metadata.*; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.SerializationUtils; import org.apache.parquet.column.statistics.LongStatistics; import org.apache.spark.sql.types.*; import org.apache.spark.sql.types.DataType; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.List; /** * Qualifiers in Conjunctive Normal Form... * * */ public class SpliceORCPredicate implements OrcPredicate, Externalizable { private Qualifier[][] qualifiers; int[] baseColumnMap; StructType structType; public SpliceORCPredicate() { } public SpliceORCPredicate(Qualifier[][] qualifiers, int[] baseColumnMap, StructType structType) { this.qualifiers = qualifiers; this.baseColumnMap = baseColumnMap; this.structType = structType; } @Override public void writeExternal(ObjectOutput out) throws IOException { ArrayUtil.writeIntArray(out,baseColumnMap); out.writeBoolean(qualifiers!=null); if (qualifiers != null) { out.writeInt(qualifiers.length); out.writeInt(qualifiers[0].length); for (int i = 0; i < qualifiers[0].length; i++) { out.writeObject(qualifiers[0][i]); } for (int and_idx = 1; and_idx < qualifiers.length; and_idx++) { out.writeInt(qualifiers[and_idx].length); for (int or_idx = 0; or_idx < qualifiers[and_idx].length; or_idx++) { out.writeObject(qualifiers[and_idx][or_idx]); } } } out.writeObject(structType.json()); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { baseColumnMap = ArrayUtil.readIntArray(in); if (in.readBoolean()) { qualifiers = new Qualifier[in.readInt()][]; qualifiers[0] = new Qualifier[in.readInt()]; for (int i = 0; i < qualifiers[0].length; i++) { qualifiers[0][i] = (Qualifier) in.readObject(); } for (int and_idx = 1; and_idx < qualifiers.length; and_idx++) { qualifiers[and_idx] = new Qualifier[in.readInt()]; for (int or_idx = 0; or_idx < qualifiers[and_idx].length; or_idx++) { qualifiers[and_idx][or_idx] = (Qualifier) in.readObject(); } } } structType = (StructType) StructType.fromJson((String)in.readObject()); } @Override public boolean matches(long numberOfRows, Map<Integer, ColumnStatistics> statisticsByColumnIndex) { try { boolean row_qualifies = true; if (qualifiers == null) return numberOfRows>0?true:false; for (int i = 0; i < qualifiers[0].length; i++) { Qualifier q = qualifiers[0][i]; if (q.getVariantType() == Qualifier.VARIANT) continue; // Cannot Push Down Qualifier StatsEval statsEval = statsEval(numberOfRows, statisticsByColumnIndex.get(q.getStoragePosition()), structType.fields()[baseColumnMap[q.getStoragePosition()]].dataType()); if (statsEval == null || statsEval.maximumDVD == null || statsEval.minimumDVD == null) return true; if (q.getOrderable() == null || q.getOrderable().isNull()) { if (!statsEval.hasNulls) return false; continue; } switch (q.getOperator()) { case com.splicemachine.db.iapi.types.DataType.ORDER_OP_LESSTHAN: case com.splicemachine.db.iapi.types.DataType.ORDER_OP_LESSOREQUALS: case com.splicemachine.db.iapi.types.DataType.ORDER_OP_GREATERTHAN: case com.splicemachine.db.iapi.types.DataType.ORDER_OP_GREATEROREQUALS: row_qualifies = statsEval.minimumDVD.compare( q.getOperator(), q.getOrderable(), q.getOrderedNulls(), q.getUnknownRV()) || statsEval.maximumDVD.compare( q.getOperator(), q.getOrderable(), q.getOrderedNulls(), q.getUnknownRV()); break; case com.splicemachine.db.iapi.types.DataType.ORDER_OP_EQUALS: row_qualifies = statsEval.minimumDVD.compare( com.splicemachine.db.iapi.types.DataType.ORDER_OP_LESSOREQUALS, q.getOrderable(), q.getOrderedNulls(), q.getUnknownRV()) && statsEval.maximumDVD.compare( com.splicemachine.db.iapi.types.DataType.ORDER_OP_GREATEROREQUALS, q.getOrderable(), q.getOrderedNulls(), q.getUnknownRV()); break; } if (q.negateCompareResult()) row_qualifies = !row_qualifies; if (!row_qualifies) return (false); } return true; } catch (Exception e) { throw new RuntimeException(e); } /* // all the qual[0] and terms passed, now process the OR clauses for (int and_idx = 1; and_idx < qual_list.length; and_idx++) { Column orCols = null; for (int or_idx = 0; or_idx < qual_list[and_idx].length; or_idx++) { Qualifier q = qual_list[and_idx][or_idx]; if (q.getVariantType() == Qualifier.VARIANT) continue; // Cannot Push Down Qualifier q.clearOrderableCache(); Column orCol = dataset.col(allColIdInSpark[(baseColumnMap != null ? baseColumnMap[q.getStoragePosition()] : q.getStoragePosition())]); Object value = q.getOrderable().getObject(); switch (q.getOperator()) { case DataType.ORDER_OP_LESSTHAN: orCol = q.negateCompareResult() ? orCol.geq(value) : orCol.lt(value); break; case DataType.ORDER_OP_LESSOREQUALS: orCol = q.negateCompareResult() ? orCol.gt(value) : orCol.leq(value); break; case DataType.ORDER_OP_GREATERTHAN: orCol = q.negateCompareResult() ? orCol.leq(value) : orCol.gt(value); break; case DataType.ORDER_OP_GREATEROREQUALS: orCol = q.negateCompareResult() ? orCol.lt(value) : orCol.geq(value); break; case DataType.ORDER_OP_EQUALS: orCol = q.negateCompareResult() ? orCol.notEqual(value) : orCol.equalTo(value); break; } if (orCols == null) orCols = orCol; else orCols = orCols.or(orCol); } } } catch (Exception e) { throw new RuntimeException(e); } */ } public String serialize() throws IOException { return Base64.encodeBase64String(SerializationUtils.serialize(this)); } public static SpliceORCPredicate deserialize(String base64String) throws IOException { return (SpliceORCPredicate) SerializationUtils.deserialize(Base64.decodeBase64(base64String)); } public static Map<Integer, ColumnStatistics> partitionStatsEval(List<Integer> baseColumnMap, StructType rowStruct, List<Integer> partitionColumns, String[] values) { try { Map<Integer, ColumnStatistics> partitionStatistics = new HashMap<>(partitionColumns.size()); for (int i = 0; i< partitionColumns.size(); i++) { int storagePos = partitionColumns.get(i); if (storagePos >= baseColumnMap.size()) continue; int j = baseColumnMap.get(storagePos); if (j==-1) // Partition Column Not In List... continue; DataType dataType = rowStruct.fields()[j].dataType(); if (dataType instanceof BooleanType) { partitionStatistics.put(storagePos, BooleanStatistics.getPartitionColumnStatistics(values[i])); } else if (dataType instanceof DecimalType) { partitionStatistics.put(storagePos, DecimalStatistics.getPartitionColumnStatistics(values[i])); } else if (dataType instanceof StringType) { partitionStatistics.put(storagePos, StringStatistics.getPartitionColumnStatistics(values[i])); } else if (dataType instanceof DateType) { partitionStatistics.put(storagePos, DateStatistics.getPartitionColumnStatistics(values[i])); } else if (dataType instanceof IntegerType) { partitionStatistics.put(storagePos, IntegerStatistics.getPartitionColumnStatistics(values[i])); } else if (dataType instanceof LongType) { partitionStatistics.put(storagePos, IntegerStatistics.getPartitionColumnStatistics(values[i])); } else if (dataType instanceof DoubleType) { partitionStatistics.put(storagePos, DoubleStatistics.getPartitionColumnStatistics(values[i])); } else if (dataType instanceof FloatType) { partitionStatistics.put(storagePos, DoubleStatistics.getPartitionColumnStatistics(values[i])); } else { } } return partitionStatistics; } catch (Exception se) { throw new RuntimeException(se); } } public StatsEval statsEval(long numberOfRows, ColumnStatistics columnStatistics, DataType dataType) throws StandardException { StatsEval statsEval = new StatsEval(); if (numberOfRows == 0) { statsEval.alwaysFalse = true; return statsEval; } if (columnStatistics == null) { statsEval.alwaysTrue = true; return statsEval; } if (columnStatistics.hasNumberOfValues() && columnStatistics.getNumberOfValues() == 0) { statsEval.allNulls = true; return statsEval; } statsEval.hasNulls = columnStatistics.getNumberOfValues() != numberOfRows; if (dataType instanceof BooleanType && columnStatistics.getBooleanStatistics() != null) { BooleanStatistics booleanStatistics = columnStatistics.getBooleanStatistics(); boolean hasTrueValues = (booleanStatistics.getTrueValueCount() != 0); boolean hasFalseValues = (columnStatistics.getNumberOfValues() != booleanStatistics.getTrueValueCount()); if (hasTrueValues && hasFalseValues) { statsEval.minimumDVD = new SQLBoolean(false); statsEval.maximumDVD = new SQLBoolean(true); } if (hasTrueValues) { statsEval.minimumDVD = new SQLBoolean(true); statsEval.maximumDVD = new SQLBoolean(true); } if (hasFalseValues) { statsEval.minimumDVD = new SQLBoolean(false); statsEval.maximumDVD = new SQLBoolean(false); } return statsEval; } else if (dataType instanceof DecimalType) { DecimalStatistics decimalStatistics = columnStatistics.getDecimalStatistics(); statsEval.minimumDVD = new SQLDecimal(decimalStatistics.getMin()); statsEval.maximumDVD = new SQLDecimal(decimalStatistics.getMax()); } else if (dataType instanceof StringType) { StringStatistics stringStatistics = columnStatistics.getStringStatistics(); statsEval.minimumDVD = new SQLVarchar(stringStatistics.getMin().toStringUtf8()); statsEval.maximumDVD = new SQLVarchar(stringStatistics.getMax().toStringUtf8()); } else if (dataType instanceof DateType) { DateStatistics dateStatistics = columnStatistics.getDateStatistics(); statsEval.minimumDVD = new SQLDate(dateStatistics.getMin()); statsEval.maximumDVD = new SQLDate(dateStatistics.getMax()); } else if (dataType instanceof IntegerType) { IntegerStatistics integerStatistics = columnStatistics.getIntegerStatistics(); statsEval.minimumDVD = new SQLInteger(integerStatistics.getMin().intValue()); statsEval.maximumDVD = new SQLInteger(integerStatistics.getMax().intValue()); } else if (dataType instanceof LongType) { IntegerStatistics integerStatistics = columnStatistics.getIntegerStatistics(); statsEval.minimumDVD = new SQLLongint(integerStatistics.getMin()); statsEval.maximumDVD = new SQLLongint(integerStatistics.getMax()); } else if (dataType instanceof DoubleType) { DoubleStatistics doubleStatistics = columnStatistics.getDoubleStatistics(); statsEval.minimumDVD = new SQLDouble(doubleStatistics.getMin()); statsEval.maximumDVD = new SQLDouble(doubleStatistics.getMax()); } else if (dataType instanceof FloatType) { DoubleStatistics doubleStatistics = columnStatistics.getDoubleStatistics(); statsEval.minimumDVD = new SQLReal(doubleStatistics.getMin().floatValue()); statsEval.maximumDVD = new SQLReal(doubleStatistics.getMax().floatValue()); } else { statsEval.alwaysTrue = true; } return statsEval; } }
package org.sakaiproject.evaluation.test.mocks; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.sakaiproject.evaluation.constant.EvalConstants; import org.sakaiproject.evaluation.logic.externals.EvalExternalLogic; import org.sakaiproject.evaluation.logic.model.EvalGroup; import org.sakaiproject.evaluation.logic.model.EvalScheduledJob; import org.sakaiproject.evaluation.logic.model.EvalUser; import org.sakaiproject.evaluation.test.EvalTestDataLoad; import org.sakaiproject.evaluation.utils.EvalUtils; /** * This is a mock class for testing purposes, it will allow us to test all the classes * that depend on it since it has way to many external dependencies to make it worth * it to mock them all up<br/> * <br/> * It is emulating the following system state:<br/> * 4 users: ADMIN_USER_ID (super admin), MAINT_USER_ID, USER_ID, STUDENT_USER_ID * 2 sites:<br/> * 1) CONTEXT1/SITE_ID (Site) - * USER_ID can take eval, MAINT_USER_ID can admin evals and be evaluated (cannot take)<br/> * 2) CONTEXT2/SITE2_ID (Group) - * USER_ID and STUDENT_USER_ID can take eval, MAINT_USER_ID can be evaluated but can not admin (cannot take)<br/> * * @author Aaron Zeckoski (aaronz@vt.edu) */ public class MockEvalExternalLogic implements EvalExternalLogic { /** * Note: Admin has all perms in all sites * 2 sites:<br/> * 1) CONTEXT1/SITE_ID - * USER_ID can take eval, MAINT_USER_ID can admin evals and be evaluated (cannot take)<br/> * 2) CONTEXT2/SITE2_ID - * USER_ID and STUDENT_USER_ID can take eval, MAINT_USER_ID can be evaluated but can not admin (cannot take)<br/> */ public int countEvalGroupsForUser(String userId, String permission) { if ( EvalTestDataLoad.ADMIN_USER_ID.equals(userId) ) { return 2; } else if ( EvalTestDataLoad.MAINT_USER_ID.equals(userId) ) { if ( EvalConstants.PERM_ASSIGN_EVALUATION.equals(permission) ) { return 1; } else if ( EvalConstants.PERM_BE_EVALUATED.equals(permission) ) { return 2; } else if ( EvalConstants.PERM_TAKE_EVALUATION.equals(permission) ) { return 0; } else if ( EvalConstants.PERM_WRITE_TEMPLATE.equals(permission) ) { return 1; } else { return 0; } } else if ( EvalTestDataLoad.USER_ID.equals(userId) ) { if ( EvalConstants.PERM_ASSIGN_EVALUATION.equals(permission) ) { return 0; } else if ( EvalConstants.PERM_BE_EVALUATED.equals(permission) ) { return 0; } else if ( EvalConstants.PERM_TAKE_EVALUATION.equals(permission) ) { return 2; } else if ( EvalConstants.PERM_WRITE_TEMPLATE.equals(permission) ) { return 0; } else { return 0; } } else if ( EvalTestDataLoad.STUDENT_USER_ID.equals(userId) ) { if ( EvalConstants.PERM_ASSIGN_EVALUATION.equals(permission) ) { return 0; } else if ( EvalConstants.PERM_BE_EVALUATED.equals(permission) ) { return 0; } else if ( EvalConstants.PERM_TAKE_EVALUATION.equals(permission) ) { return 1; } else if ( EvalConstants.PERM_WRITE_TEMPLATE.equals(permission) ) { return 0; } else { return 0; } } else { // do nothing } return 0; } /** * Note: Admin has all perms in all sites * 2 sites:<br/> * 1) CONTEXT1/SITE_ID - * USER_ID can take eval, MAINT_USER_ID can admin evals and be evaluated (cannot take)<br/> * 2) CONTEXT2/SITE2_ID - * USER_ID and STUDENT_USER_ID can take eval, MAINT_USER_ID can be evaluated but can not admin (cannot take)<br/> */ public List<EvalGroup> getEvalGroupsForUser(String userId, String permission) { List<EvalGroup> l = new ArrayList<EvalGroup>(); if ( EvalTestDataLoad.ADMIN_USER_ID.equals(userId) ) { l.add( makeEvalGroupObject(EvalTestDataLoad.SITE1_REF) ); l.add( makeEvalGroupObject(EvalTestDataLoad.SITE2_REF) ); } else if ( EvalTestDataLoad.MAINT_USER_ID.equals(userId) ) { if ( EvalConstants.PERM_ASSIGN_EVALUATION.equals(permission) ) { l.add( makeEvalGroupObject(EvalTestDataLoad.SITE1_REF) ); } else if ( EvalConstants.PERM_BE_EVALUATED.equals(permission) ) { l.add( makeEvalGroupObject(EvalTestDataLoad.SITE1_REF) ); l.add( makeEvalGroupObject(EvalTestDataLoad.SITE2_REF) ); } else if ( EvalConstants.PERM_TAKE_EVALUATION.equals(permission) ) { // nothing } else if ( EvalConstants.PERM_WRITE_TEMPLATE.equals(permission) ) { l.add( makeEvalGroupObject(EvalTestDataLoad.SITE1_REF) ); } else { // nothing } } else if ( EvalTestDataLoad.USER_ID.equals(userId) ) { if ( EvalConstants.PERM_ASSIGN_EVALUATION.equals(permission) ) { // nothing } else if ( EvalConstants.PERM_BE_EVALUATED.equals(permission) ) { // nothing } else if ( EvalConstants.PERM_TAKE_EVALUATION.equals(permission) ) { l.add( makeEvalGroupObject(EvalTestDataLoad.SITE1_REF) ); l.add( makeEvalGroupObject(EvalTestDataLoad.SITE2_REF) ); } else if ( EvalConstants.PERM_WRITE_TEMPLATE.equals(permission) ) { // nothing } else { // nothing } } else if ( EvalTestDataLoad.STUDENT_USER_ID.equals(userId) ) { if ( EvalConstants.PERM_ASSIGN_EVALUATION.equals(permission) ) { // nothing } else if ( EvalConstants.PERM_BE_EVALUATED.equals(permission) ) { // nothing } else if ( EvalConstants.PERM_TAKE_EVALUATION.equals(permission) ) { l.add( makeEvalGroupObject(EvalTestDataLoad.SITE2_REF) ); } else if ( EvalConstants.PERM_WRITE_TEMPLATE.equals(permission) ) { // nothing } else { // nothing } } else { // do nothing } return l; } /** * Note: Admin has all perms in all sites * 2 sites:<br/> * 1) CONTEXT1/SITE_ID - * USER_ID can take eval, MAINT_USER_ID can admin evals and be evaluated (cannot take)<br/> * 2) CONTEXT2/SITE2_ID - * USER_ID and STUDENT_USER_ID can take eval, MAINT_USER_ID can be evaluated but can not admin (cannot take)<br/> */ public Set<String> getUserIdsForEvalGroup(String context, String permission) { Set<String> s = new HashSet<String>(); // Maybe should add the admin user here? -AZ if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { if ( EvalConstants.PERM_ASSIGN_EVALUATION.equals(permission) ) { s.add(EvalTestDataLoad.MAINT_USER_ID); } else if ( EvalConstants.PERM_BE_EVALUATED.equals(permission) ) { s.add(EvalTestDataLoad.MAINT_USER_ID); } else if ( EvalConstants.PERM_TAKE_EVALUATION.equals(permission) ) { s.add(EvalTestDataLoad.USER_ID); } else if ( EvalConstants.PERM_WRITE_TEMPLATE.equals(permission) ) { s.add(EvalTestDataLoad.MAINT_USER_ID); } else { // nothing } } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { if ( EvalConstants.PERM_ASSIGN_EVALUATION.equals(permission) ) { // nothing } else if ( EvalConstants.PERM_BE_EVALUATED.equals(permission) ) { s.add(EvalTestDataLoad.MAINT_USER_ID); } else if ( EvalConstants.PERM_TAKE_EVALUATION.equals(permission) ) { s.add(EvalTestDataLoad.USER_ID); s.add(EvalTestDataLoad.STUDENT_USER_ID); } else if ( EvalConstants.PERM_WRITE_TEMPLATE.equals(permission) ) { // nothing } else { // nothing } } else { // do nothing } return s; } /* (non-Javadoc) * @see org.sakaiproject.evaluation.logic.externals.ExternalContexts#countUserIdsForContext(java.lang.String, java.lang.String) */ public int countUserIdsForEvalGroup(String context, String permission) { // just use the other stub method return getUserIdsForEvalGroup(context, permission).size(); } /** * Note: Admin has all perms in all sites * 2 sites:<br/> * 1) CONTEXT1/SITE_ID - * USER_ID can take eval, MAINT_USER_ID can admin evals and be evaluated (cannot take)<br/> * 2) CONTEXT2/SITE2_ID - * USER_ID and STUDENT_USER_ID can take eval, MAINT_USER_ID can be evaluated but can not admin (cannot take)<br/> */ public boolean isUserAllowedInEvalGroup(String userId, String permission, String context) { if ( EvalTestDataLoad.ADMIN_USER_ID.equals(userId) ) { return true; } else if ( EvalTestDataLoad.MAINT_USER_ID.equals(userId) ) { if ( EvalConstants.PERM_ASSIGN_EVALUATION.equals(permission) ) { if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { return true; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { return false; } } else if ( EvalConstants.PERM_BE_EVALUATED.equals(permission) ) { if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { return true; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { return true; } } else if ( EvalConstants.PERM_TAKE_EVALUATION.equals(permission) ) { if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { return false; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { return false; } } else if ( EvalConstants.PERM_WRITE_TEMPLATE.equals(permission) ) { if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { return true; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { return false; } } } else if ( EvalTestDataLoad.USER_ID.equals(userId) ) { if ( EvalConstants.PERM_ASSIGN_EVALUATION.equals(permission) ) { if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { return false; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { return false; } } else if ( EvalConstants.PERM_BE_EVALUATED.equals(permission) ) { if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { return false; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { return false; } } else if ( EvalConstants.PERM_TAKE_EVALUATION.equals(permission) ) { if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { return true; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { return true; } } else if ( EvalConstants.PERM_WRITE_TEMPLATE.equals(permission) ) { if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { return false; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { return false; } } } else if ( EvalTestDataLoad.STUDENT_USER_ID.equals(userId) ) { if ( EvalConstants.PERM_ASSIGN_EVALUATION.equals(permission) ) { if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { return false; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { return false; } } else if ( EvalConstants.PERM_BE_EVALUATED.equals(permission) ) { if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { return false; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { return false; } } else if ( EvalConstants.PERM_TAKE_EVALUATION.equals(permission) ) { if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { return false; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { return true; } } else if ( EvalConstants.PERM_WRITE_TEMPLATE.equals(permission) ) { if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { return false; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { return false; } } } else { // do nothing } return false; } /** * Always assume the current evalGroupId is CONTEXT1 */ public String getCurrentEvalGroup() { return currentGroupId; } /** * Always assume the current user is USER_ID */ public String getCurrentUserId() { return currentUserId; } public String getAdminUserId() { return EvalTestDataLoad.ADMIN_USER_ID; } public List<EvalUser> getSakaiAdmins() { List<EvalUser> sakaiAdminList = new ArrayList<EvalUser>(); sakaiAdminList.add(this.getEvalUserById(EvalTestDataLoad.ADMIN_USER_ID)); return sakaiAdminList; } /* (non-Javadoc) * @see org.sakaiproject.evaluation.logic.externals.ExternalUsers#isUserAnonymous(java.lang.String) */ public boolean isUserAnonymous(String userId) { if (userId.equals(EvalTestDataLoad.USER_ID) || userId.equals(EvalTestDataLoad.MAINT_USER_ID) || userId.equals(EvalTestDataLoad.ADMIN_USER_ID) || userId.equals(EvalTestDataLoad.STUDENT_USER_ID)) { return false; } return true; } public EvalUser getEvalUserById(String userId) { EvalUser user = new EvalUser(userId, EvalConstants.USER_TYPE_INVALID, null); if ( EvalTestDataLoad.ADMIN_USER_ID.equals(userId) ) { user = new EvalUser(userId, EvalConstants.USER_TYPE_INTERNAL, userId + "@institution.edu", EvalTestDataLoad.ADMIN_USER_NAME, EvalTestDataLoad.ADMIN_USER_DISPLAY); } else if ( EvalTestDataLoad.MAINT_USER_ID.equals(userId) ) { user = new EvalUser(userId, EvalConstants.USER_TYPE_EXTERNAL, userId + "@institution.edu", EvalTestDataLoad.MAINT_USER_NAME, EvalTestDataLoad.MAINT_USER_DISPLAY); } else if ( EvalTestDataLoad.USER_ID.equals(userId) ) { user = new EvalUser(userId, EvalConstants.USER_TYPE_EXTERNAL, userId + "@institution.edu", EvalTestDataLoad.USER_NAME, EvalTestDataLoad.USER_DISPLAY); } else if ( EvalTestDataLoad.STUDENT_USER_ID.equals(userId) ) { user = new EvalUser(userId, EvalConstants.USER_TYPE_EXTERNAL, userId + "@institution.edu", EvalTestDataLoad.STUDENT_USER_ID, EvalTestDataLoad.STUDENT_USER_ID + "name"); } return user; } public EvalUser getEvalUserByEmail(String email) { String userId = email; // userId + "@institution.edu" int position = userId.indexOf('@'); if (position != -1) { userId = userId.substring(0, position); } EvalUser user = getEvalUserById(userId); return user; } /** * Return usernames from the data load class */ public String getUserUsername(String userId) { if ( EvalTestDataLoad.ADMIN_USER_ID.equals(userId) ) { return EvalTestDataLoad.ADMIN_USER_NAME; } else if ( EvalTestDataLoad.MAINT_USER_ID.equals(userId) ) { return EvalTestDataLoad.MAINT_USER_NAME; } else if ( EvalTestDataLoad.USER_ID.equals(userId) ) { return EvalTestDataLoad.USER_NAME; } return " } public String getUserId(String username) { if ( EvalTestDataLoad.ADMIN_USER_NAME.equals(username) ) { return EvalTestDataLoad.ADMIN_USER_ID; } else if ( EvalTestDataLoad.MAINT_USER_NAME.equals(username) ) { return EvalTestDataLoad.MAINT_USER_ID; } else if ( EvalTestDataLoad.USER_NAME.equals(username) ) { return EvalTestDataLoad.USER_ID; } return null; } /** * only true for ADMIN_USER_ID */ public boolean isUserSakaiAdmin(String userId) { if ( EvalTestDataLoad.ADMIN_USER_ID.equals(userId) ) { return true; } return false; } public Locale getUserLocale(String userId) { return Locale.US; } /** * Return titles from the data load class */ public String getDisplayTitle(String evalGroupId) { if ( EvalTestDataLoad.SITE1_REF.equals(evalGroupId) ) { return EvalTestDataLoad.SITE1_TITLE; } else if ( EvalTestDataLoad.SITE2_REF.equals(evalGroupId) ) { return EvalTestDataLoad.SITE2_TITLE; } return " } /** * Return Context objects based on data from the data load class * CONTEXT1 = Site, CONTEXT2 = Group */ public EvalGroup makeEvalGroupObject(String context) { EvalGroup c = new EvalGroup(context, null, EvalConstants.GROUP_TYPE_UNKNOWN); if ( EvalTestDataLoad.SITE1_REF.equals(context) ) { c.title = EvalTestDataLoad.SITE1_TITLE; c.type = EvalConstants.GROUP_TYPE_SITE; } else if ( EvalTestDataLoad.SITE2_REF.equals(context) ) { c.title = EvalTestDataLoad.SITE2_TITLE; c.type = EvalConstants.GROUP_TYPE_GROUP; } return c; } public String[] sendEmailsToUsers(String from, String[] to, String subject, String message, boolean deferExceptions) { if (from == null || to == null || subject == null || message == null) { throw new NullPointerException("All params are required (none can be null)"); } emailsSentCounter += to.length; return to; } public String[] sendEmailsToAddresses(String from, String[] to, String subject, String message, boolean deferExceptions) { if (from == null || to == null || subject == null || message == null) { throw new NullPointerException("All params are required (none can be null)"); } emailsSentCounter += to.length; return to; } public String getServerUrl() { return "http://localhost:8080/portal/"; } public String getEntityURL(Serializable evaluationEntity) { return "http://localhost:8080/access/eval-evaluation/123/"; } public String getEntityURL(String entityPrefix, String entityId) { return getEntityURL(null); } public void registerEntityEvent(String eventName, Serializable evaluationEntity) { // pretending it worked } public void registerEntityEvent(String eventName, Class<? extends Serializable> entityClass, String entityId) { // pretending it worked } @SuppressWarnings("unchecked") public <T> T getConfigurationSetting(String settingName, T defaultValue) { T returnValue = defaultValue; if (defaultValue == null) { returnValue = (T) (settingName + ":NULL"); } return returnValue; } public byte[] getFileContent(String abspath) { return new byte[] {'H','E','L','L','O',' ','E','V','A','L','U','A','T','I','O','N' }; } public String cleanupUserStrings(String userSubmittedString) { return EvalUtils.cleanupHtmlPtags(userSubmittedString); } public String makePlainTextFromHTML(String html) { return html; } // FOR scheduling // the methods below should return some fake jobs which will correctly correspond to the jobs one would expect to find // in the system based on the current test dats (i.e. maybe 8 or so jobs should exist based on the current test data) public String createScheduledJob(Date executionDate, Long evaluationId, String jobType) { // TODO - make these return some fake data for testing - Dick should do this when he writes tests for this code throw new UnsupportedOperationException(); } public void deleteScheduledJob(String jobID) { // TODO - make these return some fake data for testing - Dick should do this when he writes tests for this code throw new UnsupportedOperationException(); } public EvalScheduledJob[] findScheduledJobs(Long evaluationId, String jobType) { // TODO - make these return some fake data for testing - Dick should do this when he writes tests for this code throw new UnsupportedOperationException(); } // testing methods private int emailsSentCounter = 0; /** * TESTING method: * Provides a way to determine the number of emails sent via this mock service since the service started up * or the counter was reset, reset the counter using {@link #resetEmailsSentCounter()} */ public int getNumEmailsSent() { return emailsSentCounter; } /** * TESTING method: * Resets the emails sent test counter to 0 */ public void resetEmailsSentCounter() { emailsSentCounter = 0; } private String currentUserId = EvalTestDataLoad.USER_ID; public void setCurrentUserId(String userId) { currentUserId = userId; } private String currentGroupId = EvalTestDataLoad.SITE1_REF; public void setCurrentGroupId(String evalGroupId) { currentGroupId = evalGroupId; } public <T> T getBean(Class<T> type) { // TODO Auto-generated method stub return null; } public Map<String, EvalUser> getEvalUsersByIds(String[] userIds) { Map<String, EvalUser> users = new HashMap<String, EvalUser>(); for (String userId : userIds) { users.put(userId, getEvalUserById(userId) ); } return users; } public String getContentCollectionId(String siteId) { // TODO Auto-generated method stub return null; } public Set<String[]> getUsersByRole(String evalGroupId, String perm) { // TODO Auto-generated method stub return null; } public List<EvalGroup> getFilteredEvalGroupsForUser(String arg0, String arg1, String arg2) { // TODO Auto-generated method stub return null; } public boolean isEvalGroupPublished(String evalGroupId) { // TODO Auto-generated method stub return true; } @SuppressWarnings("rawtypes") public String scheduleCronJob(Class jobClass, Map<String, String> dataMap) { // TODO Auto-generated method stub return null; } public Map<String,Map<String, String>> getCronJobs(String jobGroup) { return null; } public String getServerId() { // TODO Auto-generated method stub return null; } public List<String> getServers() { // TODO Auto-generated method stub return null; } public boolean deleteCronJob(String jobName, String groupName) { return false; } public String scheduleCronJob(String jobClassBeanId, Map<String, String> dataMap) { // TODO Auto-generated method stub return null; } public String getMyWorkspaceDashboard(String userId) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.sakaiproject.evaluation.logic.externals.EvalExternalLogic#getDatabaseVendor() */ public String getDatabaseVendor() { // TODO Auto-generated method stub return null; } }
package uk.ac.ebi.quickgo.index.write.job; import uk.ac.ebi.quickgo.index.reader.DocumentReaderException; import uk.ac.ebi.quickgo.index.reader.ODocReader; import uk.ac.ebi.quickgo.index.write.IndexerProperties; import uk.ac.ebi.quickgo.index.write.listener.LogJobListener; import uk.ac.ebi.quickgo.index.write.listener.LogStepListener; import uk.ac.ebi.quickgo.index.write.writer.SolrCrudRepoWriter; import uk.ac.ebi.quickgo.ontology.common.OntologyRepository; import uk.ac.ebi.quickgo.ontology.common.config.RepoConfig; import uk.ac.ebi.quickgo.ontology.common.document.OntologyDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import java.io.File; /** * Created 02/12/15 * @author Edd */ @Configuration @EnableBatchProcessing @Import({RepoConfig.class}) public class IndexingJobConfig { private static final Logger LOGGER = LoggerFactory.getLogger(IndexingJobConfig.class); @Autowired private JobBuilderFactory jobBuilders; @Autowired private StepBuilderFactory stepBuilders; @Autowired private OntologyRepository ontologyRepository; @Value("${indexing.ontology.chunk.size:500}") private int chunkSize; @Value("${indexing.ontology.skip.limit:100}") private int skipLimit; @Value("${indexing.ontology.source}") private String sourceFile; @Bean public Job job() { return jobBuilders.get("indexingJob") .start(step()) .listener(logJobListener()) .build(); } @Bean public Step step() { return stepBuilders .get("readThenWriteToRepoStep") // read and process items in chunks of the following size .<OntologyDocument, OntologyDocument>chunk(chunkSize) .reader(reader()) .faultTolerant() .skip(DocumentReaderException.class) .skipLimit(skipLimit) .writer(writer()) .listener(logStepListener()) .build(); } @Bean public ItemWriter<OntologyDocument> writer() { return new SolrCrudRepoWriter<>(ontologyRepository); } @Bean public LogJobListener logJobListener() { return new LogJobListener(); } @Bean public LogStepListener logStepListener() { return new LogStepListener(); } @Bean public ODocReader reader() { return new ODocReader(new File(sourceFile)); } }
package org.eclipse.rdf4j.sail.shacl; import org.apache.commons.io.IOUtils; import org.eclipse.rdf4j.IsolationLevels; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.vocabulary.RDF4J; import org.eclipse.rdf4j.model.vocabulary.SHACL; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.RepositoryResult; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection; import org.eclipse.rdf4j.sail.NotifyingSail; import org.eclipse.rdf4j.sail.NotifyingSailConnection; import org.eclipse.rdf4j.sail.Sail; import org.eclipse.rdf4j.sail.SailConflictException; import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.helpers.NotifyingSailWrapper; import org.eclipse.rdf4j.sail.memory.MemoryStore; import org.eclipse.rdf4j.sail.shacl.AST.NodeShape; import org.eclipse.rdf4j.sail.shacl.config.ShaclSailConfig; import org.eclipse.rdf4j.sail.shacl.planNodes.LoggingNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.StampedLock; public class ShaclSail extends NotifyingSailWrapper { private static final Logger logger = LoggerFactory.getLogger(ShaclSail.class); private List<NodeShape> nodeShapes = Collections.emptyList(); private static String IMPLICIT_TARGET_CLASS_NODE_SHAPE; private static String IMPLICIT_TARGET_CLASS_PROPERTY_SHAPE; private static String PROPERTY_SHAPE_WITH_TARGET; /** * an initialized {@link Repository} for storing/retrieving Shapes data */ private SailRepository shapesRepo; // exclusive lock for modifying the shapes. private final StampedLock lock = new StampedLock(); transient private Thread threadHoldingWriteLock; private boolean parallelValidation = ShaclSailConfig.PARALLEL_VALIDATION_DEFAULT; private boolean undefinedTargetValidatesAllSubjects = ShaclSailConfig.UNDEFINED_TARGET_VALIDATES_ALL_SUBJECTS_DEFAULT; private boolean logValidationPlans = ShaclSailConfig.LOG_VALIDATION_PLANS_DEFAULT; private boolean logValidationViolations = ShaclSailConfig.LOG_VALIDATION_VIOLATIONS_DEFAULT; private boolean ignoreNoShapesLoadedException = ShaclSailConfig.IGNORE_NO_SHAPES_LOADED_EXCEPTION_DEFAULT; private boolean validationEnabled = ShaclSailConfig.VALIDATION_ENABLED_DEFAULT; private boolean cacheSelectNodes = ShaclSailConfig.CACHE_SELECT_NODES_DEFAULT; private boolean rdfsSubClassReasoning = ShaclSailConfig.RDFS_SUB_CLASS_REASONING_DEFAULT; private boolean performanceLogging = false; static { try { IMPLICIT_TARGET_CLASS_NODE_SHAPE = resourceAsString( "shacl-sparql-inference/implicitTargetClassNodeShape.rq"); IMPLICIT_TARGET_CLASS_PROPERTY_SHAPE = resourceAsString( "shacl-sparql-inference/implicitTargetClassPropertyShape.rq"); PROPERTY_SHAPE_WITH_TARGET = resourceAsString( "shacl-sparql-inference/propertyShapeWithTarget.rq"); } catch (IOException e) { throw new IllegalStateException(e); } } private static String resourceAsString(String s) throws IOException { return IOUtils.toString(ShaclSail.class.getClassLoader().getResourceAsStream(s), StandardCharsets.UTF_8); } public ShaclSail(NotifyingSail baseSail) { super(baseSail); } public ShaclSail() { super(); } /** * Lists the predicates that have been implemented in the ShaclSail. All of these, and all combinations, * <i>should</i> work, please report any bugs. For sh:path, only single predicate paths are supported. * * @return List of IRIs (SHACL predicates) */ public static List<IRI> getSupportedShaclPredicates() { return Arrays.asList( SHACL.TARGET_CLASS, SHACL.PATH, SHACL.PROPERTY, SHACL.OR, SHACL.AND, SHACL.MIN_COUNT, SHACL.MAX_COUNT, SHACL.MIN_LENGTH, SHACL.MAX_LENGTH, SHACL.PATTERN, SHACL.FLAGS, SHACL.NODE_KIND_PROP, SHACL.LANGUAGE_IN, SHACL.DATATYPE, SHACL.MIN_EXCLUSIVE, SHACL.MIN_INCLUSIVE, SHACL.MAX_EXCLUSIVE, SHACL.MAX_INCLUSIVE, SHACL.CLASS, SHACL.TARGET_NODE, SHACL.DEACTIVATED, SHACL.TARGET_SUBJECTS_OF, SHACL.IN, SHACL.UNIQUE_LANG, SHACL.TARGET_OBJECTS_OF); } private final AtomicBoolean initialized = new AtomicBoolean(false); @Override public void initialize() throws SailException { if (!initialized.compareAndSet(false, true)) { // already initialized return; } super.initialize(); if (getDataDir() != null) { if (parallelValidation) { logger.info("Automatically disabled parallel SHACL validation because persistent base sail " + "was detected! Re-enable by calling setParallelValidation(true) after calling init() / initialize()."); } setParallelValidation(false); } if (shapesRepo != null) { shapesRepo.shutDown(); shapesRepo = null; } if (super.getBaseSail().getDataDir() != null) { String path = super.getBaseSail().getDataDir().getPath(); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } path = path + "-shapes-graph/"; shapesRepo = new SailRepository(new MemoryStore(new File(path))); } else { shapesRepo = new SailRepository(new MemoryStore()); } shapesRepo.init(); try (SailRepositoryConnection shapesRepoConnection = shapesRepo.getConnection()) { shapesRepoConnection.begin(IsolationLevels.NONE); nodeShapes = refreshShapes(shapesRepoConnection); shapesRepoConnection.commit(); } } List<NodeShape> refreshShapes(SailRepositoryConnection shapesRepoConnection) throws SailException { SailRepository shapesRepoCache = new SailRepository(new MemoryStore()); shapesRepoCache.init(); List<NodeShape> shapes; try (SailRepositoryConnection shapesRepoCacheConnection = shapesRepoCache.getConnection()) { shapesRepoCacheConnection.begin(IsolationLevels.NONE); try (RepositoryResult<Statement> statements = shapesRepoConnection.getStatements(null, null, null, false)) { shapesRepoCacheConnection.add(statements); } runInferencingSparqlQueries(shapesRepoCacheConnection); shapesRepoCacheConnection.commit(); shapes = NodeShape.Factory.getShapes(shapesRepoCacheConnection, this); } shapesRepoCache.shutDown(); return shapes; } @Override public void shutDown() throws SailException { if (shapesRepo != null) { shapesRepo.shutDown(); shapesRepo = null; } initialized.set(false); nodeShapes = Collections.emptyList(); super.shutDown(); } @Override public NotifyingSailConnection getConnection() throws SailException { return new ShaclSailConnection(this, super.getConnection(), super.getConnection(), shapesRepo.getConnection()); } List<NodeShape> getNodeShapes() { return nodeShapes; } private void runInferencingSparqlQueries(SailRepositoryConnection shaclSailConnection) { long prevSize; long currentSize = shaclSailConnection.size(); do { prevSize = currentSize; shaclSailConnection.prepareUpdate(IMPLICIT_TARGET_CLASS_PROPERTY_SHAPE).execute(); shaclSailConnection.prepareUpdate(IMPLICIT_TARGET_CLASS_NODE_SHAPE).execute(); shaclSailConnection.prepareUpdate(PROPERTY_SHAPE_WITH_TARGET).execute(); currentSize = shaclSailConnection.size(); } while (prevSize != currentSize); } /** * Tries to obtain an exclusive write lock on this store. This method will block until either the lock is obtained * or an interrupt signal is received. * * @throws SailException if the thread is interrupted while waiting to obtain the lock. */ long acquireExclusiveWriteLock(long stamp) { if (lock.validate(stamp)) { return stamp; } if (threadHoldingWriteLock == Thread.currentThread()) { throw new SailConflictException( "Deadlock detected when a single thread uses multiple connections " + "interleaved and one connection has modified the shapes without calling commit() " + "while another connection also tries to modify the shapes!"); } long newStamp = lock.writeLock(); threadHoldingWriteLock = Thread.currentThread(); return newStamp; } boolean holdsWriteLock(long stamp) { return lock.validate(stamp); } /** * Releases the exclusive write lock. */ void releaseExclusiveWriteLock(long stamp) { threadHoldingWriteLock = null; lock.unlockWrite(stamp); } long readlock() { if (threadHoldingWriteLock == Thread.currentThread()) { throw new SailConflictException( "Deadlock detected when a single thread uses multiple connections " + "interleaved and one connection has modified the shapes without calling commit() " + "while another connection calls commit()!"); } return lock.readLock(); } void releaseReadlock(long stamp) { lock.unlockRead(stamp); } /** * Log (INFO) every execution step of the SHACL validation. This is fairly costly and should not be used in * production. Recommended to disable parallel validation with setParallelValidation(false) * * @param loggingEnabled */ public void setGlobalLogValidationExecution(boolean loggingEnabled) { LoggingNode.loggingEnabled = loggingEnabled; } /** * Check if logging of every execution steps is enabled. * * @return <code>true</code> if enabled, <code>false</code> otherwise. * @see #setGlobalLogValidationExecution(boolean) */ public boolean isGlobalLogValidationExecution() { return LoggingNode.loggingEnabled; } /** * Check if logging a list of violations and the triples that caused the violations is enabled. It is recommended to * disable parallel validation with {@link #setParallelValidation(boolean)} * * @see #setLogValidationViolations(boolean) */ public boolean isLogValidationViolations() { return this.logValidationViolations; } /** * Log (INFO) a list of violations and the triples that caused the violations (BETA). Recommended to disable * parallel validation with setParallelValidation(false) * * @param logValidationViolations */ public void setLogValidationViolations(boolean logValidationViolations) { this.logValidationViolations = logValidationViolations; } /** * If no target is defined for a NodeShape, that NodeShape will be ignored. Calling this method with "true" will * make such NodeShapes wildcard shapes and validate all subjects. Equivalent to setting sh:targetClass to owl:Thing * or rdfs:Resource in an environment with a reasoner. * * @param undefinedTargetValidatesAllSubjects default false */ public void setUndefinedTargetValidatesAllSubjects(boolean undefinedTargetValidatesAllSubjects) { this.undefinedTargetValidatesAllSubjects = undefinedTargetValidatesAllSubjects; } /** * Check if {@link NodeShape}s without a defined target are considered wildcards. * * @return <code>true</code> if enabled, <code>false</code> otherwise * @see #setUndefinedTargetValidatesAllSubjects(boolean) */ public boolean isUndefinedTargetValidatesAllSubjects() { return this.undefinedTargetValidatesAllSubjects; } /** * Check if SHACL validation is run in parellel. * * @return <code>true</code> if enabled, <code>false</code> otherwise. */ public boolean isParallelValidation() { return this.parallelValidation; } /** * EXPERIMENTAL! Run SHACL validation in parallel. Default: false * <p> * May cause deadlock, especially when using NativeStore. * * @param parallelValidation default false */ public void setParallelValidation(boolean parallelValidation) { if (parallelValidation) { logger.warn("Parallel SHACL validation enabled. This is an experimental feature and may cause deadlocks!"); } this.parallelValidation = parallelValidation; } /** * Check if selected nodes caches is enabled. * * @return <code>true</code> if enabled, <code>false</code> otherwise. * @see #setCacheSelectNodes(boolean) */ public boolean isCacheSelectNodes() { return this.cacheSelectNodes; } /** * The ShaclSail retries a lot of its relevant data through running SPARQL Select queries against the underlying * sail and against the changes in the transaction. This is usually good for performance, but while validating large * amounts of data disabling this cache will use less memory. Default: true * * @param cacheSelectNodes default true */ public void setCacheSelectNodes(boolean cacheSelectNodes) { this.cacheSelectNodes = cacheSelectNodes; } public boolean isRdfsSubClassReasoning() { return rdfsSubClassReasoning; } public void setRdfsSubClassReasoning(boolean rdfsSubClassReasoning) { this.rdfsSubClassReasoning = rdfsSubClassReasoning; } /** * Disable the SHACL validation on commit() */ public void disableValidation() { this.validationEnabled = false; } /** * Enabled the SHACL validation on commit() */ public void enableValidation() { this.validationEnabled = true; } /** * Check if SHACL validation on commit() is enabled. * * @return <code>true</code> if validation is enabled, <code>false</code> otherwise. */ public boolean isValidationEnabled() { return validationEnabled; } /** * Check if logging of validation plans is enabled. * * @return <code>true</code> if validation plan logging is enabled, <code>false</code> otherwise. */ public boolean isLogValidationPlans() { return this.logValidationPlans; } public boolean isIgnoreNoShapesLoadedException() { return this.ignoreNoShapesLoadedException; } /** * Check if shapes have been loaded into the shapes graph before other data is added * * @param ignoreNoShapesLoadedException */ public void setIgnoreNoShapesLoadedException(boolean ignoreNoShapesLoadedException) { this.ignoreNoShapesLoadedException = ignoreNoShapesLoadedException; } /** * Log (INFO) the executed validation plans as GraphViz DOT Recommended to disable parallel validation with * setParallelValidation(false) * * @param logValidationPlans */ public void setLogValidationPlans(boolean logValidationPlans) { this.logValidationPlans = logValidationPlans; } public boolean isPerformanceLogging() { return performanceLogging; } // @formatter:off /** * Log (INFO) the execution time per shape. Recommended to disable the following: * <ul> * <li>setParallelValidation(false)</li> * <li>setCacheSelectNodes(false)</li> * </ul> * * @param performanceLogging default false */ // @formatter:on public void setPerformanceLogging(boolean performanceLogging) { this.performanceLogging = performanceLogging; } public void setNodeShapes(List<NodeShape> nodeShapes) { this.nodeShapes = nodeShapes; } }
package org.eclipse.rdf4j.sail.shacl; import org.apache.commons.io.IOUtils; import org.eclipse.rdf4j.IsolationLevels; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.vocabulary.RDF4J; import org.eclipse.rdf4j.model.vocabulary.SHACL; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection; import org.eclipse.rdf4j.sail.NotifyingSail; import org.eclipse.rdf4j.sail.NotifyingSailConnection; import org.eclipse.rdf4j.sail.Sail; import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.helpers.NotifyingSailWrapper; import org.eclipse.rdf4j.sail.memory.MemoryStore; import org.eclipse.rdf4j.sail.shacl.AST.NodeShape; import org.eclipse.rdf4j.sail.shacl.config.ShaclSailConfig; import org.eclipse.rdf4j.sail.shacl.planNodes.LoggingNode; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ShaclSail extends NotifyingSailWrapper { private List<NodeShape> nodeShapes = Collections.emptyList(); private static String SH_OR_UPDATE_QUERY; private static String SH_OR_NODE_SHAPE_UPDATE_QUERY; private static String IMPLICIT_TARGET_CLASS_NODE_SHAPE; private static String IMPLICIT_TARGET_CLASS_PROPERTY_SHAPE; /** * an initialized {@link Repository} for storing/retrieving Shapes data */ private SailRepository shapesRepo; private boolean parallelValidation = ShaclSailConfig.PARALLEL_VALIDATION_DEFAULT; private boolean undefinedTargetValidatesAllSubjects = ShaclSailConfig.UNDEFINED_TARGET_VALIDATES_ALL_SUBJECTS_DEFAULT; private boolean logValidationPlans = ShaclSailConfig.LOG_VALIDATION_PLANS_DEFAULT; private boolean logValidationViolations = ShaclSailConfig.LOG_VALIDATION_VIOLATIONS_DEFAULT; private boolean ignoreNoShapesLoadedException = ShaclSailConfig.IGNORE_NO_SHAPES_LOADED_EXCEPTION_DEFAULT; private boolean validationEnabled = ShaclSailConfig.VALIDATION_ENABLED_DEFAULT; private boolean cacheSelectNodes = ShaclSailConfig.CACHE_SELECT_NODES_DEFAULT; static { try { SH_OR_UPDATE_QUERY = IOUtils.toString( ShaclSail.class.getClassLoader().getResourceAsStream("shacl-sparql-inference/sh_or.rq"), "UTF-8"); SH_OR_NODE_SHAPE_UPDATE_QUERY = IOUtils.toString( ShaclSail.class.getClassLoader().getResourceAsStream( "shacl-sparql-inference/sh_or_node_shape.rq"), "UTF-8"); IMPLICIT_TARGET_CLASS_NODE_SHAPE = IOUtils.toString( ShaclSail.class.getClassLoader().getResourceAsStream( "shacl-sparql-inference/implicitTargetClassNodeShape.rq"), "UTF-8"); IMPLICIT_TARGET_CLASS_PROPERTY_SHAPE = IOUtils.toString( ShaclSail.class.getClassLoader().getResourceAsStream( "shacl-sparql-inference/implicitTargetClassPropertyShape.rq"), "UTF-8"); } catch (IOException e) { throw new IllegalStateException(e); } } public ShaclSail(NotifyingSail baseSail) { super(baseSail); } public ShaclSail() { super(); } /** * Lists the predicates that have been implemented in the ShaclSail. All of these, and all combinations, * <i>should</i> work, please report any bugs. For sh:path, only single predicate paths are supported. * * @return List of IRIs (SHACL predicates) */ public static List<IRI> getSupportedShaclPredicates() { return Arrays.asList( SHACL.TARGET_CLASS, SHACL.PATH, SHACL.PROPERTY, SHACL.OR, SHACL.MIN_COUNT, SHACL.MAX_COUNT, SHACL.MIN_LENGTH, SHACL.MAX_LENGTH, SHACL.PATTERN, SHACL.FLAGS, SHACL.NODE_KIND_PROP, SHACL.LANGUAGE_IN, SHACL.DATATYPE, SHACL.MIN_EXCLUSIVE, SHACL.MIN_INCLUSIVE, SHACL.MAX_EXCLUSIVE, SHACL.MAX_INCLUSIVE, SHACL.CLASS ); } @Override public void initialize() throws SailException { super.initialize(); if (shapesRepo != null) { shapesRepo.shutDown(); shapesRepo = null; } if (super.getBaseSail().getDataDir() != null) { String path = super.getBaseSail().getDataDir().getPath(); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } path = path + "-shapes-graph/"; shapesRepo = new SailRepository(new MemoryStore(new File(path))); } else { shapesRepo = new SailRepository(new MemoryStore()); } shapesRepo.initialize(); try (SailRepositoryConnection shapesRepoConnection = shapesRepo.getConnection()) { shapesRepoConnection.begin(IsolationLevels.NONE); refreshShapes(shapesRepoConnection); shapesRepoConnection.commit(); } } synchronized List<NodeShape> refreshShapes(SailRepositoryConnection shapesRepoConnection) throws SailException { try (SailRepositoryConnection beforeCommitConnection = shapesRepo.getConnection()) { long size = beforeCommitConnection.size(); if (size > 0) { // Our inferencer both adds and removes statements. // To support updates I recommend having two graphs, one raw one with the unmodified data. // Then copy all that data into a new graph, run inferencing on that graph and use it to generate the java objects throw new IllegalStateException( "ShaclSail does not support modifying shapes that are already loaded or loading more shapes"); } } runInferencingSparqlQueries(shapesRepoConnection); nodeShapes = NodeShape.Factory.getShapes(shapesRepoConnection, this); return nodeShapes; } @Override public void shutDown() throws SailException { if (shapesRepo != null) { shapesRepo.shutDown(); shapesRepo = null; } super.shutDown(); } @Override public NotifyingSailConnection getConnection() throws SailException { return new ShaclSailConnection(this, super.getConnection(), super.getConnection(), shapesRepo.getConnection()); } /** * Disable the SHACL validation on commit() */ public void disableValidation() { this.validationEnabled = false; } /** * Enabled the SHACL validation on commit() */ public void enableValidation() { this.validationEnabled = true; } /** * Check if SHACL validation on commit() is enabled. * * @return <code>true</code> if validation is enabled, <code>false</code> otherwise. */ public boolean isValidationEnabled() { return validationEnabled; } /** * Check if logging of validation plans is enabled. * * @return <code>true</code> if validation plan logging is enabled, <code>false</code> otherwise. */ public boolean isLogValidationPlans() { return this.logValidationPlans; } public boolean isIgnoreNoShapesLoadedException() { return this.ignoreNoShapesLoadedException; } /** * Check if shapes have been loaded into the shapes graph before other data is added * * @param ignoreNoShapesLoadedException */ public void setIgnoreNoShapesLoadedException(boolean ignoreNoShapesLoadedException) { this.ignoreNoShapesLoadedException = ignoreNoShapesLoadedException; } /** * Log (INFO) the executed validation plans as GraphViz DOT Recommended to disable parallel validation * with setParallelValidation(false) * * @param logValidationPlans */ public void setLogValidationPlans(boolean logValidationPlans) { this.logValidationPlans = logValidationPlans; } List<NodeShape> getNodeShapes() { return nodeShapes; } private void runInferencingSparqlQueries(SailRepositoryConnection shaclSailConnection) { long prevSize; long currentSize = shaclSailConnection.size(); do { prevSize = currentSize; shaclSailConnection.prepareUpdate(SH_OR_NODE_SHAPE_UPDATE_QUERY).execute(); shaclSailConnection.prepareUpdate(SH_OR_UPDATE_QUERY).execute(); shaclSailConnection.prepareUpdate(IMPLICIT_TARGET_CLASS_PROPERTY_SHAPE).execute(); shaclSailConnection.prepareUpdate(IMPLICIT_TARGET_CLASS_NODE_SHAPE).execute(); currentSize = shaclSailConnection.size(); } while (prevSize != currentSize); } /** * Log (INFO) every execution step of the SHACL validation. This is fairly costly and should not be used * in production. Recommended to disable parallel validation with setParallelValidation(false) * * @param loggingEnabled */ public void setGlobalLogValidationExecution(boolean loggingEnabled) { LoggingNode.loggingEnabled = loggingEnabled; } /** * Check if logging of every execution steps is enabled. * * @return <code>true</code> if enabled, <code>false</code> otherwise. * @see #setGlobalLogValidationExecution(boolean) */ public boolean isGlobalLogValidationExecution() { return LoggingNode.loggingEnabled; } /** * Check if logging a list of violations and the triples that caused the violations is enabled. It is * recommended to disable parallel validation with {@link #setParallelValidation(boolean)} * * @see #setLogValidationViolations(boolean) */ public boolean isLogValidationViolations() { return this.logValidationViolations; } /** * Log (INFO) a list of violations and the triples that caused the violations (BETA). Recommended to * disable parallel validation with setParallelValidation(false) * * @param logValidationViolations */ public void setLogValidationViolations(boolean logValidationViolations) { this.logValidationViolations = logValidationViolations; } /** * If no target is defined for a NodeShape, that NodeShape will be ignored. Calling this method with * "true" will make such NodeShapes wildcard shapes and validate all subjects. Equivalent to setting * sh:targetClass to owl:Thing or rdfs:Resource in an environment with a reasoner. * * @param undefinedTargetValidatesAllSubjects * default false */ public void setUndefinedTargetValidatesAllSubjects(boolean undefinedTargetValidatesAllSubjects) { this.undefinedTargetValidatesAllSubjects = undefinedTargetValidatesAllSubjects; } /** * Check if {@link NodeShape}s without a defined target are considered wildcards. * * @return <code>true</code> if enabled, <code>false</code> otherwise * @see #setUndefinedTargetValidatesAllSubjects(boolean) */ public boolean isUndefinedTargetValidatesAllSubjects() { return this.undefinedTargetValidatesAllSubjects; } /** * Check if SHACL validation is run in parellel. * * @return <code>true</code> if enabled, <code>false</code> otherwise. */ public boolean isParallelValidation() { return this.parallelValidation; } /** * Run SHACL validation in parallel. Default: true * * @param parallelValidation * default true */ public void setParallelValidation(boolean parallelValidation) { this.parallelValidation = parallelValidation; } /** * Check if selected nodes caches is enabled. * * @return <code>true</code> if enabled, <code>false</code> otherwise. * @see #setCacheSelectNodes(boolean) */ public boolean isCacheSelectNodes() { return this.cacheSelectNodes; } /** * The ShaclSail retries a lot of its relevant data through running SPARQL Select queries against the * underlying sail and against the changes in the transaction. This is usually good for performance, but * while validating large amounts of data disabling this cache will use less memory. Default: true * * @param cacheSelectNodes * default true */ public void setCacheSelectNodes(boolean cacheSelectNodes) { this.cacheSelectNodes = cacheSelectNodes; } }
package io.flutter.view; import android.graphics.Rect; import android.opengl.Matrix; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeProvider; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.StandardMessageCodec; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; class AccessibilityBridge extends AccessibilityNodeProvider implements BasicMessageChannel.MessageHandler<Object> { private static final String TAG = "FlutterView"; // Constants from higher API levels. // TODO(goderbauer): Get these from Android Support Library when private static final int ACTION_SHOW_ON_SCREEN = 16908342; // API level 23 private static final float SCROLL_EXTENT_FOR_INFINITY = 100000.0f; private static final float SCROLL_POSITION_CAP_FOR_INFINITY = 70000.0f; private static final int ROOT_NODE_ID = 0; private Map<Integer, SemanticsObject> mObjects; private final FlutterView mOwner; private boolean mAccessibilityEnabled = false; private SemanticsObject mA11yFocusedObject; private SemanticsObject mInputFocusedObject; private SemanticsObject mHoveredObject; private int previousRouteId = ROOT_NODE_ID; private List<Integer> previousRoutes; private final BasicMessageChannel<Object> mFlutterAccessibilityChannel; enum Action { TAP(1 << 0), LONG_PRESS(1 << 1), SCROLL_LEFT(1 << 2), SCROLL_RIGHT(1 << 3), SCROLL_UP(1 << 4), SCROLL_DOWN(1 << 5), INCREASE(1 << 6), DECREASE(1 << 7), SHOW_ON_SCREEN(1 << 8), MOVE_CURSOR_FORWARD_BY_CHARACTER(1 << 9), MOVE_CURSOR_BACKWARD_BY_CHARACTER(1 << 10), SET_SELECTION(1 << 11), COPY(1 << 12), CUT(1 << 13), PASTE(1 << 14), DID_GAIN_ACCESSIBILITY_FOCUS(1 << 15), DID_LOSE_ACCESSIBILITY_FOCUS(1 << 16); Action(int value) { this.value = value; } final int value; } enum Flag { HAS_CHECKED_STATE(1 << 0), IS_CHECKED(1 << 1), IS_SELECTED(1 << 2), IS_BUTTON(1 << 3), IS_TEXT_FIELD(1 << 4), IS_FOCUSED(1 << 5), HAS_ENABLED_STATE(1 << 6), IS_ENABLED(1 << 7), IS_IN_MUTUALLY_EXCLUSIVE_GROUP(1 << 8), IS_HEADER(1 << 9), IS_OBSCURED(1 << 10), SCOPES_ROUTE(1 << 11), NAMES_ROUTE(1 << 12), IS_HIDDEN(1 << 13); Flag(int value) { this.value = value; } final int value; } AccessibilityBridge(FlutterView owner) { assert owner != null; mOwner = owner; mObjects = new HashMap<Integer, SemanticsObject>(); previousRoutes = new ArrayList<>(); mFlutterAccessibilityChannel = new BasicMessageChannel<>(owner, "flutter/accessibility", StandardMessageCodec.INSTANCE); } void setAccessibilityEnabled(boolean accessibilityEnabled) { mAccessibilityEnabled = accessibilityEnabled; if (accessibilityEnabled) { mFlutterAccessibilityChannel.setMessageHandler(this); } else { mFlutterAccessibilityChannel.setMessageHandler(null); } } @Override @SuppressWarnings("deprecation") public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { if (virtualViewId == View.NO_ID) { AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mOwner); mOwner.onInitializeAccessibilityNodeInfo(result); if (mObjects.containsKey(ROOT_NODE_ID)) result.addChild(mOwner, ROOT_NODE_ID); return result; } SemanticsObject object = mObjects.get(virtualViewId); if (object == null) return null; AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mOwner, virtualViewId); result.setPackageName(mOwner.getContext().getPackageName()); result.setClassName("android.view.View"); result.setSource(mOwner, virtualViewId); result.setFocusable(object.isFocusable()); if (mInputFocusedObject != null) result.setFocused(mInputFocusedObject.id == virtualViewId); if (mA11yFocusedObject != null) result.setAccessibilityFocused(mA11yFocusedObject.id == virtualViewId); if (object.hasFlag(Flag.IS_TEXT_FIELD)) { result.setPassword(object.hasFlag(Flag.IS_OBSCURED)); result.setClassName("android.widget.EditText"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { result.setEditable(true); if (object.textSelectionBase != -1 && object.textSelectionExtent != -1) { result.setTextSelection(object.textSelectionBase, object.textSelectionExtent); } } // Cursor movements int granularities = 0; if (object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) { result.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER; } if (object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) { result.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER; } result.setMovementGranularities(granularities); } if (object.hasAction(Action.SET_SELECTION)) { result.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); } if (object.hasAction(Action.COPY)) { result.addAction(AccessibilityNodeInfo.ACTION_COPY); } if (object.hasAction(Action.CUT)) { result.addAction(AccessibilityNodeInfo.ACTION_CUT); } if (object.hasAction(Action.PASTE)) { result.addAction(AccessibilityNodeInfo.ACTION_PASTE); } if (object.hasFlag(Flag.IS_BUTTON)) { result.setClassName("android.widget.Button"); } if (object.parent != null) { assert object.id > ROOT_NODE_ID; result.setParent(mOwner, object.parent.id); } else { assert object.id == ROOT_NODE_ID; result.setParent(mOwner); } Rect bounds = object.getGlobalRect(); if (object.parent != null) { Rect parentBounds = object.parent.getGlobalRect(); Rect boundsInParent = new Rect(bounds); boundsInParent.offset(-parentBounds.left, -parentBounds.top); result.setBoundsInParent(boundsInParent); } else { result.setBoundsInParent(bounds); } result.setBoundsInScreen(bounds); result.setVisibleToUser(true); result.setEnabled(!object.hasFlag(Flag.HAS_ENABLED_STATE) || object.hasFlag(Flag.IS_ENABLED)); if (object.hasAction(Action.TAP)) { result.addAction(AccessibilityNodeInfo.ACTION_CLICK); result.setClickable(true); } if (object.hasAction(Action.LONG_PRESS)) { result.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); result.setLongClickable(true); } if (object.hasAction(Action.SCROLL_LEFT) || object.hasAction(Action.SCROLL_UP) || object.hasAction(Action.SCROLL_RIGHT) || object.hasAction(Action.SCROLL_DOWN)) { result.setScrollable(true); // This tells Android's a11y to send scroll events when reaching the end of // the visible viewport of a scrollable. result.setClassName("android.widget.ScrollView"); // TODO(ianh): Once we're on SDK v23+, call addAction to // expose AccessibilityAction.ACTION_SCROLL_LEFT, _RIGHT, // _UP, and _DOWN when appropriate. if (object.hasAction(Action.SCROLL_LEFT) || object.hasAction(Action.SCROLL_UP)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (object.hasAction(Action.SCROLL_RIGHT) || object.hasAction(Action.SCROLL_DOWN)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } if (object.hasAction(Action.INCREASE) || object.hasAction(Action.DECREASE)) { result.setClassName("android.widget.SeekBar"); if (object.hasAction(Action.INCREASE)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (object.hasAction(Action.DECREASE)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } boolean hasCheckedState = object.hasFlag(Flag.HAS_CHECKED_STATE); result.setCheckable(hasCheckedState); if (hasCheckedState) { result.setChecked(object.hasFlag(Flag.IS_CHECKED)); if (object.hasFlag(Flag.IS_IN_MUTUALLY_EXCLUSIVE_GROUP)) result.setClassName("android.widget.RadioButton"); else result.setClassName("android.widget.CheckBox"); } result.setSelected(object.hasFlag(Flag.IS_SELECTED)); result.setText(object.getValueLabelHint()); // Accessibility Focus if (mA11yFocusedObject != null && mA11yFocusedObject.id == virtualViewId) { result.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); } else { result.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); } if (object.children != null) { for (SemanticsObject child : object.children) { if (!child.hasFlag(Flag.IS_HIDDEN)) { result.addChild(mOwner, child.id); } } } return result; } @Override public boolean performAction(int virtualViewId, int action, Bundle arguments) { SemanticsObject object = mObjects.get(virtualViewId); if (object == null) { return false; } switch (action) { case AccessibilityNodeInfo.ACTION_CLICK: { mOwner.dispatchSemanticsAction(virtualViewId, Action.TAP); return true; } case AccessibilityNodeInfo.ACTION_LONG_CLICK: { mOwner.dispatchSemanticsAction(virtualViewId, Action.LONG_PRESS); return true; } case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: { if (object.hasAction(Action.SCROLL_UP)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_UP); } else if (object.hasAction(Action.SCROLL_LEFT)) { // TODO(ianh): bidi support using textDirection mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_LEFT); } else if (object.hasAction(Action.INCREASE)) { object.value = object.increasedValue; // Event causes Android to read out the updated value. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); mOwner.dispatchSemanticsAction(virtualViewId, Action.INCREASE); } else { return false; } return true; } case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: { if (object.hasAction(Action.SCROLL_DOWN)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_DOWN); } else if (object.hasAction(Action.SCROLL_RIGHT)) { // TODO(ianh): bidi support using textDirection mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_RIGHT); } else if (object.hasAction(Action.DECREASE)) { object.value = object.decreasedValue; // Event causes Android to read out the updated value. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); mOwner.dispatchSemanticsAction(virtualViewId, Action.DECREASE); } else { return false; } return true; } case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { return performCursorMoveAction(object, virtualViewId, arguments, false); } case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { return performCursorMoveAction(object, virtualViewId, arguments, true); } case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { mOwner.dispatchSemanticsAction(virtualViewId, Action.DID_LOSE_ACCESSIBILITY_FOCUS); sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mA11yFocusedObject = null; return true; } case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { mOwner.dispatchSemanticsAction(virtualViewId, Action.DID_GAIN_ACCESSIBILITY_FOCUS); sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); if (mA11yFocusedObject == null) { // When Android focuses a node, it doesn't invalidate the view. // (It does when it sends ACTION_CLEAR_ACCESSIBILITY_FOCUS, so // we only have to worry about this when the focused node is null.) mOwner.invalidate(); } mA11yFocusedObject = object; if (object.hasAction(Action.INCREASE) || object.hasAction(Action.DECREASE)) { // SeekBars only announce themselves after this event. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); } return true; } case ACTION_SHOW_ON_SCREEN: { mOwner.dispatchSemanticsAction(virtualViewId, Action.SHOW_ON_SCREEN); return true; } case AccessibilityNodeInfo.ACTION_SET_SELECTION: { final Map<String, Integer> selection = new HashMap<String, Integer>(); final boolean hasSelection = arguments != null && arguments.containsKey( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT) && arguments.containsKey( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT); if (hasSelection) { selection.put("base", arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT)); selection.put("extent", arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT)); } else { // Clear the selection selection.put("base", object.textSelectionExtent); selection.put("extent", object.textSelectionExtent); } mOwner.dispatchSemanticsAction(virtualViewId, Action.SET_SELECTION, selection); return true; } case AccessibilityNodeInfo.ACTION_COPY: { mOwner.dispatchSemanticsAction(virtualViewId, Action.COPY); return true; } case AccessibilityNodeInfo.ACTION_CUT: { mOwner.dispatchSemanticsAction(virtualViewId, Action.CUT); return true; } case AccessibilityNodeInfo.ACTION_PASTE: { mOwner.dispatchSemanticsAction(virtualViewId, Action.PASTE); return true; } } return false; } boolean performCursorMoveAction(SemanticsObject object, int virtualViewId, Bundle arguments, boolean forward) { final int granularity = arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); final boolean extendSelection = arguments.getBoolean( AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); switch (granularity) { case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { if (forward && object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_FORWARD_BY_CHARACTER, extendSelection); return true; } if (!forward && object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER, extendSelection); return true; } } // TODO(goderbauer): support other granularities. } return false; } // TODO(ianh): implement findAccessibilityNodeInfosByText() @Override public AccessibilityNodeInfo findFocus(int focus) { switch (focus) { case AccessibilityNodeInfo.FOCUS_INPUT: { if (mInputFocusedObject != null) return createAccessibilityNodeInfo(mInputFocusedObject.id); } case AccessibilityNodeInfo.FOCUS_ACCESSIBILITY: { if (mA11yFocusedObject != null) return createAccessibilityNodeInfo(mA11yFocusedObject.id); } } return null; } private SemanticsObject getRootObject() { assert mObjects.containsKey(0); return mObjects.get(0); } private SemanticsObject getOrCreateObject(int id) { SemanticsObject object = mObjects.get(id); if (object == null) { object = new SemanticsObject(); object.id = id; mObjects.put(id, object); } return object; } void handleTouchExplorationExit() { if (mHoveredObject != null) { sendAccessibilityEvent(mHoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); mHoveredObject = null; } } void handleTouchExploration(float x, float y) { if (mObjects.isEmpty()) { return; } SemanticsObject newObject = getRootObject().hitTest(new float[]{ x, y, 0, 1 }); if (newObject != mHoveredObject) { // sending ENTER before EXIT is how Android wants it if (newObject != null) { sendAccessibilityEvent(newObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); } if (mHoveredObject != null) { sendAccessibilityEvent(mHoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); } mHoveredObject = newObject; } } void updateSemantics(ByteBuffer buffer, String[] strings) { ArrayList<SemanticsObject> updated = new ArrayList<SemanticsObject>(); while (buffer.hasRemaining()) { int id = buffer.getInt(); SemanticsObject object = getOrCreateObject(id); object.updateWith(buffer, strings); if (object.hasFlag(Flag.IS_HIDDEN)) { continue; } if (object.hasFlag(Flag.IS_FOCUSED)) { mInputFocusedObject = object; } if (object.hadPreviousConfig) { updated.add(object); } } Set<SemanticsObject> visitedObjects = new HashSet<SemanticsObject>(); SemanticsObject rootObject = getRootObject(); List<SemanticsObject> newRoutes = new ArrayList<>(); if (rootObject != null) { final float[] identity = new float[16]; Matrix.setIdentityM(identity, 0); rootObject.updateRecursively(identity, visitedObjects, false); rootObject.collectRoutes(newRoutes); } // Dispatch a TYPE_WINDOW_STATE_CHANGED event if the most recent route id changed from the // previously cached route id. SemanticsObject lastAdded = null; for (SemanticsObject semanticsObject : newRoutes) { if (!previousRoutes.contains(semanticsObject.id)) { lastAdded = semanticsObject; } } if (lastAdded == null && newRoutes.size() > 0) { lastAdded = newRoutes.get(newRoutes.size() - 1); } if (lastAdded != null && lastAdded.id != previousRouteId) { previousRouteId = lastAdded.id; createWindowChangeEvent(lastAdded); } previousRoutes.clear(); for (SemanticsObject semanticsObject : newRoutes) { previousRoutes.add(semanticsObject.id); } Iterator<Map.Entry<Integer, SemanticsObject>> it = mObjects.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, SemanticsObject> entry = it.next(); SemanticsObject object = entry.getValue(); if (!visitedObjects.contains(object)) { willRemoveSemanticsObject(object); it.remove(); } } // TODO(goderbauer): Send this event only once (!) for changed subtrees, sendAccessibilityEvent(0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); for (SemanticsObject object : updated) { if (object.didScroll()) { AccessibilityEvent event = obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SCROLLED); // Android doesn't support unbound scrolling. So we pretend there is a large // bound (SCROLL_EXTENT_FOR_INFINITY), which you can never reach. float position = object.scrollPosition; float max = object.scrollExtentMax; if (Float.isInfinite(object.scrollExtentMax)) { max = SCROLL_EXTENT_FOR_INFINITY; if (position > SCROLL_POSITION_CAP_FOR_INFINITY) { position = SCROLL_POSITION_CAP_FOR_INFINITY; } } if (Float.isInfinite(object.scrollExtentMin)) { max += SCROLL_EXTENT_FOR_INFINITY; if (position < -SCROLL_POSITION_CAP_FOR_INFINITY) { position = -SCROLL_POSITION_CAP_FOR_INFINITY; } position += SCROLL_EXTENT_FOR_INFINITY; } else { max -= object.scrollExtentMin; position -= object.scrollExtentMin; } if (object.hadAction(Action.SCROLL_UP) || object.hadAction(Action.SCROLL_DOWN)) { event.setScrollY((int) position); event.setMaxScrollY((int) max); } else if (object.hadAction(Action.SCROLL_LEFT) || object.hadAction(Action.SCROLL_RIGHT)) { event.setScrollX((int) position); event.setMaxScrollX((int) max); } sendAccessibilityEvent(event); } if (mA11yFocusedObject != null && mA11yFocusedObject.id == object.id && object.hadFlag(Flag.HAS_CHECKED_STATE) && object.hasFlag(Flag.HAS_CHECKED_STATE) && object.hadFlag(Flag.IS_CHECKED) != object.hasFlag(Flag.IS_CHECKED)) { // Simulate a click so TalkBack announces the change in checked state. sendAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_CLICKED); } if (mA11yFocusedObject != null && mA11yFocusedObject.id == object.id && !object.hadFlag(Flag.IS_SELECTED) && object.hasFlag(Flag.IS_SELECTED)) { AccessibilityEvent event = obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SELECTED); event.getText().add(object.label); sendAccessibilityEvent(event); } if (mInputFocusedObject != null && mInputFocusedObject.id == object.id && object.hadFlag(Flag.IS_TEXT_FIELD) && object.hasFlag(Flag.IS_TEXT_FIELD)) { String oldValue = object.previousValue != null ? object.previousValue : ""; String newValue = object.value != null ? object.value : ""; AccessibilityEvent event = createTextChangedEvent(object.id, oldValue, newValue); if (event != null) { sendAccessibilityEvent(event); } if (object.previousTextSelectionBase != object.textSelectionBase || object.previousTextSelectionExtent != object.textSelectionExtent) { AccessibilityEvent selectionEvent = obtainAccessibilityEvent( object.id, AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); selectionEvent.getText().add(newValue); selectionEvent.setFromIndex(object.textSelectionBase); selectionEvent.setToIndex(object.textSelectionExtent); selectionEvent.setItemCount(newValue.length()); sendAccessibilityEvent(selectionEvent); } } } } private AccessibilityEvent createTextChangedEvent(int id, String oldValue, String newValue) { AccessibilityEvent e = obtainAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); e.setBeforeText(oldValue); e.getText().add(newValue); int i; for (i = 0; i < oldValue.length() && i < newValue.length(); ++i) { if (oldValue.charAt(i) != newValue.charAt(i)) { break; } } if (i >= oldValue.length() && i >= newValue.length()) { return null; // Text did not change } int firstDifference = i; e.setFromIndex(firstDifference); int oldIndex = oldValue.length() - 1; int newIndex = newValue.length() - 1; while (oldIndex >= firstDifference && newIndex >= firstDifference) { if (oldValue.charAt(oldIndex) != newValue.charAt(newIndex)) { break; } --oldIndex; --newIndex; } e.setRemovedCount(oldIndex - firstDifference + 1); e.setAddedCount(newIndex - firstDifference + 1); return e; } private AccessibilityEvent obtainAccessibilityEvent(int virtualViewId, int eventType) { assert virtualViewId != ROOT_NODE_ID; AccessibilityEvent event = AccessibilityEvent.obtain(eventType); event.setPackageName(mOwner.getContext().getPackageName()); event.setSource(mOwner, virtualViewId); return event; } private void sendAccessibilityEvent(int virtualViewId, int eventType) { if (!mAccessibilityEnabled) { return; } if (virtualViewId == ROOT_NODE_ID) { mOwner.sendAccessibilityEvent(eventType); } else { sendAccessibilityEvent(obtainAccessibilityEvent(virtualViewId, eventType)); } } private void sendAccessibilityEvent(AccessibilityEvent event) { if (!mAccessibilityEnabled) { return; } mOwner.getParent().requestSendAccessibilityEvent(mOwner, event); } // Message Handler for [mFlutterAccessibilityChannel]. public void onMessage(Object message, BasicMessageChannel.Reply<Object> reply) { @SuppressWarnings("unchecked") final HashMap<String, Object> annotatedEvent = (HashMap<String, Object>)message; final String type = (String)annotatedEvent.get("type"); @SuppressWarnings("unchecked") final HashMap<String, Object> data = (HashMap<String, Object>)annotatedEvent.get("data"); switch (type) { case "announce": mOwner.announceForAccessibility((String) data.get("message")); break; case "tooltip": { AccessibilityEvent e = obtainAccessibilityEvent(ROOT_NODE_ID, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); e.getText().add((String) data.get("message")); mOwner.getParent().requestSendAccessibilityEvent(mOwner, e); } default: assert false; } } private void createWindowChangeEvent(SemanticsObject route) { AccessibilityEvent e = obtainAccessibilityEvent(route.id, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); String routeName = route.getRouteName(); e.getText().add(routeName); mOwner.getParent().requestSendAccessibilityEvent(mOwner, e); } private void willRemoveSemanticsObject(SemanticsObject object) { assert mObjects.containsKey(object.id); assert mObjects.get(object.id) == object; object.parent = null; if (mA11yFocusedObject == object) { sendAccessibilityEvent(mA11yFocusedObject.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mA11yFocusedObject = null; } if (mInputFocusedObject == object) { mInputFocusedObject = null; } if (mHoveredObject == object) { mHoveredObject = null; } } void reset() { mObjects.clear(); if (mA11yFocusedObject != null) sendAccessibilityEvent(mA11yFocusedObject.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mA11yFocusedObject = null; mHoveredObject = null; sendAccessibilityEvent(0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } private enum TextDirection { UNKNOWN, LTR, RTL; public static TextDirection fromInt(int value) { switch (value) { case 1: return RTL; case 2: return LTR; } return UNKNOWN; } } private class SemanticsObject { SemanticsObject() { } int id = -1; int flags; int actions; int textSelectionBase; int textSelectionExtent; float scrollPosition; float scrollExtentMax; float scrollExtentMin; String label; String value; String increasedValue; String decreasedValue; String hint; TextDirection textDirection; int hitTestPosition; boolean hadPreviousConfig = false; int previousFlags; int previousActions; int previousTextSelectionBase; int previousTextSelectionExtent; float previousScrollPosition; float previousScrollExtentMax; float previousScrollExtentMin; String previousValue; private float left; private float top; private float right; private float bottom; private float[] transform; SemanticsObject parent; List<SemanticsObject> children; // In inverse hit test order (i.e. paint order). private boolean inverseTransformDirty = true; private float[] inverseTransform; private boolean globalGeometryDirty = true; private float[] globalTransform; private Rect globalRect; boolean hasAction(Action action) { return (actions & action.value) != 0; } boolean hadAction(Action action) { return (previousActions & action.value) != 0; } boolean hasFlag(Flag flag) { return (flags & flag.value) != 0; } boolean hadFlag(Flag flag) { assert hadPreviousConfig; return (previousFlags & flag.value) != 0; } boolean didScroll() { return !Float.isNaN(scrollPosition) && !Float.isNaN(previousScrollPosition) && previousScrollPosition != scrollPosition; } void log(String indent, boolean recursive) { Log.i(TAG, indent + "SemanticsObject id=" + id + " label=" + label + " actions=" + actions + " flags=" + flags + "\n" + indent + " +-- textDirection=" + textDirection + "\n"+ indent + " +-- hitTestPosition=" + hitTestPosition + "\n"+ indent + " +-- rect.ltrb=(" + left + ", " + top + ", " + right + ", " + bottom + ")\n" + indent + " +-- transform=" + Arrays.toString(transform) + "\n"); if (children != null && recursive) { String childIndent = indent + " "; for (SemanticsObject child : children) { child.log(childIndent, recursive); } } } void updateWith(ByteBuffer buffer, String[] strings) { hadPreviousConfig = true; previousValue = value; previousFlags = flags; previousActions = actions; previousTextSelectionBase = textSelectionBase; previousTextSelectionExtent = textSelectionExtent; previousScrollPosition = scrollPosition; previousScrollExtentMax = scrollExtentMax; previousScrollExtentMin = scrollExtentMin; flags = buffer.getInt(); actions = buffer.getInt(); textSelectionBase = buffer.getInt(); textSelectionExtent = buffer.getInt(); scrollPosition = buffer.getFloat(); scrollExtentMax = buffer.getFloat(); scrollExtentMin = buffer.getFloat(); int stringIndex = buffer.getInt(); label = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); value = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); increasedValue = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); decreasedValue = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); hint = stringIndex == -1 ? null : strings[stringIndex]; textDirection = TextDirection.fromInt(buffer.getInt()); hitTestPosition = buffer.getInt(); left = buffer.getFloat(); top = buffer.getFloat(); right = buffer.getFloat(); bottom = buffer.getFloat(); if (transform == null) transform = new float[16]; for (int i = 0; i < 16; ++i) transform[i] = buffer.getFloat(); inverseTransformDirty = true; globalGeometryDirty = true; final int childCount = buffer.getInt(); if (childCount == 0) { children = null; } else { if (children == null) children = new ArrayList<SemanticsObject>(childCount); else children.clear(); for (int i = 0; i < childCount; ++i) { SemanticsObject child = getOrCreateObject(buffer.getInt()); child.parent = this; children.add(child); } } } private void ensureInverseTransform() { if (!inverseTransformDirty) return; inverseTransformDirty = false; if (inverseTransform == null) inverseTransform = new float[16]; if (!Matrix.invertM(inverseTransform, 0, transform, 0)) Arrays.fill(inverseTransform, 0); } Rect getGlobalRect() { assert !globalGeometryDirty; return globalRect; } SemanticsObject hitTest(float[] point) { final float w = point[3]; final float x = point[0] / w; final float y = point[1] / w; if (x < left || x >= right || y < top || y >= bottom) return null; if (children != null) { final float[] transformedPoint = new float[4]; for (int i = children.size() - 1; i >= 0; i -= 1) { final SemanticsObject child = children.get(i); if (child.hasFlag(Flag.IS_HIDDEN)) { continue; } child.ensureInverseTransform(); Matrix.multiplyMV(transformedPoint, 0, child.inverseTransform, 0, point, 0); final SemanticsObject result = child.hitTest(transformedPoint); if (result != null) { return result; } } } return this; } // TODO(goderbauer): This should be decided by the framework once we have more information // about focusability there. boolean isFocusable() { // We enforce in the framework that no other useful semantics are merged with these // nodes. if (hasFlag(Flag.SCOPES_ROUTE)) { return false; } int scrollableActions = Action.SCROLL_RIGHT.value | Action.SCROLL_LEFT.value | Action.SCROLL_UP.value | Action.SCROLL_DOWN.value; return (actions & ~scrollableActions) != 0 || flags != 0 || (label != null && !label.isEmpty()) || (value != null && !value.isEmpty()) || (hint != null && !hint.isEmpty()); } void collectRoutes(List<SemanticsObject> edges) { if (hasFlag(Flag.SCOPES_ROUTE)) { edges.add(this); } if (children != null) { for (int i = 0; i < children.size(); ++i) { children.get(i).collectRoutes(edges); } } } String getRouteName() { // Returns the first non-null and non-empty semantic label of a child // with an NamesRoute flag. Otherwise returns null. if (hasFlag(Flag.NAMES_ROUTE)) { if (label != null && !label.isEmpty()) { return label; } } if (children != null) { for (int i = 0; i < children.size(); ++i) { String newName = children.get(i).getRouteName(); if (newName != null && !newName.isEmpty()) { return newName; } } } return null; } void updateRecursively(float[] ancestorTransform, Set<SemanticsObject> visitedObjects, boolean forceUpdate) { visitedObjects.add(this); if (globalGeometryDirty) forceUpdate = true; if (forceUpdate) { if (globalTransform == null) globalTransform = new float[16]; Matrix.multiplyMM(globalTransform, 0, ancestorTransform, 0, transform, 0); final float[] sample = new float[4]; sample[2] = 0; sample[3] = 1; final float[] point1 = new float[4]; final float[] point2 = new float[4]; final float[] point3 = new float[4]; final float[] point4 = new float[4]; sample[0] = left; sample[1] = top; transformPoint(point1, globalTransform, sample); sample[0] = right; sample[1] = top; transformPoint(point2, globalTransform, sample); sample[0] = right; sample[1] = bottom; transformPoint(point3, globalTransform, sample); sample[0] = left; sample[1] = bottom; transformPoint(point4, globalTransform, sample); if (globalRect == null) globalRect = new Rect(); globalRect.set( Math.round(min(point1[0], point2[0], point3[0], point4[0])), Math.round(min(point1[1], point2[1], point3[1], point4[1])), Math.round(max(point1[0], point2[0], point3[0], point4[0])), Math.round(max(point1[1], point2[1], point3[1], point4[1])) ); globalGeometryDirty = false; } assert globalTransform != null; assert globalRect != null; if (children != null) { for (int i = 0; i < children.size(); ++i) { children.get(i).updateRecursively(globalTransform, visitedObjects, forceUpdate); } } } private void transformPoint(float[] result, float[] transform, float[] point) { Matrix.multiplyMV(result, 0, transform, 0, point, 0); final float w = result[3]; result[0] /= w; result[1] /= w; result[2] /= w; result[3] = 0; } private float min(float a, float b, float c, float d) { return Math.min(a, Math.min(b, Math.min(c, d))); } private float max(float a, float b, float c, float d) { return Math.max(a, Math.max(b, Math.max(c, d))); } private String getValueLabelHint() { StringBuilder sb = new StringBuilder(); String[] array = { value, label, hint }; for (String word: array) { if (word != null && word.length() > 0) { if (sb.length() > 0) sb.append(", "); sb.append(word); } } return sb.length() > 0 ? sb.toString() : null; } } }
package com.jakduk.restcontroller.user; import java.util.Collections; import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Set; import javax.validation.Valid; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.social.connect.Connection; import org.springframework.social.connect.ConnectionKey; import org.springframework.social.connect.UsersConnectionRepository; import org.springframework.social.connect.web.HttpSessionSessionStrategy; import org.springframework.social.connect.web.ProviderSignInAttempt; import org.springframework.social.connect.web.ProviderSignInUtils; import org.springframework.social.connect.web.SessionStrategy; import org.springframework.social.daum.connect.DaumConnectionFactory; import org.springframework.social.facebook.connect.FacebookConnectionFactory; import org.springframework.social.oauth2.AccessGrant; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.NativeWebRequest; import com.jakduk.common.CommonConst; import com.jakduk.exception.ServiceError; import com.jakduk.exception.ServiceException; import com.jakduk.model.db.User; import com.jakduk.model.etc.AuthUserProfile; import com.jakduk.model.simple.UserProfile; import com.jakduk.restcontroller.EmptyJsonResponse; import com.jakduk.restcontroller.user.vo.LoginSocialUserForm; import com.jakduk.restcontroller.user.vo.UserProfileForm; import com.jakduk.service.CommonService; import com.jakduk.service.UserService; /** * @author pyohwan * 16. 6. 29 12:27 */ @Slf4j @Api(tags = "", description = " ") @RestController @RequestMapping("/api") public class AuthRestController { @Autowired private UsersConnectionRepository usersConnectionRepository; @Autowired private FacebookConnectionFactory facebookConnectionFactory; @Autowired private DaumConnectionFactory daumConnectionFactory; @Autowired private UserService userService; @Autowired private CommonService commonService; @Autowired private ProviderSignInUtils providerSignInUtils; private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy(); @ApiOperation(value = "SNS ", produces = "application/json", response = EmptyJsonResponse.class) @RequestMapping(value = "/login/social/{providerId}", method = RequestMethod.POST) public EmptyJsonResponse loginSocialUser( @PathVariable String providerId, @Valid @RequestBody LoginSocialUserForm form, NativeWebRequest request) { CommonConst.ACCOUNT_TYPE convertProviderId = CommonConst.ACCOUNT_TYPE.valueOf(providerId.toUpperCase()); AccessGrant accessGrant = new AccessGrant(form.getAccessToken()); Connection<?> connection = null; switch (convertProviderId) { case FACEBOOK: connection = facebookConnectionFactory.createConnection(accessGrant); break; case DAUM: connection = daumConnectionFactory.createConnection(accessGrant); break; } assert connection != null; ConnectionKey connectionKey = connection.getKey(); Set<String> userIds = usersConnectionRepository.findUserIdsConnectedTo(providerId, new HashSet<>(Collections.singletonList(connectionKey.getProviderUserId()))); User existUser = userService.findOneByProviderIdAndProviderUserId(convertProviderId, connectionKey.getProviderUserId()); if (!userIds.isEmpty()) { userService.signInSocialUser(existUser); return EmptyJsonResponse.newInstance(); } // SNS . ProviderSignInAttempt signInAttempt = new ProviderSignInAttempt(connection); sessionStrategy.setAttribute(request, ProviderSignInAttempt.SESSION_ATTRIBUTE, signInAttempt); throw new ServiceException(ServiceError.NOT_REGISTER_WITH_SNS); } @ApiOperation(value = "SNS ", produces = "application/json", response = UserProfileForm.class) @RequestMapping(value = "/social/attempted", method = RequestMethod.GET) public UserProfileForm loginSocialUser( NativeWebRequest request) { Connection<?> connection = providerSignInUtils.getConnectionFromSession(request); if (Objects.isNull(connection)) throw new ServiceException(ServiceError.CANNOT_GET_SNS_PROFILE); ConnectionKey connectionKey = connection.getKey(); CommonConst.ACCOUNT_TYPE convertProviderId = CommonConst.ACCOUNT_TYPE.valueOf(connectionKey.getProviderId().toUpperCase()); UserProfile existUser = userService.findUserProfileByProviderIdAndProviderUserId(convertProviderId, connectionKey.getProviderUserId()); org.springframework.social.connect.UserProfile socialProfile = connection.fetchUserProfile(); String username = null; if (Objects.nonNull(socialProfile.getName())) { username = socialProfile.getName(); } else if (Objects.nonNull(socialProfile.getUsername())) { username = socialProfile.getUsername(); } else { if (Objects.nonNull(socialProfile.getFirstName())) { username = socialProfile.getFirstName(); } if (Objects.nonNull(socialProfile.getLastName())) { username = Objects.isNull(username) ? socialProfile.getLastName() : ' ' + socialProfile.getLastName(); } } UserProfileForm user = new UserProfileForm(); user.setEmail(socialProfile.getEmail()); user.setUsername(username); if (Objects.nonNull(existUser)) { user.setId(existUser.getId()); user.setAbout(existUser.getAbout()); if (Objects.nonNull(existUser.getSupportFC())) user.setFootballClub(existUser.getSupportFC().getId()); } return user; } @ApiOperation(value = " ", produces = "application/json", response = AuthUserProfile.class) @RequestMapping(value = "/auth/user", method = RequestMethod.GET) public AuthUserProfile getMyProfile() { AuthUserProfile authUserProfile = commonService.getAuthUserProfile(); if (Objects.isNull(authUserProfile)) throw new NoSuchElementException(commonService.getResourceBundleMessage("messages.common", "common.exception.no.such.element")); return authUserProfile; } }
package net.bull.javamelody; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.lowagie.text.Anchor; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.Paragraph; import com.lowagie.text.Phrase; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; /** * Partie du rapport pdf pour les jobs. * @author Emeric Vernat */ class PdfJobInformationsReport { private final List<JobInformations> jobInformationsList; private final Document document; private final DateFormat fireTimeFormat = I18N.createDateAndTimeFormat(); private final DateFormat elapsedTimeFormat = I18N.createDurationFormat(); private final Font cellFont = PdfDocumentFactory.TABLE_CELL_FONT; private PdfPTable currentTable; PdfJobInformationsReport(List<JobInformations> jobInformationsList, Document document) { super(); assert jobInformationsList != null; assert document != null; this.jobInformationsList = jobInformationsList; this.document = document; } void toPdf() throws DocumentException { writeHeader(); final PdfPCell defaultCell = getDefaultCell(); boolean odd = false; for (final JobInformations jobInformations : jobInformationsList) { if (odd) { defaultCell.setGrayFill(0.97f); } else { defaultCell.setGrayFill(1); } odd = !odd; // NOPMD writeJobInformations(jobInformations); } document.add(currentTable); addConfigurationReference(); } private void addConfigurationReference() throws DocumentException { final Anchor quartzAnchor = new Anchor("Configuration reference", PdfDocumentFactory.BLUE_FONT); quartzAnchor.setName("Quartz configuration reference"); quartzAnchor.setReference("http: quartzAnchor.setFont(PdfDocumentFactory.BLUE_FONT); final Paragraph quartzParagraph = new Paragraph(); quartzParagraph.add(quartzAnchor); quartzParagraph.setAlignment(Element.ALIGN_RIGHT); document.add(quartzParagraph); } private void writeHeader() throws DocumentException { final List<String> headers = createHeaders(); final int[] relativeWidths = new int[headers.size()]; Arrays.fill(relativeWidths, 0, headers.size(), 1); relativeWidths[1] = 2; relativeWidths[2] = 3; relativeWidths[3] = 3; currentTable = PdfDocumentFactory.createPdfPTable(headers, relativeWidths); } private List<String> createHeaders() { final List<String> headers = new ArrayList<String>(); headers.add(getI18nString("JobGroup")); headers.add(getI18nString("JobName")); headers.add(getI18nString("JobDescription")); headers.add(getI18nString("JobClassName")); headers.add(getI18nString("JobPreviousFireTime")); headers.add(getI18nString("JobNextFireTime")); headers.add(getI18nString("JobElapsedTime")); headers.add(getI18nString("JobPaused")); return headers; } private void writeJobInformations(JobInformations jobInformations) { final PdfPCell defaultCell = getDefaultCell(); defaultCell.setHorizontalAlignment(Element.ALIGN_LEFT); addCell(jobInformations.getGroup()); addCell(jobInformations.getName()); if (jobInformations.getDescription() != null) { addCell(jobInformations.getDescription()); } else { addCell(""); } addCell(jobInformations.getJobClassName()); defaultCell.setHorizontalAlignment(Element.ALIGN_RIGHT); if (jobInformations.getPreviousFireTime() != null) { addCell(fireTimeFormat.format(jobInformations.getPreviousFireTime())); } else { addCell(""); } if (jobInformations.getNextFireTime() != null) { addCell(fireTimeFormat.format(jobInformations.getNextFireTime())); } else { addCell(""); } if (jobInformations.getElapsedTime() >= 0) { addCell(elapsedTimeFormat.format(jobInformations.getElapsedTime())); } else { addCell(""); } defaultCell.setHorizontalAlignment(Element.ALIGN_CENTER); if (jobInformations.isPaused()) { addCell(getI18nString("oui")); } else { addCell(getI18nString("non")); } } private static String getI18nString(String key) { return I18N.getString(key); } private PdfPCell getDefaultCell() { return currentTable.getDefaultCell(); } private void addCell(String string) { currentTable.addCell(new Phrase(string, cellFont)); } }
package org.javers.common.reflection; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * @author bartosz walacik */ class JaversGetterFactory { private final Class getterSource; private final List<JaversGetter> getters = new ArrayList<>(); private final TypeResolvingContext context = new TypeResolvingContext(); JaversGetterFactory(Class getterSource) { this.getterSource = getterSource; } /** * List all class getters, including inherited and private. */ List<JaversGetter> getAllGetters() { if (getters.size() > 0) { throw new IllegalStateException("getters.size() > 0"); } findAllGetters(getterSource); return getters; } private void findAllGetters(Class currentGetterSource) { Class clazz = currentGetterSource; while (clazz != null && clazz != Object.class) { context.addTypeSubstitutions(clazz); Arrays.stream(clazz.getDeclaredMethods()) .filter(method -> isGetter(method) && !method.isBridge()) .filter(method -> !isOverridden(method, getters)) .map(getter -> createJaversGetter(getter, context)) .forEach(getters::add); Arrays.stream(clazz.getInterfaces()).forEach(this::findAllGetters); clazz = clazz.getSuperclass(); } } private static boolean isGetter(Method rawMethod) { return hasGetOrIsPrefix(rawMethod) && hasNoParamters(rawMethod) && returnsSomething(rawMethod) && isNotStatic(rawMethod) && //isNotAbstract(rawMethod) && isNotNative(rawMethod); } private static boolean hasGetOrIsPrefix(Method rawMethod) { return rawMethod.getName().startsWith("get") || rawMethod.getName().startsWith("is"); } private static boolean hasNoParamters(Method rawMethod) { return rawMethod.getParameterTypes().length == 0; } private static boolean returnsSomething(Method rawMethod) { return rawMethod.getGenericReturnType() != void.class; } private static boolean isNotStatic(Method rawMethod) { return !Modifier.isStatic(rawMethod.getModifiers()); } private static boolean isNotNative(Method rawMethod) { return !Modifier.isNative(rawMethod.getModifiers()); } private static boolean isOverridden(Method parent, Collection<JaversGetter> toCheck) { return toCheck.stream() .map(it -> it.getRawMember()) .anyMatch(it -> isOverridden(parent, it)); } private static boolean isOverridden(Method parent, Method toCheck) { return isSubClass(parent, toCheck) && sameMethodName(parent, toCheck) && returnTypeCovariant(parent, toCheck) && sameArguments(parent, toCheck); } private static boolean isSubClass(final Method parent, final Method toCheck) { return parent.getDeclaringClass().isAssignableFrom(toCheck.getDeclaringClass()); } private static boolean sameMethodName(final Method parent, final Method toCheck) { return parent.getName().equals(toCheck.getName()); } private static boolean returnTypeCovariant(final Method parent, final Method toCheck) { return parent.getReturnType().isAssignableFrom(toCheck.getReturnType()); } private static boolean sameArguments(final Method parent, final Method toCheck) { return Arrays.equals(parent.getParameterTypes(), toCheck.getParameterTypes()); } private JaversGetter createJaversGetter(Method getterMethod, TypeResolvingContext context) { Type actualReturnType = context.getSubstitution(getterMethod.getGenericReturnType()); if (hasInheritedId(getterMethod)) { return new JaversGetter(getterMethod, actualReturnType, true); } return new JaversGetter(getterMethod, actualReturnType); } private static boolean hasInheritedId(Method concrete) { List<Method> overridden = new ArrayList<>(); Class clazz = concrete.getDeclaringClass().getSuperclass(); while (clazz != null && clazz != Object.class) { Arrays.asList(clazz.getDeclaredMethods()) .stream() .filter(parent -> isOverridden(parent, concrete)) .findFirst().ifPresent(parent -> overridden.add(parent)); clazz = clazz.getSuperclass(); } return overridden.stream().anyMatch(ReflectionUtil::looksLikeId); } }
package io.searchbox.client.config.discovery; import com.google.common.util.concurrent.AbstractScheduledService; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import io.searchbox.client.JestClient; import io.searchbox.client.JestResult; import io.searchbox.client.config.ClientConfig; import io.searchbox.cluster.NodesInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.LinkedHashSet; import java.util.Map.Entry; /** * used to discover new nodes */ public class NodeChecker extends AbstractScheduledService { final static Logger logger = LoggerFactory.getLogger(NodeChecker.class); //actual client config instance JestClient client; ClientConfig clientConfig; public NodeChecker(ClientConfig clientConfig, JestClient jestClient) { this.client = jestClient; this.clientConfig = clientConfig; } @Override protected void runOneIteration() throws Exception { NodesInfo action = new NodesInfo.Builder().build(); JestResult result = null; try { result = client.execute(action); } catch (Exception e) { logger.error("Error executing NodesInfo!", e); // do not elevate the exception since that will stop the scheduled calls. // throw new RuntimeException("Error executing NodesInfo!", e); } if (result != null) { LinkedHashSet<String> httpHosts = new LinkedHashSet<String>(); JsonObject jsonMap = result.getJsonObject(); JsonObject nodes = (JsonObject) jsonMap.get("nodes"); if (nodes != null) { for (Entry<String, JsonElement> entry : nodes.entrySet()) { JsonObject host = (JsonObject) entry.getValue(); String http_address = host.get("http_address").getAsString(); if (null != http_address) { String cleanHttpAddress = "http://" + http_address.substring(6, http_address.length() - 1); httpHosts.add(cleanHttpAddress); } } } logger.info("Discovered Http Hosts: {}", httpHosts); client.setServers(httpHosts); } } @Override protected Scheduler scheduler() { return Scheduler.newFixedDelaySchedule(0l, clientConfig.getDiscoveryFrequency(), clientConfig.getDiscoveryFrequencyTimeUnit()); } }
package com.intellij.psi.impl.source.codeStyle; import com.intellij.codeFormatting.PseudoText; import com.intellij.codeFormatting.PseudoTextBuilder; import com.intellij.codeFormatting.general.FormatterUtil; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lexer.JavaLexer; import com.intellij.lexer.Lexer; import com.intellij.newCodeFormatting.Formatter; import com.intellij.newCodeFormatting.FormattingModel; import com.intellij.newCodeFormatting.FormattingModelBuilder; import com.intellij.newCodeFormatting.IndentInfo; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.pom.PomModel; import com.intellij.pom.event.PomModelEvent; import com.intellij.pom.impl.PomTransactionBase; import com.intellij.pom.java.LanguageLevel; import com.intellij.pom.tree.TreeAspect; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.parsing.ParseUtil; import com.intellij.psi.impl.source.tree.*; import com.intellij.psi.tree.IChameleonElementType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.java.IJavaElementType; import com.intellij.util.CharTable; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.HashMap; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; public class CodeEditUtil { private static final boolean DO_OUTPUT = false; private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.codeStyle.CodeEditUtil"); public static final Key<IndentInfo> INDENT_INFO_KEY = new Key<IndentInfo>("IndentInfo"); public static ASTNode addChild(CompositeElement parent, ASTNode child, ASTNode anchorBefore) { return addChildren(parent, child, child, anchorBefore); } public static TreeElement addChildren(CompositeElement parent, ASTNode first, ASTNode last, ASTNode anchorBefore) { checkAllWhiteSpaces(parent); if (DO_OUTPUT) { System.out.println("CodeEditUtil.addChildrenBefore\n" + parent.getPsi().getContainingFile().getText()); } ASTNode lastChild = last != null ? last.getTreeNext() : null; ASTNode nextElement = saveIndentsBeforeAdd(first, lastChild, anchorBefore, parent); first = trimWhiteSpaces(first, lastChild); if (first == null) { return null; } boolean keepFirstIndent = false; final ASTNode elemBeforeAnchor = getElementBeforeAnchor(parent, anchorBefore); if (elemBeforeAnchor != null) { ASTNode firstNonEmpty = findFirstNonEmpty(first, lastChild, parent, anchorBefore); if (firstNonEmpty == null || mustKeepFirstIndent(elemBeforeAnchor, parent)){ keepFirstIndent = true; } } parent.addChildren(first, lastChild, anchorBefore); final List<ASTNode> treePrev = getPreviousElements(first); adjustWhiteSpaces(first, anchorBefore, keepFirstIndent); if (nextElement != null) { adjustWhiteSpaces(nextElement, nextElement.getTreeNext(), false); } checkAllWhiteSpaces(parent); if (DO_OUTPUT) { System.out.println("CodeEditUtil.addChildren\n" + parent.getPsi().getContainingFile().getText()); } if (treePrev == null) { return (TreeElement)parent.getFirstChildNode(); } else { ASTNode firstValid = findFirstValid(treePrev); if (firstValid == null) { return (TreeElement)parent.getFirstChildNode(); } else { return (TreeElement)firstValid.getTreeNext(); } } } private static ASTNode saveIndentsBeforeAdd(final ASTNode first, final ASTNode lastChild, final ASTNode anchorBefore, final CompositeElement parent) { saveIndents(first, lastChild); ASTNode nextElement = anchorBefore; if (nextElement == null) { nextElement = findElementAfter(parent, false); } else if (isWS(nextElement)) { nextElement = findElementAfter(anchorBefore, false); } if (nextElement != null) { saveIndents(nextElement); } return nextElement; } private static ASTNode findFirstNonEmpty(final ASTNode first, final ASTNode last, final CompositeElement parent, final ASTNode anchorBefore) { ASTNode firstNonEmpty = first; while (firstNonEmpty != null && firstNonEmpty != last && firstNonEmpty.getTextLength() == 0) { firstNonEmpty = firstNonEmpty.getTreeNext(); } if (firstNonEmpty == null && anchorBefore != null) { firstNonEmpty = TreeUtil.findFirstLeaf(anchorBefore); while (firstNonEmpty != null && firstNonEmpty.getTextLength() == 0) { firstNonEmpty = firstNonEmpty.getTreeNext(); } } if (firstNonEmpty == null) { firstNonEmpty = TreeUtil.nextLeaf(parent); } return firstNonEmpty; } private static boolean mustKeepFirstIndent(final ASTNode elementBeforeChange, final CompositeElement parent) { if (elementBeforeChange == null) return true; if (elementBeforeChange.getElementType() != ElementType.WHITE_SPACE) { return false; } return elementBeforeChange.getTextRange().getStartOffset() < parent.getTextRange().getStartOffset(); } private static ASTNode getElementBeforeAnchor(final CompositeElement parent, final ASTNode anchorBefore) { if (anchorBefore != null) { return TreeUtil.prevLeaf(anchorBefore); } final ASTNode lastChild = parent.getLastChildNode(); if (lastChild != null) { if (lastChild.getTextLength() > 0) { return lastChild; } else { return TreeUtil.prevLeaf(lastChild); } } else { return TreeUtil.prevLeaf(parent); } } private static void checkAllWhiteSpaces(final ASTNode parent) { LOG.assertTrue(parent.getPsi().isValid()); /* if (CodeStyleSettingsManager.getSettings(parent.getPsi().getProject()).JAVA_INDENT_OPTIONS.INDENT_SIZE == 2) { LOG.assertTrue(false); } */ ASTNode node = parent.getPsi().getContainingFile().getNode(); ASTNode leaf = TreeUtil.findFirstLeaf(node); while (leaf != null) { if (isWS(leaf) && whiteSpaceHasInvalidPosition(leaf)) { LOG.assertTrue(false); } leaf = TreeUtil.nextLeaf(leaf); } } public static void removeChild(CompositeElement parent, ASTNode child) { removeChildren(parent, child, child); } public static void removeChildren(CompositeElement parent, ASTNode first, ASTNode last) { if (DO_OUTPUT) { System.out.println("CodeEditUtil.removeChildrenBefore\n" + parent.getPsi().getContainingFile().getText()); } checkAllWhiteSpaces(parent); ASTNode lastChild = last == null ? null : last.getTreeNext(); final ASTNode prevElement = TreeUtil.prevLeaf(first); final ASTNode nextElement = findElementAfter(last == null ? parent : last, false); if (nextElement != null) { saveIndents(nextElement); } boolean adjustWSBefore = containLineBreaks(first, lastChild); if (!mustKeepFirstIndent(prevElement, parent)) { adjustWSBefore = true; } parent.removeRange(first, lastChild); if (!adjustWSBefore && parent.getTextLength() == 0 && prevElement != null && isWS(prevElement) && !prevElement.textContains('\n')) { adjustWSBefore = true; } final PsiFile file = parent.getPsi().getContainingFile(); final CodeStyleSettings.IndentOptions options = CodeStyleSettingsManager.getSettings(file.getProject()) .getIndentOptions(file.getFileType()); if (nextElement != null) { ASTNode elementBeforeNext = TreeUtil.prevLeaf(nextElement); if (prevElement != null && isWS(prevElement) && isWS(elementBeforeNext) && prevElement != elementBeforeNext) { if (!elementBeforeNext.textContains('\n') && prevElement.textContains('\n')) { /* void foo1(){} static void foo2(){} remove static */ delete(elementBeforeNext); } else { final String text = composeNewWS(prevElement.getText(), elementBeforeNext.getText(), options); delete(elementBeforeNext); replace(prevElement, text); } } elementBeforeNext = TreeUtil.prevLeaf(nextElement); if (isWS(elementBeforeNext) && whiteSpaceHasInvalidPosition(elementBeforeNext)) { final String text = elementBeforeNext.getText(); delete(elementBeforeNext); FormatterUtil.replaceWhiteSpace(text, nextElement, ElementType.WHITE_SPACE); } elementBeforeNext = TreeUtil.prevLeaf(nextElement); if (elementBeforeNext != null && isWS(elementBeforeNext) && elementBeforeNext.getTextRange().getStartOffset() == 0) { final IndentInfo info = createInfo(elementBeforeNext.getText(), options); if (info.getLineFeeds() > 0) { final String text = new IndentInfo(0,info.getIndentSpaces(), info.getSpaces()).generateNewWhiteSpace(options); replace(elementBeforeNext, text); } } if (adjustWSBefore) { adjustWhiteSpaceBefore(nextElement, true, true, true, false); } } else { final ASTNode fileNode = SourceTreeToPsiMap.psiElementToTree(parent.getPsi().getContainingFile()); ASTNode lastLeaf = TreeUtil.findLastLeaf(fileNode); if (isWS(lastLeaf)) { delete(lastLeaf); } } checkAllWhiteSpaces(parent); if (DO_OUTPUT) { System.out.println("CodeEditUtil.removeChildren\n" + parent.getPsi().getContainingFile().getText()); } //removeChildrenOld(parent,first, last); } private static void runTransaction(final ASTNode prevElement, final ASTNode elementBeforeNext1, final Runnable action) { final PomModel model = prevElement.getPsi().getProject().getModel(); try { model.runTransaction( new PomTransactionBase(TreeUtil.findCommonParent(elementBeforeNext1, prevElement).getPsi()) { public PomModelEvent runInner() { action.run(); return null; } }, model.getModelAspect(TreeAspect.class)); } catch (IncorrectOperationException e){ } } private static void replace(final ASTNode element, final String text) { if (!text.equals(element.getText())){ final CharTable charTable = SharedImplUtil.findCharTableByTree(element); LeafElement newWhiteSpace = Factory.createSingleLeafElement(element.getElementType(), text.toCharArray(), 0, text.length(), charTable, SharedImplUtil.getManagerByTree(element)); element.getTreeParent().replaceChild(element, newWhiteSpace); } } private static boolean hasNonEmptyNext(final ASTNode element) { ASTNode current = element.getTreeNext(); while (current != null) { if (current.getTextLength() > 0) { return true; } if (current.getElementType() == ElementType.WHITE_SPACE) { return false; } current = current.getTreeNext(); } if (element.getTextRange().getEndOffset() == element.getPsi().getContainingFile().getTextLength()) { return element.getTreeNext() == null; } return false; } private static boolean hasNonEmptyPrev(ASTNode element) { ASTNode current = element.getTreePrev(); while (current != null) { if (current.getTextLength() > 0) { return true; } if (current.getElementType() == ElementType.WHITE_SPACE) { return false; } current = current.getTreePrev(); } if (element.getTextRange().getStartOffset() == 0) return element.getTreePrev() == null; return false; } private static boolean whiteSpaceHasInvalidPosition(final ASTNode element) { final ASTNode treeParent = element.getTreeParent(); if (isWS(element) && treeParent.getElementType() == ElementType.XML_TEXT) return false; if (treeParent.getPsi().getUserData(ParseUtil.UNCLOSED_ELEMENT_PROPERTY) != null) return false; if (hasNonEmptyPrev(element) && hasNonEmptyNext(element)) return false; if (treeParent.getElementType() == ElementType.XML_PROLOG) return false; if (treeParent.getElementType() instanceof IChameleonElementType) { if (((IChameleonElementType)treeParent.getElementType()).isParsable(treeParent.getText(), element.getPsi().getProject())){ return false; } else { return true; } } else { return true; } } private static boolean containLineBreaks(final ASTNode first, final ASTNode last) { ASTNode current = first; while (current != last) { if (current.textContains('\n')) return true; current = current.getTreeNext(); } return false; } private static void saveIndents(final ASTNode first, final ASTNode lastChild) { final PsiFile file = first.getPsi().getContainingFile(); final Language language = file.getLanguage(); final FormattingModelBuilder builder = language.getFormattingModelBuilder(); if (builder != null) { final CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(file.getProject()); final FormattingModel model = builder.createModel(file, settings); ASTNode current = first; while (current != lastChild) { final IElementType elementType = current.getElementType(); if (elementType != ElementType.WHITE_SPACE && elementType != ElementType.DOC_COMMENT_LEADING_ASTERISKS && elementType != ElementType.DOC_TAG && current.getTextLength() > 0) { Formatter.getInstance().saveIndents(model, current.getTextRange(), new MyIndentInfoStorage(file), settings, settings.getIndentOptions(file.getFileType())); } current = current.getTreeNext(); } } } private static ASTNode trimWhiteSpaces(final ASTNode first, final ASTNode lastChild) { ASTNode current = first; ASTNode result = first; while(current != null && current != lastChild) { LeafElement leaf = TreeUtil.findFirstLeaf(current); if ((current == first && current.getTreeNext() != lastChild) || current.getElementType() != ElementType.WHITE_SPACE) { if (leaf != null && leaf.getElementType() == ElementType.WHITE_SPACE) { if (leaf == result) result = leaf.getTreeNext(); delete(leaf); } } leaf = TreeUtil.findLastLeaf(current); if (current.getElementType() != ElementType.WHITE_SPACE) { if (leaf != null && leaf.getElementType() == ElementType.WHITE_SPACE) { if (leaf == result) result = leaf.getTreeNext(); delete(leaf); } } current = current.getTreeNext(); } return result; } private static ASTNode findFirstValid(final List<ASTNode> treePrev) { for (Iterator<ASTNode> iterator = treePrev.iterator(); iterator.hasNext();) { ASTNode treeElement = iterator.next(); if (treeElement.getPsi().isValid()) return treeElement; } return null; } private static List<ASTNode> getPreviousElements(final ASTNode first) { ASTNode current = first.getTreePrev(); if (current == null) return null; final ArrayList<ASTNode> result = new ArrayList<ASTNode>(); while (current != null) { result.add(current); current = current.getTreePrev(); } return result; } private static void adjustWhiteSpaces(final ASTNode first, final ASTNode last, final boolean keepFirstIndent) { ASTNode current = first; while (current != null && current != last) { if (notIsSpace(current)) { adjustWhiteSpaceBefore(current, true, false, !keepFirstIndent || current != first, true); } current = current.getTreeNext(); } } private static boolean notIsSpace(final ASTNode current) { return current.getElementType() != ElementType.WHITE_SPACE && current.getText().trim().length() > 0; } private static void adjustWhiteSpaceBefore(final ASTNode first, final boolean keepBlankLines, final boolean keepLineBreaks, final boolean changeWSBeforeFirstElement, final boolean changeLineFeedsBeforeFirstElement) { CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(first.getPsi().getProject()); final PsiElement psi = first.getPsi(); final PsiFile file = psi.getContainingFile(); final FormattingModelBuilder builder = file.getLanguage().getFormattingModelBuilder(); final FormattingModelBuilder elementBuilder = psi.getLanguage().getFormattingModelBuilder(); if (builder != null && elementBuilder != null) { Formatter.getInstance().adjustTextRange(builder.createModel(file, settings), settings, settings.getIndentOptions(file.getFileType()), first.getTextRange(), keepBlankLines, keepLineBreaks, changeWSBeforeFirstElement, changeLineFeedsBeforeFirstElement, new MyIndentInfoStorage(file)); } } private static String composeNewWS(final String firstText, final String secondText, final CodeStyleSettings.IndentOptions options) { IndentInfo first = createInfo(firstText, options); IndentInfo second = createInfo(secondText, options); final int lineFeeds = Math.max(first.getLineFeeds(), second.getLineFeeds()); return new IndentInfo(lineFeeds, 0, second.getSpaces()).generateNewWhiteSpace(options); } private static IndentInfo createInfo(final String text, final CodeStyleSettings.IndentOptions options) { int lf = 0; int spaces = 0; for (int i = 0; i < text.length(); i++) { final char c = text.charAt(i); switch(c) { case ' ': spaces++; break; case '\t': spaces += options.TAB_SIZE; break; case '\n': lf++; spaces = 0; break; } } return new IndentInfo(lf, 0, spaces); } private static boolean containLineBreaks(final ASTNode first, final int endOffset) { ASTNode current = first; while (current != null && current.getTextRange().getStartOffset()< endOffset) { if (current.textContains('\n')) return true; current = TreeUtil.nextLeaf(current); } return false; } private static void delete(final ASTNode prevElement) { prevElement.getTreeParent().removeRange(prevElement, prevElement.getTreeNext()); } private static ASTNode findElementAfter(final ASTNode parent, boolean canBeWhiteSpace) { ASTNode candidate = parent.getTreeNext(); while (candidate !=null) { if ((canBeWhiteSpace || !isWS(candidate)) && candidate.getTextLength() > 0) return candidate; candidate = candidate.getTreeNext(); } final ASTNode treeParent = parent.getTreeParent(); if (treeParent != null) { return findElementAfter(treeParent, canBeWhiteSpace); } else { return null; } } private static boolean isWS(final ASTNode lastChild) { if (lastChild == null)return false; return lastChild.getElementType() == ElementType.WHITE_SPACE; } public static ASTNode replaceChild(CompositeElement parent, ASTNode oldChild, ASTNode newChild) { if (DO_OUTPUT) { System.out.println("CodeEditUtil.replaceChildrenBefore\n" + parent.getPsi().getContainingFile().getText()); } checkAllWhiteSpaces(parent); final ASTNode elementAfter = findElementAfter(oldChild, true); boolean changeFirstWS = newChild.textContains('\n') || oldChild.textContains('\n'); ASTNode firstNonEmpty = findFirstNonEmpty(newChild, newChild.getTreeNext(), parent, newChild.getTreeNext()); if (!canStickChildrenTogether(TreeUtil.prevLeaf(oldChild), firstNonEmpty)) { changeFirstWS = true; } if (changeFirstWS) { saveIndents(newChild); } if (elementAfter != null && !isWS(elementAfter)) { saveIndents(elementAfter); } parent.replaceChild(oldChild, newChild); final List<ASTNode> treePrev = getPreviousElements(newChild); adjustWhiteSpaceBefore(newChild, true, false, changeFirstWS, false); if (elementAfter != null && !isWS(elementAfter)) { adjustWhiteSpaceBefore(elementAfter, true, true, true, false); } checkAllWhiteSpaces(parent); if (DO_OUTPUT) { System.out.println("CodeEditUtil.replaceChildren\n" + parent.getPsi().getContainingFile().getText()); } if (treePrev == null) { return (TreeElement)parent.getFirstChildNode(); } else { ASTNode firstValid = findFirstValid(treePrev); if (firstValid == null) { return (TreeElement)parent.getFirstChildNode(); } else { return (TreeElement)firstValid.getTreeNext(); } } } private static void saveIndents(final ASTNode newChild) { saveIndents(newChild, newChild.getTreeNext()); } public static boolean canStickChildrenTogether(final ASTNode child1, final ASTNode child2) { if (child1 == null || child2 == null) return true; if (isWS(child1) || isWS(child2)) return true; ASTNode token1 = TreeUtil.findLastLeaf(child1); ASTNode token2 = TreeUtil.findFirstLeaf(child2); LOG.assertTrue(token1 != null); LOG.assertTrue(token2 != null); if (token1.getElementType() instanceof IJavaElementType && token2.getElementType() instanceof IJavaElementType) { return canStickJavaTokens((PsiJavaToken)SourceTreeToPsiMap.treeElementToPsi(token1), (PsiJavaToken)SourceTreeToPsiMap.treeElementToPsi(token2)); } else { return true; } } private static Map<Pair<IElementType, IElementType>, Boolean> myCanStickJavaTokensMatrix = new HashMap<Pair<IElementType, IElementType>, Boolean>(); public static boolean canStickJavaTokens(PsiJavaToken token1, PsiJavaToken token2) { IElementType type1 = token1.getTokenType(); IElementType type2 = token2.getTokenType(); Pair<IElementType, IElementType> pair = new Pair<IElementType, IElementType>(type1, type2); Boolean res = myCanStickJavaTokensMatrix.get(pair); if (res == null) { String text = token1.getText() + token2.getText(); Lexer lexer = new JavaLexer(LanguageLevel.HIGHEST); lexer.start(text.toCharArray(), 0, text.length()); boolean canMerge = lexer.getTokenType() == type1; lexer.advance(); canMerge &= lexer.getTokenType() == type2; res = Boolean.valueOf(canMerge); myCanStickJavaTokensMatrix.put(pair, res); } return res.booleanValue(); } public static void unindentSubtree(ASTNode clone, TreeElement original, CharTable table) { PsiManager manager = original.getManager(); LOG.assertTrue(manager != null, "Manager should present (?)"); LOG.assertTrue(clone.getTreeParent().getElementType() == ElementType.DUMMY_HOLDER); final PsiFile file = SourceTreeToPsiMap.treeElementToPsi(original).getContainingFile(); FileType fileType = file.getFileType(); Helper helper = new Helper(fileType, manager.getProject()); /* TreeElement prevWS = helper.getPrevWhitespace(original); if( prevWS == null || prevWS.getText().indexOf('\n') < 0 ) return; */ if (clone instanceof CompositeElement) { int origIndent = helper.getIndent(original); helper.indentSubtree(clone, origIndent, 0, table); } } public static ASTNode getDefaultAnchor(PsiImportList list, PsiImportStatementBase statement) { CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(list.getProject()); ImportHelper importHelper = new ImportHelper(settings); return importHelper.getDefaultAnchor(list, statement); } private static final HashMap<String, Integer> ourModifierToOrderMap = new HashMap<String, Integer>(); static { //TODO : options? ourModifierToOrderMap.put(PsiModifier.PUBLIC, new Integer(1)); ourModifierToOrderMap.put(PsiModifier.PRIVATE, new Integer(1)); ourModifierToOrderMap.put(PsiModifier.PROTECTED, new Integer(1)); ourModifierToOrderMap.put(PsiModifier.NATIVE, new Integer(2)); ourModifierToOrderMap.put(PsiModifier.STATIC, new Integer(3)); ourModifierToOrderMap.put(PsiModifier.ABSTRACT, new Integer(3)); ourModifierToOrderMap.put(PsiModifier.FINAL, new Integer(4)); ourModifierToOrderMap.put(PsiModifier.SYNCHRONIZED, new Integer(5)); ourModifierToOrderMap.put(PsiModifier.TRANSIENT, new Integer(5)); ourModifierToOrderMap.put(PsiModifier.VOLATILE, new Integer(5)); ourModifierToOrderMap.put(PsiModifier.STRICTFP, new Integer(6)); } public static ASTNode getDefaultAnchor(PsiModifierList modifierList, PsiKeyword modifier) { Integer order = ourModifierToOrderMap.get(modifier.getText()); if (order == null) return null; for (ASTNode child = SourceTreeToPsiMap.psiElementToTree(modifierList).getFirstChildNode(); child != null; child = child.getTreeNext()) { if (ElementType.KEYWORD_BIT_SET.isInSet(child.getElementType())) { Integer order1 = ourModifierToOrderMap.get(child.getText()); if (order1 == null) continue; if (order1.intValue() > order.intValue()) { return child; } } } return null; } public static PsiElement getDefaultAnchor(PsiClass aClass, PsiMember member) { CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(aClass.getProject()); int order = getMemberOrderWeight(member, settings); if (order < 0) return null; PsiElement lastMember = null; for (PsiElement child = aClass.getFirstChild(); child != null; child = child.getNextSibling()) { int order1 = getMemberOrderWeight(child, settings); if (order1 < 0) continue; if (order1 > order) { if (lastMember != null) { PsiElement nextSibling = lastMember.getNextSibling(); while (nextSibling instanceof PsiJavaToken && (nextSibling.getText().equals(",") || nextSibling.getText().equals(";"))) { nextSibling = nextSibling.getNextSibling(); } return nextSibling == null ? aClass.getLBrace().getNextSibling() : nextSibling; } else { return aClass.getLBrace().getNextSibling(); } } lastMember = child; } return aClass.getRBrace(); } private static int getMemberOrderWeight(PsiElement member, CodeStyleSettings settings) { if (member instanceof PsiField) { return member instanceof PsiEnumConstant ? 1 : settings.FIELDS_ORDER_WEIGHT + 1; } else if (member instanceof PsiMethod) { return ((PsiMethod)member).isConstructor() ? settings.CONSTRUCTORS_ORDER_WEIGHT + 1 : settings.METHODS_ORDER_WEIGHT + 1; } else if (member instanceof PsiClass) { return settings.INNER_CLASSES_ORDER_WEIGHT + 1; } else { return -1; } } public static void normalizeSpace(Helper helper, ASTNode parent, ASTNode child1, ASTNode child2, CharTable table) { StringBuffer buffer = null; int count = 0; for (ASTNode child = child1 != null ? child1.getTreeNext() : parent.getFirstChildNode(); child != child2; child = child.getTreeNext()) { if (child instanceof CompositeElement && child.getFirstChildNode() == null) continue; if (Helper.isNonSpace(child)) { LOG.error("Whitespace expected"); } if (buffer == null) { buffer = new StringBuffer(); } buffer.append(child.getText()); count++; } if (count > 1) { LeafElement newSpace = Factory.createSingleLeafElement(JavaTokenType.WHITE_SPACE, buffer.toString().toCharArray(), 0, buffer.length(), table, SharedImplUtil.getManagerByTree(parent)); count = 0; ASTNode next; for (ASTNode child = child1 != null ? child1.getTreeNext() : parent.getFirstChildNode(); child != child2; child = next) { next = child.getTreeNext(); if (child instanceof CompositeElement && child.getTextLength() == 0) continue; if (count == 0) { parent.replaceChild(child, newSpace); } else { parent.removeChild(child); } count++; } } if (child1 != null && child2 != null && Helper.getSpaceText(parent, child1, child2).length() == 0) { if (!helper.canStickChildrenTogether(child1, child2)) { helper.makeSpace(parent, child1, child2, " "); } } } public static String getStringWhiteSpaceBetweenTokens(ASTNode first, ASTNode second, Language language) { final PseudoTextBuilder pseudoTextBuilder = language.getFormatter(); if (pseudoTextBuilder == null) { final LeafElement leafElement = ParseUtil.nextLeaf((TreeElement)first, null); if (leafElement != second) { return leafElement.getText(); } else { return null; } } else { final PsiElement secondAsPsiElement = SourceTreeToPsiMap.treeElementToPsi(second); LOG.assertTrue(secondAsPsiElement != null); final PsiFile file = secondAsPsiElement.getContainingFile(); final Project project = secondAsPsiElement.getProject(); final CodeStyleSettings settings = CodeStyleSettingsManager.getInstance(project).getCurrentSettings(); return getWhiteSpaceBeforeToken(second, language, true).generateNewWhiteSpace(settings.getIndentOptions(file.getFileType())); } } public static IndentInfo getIndentWhiteSpaceBeforeToken(final ASTNode tokenNode, final Language language) { return getWhiteSpaceBeforeToken(tokenNode, chooseLanguage(tokenNode, language), false); } private static Language chooseLanguage(final ASTNode tokenNode, final Language language) { if (tokenNode == null) return language; final PsiElement secondAsPsiElement = SourceTreeToPsiMap.treeElementToPsi(tokenNode); if (secondAsPsiElement == null) return language; final PsiFile file = secondAsPsiElement.getContainingFile(); if (file == null) return language; final FileType fileType = file.getFileType(); if (!(fileType instanceof LanguageFileType)) { return language; } if (((LanguageFileType)fileType).getLanguage().getFormatter() == null) { return language; } else { return ((LanguageFileType)fileType).getLanguage(); } } public static IndentInfo getWhiteSpaceBeforeToken(final ASTNode tokenNode, final Language language, final boolean mayChangeLineFeeds) { LOG.assertTrue(tokenNode != null); final PsiElement secondAsPsiElement = SourceTreeToPsiMap.treeElementToPsi(tokenNode); LOG.assertTrue(secondAsPsiElement != null); final PsiFile file = secondAsPsiElement.getContainingFile(); final Project project = secondAsPsiElement.getProject(); final CodeStyleSettings settings = CodeStyleSettingsManager.getInstance(project).getCurrentSettings(); final int tokenStartOffset = tokenNode.getStartOffset(); final boolean oldValue = settings.XML_KEEP_LINE_BREAKS; //settings.XML_KEEP_LINE_BREAKS = false; final int oldKeepBlankLines = settings.XML_KEEP_BLANK_LINES; settings.XML_KEEP_BLANK_LINES = 0; try { return getWhiteSpaceBeforeImpl(file, tokenStartOffset, language, project, settings, mayChangeLineFeeds); } finally { settings.XML_KEEP_LINE_BREAKS = oldValue; settings.XML_KEEP_BLANK_LINES = oldKeepBlankLines; } } private static IndentInfo getWhiteSpaceBeforeImpl(final PsiFile file, final int tokenStartOffset, final Language language, final Project project, final CodeStyleSettings settings, final boolean mayChangeLineFeeds) { final FormattingModelBuilder builder = language.getFormattingModelBuilder(); final PsiElement element = file.findElementAt(tokenStartOffset); if (builder != null && element.getLanguage().getFormattingModelBuilder() != null) { final TextRange textRange = element.getTextRange(); final FormattingModel model = builder.createModel(file, settings); return Formatter.getInstance().getWhiteSpaceBefore(model.getDocumentModel(), model.getRootBlock(), settings, settings.getIndentOptions(file.getFileType()), textRange, mayChangeLineFeeds); } else { final PseudoTextBuilder pseudoTextBuilder = language.getFormatter(); LOG.assertTrue(pseudoTextBuilder != null); final PseudoText pseudoText = pseudoTextBuilder.build(project, settings, file); return GeneralCodeFormatter.getWhiteSpaceBetweenTokens(pseudoText, settings, file.getFileType(), tokenStartOffset, mayChangeLineFeeds); } } private static class MyIndentInfoStorage implements Formatter.IndentInfoStorage { private final PsiFile myFile; public MyIndentInfoStorage(final PsiFile file) { myFile = file; } public void saveIndentInfo(IndentInfo info, int startOffset) { myFile.findElementAt(startOffset).putUserData(INDENT_INFO_KEY, info); } public IndentInfo getIndentInfo(int startOffset) { return myFile.findElementAt(startOffset).getUserData(INDENT_INFO_KEY); } } }
package org.jasig.portal.security.provider; import java.util.Enumeration; import org.jasig.portal.EntityIdentifier; import org.jasig.portal.security.IPerson; import org.jasig.portal.security.ISecurityContext; /** * An IPerson object that wraps another IPerson * object and prevents access to the * underlying sercurity context. * @author Ken Weiner, kweiner@unicon.net * @version $Revision$ */ public class RestrictedPerson implements IPerson { private IPerson person; public RestrictedPerson(IPerson person) { this.person = person; } public Object getAttribute(String key) { return this.person.getAttribute(key); } public Object[] getAttributeValues(String key) { return this.person.getAttributeValues(key); } public Enumeration getAttributeNames() { return this.person.getAttributeNames(); } public Enumeration getAttributes() { return this.person.getAttributes(); } public String getFullName() { return this.person.getFullName(); } public int getID() { return this.person.getID(); } public boolean isGuest() { return this.person.isGuest(); } /** * RestrictedPerson's implementation of setAttribute does nothing. */ public void setAttribute(String key, Object value) { // Part of RestrictedPerson's restrictedness is to do nothing // when this method is invoked. } /** * RestrictedPerson's implementation of setFullName does nothing. */ public void setFullName(String sFullName) { // Part of RestrictedPerson's restrictedness is to do nothing // when this method is invoked. } /** * RestrictedPerson's implementation of setID does nothing. */ public void setID(int sID) { // Part of RestrictedPerson's restrictedness is to do nothing // when this method is invoked. } /** * RestrictedPerson's implementation of getSecurityContext prevents * access to the security context by always returning null. * @return null */ public ISecurityContext getSecurityContext() { return null; } /** * RestrictedPerson's implementation of setSecurityContext does nothing. */ public void setSecurityContext(ISecurityContext securityContext) { // Part of RestrictedPerson's restrictedness is to do nothing // when this method is invoked. } /** * RestrictedPerson's implementation of getEntityIdentifier always returns null, * as part of the restrictedness of this IPerson implementation. * @return null */ public EntityIdentifier getEntityIdentifier() { return this.person.getEntityIdentifier(); } }
package org.languagetool.server; import org.apache.commons.lang3.ArrayUtils; import org.jetbrains.annotations.Nullable; import org.languagetool.Experimental; import org.languagetool.Language; import org.languagetool.Languages; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * @since 2.0 */ public class HTTPServerConfig { enum Mode { LanguageTool } public static final String DEFAULT_HOST = "localhost"; /** The default port on which the server is running (8081). */ public static final int DEFAULT_PORT = 8081; static final String LANGUAGE_MODEL_OPTION = "--languageModel"; static final String WORD2VEC_MODEL_OPTION = "--word2vecModel"; protected boolean verbose = false; protected boolean publicAccess = false; protected int port = DEFAULT_PORT; protected String allowOriginUrl = null; protected int maxTextLength = Integer.MAX_VALUE; protected int maxTextHardLength = Integer.MAX_VALUE; protected String secretTokenKey = null; protected long maxCheckTimeMillis = -1; protected int maxCheckThreads = 10; protected Mode mode; protected File languageModelDir = null; protected File word2vecModelDir = null; protected int requestLimit; protected int requestLimitInBytes; protected int timeoutRequestLimit; protected int requestLimitPeriodInSeconds; protected boolean trustXForwardForHeader; protected int maxWorkQueueSize; protected File rulesConfigFile = null; protected int cacheSize = 0; protected boolean warmUp = false; protected float maxErrorsPerWordRate = 0; protected String hiddenMatchesServer; protected int hiddenMatchesServerTimeout; protected List<Language> hiddenMatchesLanguages = new ArrayList<>(); /** * Create a server configuration for the default port ({@link #DEFAULT_PORT}). */ public HTTPServerConfig() { this(DEFAULT_PORT, false); } /** * @param serverPort the port to bind to * @since 2.8 */ public HTTPServerConfig(int serverPort) { this(serverPort, false); } /** * @param serverPort the port to bind to * @param verbose when set to <tt>true</tt>, the input text will be logged in case there is an exception */ public HTTPServerConfig(int serverPort, boolean verbose) { this.port = serverPort; this.verbose = verbose; } /** * Parse command line options. */ HTTPServerConfig(String[] args) { for (int i = 0; i < args.length; i++) { if (args[i].matches("--[a-zA-Z]+=.+")) { System.err.println("WARNING: use `--option value`, not `--option=value`, parameters will be ignored otherwise: " + args[i]); } switch (args[i]) { case "--config": parseConfigFile(new File(args[++i]), !ArrayUtils.contains(args, LANGUAGE_MODEL_OPTION), !ArrayUtils.contains(args, WORD2VEC_MODEL_OPTION)); break; case "-p": case "--port": port = Integer.parseInt(args[++i]); break; case "-v": case "--verbose": verbose = true; break; case "--public": publicAccess = true; break; case "--allow-origin": try { allowOriginUrl = args[++i]; if (allowOriginUrl.startsWith(" throw new IllegalArgumentException("Missing argument for '--allow-origin' (e.g. an URL or '*')"); } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("Missing argument for '--allow-origin' (e.g. an URL or '*')"); } break; case LANGUAGE_MODEL_OPTION: setLanguageModelDirectory(args[++i]); break; case WORD2VEC_MODEL_OPTION: setWord2VecModelDirectory(args[++i]); break; default: if (args[i].contains("=")) { System.out.println("WARNING: unknown option: " + args[i] + " - please note that parameters are given as '--arg param', i.e. without '=' between argument and parameter"); } else { System.out.println("WARNING: unknown option: " + args[i]); } } } } private void parseConfigFile(File file, boolean loadLangModel, boolean loadWord2VecModel) { try { Properties props = new Properties(); try (FileInputStream fis = new FileInputStream(file)) { props.load(fis); maxTextLength = Integer.parseInt(getOptionalProperty(props, "maxTextLength", Integer.toString(Integer.MAX_VALUE))); maxTextHardLength = Integer.parseInt(getOptionalProperty(props, "maxTextHardLength", Integer.toString(Integer.MAX_VALUE))); secretTokenKey = getOptionalProperty(props, "secretTokenKey", null); maxCheckTimeMillis = Long.parseLong(getOptionalProperty(props, "maxCheckTimeMillis", "-1")); requestLimit = Integer.parseInt(getOptionalProperty(props, "requestLimit", "0")); requestLimitInBytes = Integer.parseInt(getOptionalProperty(props, "requestLimitInBytes", "0")); timeoutRequestLimit = Integer.parseInt(getOptionalProperty(props, "timeoutRequestLimit", "0")); requestLimitPeriodInSeconds = Integer.parseInt(getOptionalProperty(props, "requestLimitPeriodInSeconds", "0")); trustXForwardForHeader = Boolean.valueOf(getOptionalProperty(props, "trustXForwardForHeader", "false")); maxWorkQueueSize = Integer.parseInt(getOptionalProperty(props, "maxWorkQueueSize", "0")); if (maxWorkQueueSize < 0) { throw new IllegalArgumentException("maxWorkQueueSize must be >= 0: " + maxWorkQueueSize); } String langModel = getOptionalProperty(props, "languageModel", null); if (langModel != null && loadLangModel) { setLanguageModelDirectory(langModel); } String word2vecModel = getOptionalProperty(props, "word2vecModel", null); if (word2vecModel != null && loadWord2VecModel) { setWord2VecModelDirectory(word2vecModel); } maxCheckThreads = Integer.parseInt(getOptionalProperty(props, "maxCheckThreads", "10")); if (maxCheckThreads < 1) { throw new IllegalArgumentException("Invalid value for maxCheckThreads, must be >= 1: " + maxCheckThreads); } boolean atdMode = getOptionalProperty(props, "mode", "LanguageTool").equalsIgnoreCase("AfterTheDeadline"); if (atdMode) { throw new IllegalArgumentException("The AfterTheDeadline mode is not supported anymore in LanguageTool 3.8 or later"); } String rulesConfigFilePath = getOptionalProperty(props, "rulesFile", null); if (rulesConfigFilePath != null) { rulesConfigFile = new File(rulesConfigFilePath); if (!rulesConfigFile.exists() || !rulesConfigFile.isFile()) { throw new RuntimeException("Rules Configuration file can not be found: " + rulesConfigFile); } } cacheSize = Integer.parseInt(getOptionalProperty(props, "cacheSize", "0")); if (cacheSize < 0) { throw new IllegalArgumentException("Invalid value for cacheSize: " + cacheSize + ", use 0 to deactivate cache"); } String warmUpStr = getOptionalProperty(props, "warmUp", "false"); if (warmUpStr.equals("true")) { warmUp = true; } else if (warmUpStr.equals("false")) { warmUp = false; } else { throw new IllegalArgumentException("Invalid value for warmUp: '" + warmUpStr + "', use 'true' or 'false'"); } maxErrorsPerWordRate = Float.parseFloat(getOptionalProperty(props, "maxErrorsPerWordRate", "0")); hiddenMatchesServer = getOptionalProperty(props, "hiddenMatchesServer", null); hiddenMatchesServerTimeout = Integer.parseInt(getOptionalProperty(props, "hiddenMatchesServerTimeout", "1000")); String langCodes = getOptionalProperty(props, "hiddenMatchesLanguages", ""); for (String code : langCodes.split(",\\s*")) { if (!code.isEmpty()) { hiddenMatchesLanguages.add(Languages.getLanguageForShortCode(code)); } } } } catch (IOException e) { throw new RuntimeException("Could not load properties from '" + file + "'", e); } } private void setLanguageModelDirectory(String langModelDir) { languageModelDir = new File(langModelDir); if (!languageModelDir.exists() || !languageModelDir.isDirectory()) { throw new RuntimeException("LanguageModel directory not found or is not a directory: " + languageModelDir); } } private void setWord2VecModelDirectory(String w2vModelDir) { word2vecModelDir = new File(w2vModelDir); if (!word2vecModelDir.exists() || !word2vecModelDir.isDirectory()) { throw new RuntimeException("Word2Vec directory not found or is not a directory: " + word2vecModelDir); } } /* * @param verbose if true, the text to be checked will be displayed in case of exceptions */ public boolean isVerbose() { return verbose; } public boolean isPublicAccess() { return publicAccess; } public int getPort() { return port; } /** * Value to set as the "Access-Control-Allow-Origin" http header. {@code null} * will not return that header at all. With {@code *} your server can be used from any other web site * from Javascript/Ajax (search Cross-origin resource sharing (CORS) for details). */ @Nullable public String getAllowOriginUrl() { return allowOriginUrl; } /** * @param len the maximum text length allowed (in number of characters), texts that are longer * will cause an exception when being checked, unless the user can provide * a JWT 'token' parameter with a 'maxTextLength' claim */ public void setMaxTextLength(int len) { this.maxTextLength = len; } /** * @param len the maximum text length allowed (in number of characters), texts that are longer * will cause an exception when being checked even if the user can provide a JWT token * @since 3.9 */ public void setMaxTextHardLength(int len) { this.maxTextHardLength = len; } int getMaxTextLength() { return maxTextLength; } /** * Limit for maximum text length - text cannot be longer than this, even if user has valid secret token. * @since 3.9 */ int getMaxTextHardLength() { return maxTextHardLength; } /** * Optional JWT token key. Can be used to circumvent the maximum text length (but not maxTextHardLength). * @since 3.9 */ @Nullable String getSecretTokenKey() { return secretTokenKey; } /** * @since 4.0 */ void setSecretTokenKey(String secretTokenKey) { this.secretTokenKey = secretTokenKey; } int getRequestLimit() { return requestLimit; } /** @since 4.0 */ int getTimeoutRequestLimit() { return timeoutRequestLimit; } /** @since 4.0 */ int getRequestLimitInBytes() { return requestLimitInBytes; } int getRequestLimitPeriodInSeconds() { return requestLimitPeriodInSeconds; } /** * @param maxCheckTimeMillis The maximum duration allowed for a single check in milliseconds, checks that take longer * will stop with an exception. Use {@code -1} for no limit. * @since 2.6 */ void setMaxCheckTimeMillis(int maxCheckTimeMillis) { this.maxCheckTimeMillis = maxCheckTimeMillis; } /** @since 2.6 */ long getMaxCheckTimeMillis() { return maxCheckTimeMillis; } /** * Get language model directory (which contains '3grams' sub directory) or {@code null}. * @since 2.7 */ @Nullable File getLanguageModelDir() { return languageModelDir; } /** * Get word2vec model directory (which contains 'en' sub directories and final_embeddings.txt and dictionary.txt) or {@code null}. * @since 4.0 */ @Nullable File getWord2VecModelDir() { return word2vecModelDir; } /** @since 2.7 */ Mode getMode() { return mode; } /** * @param maxCheckThreads The maximum number of threads serving requests running at the same time. * If there are more requests, they will be queued until a thread can work on them. * @since 2.7 */ void setMaxCheckThreads(int maxCheckThreads) { this.maxCheckThreads = maxCheckThreads; } /** @since 2.7 */ int getMaxCheckThreads() { return maxCheckThreads; } /** * Set to {@code true} if this is running behind a (reverse) proxy which * sets the {@code X-forwarded-for} HTTP header. The last IP address (but not local IP addresses) * in that header will then be used for enforcing a request limitation. * @since 2.8 */ void setTrustXForwardForHeader(boolean trustXForwardForHeader) { this.trustXForwardForHeader = trustXForwardForHeader; } /** @since 2.8 */ boolean getTrustXForwardForHeader() { return trustXForwardForHeader; } /** @since 2.9 */ int getMaxWorkQueueSize() { return maxWorkQueueSize; } /** @since 3.7 */ int getCacheSize() { return cacheSize; } /** @since 3.7 */ boolean getWarmUp() { return warmUp; } /** * Maximum errors per word rate, checking will stop if the rate is higher. * For example, with a rate of 0.33, the checking would stop if the user's * text has so many errors that more than every 3rd word causes a rule match. * Note that this may not apply for very short texts. * @since 4.0 */ float getMaxErrorsPerWordRate() { return maxErrorsPerWordRate; } /** * URL of server that is queried to add additional (but hidden) matches to the result. * @since 4.0 */ @Nullable @Experimental String getHiddenMatchesServer() { return hiddenMatchesServer; } /** * Timeout in milliseconds for querying {@link #getHiddenMatchesServer()}. * @since 4.0 */ @Experimental int getHiddenMatchesServerTimeout() { return hiddenMatchesServerTimeout; } /** * Languages for which {@link #getHiddenMatchesServer()} will be queried. * @since 4.0 */ @Experimental List<Language> getHiddenMatchesLanguages() { return hiddenMatchesLanguages; } /** * @return the file from which server rules configuration should be loaded, or {@code null} * @since 3.0 */ @Nullable File getRulesConfigFile() { return rulesConfigFile; } protected String getProperty(Properties props, String propertyName, File config) { String propertyValue = (String)props.get(propertyName); if (propertyValue == null || propertyValue.trim().isEmpty()) { throw new IllegalConfigurationException("Property '" + propertyName + "' must be set in " + config); } return propertyValue; } protected String getOptionalProperty(Properties props, String propertyName, String defaultValue) { String propertyValue = (String)props.get(propertyName); if (propertyValue == null) { return defaultValue; } return propertyValue; } }
package de.hska.ld.content.service.impl; import de.hska.ld.content.persistence.domain.Access; import de.hska.ld.content.persistence.domain.Document; import de.hska.ld.content.persistence.domain.Folder; import de.hska.ld.content.persistence.domain.UserGroup; import de.hska.ld.content.persistence.repository.FolderRepository; import de.hska.ld.content.service.DocumentService; import de.hska.ld.content.service.FolderService; import de.hska.ld.core.exception.NotFoundException; import de.hska.ld.core.persistence.domain.User; import de.hska.ld.core.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class FolderServiceImpl extends AbstractContentService<Folder> implements FolderService { @Autowired private FolderRepository repository; @Autowired private DocumentService documentService; @Autowired private UserService userService; @Override public Folder createFolder(String folderName) { return save(new Folder(folderName)); } @Override @Transactional public Folder createFolder(String folderName, Long parentId) { Folder parent = null; if (parentId != null) { parent = findById(parentId); if (parent == null) { throw new NotFoundException("predecessorId"); } } Folder folder = new Folder(folderName); if (parent != null) { folder.getParentFolderList().add(parent); parent.getFolderList().add(folder); save(parent); return parent.getFolderList().get(parent.getFolderList().size() - 1); } return null; } @Override public Folder placeDocumentInFolder(Long folderId, Long documentId) { Document document = documentService.findById(documentId); Folder folder = findById(folderId); folder.getDocumentList().add(document); return save(folder); } @Override @Transactional public Folder shareFolder(Long folderId, UserGroup userGroup, Access.Permission... permission) { Folder folder = findById(folderId); if (folder == null) { throw new NotFoundException("folderId"); } shareFolder(folderId, userGroup.getUserList(), permission); for (UserGroup subUserGroup : userGroup.getUserGroupList()) { shareFolder(folderId, subUserGroup, permission); } return folder; } @Override public Folder revokeShareFolder(Long folderId, UserGroup userGroup, Access.Permission... permission) { Folder folder = findById(folderId); if (folder == null) { throw new NotFoundException("folderId"); } revokeShareFolder(folderId, userGroup.getUserList(), permission); for (UserGroup subUserGroup : userGroup.getUserGroupList()) { shareFolder(folderId, subUserGroup, permission); } return folder; } @Override public Folder revokeShareFolder(Long folderId, List<User> userList, Access.Permission... permission) { Folder folder = findById(folderId); List<Folder> parentFolderList = folder.getParentFolderList(); for (User user : userList) { Folder sharedItemsFolder = getSharedItemsFolder(user.getId()); sharedItemsFolder.getFolderList().remove(folder); if (parentFolderList != null && parentFolderList.size() > 0) { parentFolderList.stream().filter(pf -> user.getId().equals(pf.getCreator().getId())).forEach(pf -> { pf.getFolderList().remove(folder); folder.getParentFolderList().remove(pf); super.save(pf); }); } removeAccess(folder.getId(), user, permission); super.save(folder); } for (Folder subFolder : folder.getFolderList()) { revokeShareSubFolder(subFolder.getId(), userList, permission); } return folder; } private Folder revokeShareSubFolder(Long folderId, List<User> userList, Access.Permission... permission) { Folder folder = findById(folderId); for (User user : userList) { removeAccess(folder.getId(), user, permission); } return folder; } @Override @Transactional public Folder loadSubFolderList(Long folderId) { Folder folder = findById(folderId); folder.getFolderList().size(); return folder; } @Override @Transactional public Folder getSharedItemsFolder(Long userId) { User user = userService.findById(userId); List<Folder> folders = repository.findByCreatorAndSharingFolderTrue(user); Folder sharedFolder = null; if (folders != null && folders.size() > 0) { sharedFolder = folders.get(0); } else { sharedFolder = createSharedItemsFolder(user); } return sharedFolder; } @Override @Transactional public Folder shareFolder(Long folderId, List<User> userList, Access.Permission... permission) { Folder folder = findById(folderId); for (User user : userList) { Folder sharedItemsFolder = getSharedItemsFolder(user.getId()); sharedItemsFolder.getFolderList().add(folder); super.save(sharedItemsFolder); addAccess(folder.getId(), user, permission); } for (Folder subFolder : folder.getFolderList()) { shareSubFolder(subFolder.getId(), userList, permission); } // TODO add document access return folder; } public Folder shareSubFolder(Long folderId, List<User> userList, Access.Permission... permission) { Folder folder = findById(folderId); for (User user : userList) { addAccess(folder.getId(), user, permission); } return folder; } private Folder createSharedItemsFolder(User user) { Folder newSharedItemsFolder = new Folder("SharedItems"); newSharedItemsFolder.setCreator(user); newSharedItemsFolder.setSharingFolder(true); return super.save(newSharedItemsFolder); } @Override public FolderRepository getRepository() { return repository; } }
package ch.usi.dag.disl.staticcontext; import org.objectweb.asm.Opcodes; import ch.usi.dag.disl.util.Constants; /** * Provides static context information about the instrumented method. */ public class MethodStaticContext extends AbstractStaticContext { /** * Returns the internal name of the instrumented class, i.e., a fully * qualified class name, with packages delimited by the '/' character. */ // XXX LB: This would be better named "thisClassInternalName". public String thisClassName () { return __classInternalName (); } /** * Returns the simple name of the instrumented class, i.e., a class name * without the package part of the name. */ public String thisClassSimpleName () { final String name = __classInternalName (); final int start = name.lastIndexOf (Constants.PACKAGE_INTERN_DELIM); return (start >= 0) ? name.substring (start + 1) : name; } /** * Returns the canonical name of the instrumented class, i.e., a fully * qualified class name, with packages delimited by the '.' character. */ public String thisClassCanonicalName () { return __classInternalName ().replace ( Constants.PACKAGE_INTERN_DELIM, Constants.PACKAGE_STD_DELIM ); } /** * Returns the internal name of the class enclosing the instrumented class, * or {@code null} if the instrumented class is not enclosed in another * class. */ public String thisClassOuterClass () { return staticContextData.getClassNode ().outerClass; } /** * Returns the name of the method enclosing the instrumented class, or * {@code null} if the class is not enclosed in a method. */ public String thisClassOuterMethod () { return staticContextData.getClassNode ().outerMethod; } /** * Returns outer method descriptor of the instrumented class. */ public String thisClassOuterMethodDesc () { return staticContextData.getClassNode ().outerMethodDesc; } /** * Returns the signature of the instrumented class, or {@code null} if the * class is not a generic type. */ public String thisClassSignature () { return staticContextData.getClassNode ().signature; } /** * Returns the name of the source file containing the instrumented class. */ public String thisClassSourceFile () { return staticContextData.getClassNode ().sourceFile; } /** * Returns the internal name of the super class of the instrumented class, * i.e., a fully qualified class name, with package names delimited by the * '/' character. */ public String thisClassSuperName () { return staticContextData.getClassNode ().superName; } /** * Returns class version as (ASM) integer of the instrumented class. */ public int thisClassVersion () { return staticContextData.getClassNode ().version; } /** * Returns {@code true} if the instrumented class is abstract. */ public boolean isClassAbstract () { return __classAccessFlag (Opcodes.ACC_ABSTRACT); } /** * Returns {@code true} if the instrumented class is an annotation. */ public boolean isClassAnnotation () { return __classAccessFlag (Opcodes.ACC_ANNOTATION); } /** * Returns {@code true} if the instrumented class is an enum. */ public boolean isClassEnum () { return __classAccessFlag (Opcodes.ACC_ENUM); } /** * Returns {@code true} if the instrumented class is final. */ public boolean isClassFinal () { return __classAccessFlag (Opcodes.ACC_FINAL); } /** * Returns {@code true} if the instrumented class is an interface. */ public boolean isClassInterface () { return __classAccessFlag (Opcodes.ACC_INTERFACE); } /** * Returns {@code true} if the instrumented class is private. */ public boolean isClassPrivate () { return __classAccessFlag (Opcodes.ACC_PRIVATE); } /** * Returns {@code true} if the instrumented class is protected. */ public boolean isClassProtected () { return __classAccessFlag (Opcodes.ACC_PROTECTED); } /** * Returns {@code true} if the instrumented class is public. */ public boolean isClassPublic () { return __classAccessFlag (Opcodes.ACC_PUBLIC); } /** * Returns {@code true} if the instrumented class is synthetic. */ public boolean isClassSynthetic () { return __classAccessFlag (Opcodes.ACC_SYNTHETIC); } /** * Returns the name of the instrumented method. */ public String thisMethodName () { return __methodName (); } /** * Returns the fully qualified (internal) name of the instrumented method, * i.e., including the (internal) name of the class containing the method. */ public String thisMethodFullName () { return __classInternalName () + Constants.STATIC_CONTEXT_METHOD_DELIM + __methodName (); } /** * Returns the descriptor of the instrumented method. */ public String thisMethodDescriptor () { return staticContextData.getMethodNode ().desc; } /** * Returns the signature of the instrumented method. */ public String thisMethodSignature () { return staticContextData.getMethodNode ().signature; } /** * Returns {@code true} if the instrumented method is a bridge. */ public boolean isMethodBridge () { return __methodAccessFlag (Opcodes.ACC_BRIDGE); } /** * Returns {@code true} if the instrumented method is final. */ public boolean isMethodFinal () { return __methodAccessFlag (Opcodes.ACC_FINAL); } /** * Returns {@code true} if the instrumented method is private. */ public boolean isMethodPrivate () { return __methodAccessFlag (Opcodes.ACC_PRIVATE); } /** * Returns {@code true} if the instrumented method is protected. */ public boolean isMethodProtected () { return __methodAccessFlag (Opcodes.ACC_PROTECTED); } /** * Returns {@code true} if the instrumented method is public. */ public boolean isMethodPublic () { return __methodAccessFlag (Opcodes.ACC_PUBLIC); } /** * Returns {@code true} if the instrumented method is static. */ public boolean isMethodStatic () { return __methodAccessFlag (Opcodes.ACC_STATIC); } /** * Returns {@code true} if the instrumented method is synchronized. */ public boolean isMethodSynchronized () { return __methodAccessFlag (Opcodes.ACC_SYNCHRONIZED); } /** * Returns {@code true} if the instrumented method accepts a variable number * of arguments. */ public boolean isMethodVarArgs () { return __methodAccessFlag (Opcodes.ACC_VARARGS); } private String __classInternalName () { return staticContextData.getClassNode ().name; } private boolean __classAccessFlag (final int flagMask) { final int access = staticContextData.getClassNode ().access; return (access & flagMask) != 0; } private String __methodName () { return staticContextData.getMethodNode ().name; } private boolean __methodAccessFlag (final int flagMask) { final int access = staticContextData.getMethodNode ().access; return (access & flagMask) != 0; } }
package org.navalplanner.web.users; import static org.navalplanner.web.I18nHelper._; import java.util.ArrayList; import java.util.List; import org.navalplanner.business.orders.entities.Order; import org.navalplanner.business.users.entities.OrderAuthorization; import org.navalplanner.business.users.entities.OrderAuthorizationType; import org.navalplanner.business.users.entities.Profile; import org.navalplanner.business.users.entities.ProfileOrderAuthorization; import org.navalplanner.business.users.entities.User; import org.navalplanner.business.users.entities.UserOrderAuthorization; import org.navalplanner.web.common.IMessagesForUser; import org.navalplanner.web.common.Level; import org.navalplanner.web.common.Util; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Comboitem; /** * Controller for CRUD actions over an {@link OrderAuthorization} * * @author Jacobo Aragunde Perez <jaragunde@igalia.com> */ @SuppressWarnings("serial") public class OrderAuthorizationController extends GenericForwardComposer{ private Component window; private IOrderAuthorizationModel orderAuthorizationModel; private IMessagesForUser messagesForUser; @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); comp.setVariable("orderAuthorizationController", this, true); this.window = comp; } public void setOrder(Order order) { orderAuthorizationModel.initSetOrder(order); Util.reloadBindings(window); } public void save() { orderAuthorizationModel.confirmSave(); } public List<ProfileOrderAuthorization> getProfileOrderAuthorizations() { return orderAuthorizationModel.getProfileOrderAuthorizations(); } public List<UserOrderAuthorization> getUserOrderAuthorizations() { return orderAuthorizationModel.getUserOrderAuthorizations(); } public void addOrderAuthorization(Comboitem comboItem, boolean readAuthorization, boolean writeAuthorization) { if(comboItem != null) { if(!readAuthorization && !writeAuthorization) { messagesForUser.showMessage(Level.WARNING, _("No authorizations were added because you did not select any.")); return; } List<OrderAuthorizationType> authorizations = new ArrayList<OrderAuthorizationType>(); if(readAuthorization) { authorizations.add(OrderAuthorizationType.READ_AUTHORIZATION); } if(writeAuthorization) { authorizations.add(OrderAuthorizationType.WRITE_AUTHORIZATION); } if (comboItem.getValue() instanceof User) { List<OrderAuthorizationType> result = orderAuthorizationModel.addUserOrderAuthorization( (User)comboItem.getValue(), authorizations); if(result != null) { messagesForUser.showMessage(Level.WARNING, _("Cannot add some authorizations for user {0}. " + "Probably they are already present.", ((User)comboItem.getValue()).getLoginName())); } } else if (comboItem.getValue() instanceof Profile) { List<OrderAuthorizationType> result = orderAuthorizationModel.addProfileOrderAuthorization( (Profile)comboItem.getValue(), authorizations); if(result != null) { messagesForUser.showMessage(Level.WARNING, _("Cannot add some authorizations for profile {0}. " + "Probably they are already present.", ((Profile)comboItem.getValue()).getProfileName())); } } } Util.reloadBindings(window); } public void removeOrderAuthorization(OrderAuthorization orderAuthorization) { orderAuthorizationModel.removeOrderAuthorization(orderAuthorization); Util.reloadBindings(window); } public void setMessagesForUserComponent(IMessagesForUser component) { messagesForUser = component; } }
package com.echsylon.atlantis.extra; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceActivity; public class AtlantisSettingsActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent(getApplicationContext(), AtlantisService.class); startService(intent); getFragmentManager().beginTransaction() .replace(android.R.id.content, new AtlantisSettingsFragment()) .commit(); } }
package edu.wustl.xipHost.caGrid; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.zip.ZipInputStream; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.apache.log4j.Logger; import org.cagrid.transfer.context.client.TransferServiceContextClient; import org.cagrid.transfer.context.client.helper.TransferClientHelper; import org.cagrid.transfer.context.stubs.types.TransferServiceContextReference; import org.globus.gsi.GlobusCredential; import edu.osu.bmi.utils.io.zip.ZipEntryInputStream; import gov.nih.nci.cagrid.ncia.client.NCIACoreServiceClient; /** * @author Jaroslaw Krych * */ public class RetrieveNBIASecuredTest { final static Logger logger = Logger.getLogger(RetrieveNBIASecuredTest.class); String gridServiceUrl = "http://imaging.nci.nih.gov/wsrf/services/cagrid/NCIACoreService"; String authUrl = "https://cagrid-auth.nci.nih.gov:8443/wsrf/services/cagrid/AuthenticationService"; String dorianURL = "https://cagrid-dorian.nci.nih.gov:8443/wsrf/services/cagrid/Dorian"; File inputDir; @BeforeClass public static void setUpBeforeClass() throws Exception { } /** * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { } @Test public void test() throws Exception { System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.NoOpLog"); GridLogin login = new GridLogin(); String userName = "KrychJ"; String password = ""; GlobusCredential globusCred = login.acquireGlobusCredential(userName, password); boolean isConnectionSecured = GridLogin.isConnectionSecured(); logger.debug("Acquired NBIA GlobusCredential. Connection secured = " + isConnectionSecured); if(!isConnectionSecured){ fail("Unable to acquire NBIA GlobusCredential. Check username and password."); return; } NCIACoreServiceClient client = new NCIACoreServiceClient(gridServiceUrl, globusCred); client.setAnonymousPrefered(false); TransferServiceContextReference tscr = client.retrieveDicomDataBySeriesUID("1.3.6.1.4.1.9328.50.1.4718"); TransferServiceContextClient tclient = new TransferServiceContextClient(tscr.getEndpointReference(), globusCred); InputStream istream = TransferClientHelper.getData(tclient.getDataTransferDescriptor(), globusCred); ZipInputStream zis = new ZipInputStream(istream); ZipEntryInputStream zeis = null; BufferedInputStream bis = null; File importDir = new File("./test-content/NBIA5"); if(!importDir.exists()){ importDir.mkdirs(); } else { File[] files = importDir.listFiles(); for(int j = 0; j < files.length; j++){ File file = files[j]; file.delete(); } } while(true) { try { zeis = new ZipEntryInputStream(zis); } catch (EOFException e) { break; } catch (IOException e) { logger.error(e, e); } String unzzipedFile = null; try { unzzipedFile = importDir.getCanonicalPath(); } catch (IOException e) { logger.error(e, e); } logger.debug(" filename: " + zeis.getName()); bis = new BufferedInputStream(zeis); byte[] data = new byte[8192]; int bytesRead = 0; String retrievedFilePath = unzzipedFile + File.separator + zeis.getName(); try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(retrievedFilePath)); while ((bytesRead = (bis.read(data, 0, data.length))) != -1) { bos.write(data, 0, bytesRead); } bos.flush(); bos.close(); } catch (IOException e) { logger.error(e, e); } } try { zis.close(); tclient.destroy(); } catch (IOException e) { logger.error(e, e); } File[] retrievedFiles = importDir.listFiles(); int numbOfRetreivedFiles = retrievedFiles.length; assertEquals("Number of retrieved files should be 1 but is. " + numbOfRetreivedFiles, numbOfRetreivedFiles, 2); //Assert file names. They should be equal to items' SeriesInstanceUIDs Map<String, File> mapRetrievedFiles = new HashMap<String, File>(); for(int i = 0; i < numbOfRetreivedFiles; i++){ File file = retrievedFiles[i]; mapRetrievedFiles.put(file.getName(), file); } boolean retrievedFilesCorrect = false; if(mapRetrievedFiles.containsKey("1.3.6.1.4.1.9328.50.1.4716.dcm") && mapRetrievedFiles.containsKey("1.3.6.1.4.1.9328.50.1.4720.dcm")){ retrievedFilesCorrect = true; } assertTrue("Retrieved files ar enot as expected.", retrievedFilesCorrect); } }
package com.facebook.litho.processor; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import java.lang.annotation.Annotation; import java.util.Arrays; import com.facebook.litho.annotations.FromBind; import com.facebook.litho.annotations.FromBoundsDefined; import com.facebook.litho.annotations.FromMeasure; import com.facebook.litho.annotations.FromPrepare; import com.facebook.litho.annotations.GetExtraAccessibilityNodeAt; import com.facebook.litho.annotations.GetExtraAccessibilityNodesCount; import com.facebook.litho.annotations.MountSpec; import com.facebook.litho.annotations.OnBind; import com.facebook.litho.annotations.OnBoundsDefined; import com.facebook.litho.annotations.OnCreateMountContent; import com.facebook.litho.annotations.OnMeasure; import com.facebook.litho.annotations.OnMeasureBaseline; import com.facebook.litho.annotations.OnMount; import com.facebook.litho.annotations.OnPopulateAccessibilityNode; import com.facebook.litho.annotations.OnPopulateExtraAccessibilityNode; import com.facebook.litho.annotations.OnPrepare; import com.facebook.litho.annotations.OnUnbind; import com.facebook.litho.annotations.OnUnmount; import com.facebook.litho.annotations.ShouldUpdate; import com.facebook.litho.specmodels.model.ClassNames; import com.facebook.litho.specmodels.model.SpecModel; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; public class MountSpecHelper extends ComponentSpecHelper { private enum MountType { NONE, DRAWABLE, VIEW, } private static final Class<Annotation>[] STAGE_ANNOTATIONS = new Class[] { /* Methods that can have inter-stage props - these MUST come first in this list */ OnPrepare.class, OnMeasure.class, OnBoundsDefined.class, OnBind.class, /* Methods that do not support inter-stage props */ OnMount.class, OnPopulateAccessibilityNode.class, GetExtraAccessibilityNodesCount.class, OnPopulateExtraAccessibilityNode.class, GetExtraAccessibilityNodeAt.class, OnUnbind.class, OnUnmount.class, }; private static final Class<Annotation>[] INTER_STAGE_INPUT_ANNOTATIONS = new Class[] { FromPrepare.class, FromMeasure.class, FromBoundsDefined.class, FromBind.class, }; public MountSpecHelper( ProcessingEnvironment processingEnv, TypeElement specElement, SpecModel specModel) { super( processingEnv, specElement, specElement.getAnnotation(MountSpec.class).value(), specElement.getAnnotation(MountSpec.class).isPublic(), STAGE_ANNOTATIONS, INTER_STAGE_INPUT_ANNOTATIONS, specModel); } @Override protected void validate() { if (mQualifiedClassName == null) { throw new ComponentsProcessingException( mSpecElement, "You should either provide an explicit component name " + "e.g. @MountSpec(\"MyComponent\"); or suffix your class name with " + "\"Spec\" e.g. a \"MyComponentSpec\" class name generates a component named " + "\"MyComponent\"."); } if (Utils.getAnnotatedMethod(mStages.getSourceElement(), OnCreateMountContent.class) == null) { throw new ComponentsProcessingException( mSpecElement, "You need to have a method annotated with @OnCreateMountContent in your spec"); } } /** * Generate an onPrepare implementation that delegates to the @OnPrepare-annotated method. */ public void generateOnPrepare() { final ExecutableElement onPrepare = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnPrepare.class); if (onPrepare == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.returnType = null; methodDescription.name = "onPrepare"; methodDescription.parameterTypes = new TypeName[] {ClassNames.COMPONENT_CONTEXT}; mStages.generateDelegate( methodDescription, onPrepare, ClassNames.COMPONENT); } /** * Generate an onMeasure implementation that delegates to the @OnCreateLayout-annotated method. */ public void generateOnMeasure() { final ExecutableElement onMeasure = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnMeasure.class); if (onMeasure == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.name = "onMeasure"; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, ClassNames.COMPONENT_LAYOUT, ClassName.INT, ClassName.INT, ClassNames.SIZE, }; mTypeSpec.addMethod( MethodSpec.methodBuilder("canMeasure") .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .returns(TypeName.BOOLEAN) .addStatement("return true") .build()); mStages.generateDelegate( methodDescription, onMeasure, ClassNames.COMPONENT); } /** * Generate an onBoundsDefined implementation that delegates to the * @OnBoundsDefined-annotated method. */ public void generateOnBoundsDefined() { final ExecutableElement onBoundsDefined = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnBoundsDefined.class); if (onBoundsDefined == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.name = "onBoundsDefined"; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, ClassNames.COMPONENT_LAYOUT, }; mStages.generateDelegate( methodDescription, onBoundsDefined, ClassNames.COMPONENT); } /** * Generate an onMeasureBaseline implementation that delegates to the * @OnMeasureBaseline-annotated method. */ public void generateOnMeasureBaseline() { final ExecutableElement onMeasureBaseline = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnMeasureBaseline.class); if (onMeasureBaseline == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.name = "onMeasureBaseline"; methodDescription.returnType = TypeName.INT; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, TypeName.INT, TypeName.INT, }; mStages.generateDelegate( methodDescription, onMeasureBaseline, ClassNames.COMPONENT); } /** * Generate an onCreateMountContent implementation that delegates to the * @OnCreateMountContent-annotated method. */ public void generateOnCreateMountContentAndGetMountType() { final ExecutableElement onCreateMountContent = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnCreateMountContent.class); final MountType componentMountType = getMountType(onCreateMountContent.getReturnType()); if (componentMountType != MountType.VIEW && componentMountType != MountType.DRAWABLE) { throw new ComponentsProcessingException( onCreateMountContent, "onCreateMountContent's return type should be either a View or a Drawable subclass"); } mTypeSpec.addMethod( MethodSpec.methodBuilder("getMountType") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE) .addStatement( "return $T.$L", ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE, componentMountType) .build()); mTypeSpec.addMethod( MethodSpec.methodBuilder("poolSize") .addAnnotation(Override.class) .addModifiers(javax.lang.model.element.Modifier.PROTECTED) .returns(TypeName.INT) .addStatement("return "+mSpecElement.getAnnotation(MountSpec.class).poolSize()) .build()); mTypeSpec.addMethod( new OnCreateMountContentMethodBuilder() .target(mStages.getSourceDelegateAccessorName()) .delegateName(onCreateMountContent.getSimpleName().toString()) .build()); } /** * Generate an onMount implementation that delegates to the @OnMount-annotated method. */ public void generateOnMount() { final ExecutableElement onMount = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnMount.class); if (onMount == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.name = "onMount"; methodDescription.returnType = ClassName.VOID; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, ClassName.OBJECT, }; if (!Utils.getParametersWithAnnotation(onMount, FromMeasure.class).isEmpty() || !Utils.getParametersWithAnnotation(onMount, FromBoundsDefined.class).isEmpty()) { mTypeSpec.addMethod(new IsMountSizeDependentMethodSpecBuilder().build()); } mStages.generateDelegate( methodDescription, onMount, Arrays.asList(ClassNames.COMPONENT_CONTEXT, getMountType()), ClassNames.COMPONENT); } private TypeName getMountType() { final ExecutableElement onCreateMountContent = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnCreateMountContent.class); return ClassName.get(onCreateMountContent.getReturnType()); } /** * Generate an onBind implementation that delegates to the @OnBind-annotated method. */ public void generateOnBind() { final ExecutableElement onBind = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnBind.class); if (onBind == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.returnType = ClassName.VOID; methodDescription.name = "onBind"; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, ClassName.OBJECT, }; generateMountCompliantMethod(onBind, methodDescription); } /** * Generate an onUnbind implementation that delegates to the @OnUnbind-annotated method. */ public void generateOnUnbind() { final ExecutableElement onIdle = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnUnbind.class); if (onIdle == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.returnType = ClassName.VOID; methodDescription.name = "onUnbind"; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, ClassName.OBJECT, }; generateMountCompliantMethod(onIdle, methodDescription); } /** * Generate an onUnmount implementation that delegates to the @OnUnmount-annotated method. */ public void generateOnUnmount() { final ExecutableElement onUnmount = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnUnmount.class); if (onUnmount == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.returnType = ClassName.VOID; methodDescription.name = "onUnmount"; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, ClassName.OBJECT, }; generateMountCompliantMethod(onUnmount, methodDescription); } private void generateMountCompliantMethod( ExecutableElement method, MethodDescription methodDescription) { final ExecutableElement onCreateMountContent = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnCreateMountContent.class); final TypeMirror mountReturnType = onCreateMountContent.getReturnType(); final VariableElement mountParameter = method.getParameters().get(1); final TypeMirror mountParameterType = mountParameter.asType(); // The return type of onMount() and the second parameter on onUnmount() // should have the same type. if (!mStages.isSameType(mountParameterType, mountReturnType)) { throw new ComponentsProcessingException( mountParameter, "Second parameter of " + methodDescription.name + " should be of same type " + "of onCreateMountContent()'s return"); } mStages.generateDelegate( methodDescription, method, Arrays.asList(ClassNames.COMPONENT_CONTEXT, ClassName.get(mountParameterType)), ClassNames.COMPONENT); } private static MountType getMountType(TypeMirror returnTypeParam) { TypeMirror returnType = returnTypeParam; while (returnType.getKind() != TypeKind.NONE && returnType.getKind() != TypeKind.VOID) { final TypeElement returnElement = (TypeElement) ((DeclaredType) returnType).asElement(); final TypeName type = ClassName.get(returnElement); if (type.equals(ClassNames.VIEW)) { return MountType.VIEW; } else if (type.equals(ClassNames.DRAWABLE)) { return MountType.DRAWABLE; } returnType = returnElement.getSuperclass(); } return MountType.NONE; } /** * Generate an onPopulateAccessibilityNode implementation that delegates to the * {@link com.facebook.litho.annotations.OnPopulateAccessibilityNode}-annotated method. */ public void generateAccessibilityMethods() { final ExecutableElement onPopulateAccessibilityNode = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnPopulateAccessibilityNode.class); final ExecutableElement onPopulateExtraAccessibilityNode = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnPopulateExtraAccessibilityNode.class); final ExecutableElement getExtraAccessibilityNodeAt = Utils.getAnnotatedMethod( mStages.getSourceElement(), GetExtraAccessibilityNodeAt.class); final ExecutableElement getNumExtraAccessibilityNodes = Utils.getAnnotatedMethod( mStages.getSourceElement(), GetExtraAccessibilityNodesCount.class); if (onPopulateAccessibilityNode == null && onPopulateExtraAccessibilityNode == null && getExtraAccessibilityNodeAt == null && getNumExtraAccessibilityNodes == null) { return; } if ((onPopulateExtraAccessibilityNode != null || getExtraAccessibilityNodeAt != null || getNumExtraAccessibilityNodes != null) && (onPopulateExtraAccessibilityNode == null || getExtraAccessibilityNodeAt == null || getNumExtraAccessibilityNodes == null)) { throw new ComponentsProcessingException( mSpecElement, "In order to implement accessibility support for extra nodes, you need to implement " + "onPopulateExtraAccessibilityNode() AND getExtraAccessibilityNodeAt AND " + "getExtraAccessibilityNodesCount()."); } final ExecutableElement onCreateMountContent = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnCreateMountContent.class); final MountType componentMountType = getMountType(onCreateMountContent.getReturnType()); if (componentMountType != MountType.DRAWABLE) { throw new ComponentsProcessingException( mSpecElement, "Only implement accessibility support for Mount Specs that mount drawables."); } if (onPopulateAccessibilityNode != null) { generateOnPopulateAccessibilityNode(onPopulateAccessibilityNode); } if (onPopulateExtraAccessibilityNode != null) { generateOnPopulateExtraAccessibilityNode(onPopulateExtraAccessibilityNode); generateGetExtraAccessibilityNodeAt(getExtraAccessibilityNodeAt); generateGetNumExtraAccessibilityNodes(getNumExtraAccessibilityNodes); generateImplementsExtraAccessibilityNodes(); } generatePopulatesAccessibilityTrue(); } private void generateOnPopulateAccessibilityNode(ExecutableElement onPopulateAccessibilityNode) { final MethodDescription methodDescription = new MethodDescription();
package com.macro.mall.dao; import com.macro.mall.dto.PmsProductAttributeCategoryItem; import java.util.List; public interface PmsProductAttributeCategoryDao { List<PmsProductAttributeCategoryItem> getListWithAttr(); }
package org.gbif.occurrence.search; import org.gbif.api.model.occurrence.search.OccurrenceSearchParameter; import org.gbif.api.model.occurrence.search.OccurrenceSearchRequest; import org.gbif.common.search.util.QueryUtils; import org.gbif.occurrence.search.solr.OccurrenceSolrField; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import org.apache.solr.client.solrj.SolrQuery; import static org.gbif.common.search.util.QueryUtils.PARAMS_AND_JOINER; import static org.gbif.common.search.util.QueryUtils.PARAMS_JOINER; import static org.gbif.common.search.util.QueryUtils.PARAMS_OR_JOINER; import static org.gbif.common.search.util.QueryUtils.setQueryPaging; import static org.gbif.common.search.util.QueryUtils.setRequestHandler; import static org.gbif.common.search.util.QueryUtils.setSortOrder; import static org.gbif.common.search.util.QueryUtils.toParenthesesQuery; import static org.gbif.common.search.util.SolrConstants.DEFAULT_QUERY; import static org.gbif.common.search.util.SolrConstants.RANGE_FORMAT; import static org.gbif.occurrence.search.OccurrenceSearchDateUtils.toDateQuery; /** * Utility class for building Solr queries from supported parameters for occurrences search. */ public class OccurrenceSearchRequestBuilder { private static final String SOLR_SPELLCHECK = "spellcheck"; private static final String SOLR_SPELLCHECK_COUNT = "spellcheck.count"; private static final String SOLR_SPELLCHECK_Q = "spellcheck.q"; private static final Integer DEFAULT_SPELL_CHECK_COUNT = 4; /** * Utility class to generates full text queries. */ private static final class OccurrenceFullTextQueryBuilder { private String q; private static final Double FUZZY_DISTANCE = 0.7; private static final String TERM_PATTERN = "%1$s^%2$s %1$s~%3$s^%4$s"; private static final String NON_TOKENIZED_QUERY_PATTERN = ":%1$s^1000"; private static final Set<String> NON_TOKENIZABLE_FIELDS = ImmutableSet.<String>of(OccurrenceSolrField.CATALOG_NUMBER.getFieldName() + NON_TOKENIZED_QUERY_PATTERN, OccurrenceSolrField.OCCURRENCE_ID.getFieldName() + NON_TOKENIZED_QUERY_PATTERN); private static final String NON_TOKENIZED_QUERY = QueryUtils.PARAMS_OR_JOINER.join(NON_TOKENIZABLE_FIELDS); private static final Integer MAX_SCORE = 100; private static final Integer SCORE_DECREMENT = 20; /** * Query parameter. */ private OccurrenceFullTextQueryBuilder withQ(String q){ this.q = q; return this; } /** * Builds a Solr expression query with the form: "term1 ..termN" term1^100 term1~0.7^50 ... termN^20 termN~0.7^10. * Each boosting parameter is calculated using the formula: MAX_SCORE - SCORE_DECREMENT * i. Where 'i' is the * position of the term in the query. */ public String build() { String[] qs = q.split(" "); String phraseQ = QueryUtils.toPhraseQuery(q); if(qs.length > 1){ StringBuilder ftQ = new StringBuilder(); ftQ.append(phraseQ + ' '); for(int i = 0; i < qs.length; i++) { if (qs[i].length() > 1) { //ignore tokens of single letters int termScore = Math.max(MAX_SCORE - (SCORE_DECREMENT * i), SCORE_DECREMENT); ftQ.append(String.format(TERM_PATTERN, qs[i], termScore, FUZZY_DISTANCE, termScore / 2)); if (i < (qs.length - 1)) { ftQ.append(' '); } } } return QueryUtils.PARAMS_OR_JOINER.join(String.format(NON_TOKENIZED_QUERY,phraseQ), ftQ.toString()); } return QueryUtils.PARAMS_OR_JOINER.join(String.format(NON_TOKENIZED_QUERY, phraseQ), String.format(TERM_PATTERN, q, MAX_SCORE, FUZZY_DISTANCE, MAX_SCORE / 2)); } } // This is a placeholder to map from the JSON definition ID to the query field public static final ImmutableMap<OccurrenceSearchParameter, OccurrenceSolrField> QUERY_FIELD_MAPPING = ImmutableMap.<OccurrenceSearchParameter, OccurrenceSolrField>builder() .put(OccurrenceSearchParameter.DECIMAL_LATITUDE, OccurrenceSolrField.LATITUDE) .put(OccurrenceSearchParameter.DECIMAL_LONGITUDE, OccurrenceSolrField.LONGITUDE) .put(OccurrenceSearchParameter.YEAR, OccurrenceSolrField.YEAR) .put(OccurrenceSearchParameter.MONTH, OccurrenceSolrField.MONTH) .put(OccurrenceSearchParameter.CATALOG_NUMBER, OccurrenceSolrField.CATALOG_NUMBER) .put(OccurrenceSearchParameter.RECORDED_BY, OccurrenceSolrField.RECORDED_BY) .put(OccurrenceSearchParameter.RECORD_NUMBER, OccurrenceSolrField.RECORD_NUMBER) .put(OccurrenceSearchParameter.COLLECTION_CODE, OccurrenceSolrField.COLLECTION_CODE) .put(OccurrenceSearchParameter.INSTITUTION_CODE, OccurrenceSolrField.INSTITUTION_CODE) .put(OccurrenceSearchParameter.DEPTH, OccurrenceSolrField.DEPTH) .put(OccurrenceSearchParameter.ELEVATION, OccurrenceSolrField.ELEVATION) .put(OccurrenceSearchParameter.BASIS_OF_RECORD, OccurrenceSolrField.BASIS_OF_RECORD) .put(OccurrenceSearchParameter.DATASET_KEY, OccurrenceSolrField.DATASET_KEY) .put(OccurrenceSearchParameter.HAS_GEOSPATIAL_ISSUE, OccurrenceSolrField.SPATIAL_ISSUES) .put(OccurrenceSearchParameter.HAS_COORDINATE, OccurrenceSolrField.HAS_COORDINATE) .put(OccurrenceSearchParameter.EVENT_DATE, OccurrenceSolrField.EVENT_DATE) .put(OccurrenceSearchParameter.LAST_INTERPRETED, OccurrenceSolrField.LAST_INTERPRETED) .put(OccurrenceSearchParameter.COUNTRY, OccurrenceSolrField.COUNTRY) .put(OccurrenceSearchParameter.PUBLISHING_COUNTRY, OccurrenceSolrField.PUBLISHING_COUNTRY) .put(OccurrenceSearchParameter.CONTINENT, OccurrenceSolrField.CONTINENT) .put(OccurrenceSearchParameter.TAXON_KEY, OccurrenceSolrField.TAXON_KEY) .put(OccurrenceSearchParameter.TYPE_STATUS, OccurrenceSolrField.TYPE_STATUS) .put(OccurrenceSearchParameter.MEDIA_TYPE, OccurrenceSolrField.MEDIA_TYPE) .put(OccurrenceSearchParameter.ISSUE, OccurrenceSolrField.ISSUE) .put(OccurrenceSearchParameter.OCCURRENCE_ID, OccurrenceSolrField.OCCURRENCE_ID) .put(OccurrenceSearchParameter.ESTABLISHMENT_MEANS, OccurrenceSolrField.ESTABLISHMENT_MEANS) .build(); public static final String GEO_INTERSECTS_QUERY_FMT = "\"IsWithin(%s) distErrPct=0\""; // Solr full text search handle private static final String FULL_TEXT_HANDLER = "/search"; // Holds the value used for an optional sort order applied to a search via param "sort" private final Map<String, SolrQuery.ORDER> sortOrder; // Solr request handler. private final String requestHandler; private final int maxOffset; private final int maxLimit; public static final int MAX_OFFSET = 1000000; public static final int MAX_PAGE_SIZE = 300; /** * Default constructor. */ public OccurrenceSearchRequestBuilder(String requestHandler, Map<String, SolrQuery.ORDER> sortOrder, int maxOffset, int maxLimit) { Preconditions.checkArgument(maxOffset > 0, "Max offset can't less than zero"); Preconditions.checkArgument(maxLimit > 0, "Max limit can't less than zero"); this.requestHandler = requestHandler; this.sortOrder = sortOrder; this.maxOffset = Math.min(maxOffset,MAX_OFFSET); this.maxLimit = Math.min(maxLimit,MAX_PAGE_SIZE); } /** * Parses a geometry parameter in WKT format. * If the parsed geometry is a polygon the produced query will be in INTERSECTS(wkt parameter) format. * If the parsed geometry is a rectangle, the query is transformed into a range query using the southmost and * northmost points. */ protected static String parseGeometryParam(String wkt) { try { Geometry geometry = new WKTReader().read(wkt); if (geometry.isRectangle()) { Envelope bbox = geometry.getEnvelopeInternal(); return String .format(RANGE_FORMAT, bbox.getMinY() + "," + bbox.getMinX(), bbox.getMaxY() + "," + bbox.getMaxX()); } return String.format(GEO_INTERSECTS_QUERY_FMT, geometry.toText()); } catch (ParseException e) { throw new IllegalArgumentException(e); } } public SolrQuery build(@Nullable OccurrenceSearchRequest request) { Preconditions.checkArgument(request.getOffset() <= maxOffset - request.getLimit(), "maximum offset allowed is %s", this.maxOffset); SolrQuery solrQuery = new SolrQuery(); solrQuery.setParam(SOLR_SPELLCHECK, request.isSpellCheck()); if(request.isSpellCheck()){ solrQuery.setParam(SOLR_SPELLCHECK_COUNT, request.getSpellCheckCount() < 0 ? DEFAULT_SPELL_CHECK_COUNT.toString() : Integer.toString(request.getSpellCheckCount())); } // q param if(Strings.isNullOrEmpty(request.getQ())) { solrQuery.setQuery(DEFAULT_QUERY); solrQuery.setParam(SOLR_SPELLCHECK, Boolean.FALSE); // sorting is set only when the q parameter is empty, otherwise the score value es used setSortOrder(solrQuery, sortOrder); } else { OccurrenceFullTextQueryBuilder occurrenceFullTextQueryBuilder = new OccurrenceFullTextQueryBuilder(); occurrenceFullTextQueryBuilder.withQ(request.getQ()); solrQuery.setQuery(occurrenceFullTextQueryBuilder.build()); solrQuery.setParam(SOLR_SPELLCHECK_Q,request.getQ()); } solrQuery.setRequestHandler(FULL_TEXT_HANDLER); // paging setQueryPaging(request, solrQuery, maxLimit); // sets the filters setFilterParameters(request, solrQuery); // set the request handler setRequestHandler(solrQuery, requestHandler); return solrQuery; } /** * Adds an occurrence date parameter: DATE or MODIFIED. */ private static void addDateQuery(Multimap<OccurrenceSearchParameter, String> params, OccurrenceSearchParameter dateParam, OccurrenceSolrField solrField, List<String> filterQueries) { if (params.containsKey(dateParam)) { Collection<String> dateParams = new ArrayList<String>(); for (String value : params.get(dateParam)) { dateParams.add(PARAMS_JOINER.join(solrField.getFieldName(), toDateQuery(value))); } filterQueries.add(toParenthesesQuery(PARAMS_OR_JOINER.join(dateParams))); } } /** * Add the occurrence bounding box and polygon parameters. * Those 2 parameters are returned in 1 filter expression because both refer to same Solr field: coordinate. */ private static void addLocationQuery(Multimap<OccurrenceSearchParameter,String> params, Collection<String> filterQueries) { if (params.containsKey(OccurrenceSearchParameter.GEOMETRY)) { Collection<String> locationParams = new ArrayList<String>(); for (String value : params.get(OccurrenceSearchParameter.GEOMETRY)) { locationParams .add(PARAMS_JOINER.join(OccurrenceSolrField.COORDINATE.getFieldName(), parseGeometryParam(value))); } filterQueries.add(toParenthesesQuery(PARAMS_OR_JOINER.join(locationParams))); } } /** * Adds the filter query to SolrQuery object. * Creates a conjunction of disjunctions: disjunctions(ORs) are created for the filter applied to the same field; * The those disjunctions are joint in a big conjunction. */ private static void setFilterParameters(OccurrenceSearchRequest request, SolrQuery solrQuery) { Multimap<OccurrenceSearchParameter, String> params = request.getParameters(); if (params != null && !params.isEmpty()) { List<String> filterQueries = Lists.newArrayList(); for (OccurrenceSearchParameter param : params.keySet()) { List<String> aFieldParameters = Lists.newArrayList(); for (String value : params.get(param)) { OccurrenceSolrField solrField = QUERY_FIELD_MAPPING.get(param); if (solrField != null && param.type() != Date.class) { String parsedValue = QueryUtils.parseQueryValue(value); if (QueryUtils.isRangeQuery(parsedValue)) { parsedValue = parsedValue.replace(",", " TO "); } if (Enum.class.isAssignableFrom(param.type())) { // enums are capitalized parsedValue = parsedValue.toUpperCase(); } aFieldParameters.add(PARAMS_JOINER.join(solrField.getFieldName(), parsedValue)); } } if (!aFieldParameters.isEmpty()) { filterQueries.add(toParenthesesQuery(PARAMS_OR_JOINER.join(aFieldParameters))); } } addLocationQuery(params, filterQueries); addDateQuery(params, OccurrenceSearchParameter.EVENT_DATE, OccurrenceSolrField.EVENT_DATE, filterQueries); addDateQuery(params, OccurrenceSearchParameter.LAST_INTERPRETED, OccurrenceSolrField.LAST_INTERPRETED, filterQueries); if (!filterQueries.isEmpty()) { solrQuery.addFilterQuery(PARAMS_AND_JOINER.join(filterQueries)); } } } }
package org.opencb.opencga.storage.variant; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.mongodb.*; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import org.apache.commons.lang.mutable.MutableInt; import org.apache.hadoop.hbase.MasterNotRunningException; import org.apache.hadoop.hbase.ZooKeeperConnectionException; import org.opencb.commons.bioformats.feature.Region; import org.opencb.commons.bioformats.variant.Variant; import org.opencb.commons.bioformats.variant.json.VariantAnalysisInfo; import org.opencb.commons.bioformats.variant.json.VariantInfo; import org.opencb.commons.bioformats.variant.utils.effect.VariantEffect; import org.opencb.commons.bioformats.variant.utils.stats.VariantStats; import org.opencb.commons.containers.QueryResult; import org.opencb.commons.containers.map.QueryOptions; import org.opencb.opencga.lib.auth.MongoCredentials; import java.io.IOException; import java.net.UnknownHostException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Alejandro Aleman Ramos <aaleman@cipf.es> */ public class VariantMongoQueryBuilder implements VariantQueryBuilder { private final MongoClient mongoClient; private final DB db; public VariantMongoQueryBuilder(MongoCredentials credentials) throws MasterNotRunningException, ZooKeeperConnectionException, UnknownHostException { // Mongo configuration mongoClient = new MongoClient(credentials.getMongoHost()); db = mongoClient.getDB(credentials.getMongoDbName()); } @Override public QueryResult getAllVariantsByRegion(Region region, String studyName, QueryOptions options) { Long start, end, dbstart, dbend; start = System.currentTimeMillis(); QueryResult<DBObject> queryResult = new QueryResult<>( String.format("%s:%d-%d", region.getChromosome(), region.getStart(), region.getEnd())); List<DBObject> results = new LinkedList<>(); boolean includeSamples; boolean includeStats; boolean includeEffects; if (!options.containsKey("samples") && !options.containsKey("stats") && !options.containsKey("effects")) { includeSamples = true; includeStats = true; includeEffects = true; } else { includeSamples = options.containsKey("samples") && options.getBoolean("samples"); includeStats = options.containsKey("stats") && options.getBoolean("stats"); includeEffects = options.containsKey("effects") && options.getBoolean("effects"); } String startRow = buildRowkey(region.getChromosome(), Long.toString(region.getStart())); String stopRow = buildRowkey(region.getChromosome(), Long.toString(region.getEnd())); // HTable table = new HTable(admin.getConfiguration(), tableName); dbstart = System.currentTimeMillis(); // Scan regionScan = new Scan(startRow.getBytes(), stopRow.getBytes()); // ResultScanner scanres = table.getScanner(regionScan); dbend = System.currentTimeMillis(); queryResult.setDbTime(dbend - dbstart); DBCollection coll = db.getCollection("variants"); // Iterate over results and, optionally, their samples and statistics DBObject query = new BasicDBObject(); DBObject match = new BasicDBObject("sources.sourceId", studyName); query.put("$match", match); DBObject unwind = new BasicDBObject("$unwind", "$sources"); DBObject match2 = new BasicDBObject("$match", new BasicDBObject("sources.studyId", studyName)); // db.variants.aggregate( // {$match: {'studies.studyId': 'ale'}}, // {$project: {"studies.effects":1,'studies.studyId':1 }}, // {$unwind:'$studies'}, {$match: {'studies.studyId':'ale'}}, // {$project: {effects: '$studies.effects'}}, // {$unwind: '$effects'}, // {$group: {_id:'$effects', count:{$sum:1}}}) System.out.println(query); System.out.println(unwind); System.out.println(match2); AggregationOutput cursor = coll.aggregate(query, unwind, match2); // db.variants.aggregate({ "$match" : { "studies.studyId" : "test9"}}, { "$unwind" : "$studies"} , { "$match" : { "studies.studyId" : "test9"}} ,{$skip: 900}, {$limit: 5}) for (DBObject obj : cursor.results()) { results.add(obj); } end = System.currentTimeMillis(); queryResult.setDbTime(end - dbstart); queryResult.setResult(results); queryResult.setNumResults(results.size()); end = System.currentTimeMillis(); queryResult.setTime(end - start); return queryResult; } @Override public List<QueryResult> getAllVariantsByRegionList(List<Region> regions, String studyName, QueryOptions options) { List<QueryResult> allResults = new LinkedList<>(); for (Region r : regions) { QueryResult queryResult = getAllVariantsByRegion(r, studyName, options); allResults.add(queryResult); } return allResults; } @Override public QueryResult getVariantsHistogramByRegion(Region region, String studyName, boolean histogramLogarithm, int histogramMax) { return null; } @Override public QueryResult getStatsByVariant(Variant variant, QueryOptions options) { return null; } @Override public QueryResult getSimpleStatsByVariant(Variant variant, QueryOptions options) { return null; } @Override public QueryResult getEffectsByVariant(Variant variant, QueryOptions options) { return null; } @Override public List<VariantStats> getRecordsStats(Map<String, String> options) { return null; } @Override public List<VariantEffect> getEffect(Map<String, String> options) { return null; } @Override public VariantAnalysisInfo getAnalysisInfo(Map<String, String> options) { return null; } @Override public boolean close() { mongoClient.close(); return true; } private String buildRowkey(String chromosome, String position) { return chromosome + "_" + position; } @Override public List<VariantInfo> getRecords(Map<String, String> options) { return null; } public QueryResult<VariantInfo> getRecordsMongo(int page, int start, int limit, MutableInt count, Map<String, String> options) { long startTime = System.currentTimeMillis(); QueryResult<VariantInfo> queryResult = new QueryResult<>(); List<VariantInfo> res = new ArrayList<>(); String sourceId = options.get("studyId"); DBCollection coll = db.getCollection("variants"); DBObject elemMatch = new BasicDBObject("sourceId", sourceId); DBObject query = new BasicDBObject(); BasicDBList orList = new BasicDBList(); Map<String, List<String>> sampleGenotypes = processSamplesGT(options); System.out.println("map = " + options); if (options.containsKey("region_list") && !options.get("region_list").equals("")) { String[] regions = options.get("region_list").split(","); Pattern pattern = Pattern.compile("(\\w+):(\\d+)-(\\d+)"); Matcher matcher, matcherChr; for (int i = 0; i < regions.length; i++) { String region = regions[i]; matcher = pattern.matcher(region); if (matcher.find()) { String chr = matcher.group(1); int s = Integer.valueOf(matcher.group(2)); int e = Integer.valueOf(matcher.group(3)); DBObject regionClause = new BasicDBObject("chr", chr); regionClause.put("pos", new BasicDBObject("$gte", s).append("$lte", e)); orList.add(regionClause); } else { Pattern patternChr = Pattern.compile("(\\w+)"); matcherChr = patternChr.matcher(region); if (matcherChr.find()) { String chr = matcherChr.group(); DBObject regionClause = new BasicDBObject("chr", chr); orList.add(regionClause); } } } query.put("$or", orList); } else if (options.containsKey("genes") && !options.get("genes").equals("")) { orList = processGeneList(options.get("genes")); if (orList.size() > 0) { query.put("$or", orList); } else { queryResult.setWarningMsg("Wrong gene name"); queryResult.setResult(res); queryResult.setNumResults(res.size()); return queryResult; } } if (options.containsKey("conseq_type") && !options.get("conseq_type").equals("")) { String[] cts = options.get("conseq_type").split(","); BasicDBList ctList = new BasicDBList(); for (String ct : cts) { ctList.add(ct); } elemMatch.put("effects", new BasicDBObject("$in", ctList)); } if (sampleGenotypes.size() > 0) { for (Map.Entry<String, List<String>> entry : sampleGenotypes.entrySet()) { BasicDBList gtList = new BasicDBList(); for (String gt : entry.getValue()) { gtList.add(gt); } elemMatch.put("samples." + entry.getKey() + ".GT", new BasicDBObject("$in", gtList)); } } if (options.containsKey("miss_gt") && !options.get("miss_gt").equalsIgnoreCase("")) { Integer val = Integer.valueOf(options.get("miss_gt")); Object missGt = getMongoOption(options.get("option_miss_gt"), val); elemMatch.put("stats.missGenotypes", missGt); } if (options.containsKey("maf_1000g_controls") && !options.get("maf_1000g_controls").equalsIgnoreCase("")) { elemMatch.put("attributes.1000G_maf", new BasicDBObject("$lte", options.get("maf_1000g_controls"))); } if (options.containsKey("maf_evs_controls") && !options.get("maf_evs_controls").equalsIgnoreCase("")) { elemMatch.put("attributes.EVS_maf", new BasicDBObject("$lte", options.get("maf_evs_controls"))); } if (options.containsKey("maf_bier_controls") && !options.get("maf_bier_controls").equalsIgnoreCase("")) { elemMatch.put("attributes.BIER_maf", new BasicDBObject("$lte", options.get("maf_bier_controls"))); } query.put("sources", new BasicDBObject("$elemMatch", elemMatch)); System.out.println(" System.out.println(query); System.out.println(" long dbStart = System.currentTimeMillis(); DBObject sort = null; DBCursor cursor; if (options.containsKey("sort")) { sort = getQuerySort(options.get("sort")); System.out.println(sort); cursor = coll.find(query).sort(sort).skip(start).limit(limit); } else { cursor = coll.find(query).skip(start).limit(limit); } count.setValue(cursor.count()); queryResult.setDbTime(dbStart - System.currentTimeMillis()); for (DBObject obj : cursor) { BasicDBObject elem = (BasicDBObject) obj; VariantInfo vi = new VariantInfo(); VariantStats vs = new VariantStats(); String chr = elem.getString("chr"); int pos = elem.getInt("pos"); vi.setChromosome(chr); vi.setPosition(pos); BasicDBList studies = (BasicDBList) elem.get("sources"); Iterator<Object> it = studies.iterator(); while (it.hasNext()) { BasicDBObject study = (BasicDBObject) it.next(); if (study.getString("sourceId").equalsIgnoreCase(sourceId)) { BasicDBObject stats = (BasicDBObject) study.get("stats"); String ref = study.getString("ref"); BasicDBList alt = (BasicDBList) study.get("alt"); vi.setRef(ref); vi.setAlt(Joiner.on(",").join(alt.toArray())); vs.setMaf((float) stats.getDouble("maf")); vs.setMgf((float) stats.getDouble("mgf")); vs.setMafAllele(stats.getString("alleleMaf")); vs.setMgfAllele(stats.getString("genotypeMaf")); vs.setMissingAlleles(stats.getInt("missAllele")); vs.setMissingGenotypes(stats.getInt("missGenotypes")); vs.setMendelinanErrors(stats.getInt("mendelErr")); vs.setCasesPercentDominant((float) stats.getDouble("casesPercentDominant")); vs.setControlsPercentDominant((float) stats.getDouble("controlsPercentDominant")); vs.setCasesPercentRecessive((float) stats.getDouble("casesPercentRecessive")); vs.setControlsPercentRecessive((float) stats.getDouble("controlsPercentRecessive")); BasicDBObject samples = (BasicDBObject) study.get("samples"); for (String sampleName : samples.keySet()) { DBObject sample = (DBObject) samples.get(sampleName); if (sample.containsField("GT")) { String sampleGT = (String) sample.get("GT"); vi.addSammpleGenotype(sampleName, sampleGT); } } vi.setSnpid((String) study.get("snpId")); if (study.containsField("effects")) { BasicDBList conseqTypes = (BasicDBList) study.get("effects"); conseqTypes.remove(""); String cts = Joiner.on(",").join(conseqTypes.iterator()); vi.addConsequenceTypes(cts); } if (study.containsField("genes")) { BasicDBList genesList = (BasicDBList) study.get("genes"); String genes = Joiner.on(",").join(genesList.iterator()); vi.addGenes(genes); } if (study.containsField("attributes")) { BasicDBObject attr = (BasicDBObject) study.get("attributes"); if (attr.containsField("1000G_maf")) { vi.addControl("1000G_maf", (String) attr.get("1000G_maf")); vi.addControl("1000G_amaf", (String) attr.get("1000G_amaf")); vi.addControl("1000G_gt", (String) attr.get("1000G_gt")); } if (attr.containsField("EVS_maf")) { vi.addControl("EVS_maf", (String) attr.get("EVS_maf")); vi.addControl("EVS_amaf", (String) attr.get("EVS_amaf")); vi.addControl("EVS_gt", (String) attr.get("EVS_gt")); } if (attr.containsField("BIER_maf")) { vi.addControl("BIER_maf", (String) attr.get("BIER_maf")); vi.addControl("BIER_amaf", (String) attr.get("BIER_amaf")); vi.addControl("BIER_gt", (String) attr.get("BIER_gt")); } } continue; } } vi.addStats(vs); res.add(vi); } queryResult.setResult(res); queryResult.setTime(startTime - System.currentTimeMillis()); return queryResult; } private DBObject getQuerySort(String sort) { DBObject res = new BasicDBObject(); // sort=[{"property":"stats_id_snp","direction":"ASC"}], // Pattern pattern = Pattern.compile("(\\w+):(\\d+)-(\\d+)"); Pattern pattern = Pattern.compile("\"property\":\"(\\w+)\",\"direction\":\"(ASC|DESC)\""); Matcher matcher = pattern.matcher(sort); if (matcher.find()) { String field = matcher.group(1); String direction = matcher.group(2); int dir = 1; if (direction.equalsIgnoreCase("ASC")) { dir = 1; } else if (direction.equalsIgnoreCase("DESC")) { dir = -1; } switch (field) { case "chromosome": res.put("chr", dir); res.put("pos", dir); break; case "snpid": res.put("sources.snpId", dir); break; case "consecuente_types": res.put("sources.effects", dir); break; case "genes": res.put("sources.genes.1", dir); break; } } return res; } private Object getMongoOption(String option, float val) { Object res = null; switch (option) { case ("<"): res = new BasicDBObject("$lt", val); break; case ("<="): res = new BasicDBObject("$lte", val); break; case (">"): res = new BasicDBObject("$gt", val); break; case (">="): res = new BasicDBObject("$gte", val); break; case ("="): res = val; break; case ("!="): res = new BasicDBObject("$ne", val); break; } return res; } private BasicDBList processGeneList(String genes) { BasicDBList list = new BasicDBList(); Client wsRestClient = Client.create(); WebResource webResource = wsRestClient.resource("http://ws.bioinfo.cipf.es/cellbase/rest/latest/hsa/feature/gene/"); ObjectMapper mapper = new ObjectMapper(); String response = webResource.path(genes).path("info").queryParam("of", "json").get(String.class); try { JsonNode actualObj = mapper.readTree(response); Iterator<JsonNode> it = actualObj.iterator(); Iterator<JsonNode> aux; while (it.hasNext()) { JsonNode node = it.next(); if (node.isArray()) { aux = node.iterator(); while (aux.hasNext()) { JsonNode auxNode = aux.next(); DBObject regionClause = new BasicDBObject("chr", auxNode.get("chromosome").asText()); regionClause.put("pos", new BasicDBObject("$gte", auxNode.get("start").asInt()).append("$lte", auxNode.get("end").asInt())); list.add(regionClause); } } } } catch (IOException e) { e.printStackTrace(); } return list; } private Map<String, List<String>> processSamplesGT(Map<String, String> options) { Map<String, List<String>> samplesGenotypes = new LinkedHashMap<>(10); List<String> genotypesList; String key, val; for (Map.Entry<String, String> entry : options.entrySet()) { key = entry.getKey(); val = entry.getValue(); if (key.startsWith("sampleGT_")) { String sampleName = key.replace("sampleGT_", "").replace("[]", ""); String[] genotypes = val.split(","); if (samplesGenotypes.containsKey(sampleName)) { genotypesList = samplesGenotypes.get(sampleName); } else { genotypesList = new ArrayList<>(); samplesGenotypes.put(sampleName, genotypesList); } for (int i = 0; i < genotypes.length; i++) { genotypesList.add(genotypes[i]); } } } return samplesGenotypes; } public QueryResult<VariantAnalysisInfo> getAnalysisInfo(String studyId) { long start = System.currentTimeMillis(); QueryResult<VariantAnalysisInfo> qres = new QueryResult<>(); VariantAnalysisInfo vi = new VariantAnalysisInfo(); DBCollection coll = db.getCollection("sources"); DBCollection collV = db.getCollection("variants"); long dbStart = System.currentTimeMillis(); DBObject study = coll.findOne(new BasicDBObject("alias", studyId)); if (study != null) { Iterator<Object> it = ((BasicDBList) study.get("samples")).iterator(); while (it.hasNext()) { vi.addSample((String) it.next()); } BasicDBObject gs = (BasicDBObject) study.get("globalStats"); for (String elem : gs.keySet()) { if (!elem.equalsIgnoreCase("consequenceTypes")) { double val = gs.getDouble(elem); vi.addGlobalStats(elem, val); } else { BasicDBObject cts = (BasicDBObject) gs.get("consequenceTypes"); for (String ct : cts.keySet()) { vi.addConsequenceType(ct, cts.getInt(ct)); } } } } qres.setDbTime(System.currentTimeMillis() - dbStart); qres.setResult(Arrays.asList(vi)); qres.setTime(System.currentTimeMillis() - start); return qres; } }
package org.apache.maven.plugin; import org.codehaus.plexus.compiler.Compiler; import org.codehaus.plexus.compiler.CompilerError; import java.io.File; import java.util.Iterator; import java.util.List; import java.util.Map; /** * @plugin.id compiler * @plugin.description A maven2 plugin which integrates the use of Maven2 with IntelliJ's IDEA * * @parameter <name> <type> <required> <validatator> <description> * * This may be on a per method basis * @parameter sourceDirectories String[] required validator * @parameter outputDirectory String required validator * @parameter classpathElements String[] required validator * @parameter compiler String required validator * * The goal would map to a method if multiple methods were allowed * @goal.name idea * @goal.idea.parameter project #project * * There could be threadsafe and non threadsafe versions of a compiler * plugin. The case where you instantiate a compiler plugin that maintains * a reference to an incremental compiler. * * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> * @version $Id$ * @todo make a plugin for each plugin type so that they are not all globbed in here * this will remove the magic plexus does with Map requirements which will make * reuse outside of the maven/plexus context easier * @todo use compile source roots and not the pom.build.sourceDirectory so that any * sort of preprocessing and/or source generation can be taken into consideration. */ public class CompilerPlugin extends AbstractPlugin { private Map compilers; private boolean debug = false; public void execute( PluginExecutionRequest request, PluginExecutionResponse response ) throws Exception { String sourceDirectory = (String) request.getParameter( "sourceDirectory" ); String outputDirectory = (String) request.getParameter( "outputDirectory" ); String[] classpathElements = (String[]) request.getParameter( "classpathElements" ); String compilerId = (String) request.getParameter( "compiler" ); if ( ! new File( sourceDirectory ).exists() ) { return; } Compiler compiler = (Compiler) compilers.get( compilerId ); List messages = compiler.compile( classpathElements, new String[]{sourceDirectory}, outputDirectory ); if ( debug ) { for ( int i = 0; i < classpathElements.length; i++ ) { String message; if ( new File( classpathElements[i] ).exists() ) { message = "present in repository."; } else { message = "Warning! not present in repository!"; } System.out.println( "classpathElements[ "+ i +" ] = " + classpathElements[i] + ": " + message ); } } boolean compilationError = false; for ( Iterator i = messages.iterator(); i.hasNext(); ) { CompilerError message = (CompilerError) i.next(); if ( message.isError() ) { compilationError = true; } System.out.println( message.getMessage() ); } if ( compilationError ) { throw new Exception( "Compilation failure!" ); } } }
package com.gl.order.frontend.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.gl.order.common.dict.MessageType; import com.gl.order.frontend.exception.OrderException; import com.gl.order.frontend.helper.SimpleOrderControllerHelper; import com.gl.order.frontend.msg.SimpleOrderReq; import com.gl.order.frontend.msg.SimpleOrderResp; import com.gl.order.frontend.pojo.SimpleOrder; import com.gl.order.frontend.service.SimpleOrderService; @RestController public class SimpleOrderController { private static final Logger log = LoggerFactory.getLogger(SimpleOrderController.class); @Autowired private SimpleOrderService simpleOrderService; @Autowired private SimpleOrderControllerHelper helper; @PostMapping(path = "/simpleorders") public SimpleOrderResp createOrder(@RequestBody SimpleOrderReq req) { log.info(String.format("<<< RECV:%s", req)); SimpleOrderResp resp = null; resp = processCreateOrder(req); log.info(String.format(">>> SEND:%s", resp)); return resp; } @PostMapping(path = "/heartbeats") public SimpleOrderResp heartbeat(@RequestBody SimpleOrderReq req) { log.info(String.format("<<< HeartBeat RECV:%s", req)); SimpleOrderResp resp = null; if (req.getMessageType() == MessageType.HeartBeatReq.ordinal()) { resp = processHeartBeatOrder(req); } log.info(String.format(">>> HeartBeat SEND:%s", resp)); return resp; } protected SimpleOrderResp processCreateOrder(SimpleOrderReq req) { log.info("*********** create order st *********"); SimpleOrder orderReq = req.getOrder(); SimpleOrderResp resp = null; try { log.info(String.format("before created : %s", req)); SimpleOrder orderRet = simpleOrderService.order(orderReq); log.info(String.format("after created : %s", orderRet)); resp = helper.buildResp(orderRet); } catch (OrderException e) { log.error("", e); resp = helper.buildAbnormalResp(orderReq, e); } log.info("*********** create order ed *********"); return resp; } protected SimpleOrderResp processHeartBeatOrder(SimpleOrderReq req) { SimpleOrderResp resp = helper.buildHeartBeatResp(req); return resp; } }
package ua.com.fielden.platform.dao; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.expr; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select; import java.lang.reflect.Field; import java.util.Iterator; import java.util.List; import java.util.Set; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.AbstractUnionEntity; import ua.com.fielden.platform.entity.DynamicEntityKey; import ua.com.fielden.platform.entity.annotation.Calculated; import ua.com.fielden.platform.entity.meta.PropertyDescriptor; import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.ICaseWhenFunctionWhen; import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.IStandAloneExprOperationAndClose; import ua.com.fielden.platform.entity.query.model.ExpressionModel; import ua.com.fielden.platform.entity.query.model.PrimitiveResultQueryModel; import ua.com.fielden.platform.expression.ExpressionText2ModelConverter; import ua.com.fielden.platform.reflection.AnnotationReflector; import ua.com.fielden.platform.reflection.Finder; import ua.com.fielden.platform.reflection.Reflector; import ua.com.fielden.platform.utils.EntityUtils; import ua.com.fielden.platform.utils.Pair; public class DomainMetadataExpressionsGenerator { ExpressionModel generateUnionEntityPropertyExpression(final Class<? extends AbstractUnionEntity> entityType, final String commonPropName) { final List<Field> props = AbstractUnionEntity.unionProperties(entityType); final Iterator<Field> iterator = props.iterator(); final String firstUnionPropName = iterator.next().getName(); ICaseWhenFunctionWhen<IStandAloneExprOperationAndClose, AbstractEntity<?>> expressionModelInProgress = expr().caseWhen().prop(firstUnionPropName).isNotNull().then().prop(firstUnionPropName + "." + commonPropName); for (; iterator.hasNext();) { final String unionPropName = iterator.next().getName(); expressionModelInProgress = expressionModelInProgress.when().prop(unionPropName).isNotNull().then().prop(unionPropName + "." + commonPropName); } return expressionModelInProgress.otherwise().val(null).end().model(); } // ExpressionModel getVirtualKeyPropForEntityWithCompositeKey(final Class<? extends AbstractEntity<DynamicEntityKey>> entityType, final List<Pair<Field, Boolean>> keyMembers) { // final Iterator<Pair<Field, Boolean>> iterator = keyMembers.iterator(); // final Pair<Field, Boolean> firstMember = iterator.next(); // IConcatFunctionWith<IStandAloneExprOperationAndClose, AbstractEntity<?>> expressionModelInProgress = firstMember.getValue() ? // // expr().concat().prop(getKeyMemberConcatenationExpression(firstMember.getKey())) // expr().concat().prop(getKeyMemberConcatenationExpression(firstMember.getKey())); // for (; iterator.hasNext();) { // expressionModelInProgress = expressionModelInProgress.with().val(Reflector.getKeyMemberSeparator(entityType)); // expressionModelInProgress = expressionModelInProgress.with().prop(getKeyMemberConcatenationExpression(iterator.next().getKey())); // return expressionModelInProgress.end().model(); ExpressionModel getVirtualKeyPropForEntityWithCompositeKey(final Class<? extends AbstractEntity<DynamicEntityKey>> entityType, final List<Pair<Field, Boolean>> keyMembers) { return composeExpression(keyMembers, Reflector.getKeyMemberSeparator(entityType)); } private String getKeyMemberConcatenationExpression(final Field keyMember) { if (PropertyDescriptor.class != keyMember.getType() && EntityUtils.isEntityType(keyMember.getType())) { return keyMember.getName() + ".key"; } else { return keyMember.getName(); } } private ExpressionModel composeExpression(final List<Pair<Field, Boolean>> original, final String separator) { ExpressionModel currExp = null; Boolean currExpIsOptional = null; for (final Pair<Field, Boolean> originalField : original) { currExp = composeTwo(new Pair<ExpressionModel, Boolean>(currExp, currExpIsOptional), originalField, separator); currExpIsOptional = currExpIsOptional != null ? currExpIsOptional && originalField.getValue() : originalField.getValue(); } return currExp; } private ExpressionModel concatTwo(final ExpressionModel first, final String secondPropName, final String separator) { return expr().concat().expr(first).with().val(separator).with().prop(secondPropName).end().model(); } private ExpressionModel composeTwo(final Pair<ExpressionModel, Boolean> first, final Pair<Field, Boolean> second, final String separator) { final ExpressionModel firstModel = first.getKey(); final Boolean firstIsOptional = first.getValue(); final String secondPropName = getKeyMemberConcatenationExpression(second.getKey()); final boolean secondPropIsOptional = second.getValue(); if (first.getKey() == null) { return expr().prop(secondPropName).model(); } else { if (firstIsOptional) { if (secondPropIsOptional) { return expr().caseWhen().expr(firstModel).isNotNull().and().prop(secondPropName).isNotNull().then().expr(concatTwo(firstModel, secondPropName, separator)). when().expr(firstModel).isNotNull().and().prop(secondPropName).isNull().then().expr(firstModel). when().prop(secondPropName).isNotNull().then().prop(secondPropName). otherwise().val(null).endAsStr(256).model(); } else { return expr().caseWhen().expr(firstModel).isNotNull().then().expr(concatTwo(firstModel, secondPropName, separator)). otherwise().prop(secondPropName).endAsStr(256).model(); } } else { if (secondPropIsOptional) { return expr().caseWhen().prop(secondPropName).isNotNull().then().expr(concatTwo(firstModel, secondPropName, separator)). otherwise().expr(firstModel).endAsStr(256).model(); } else { return concatTwo(firstModel, secondPropName, separator); } } } } ExpressionModel extractExpressionModelFromCalculatedProperty(final Class<? extends AbstractEntity<?>> entityType, final Field calculatedPropfield) throws Exception { final Calculated calcAnnotation = AnnotationReflector.getAnnotation(calculatedPropfield, Calculated.class); if (!"".equals(calcAnnotation.value())) { return createExpressionText2ModelConverter(entityType, calcAnnotation).convert().getModel(); } else { try { final Field exprField = Finder.getFieldByName(entityType, calculatedPropfield.getName() + "_"); exprField.setAccessible(true); return (ExpressionModel) exprField.get(null); } catch (final Exception e) { throw new IllegalStateException("Hard-coded expression model for prop [" + calculatedPropfield.getName() + "] is missing! } } } private ExpressionText2ModelConverter createExpressionText2ModelConverter(final Class<? extends AbstractEntity<?>> entityType, final Calculated calcAnnotation) throws Exception { if (AnnotationReflector.isContextual(calcAnnotation)) { return new ExpressionText2ModelConverter(getRootType(calcAnnotation), calcAnnotation.contextPath(), calcAnnotation.value()); } else { return new ExpressionText2ModelConverter(entityType, calcAnnotation.value()); } } public Class<? extends AbstractEntity<?>> getRootType(final Calculated calcAnnotation) throws ClassNotFoundException { return (Class<? extends AbstractEntity<?>>) ClassLoader.getSystemClassLoader().loadClass(calcAnnotation.rootTypeName()); } private PrimitiveResultQueryModel getReferenceCountForSingleProp(final Class<? extends AbstractEntity<?>> entityType, final String propName) { return select(entityType).where().prop(propName).eq().extProp("id").yield().countAll().modelAsPrimitive(); } ExpressionModel getReferencesCountPropForEntity(final Set<Pair<Class<? extends AbstractEntity<?>>, String>> references) { if (references.size() == 0) { return expr().val(0).model(); } final Iterator<Pair<Class<? extends AbstractEntity<?>>, String>> iterator = references.iterator(); final Pair<Class<? extends AbstractEntity<?>>, String> firstEntry = iterator.next(); IStandAloneExprOperationAndClose expressionModelInProgress = expr().model(getReferenceCountForSingleProp(firstEntry.getKey(), firstEntry.getValue())); for (; iterator.hasNext();) { final Pair<Class<? extends AbstractEntity<?>>, String> entry = iterator.next(); expressionModelInProgress = expressionModelInProgress.add().model(getReferenceCountForSingleProp(entry.getKey(), entry.getValue())); } return expressionModelInProgress.model(); } }
package com.intellij.openapi.application.impl; import com.intellij.concurrency.Job; import com.intellij.concurrency.JobLauncher; import com.intellij.concurrency.JobSchedulerImpl; import com.intellij.diagnostic.ThreadDumper; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.*; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.application.ex.ApplicationUtil; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.progress.impl.ProgressManagerImpl; import com.intellij.openapi.progress.util.ProgressIndicatorBase; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.testFramework.CpuUsageData; import com.intellij.testFramework.LightPlatformTestCase; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.testFramework.RunFirst; import com.intellij.util.*; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.junit.Assert; import javax.swing.*; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import static com.intellij.util.TestTimeOut.setTimeout; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.core.IsNot.not; @RunFirst public class ApplicationImplTest extends LightPlatformTestCase { private TestTimeOut t; @Override protected void setUp() throws Exception { super.setUp(); exception = null; t = setTimeout(2, TimeUnit.MINUTES); } @Override protected void tearDown() throws Exception { readThreads = null; exception = null; super.tearDown(); } private volatile Throwable exception; public void testAcquireReadActionLockVsRunReadActionPerformance() throws Throwable { final int N = 100_000_000; final Application application = ApplicationManager.getApplication(); String err = null; for (int i=0; i<4; i++) { Callable<String> runnable = () -> { try { assertFalse(application.isReadAccessAllowed()); CpuUsageData dataAcq = CpuUsageData.measureCpuUsage(() -> { for (int i1 = 0; i1 < N; i1++) { AccessToken token = application.acquireReadActionLock(); //noinspection EmptyTryBlock try { // do it } finally { token.finish(); } } }); CpuUsageData dataRun = CpuUsageData.measureCpuUsage(() -> { for (int i1 = 0; i1 < N; i1++) { application.runReadAction(() -> { }); } }); long l1 = dataRun.durationMs; long l2 = dataAcq.durationMs; assertFalse(application.isReadAccessAllowed()); int ratioPercent = (int)((l1 - l2) * 100.0 / l1); String msg = "acquireReadActionLock(" + l2 + "ms) vs runReadAction(" + l1 + "ms). Ratio: " + ratioPercent + "% (in "+(ratioPercent<0 ? "my" : "Maxim's") +" favor)"; LOG.debug(msg + "\nAcquire:\n" + dataAcq.getSummary(" ") + "\nRun:\n" + dataRun.getSummary(" ")); if (Math.abs(ratioPercent) > 40) { return "Suspiciously different times for " + msg; } } catch (Throwable e) { exception = e; } return null; }; err = application.executeOnPooledThread(runnable).get(); if (err == null) break; System.err.println("Still trying, attempt "+i+": "+err); System.gc(); } assertNull(err); if (exception != null) throw exception; } public void testRead50Write50LockPerformance() { runReadWrites(600_000, 600_000, 2000); } public void testRead100Write0LockPerformance() { runReadWrites(60_000_000, 0, 10_000); } private static void runReadWrites(final int readIterations, final int writeIterations, int expectedMs) { NonBlockingReadActionImpl.waitForAsyncTaskCompletion(); // someone might've submitted a task depending on app events which we disable now final ApplicationImpl application = (ApplicationImpl)ApplicationManager.getApplication(); Disposable disposable = Disposer.newDisposable(); application.disableEventsUntil(disposable); application.assertIsDispatchThread(); try { PlatformTestUtil.startPerformanceTest("lock/unlock", expectedMs, () -> { final int numOfThreads = JobSchedulerImpl.getJobPoolParallelism(); List<Job<Void>> threads = new ArrayList<>(numOfThreads); for (int i = 0; i < numOfThreads; i++) { Job<Void> thread = JobLauncher.getInstance().submitToJobThread(() -> { assertFalse(application.isReadAccessAllowed()); for (int i1 = 0; i1 < readIterations; i1++) { application.runReadAction(() -> { }); } }, null); threads.add(thread); } if (writeIterations > 0) { for (int i = 0; i < writeIterations; i++) { ApplicationManager.getApplication().runWriteAction(() -> { }); } } waitWithTimeout(threads); }).assertTiming(); } finally { Disposer.dispose(disposable); } } private static void joinWithTimeout(Future<?>... threads) throws TimeoutException { for (Future<?> thread : threads) { try { thread.get(20, TimeUnit.SECONDS); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } if (!thread.isDone()) { System.err.println(thread + " is still running. threaddump:\n" + ThreadDumper.dumpThreadsToString()); throw new TimeoutException(); } } } private static void waitWithTimeout(List<? extends Job<?>> threads) throws TimeoutException { for (Job<?> thread : threads) { try { thread.waitForCompletion(20_000); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } if (!thread.isDone()) { System.err.println(thread + " is still running. threaddump:\n" + ThreadDumper.dumpThreadsToString()); throw new TimeoutException(); } } } private void checkTimeout() throws Throwable { if (exception != null) throw exception; if (t.timedOut()) throw new TimeoutException("timeout"); } public void testAppLockReadWritePreference() throws Throwable { ApplicationImpl application = (ApplicationImpl)ApplicationManager.getApplication(); application.assertIsDispatchThread(); assertFalse(application.isWriteAccessAllowed()); assertFalse(application.isWriteActionPending()); // take read lock1. // try to take write lock - must wait (because of taken read lock) // try to take read lock2 - must wait (because of write preference - write lock is pending) // release read lock1 - write lock must be taken first // release write - read lock2 must be taken LOG.debug(" AtomicBoolean holdRead1 = new AtomicBoolean(true); AtomicBoolean holdWrite = new AtomicBoolean(true); AtomicBoolean read1Acquired = new AtomicBoolean(false); AtomicBoolean read1Released = new AtomicBoolean(false); AtomicBoolean read2Acquired = new AtomicBoolean(false); AtomicBoolean read2Released = new AtomicBoolean(false); AtomicBoolean writeAcquired = new AtomicBoolean(false); AtomicBoolean writeReleased = new AtomicBoolean(false); Future<?> readAction1 = ApplicationManager.getApplication().executeOnPooledThread(() -> { try { assertFalse(application.isDispatchThread()); AccessToken stamp = application.acquireReadActionLock(); try { LOG.debug("read lock1 acquired"); read1Acquired.set(true); while (holdRead1.get()) checkTimeout(); } finally { read1Released.set(true); stamp.finish(); LOG.debug("read lock1 released"); } } catch (Throwable e) { exception = e; throw new RuntimeException(e); } }); while (!read1Acquired.get()) checkTimeout(); AtomicBoolean aboutToAcquireWrite = new AtomicBoolean(); // readActions2 should try to acquire read action when write action is pending Future<?> readActions2 = ApplicationManager.getApplication().executeOnPooledThread(() -> { try { assertFalse(application.isDispatchThread()); while (!aboutToAcquireWrite.get()) checkTimeout(); // make sure EDT called writelock while (!application.myLock.writeRequested) checkTimeout(); assertTrue(application.isWriteActionPending()); //assertFalse(application.tryRunReadAction(EmptyRunnable.getInstance())); AccessToken stamp = application.acquireReadActionLock(); assertFalse(application.isWriteActionPending()); try { LOG.debug("read lock2 acquired"); read2Acquired.set(true); } finally { read2Released.set(true); stamp.finish(); LOG.debug("read lock2 released"); } } catch (Throwable e) { exception = e; throw new RuntimeException(e); } }); Future<?> checkThread = ApplicationManager.getApplication().executeOnPooledThread(()->{ try { assertFalse(application.isDispatchThread()); while (!aboutToAcquireWrite.get()) checkTimeout(); while (!read1Acquired.get()) checkTimeout(); // make sure EDT called writelock while (!application.myLock.writeRequested) checkTimeout(); TestTimeOut c = setTimeout(100, TimeUnit.MILLISECONDS); while (!c.timedOut()) { checkTimeout(); assertTrue(aboutToAcquireWrite.get()); assertTrue(read1Acquired.get()); assertFalse(read1Released.get()); assertFalse(read2Acquired.get()); assertFalse(read2Released.get()); assertFalse(writeAcquired.get()); assertFalse(writeReleased.get()); assertFalse(application.tryRunReadAction(EmptyRunnable.getInstance())); // write pending assertFalse(application.isWriteActionInProgress()); assertFalse(application.isWriteAccessAllowed()); assertTrue(application.isWriteActionPending()); } holdRead1.set(false); while (!writeAcquired.get()) checkTimeout(); c = setTimeout(100, TimeUnit.MILLISECONDS); while (!c.timedOut()) { checkTimeout(); assertTrue(aboutToAcquireWrite.get()); assertTrue(read1Acquired.get()); assertTrue(read1Released.get()); assertFalse(read2Acquired.get()); assertFalse(read2Released.get()); assertTrue(writeAcquired.get()); assertFalse(writeReleased.get()); assertFalse(application.tryRunReadAction(EmptyRunnable.getInstance())); assertTrue(application.isWriteActionInProgress()); assertFalse(application.isWriteAccessAllowed()); assertFalse(application.isWriteActionPending()); } holdWrite.set(false); while (!read2Released.get()) checkTimeout(); c = setTimeout(100, TimeUnit.MILLISECONDS); while (!c.timedOut()) { checkTimeout(); assertTrue(aboutToAcquireWrite.get()); assertTrue(read1Acquired.get()); assertTrue(read1Released.get()); assertTrue(read2Acquired.get()); assertTrue(read2Released.get()); assertTrue(writeAcquired.get()); assertTrue(writeReleased.get()); assertFalse(application.isWriteActionInProgress()); assertFalse(application.isWriteAccessAllowed()); assertFalse(application.isWriteActionPending()); } } catch (Throwable e) { exception = e; throw new RuntimeException(e); } }); aboutToAcquireWrite.set(true); AccessToken stamp = application.acquireWriteActionLock(getClass()); try { LOG.debug("write lock acquired"); writeAcquired.set(true); while (holdWrite.get()) { checkTimeout(); assertTrue(application.isWriteActionInProgress()); assertTrue(application.isWriteAccessAllowed()); assertFalse(application.isWriteActionPending()); } } finally { writeReleased.set(true); stamp.finish(); LOG.debug("write lock released"); } joinWithTimeout(readAction1, readActions2, checkThread); if (exception != null) throw exception; } private volatile boolean tryingToStartWriteAction; private volatile boolean readStarted; private volatile List<Future<?>> readThreads; @SuppressWarnings("StringConcatenationInsideStringBufferAppend") // to prevent tearing public void testReadWontStartWhenWriteIsPending() throws Throwable { int N = 5; final AtomicBoolean[] anotherThreadStarted = new AtomicBoolean[N]; final AtomicBoolean[] anotherReadActionStarted = new AtomicBoolean[N]; for (int i = 0; i < anotherReadActionStarted.length; i++) { anotherReadActionStarted[i] = new AtomicBoolean(); anotherThreadStarted[i] = new AtomicBoolean(); } final StringBuffer LOG = new StringBuffer(); Future<?> main = ApplicationManager.getApplication().executeOnPooledThread(() -> { try { ApplicationManager.getApplication().runReadAction((ThrowableComputable<Object, Throwable>)() -> { LOG.append("inside read action\n"); readStarted = true; while (!tryingToStartWriteAction) checkTimeout(); TimeoutUtil.sleep(100); readThreads = new ArrayList<>(); readThreads.addAll(ContainerUtil.map(anotherReadActionStarted, readActionStarted -> ApplicationManager.getApplication().executeOnPooledThread(() -> { int finalI = ArrayUtil.indexOf(anotherReadActionStarted, readActionStarted); LOG.append("\nanother thread started " + finalI); anotherThreadStarted[finalI].set(true); ApplicationManager.getApplication().runReadAction(() -> { LOG.append("\ninside another thread read action " + finalI); readActionStarted.set(true); try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } readActionStarted.set(false); LOG.append("\nfinished another thread read action " + finalI); }); LOG.append("\nanother thread finished " + finalI); }))); for (AtomicBoolean threadStarted : anotherThreadStarted) { while (!threadStarted.get()) checkTimeout(); } // now the other threads try to get read lock. we should not let them for (int i = 0; i < 10; i++) { for (AtomicBoolean readStarted1 : anotherReadActionStarted) { assertThat(!readStarted1.get(), "must not start another read action while write is pending"); } TimeoutUtil.sleep(20); } LOG.append("\nfinished read action"); return null; }); } catch (Throwable e) { exception = e; } }); while (!readStarted) checkTimeout(); tryingToStartWriteAction = true; LOG.append("\nwrite about to start"); ApplicationManager.getApplication().runWriteAction(() -> { LOG.append("\ninside write action"); for (AtomicBoolean readStarted1 : anotherReadActionStarted) { assertThat(!readStarted1.get(), "must not start another read action while write is running"); } LOG.append("\nfinished write action"); }); readThreads.add(main); joinWithTimeout(readThreads.toArray(new Future[0])); if (exception != null) { System.err.println(LOG); throw exception; } } private void assertThat(boolean condition, String msg) { if (!condition) { exception = new Exception(msg); throw new RuntimeException(msg); } } public void testProgressVsReadAction() throws Throwable { ProgressManager.getInstance().runProcessWithProgressSynchronously((ThrowableComputable<Void, Exception>)() -> { try { assertFalse(ApplicationManager.getApplication().isReadAccessAllowed()); assertFalse(ApplicationManager.getApplication().isDispatchThread()); for (int i=0; i<100;i++) { SwingUtilities.invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> TimeoutUtil.sleep(20))); ApplicationManager.getApplication().runReadAction(() -> TimeoutUtil.sleep(20)); } } catch (Exception e) { exception = e; } return null; }, "Cc", false, getProject()); UIUtil.dispatchAllInvocationEvents(); if (exception != null) throw exception; } public void testAsyncProgressVsReadAction() throws Throwable { Future<?> future = ((ProgressManagerImpl)ProgressManager.getInstance()).runProcessWithProgressAsynchronously( new Task.Backgroundable(getProject(), "Xx") { @Override public void run(@NotNull ProgressIndicator indicator) { try { assertFalse(ApplicationManager.getApplication().isReadAccessAllowed()); assertFalse(ApplicationManager.getApplication().isDispatchThread()); } catch (Exception e) { exception = e; } } }); future.get(); if (exception != null) throw exception; } public void testWriteActionIsAllowedFromEDTOnly() throws TimeoutException { Future<?> thread = ApplicationManager.getApplication().executeOnPooledThread(()-> { try { ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance()); } catch (Throwable e) { exception = e; } }); joinWithTimeout(thread); assertNotNull(exception); } public void testRunProcessWithProgressFromPooledThread() throws Throwable { Future<?> thread = ApplicationManager.getApplication().executeOnPooledThread(() -> { try { boolean result = ApplicationManagerEx.getApplicationEx().runProcessWithProgressSynchronously(() -> { // check that defaultModalityState() carries write-safe context now ApplicationManager.getApplication().invokeAndWait(() -> { ApplicationManager.getApplication().assertIsWriteThread(); ((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed(); }); }, "Title", true, getProject()); assertTrue(result); } catch (Throwable e) { exception = e; } }); TestTimeOut p = setTimeout(500, TimeUnit.MILLISECONDS); while (!p.timedOut()) { UIUtil.dispatchAllInvocationEvents(); } joinWithTimeout(thread); if (exception != null) throw exception; } public void testRWLockPerformance() { TestTimeOut p = setTimeout(2, TimeUnit.SECONDS); while (!p.timedOut()) { UIUtil.dispatchAllInvocationEvents(); } int readIterations = 200_000_000; ApplicationManager.getApplication().assertIsDispatchThread(); ReadMostlyRWLock lock = new ReadMostlyRWLock(Thread.currentThread()); final int numOfThreads = JobSchedulerImpl.getJobPoolParallelism(); final Field myThreadLocalsField = Objects.requireNonNull(ReflectionUtil.getDeclaredField(Thread.class, "threadLocals")); //noinspection Convert2Lambda List<Callable<Void>> callables = Collections.nCopies(numOfThreads, new Callable<>() { @Override public Void call() { // It's critical there are no collisions in the thread-local map ReflectionUtil.resetField(Thread.currentThread(), myThreadLocalsField); for (int r = 0; r < readIterations; r++) { try { lock.readLock(); } finally { lock.readUnlock(); } } return null; } }); PlatformTestUtil.startPerformanceTest("RWLock/unlock", 27_000, ()-> { ApplicationManager.getApplication().assertIsDispatchThread(); assertFalse(ApplicationManager.getApplication().isWriteAccessAllowed()); List<Future<Void>> futures = AppExecutorUtil.getAppExecutorService().invokeAll(callables); ConcurrencyUtil.getAll(futures); }).assertTiming(); } public void testCheckCanceledReadAction() throws Exception { Semaphore mayStartReadAction = new Semaphore(); mayStartReadAction.down(); ProgressIndicatorBase progress = new ProgressIndicatorBase(); Future<?> future = ApplicationManager.getApplication().executeOnPooledThread(() -> ProgressManager.getInstance().runProcess(() -> { mayStartReadAction.waitFor(); ReadAction.run(() -> fail("should be canceled before entering read action")); }, progress)); WriteAction.run(() -> { mayStartReadAction.up(); progress.cancel(); future.get(1, TimeUnit.SECONDS); }); } private static void safeWrite(ThrowableRunnable<RuntimeException> r) throws Throwable { Ref<Throwable> e = new Ref<>(); ApplicationManager.getApplication().invokeLater(() -> { try { WriteAction.run(r); } catch (Throwable e1) { e.set(e1); } }); UIUtil.dispatchAllInvocationEvents(); if (e.get() != null) throw e.get(); } private static void waitForFuture(Future<?> future) { try { future.get(10_000, TimeUnit.MILLISECONDS); } catch (Exception e) { throw new RuntimeException(e); } } public void testHasWriteActionWorksInOtherThreads() throws Throwable { ApplicationImpl app = (ApplicationImpl)ApplicationManager.getApplication(); ThrowableRunnable<RuntimeException> runnable = new ThrowableRunnable<>() { @Override public void run() throws RuntimeException { Class<? extends ThrowableRunnable<RuntimeException>> actionClass = getClass(); assertTrue(app.hasWriteAction(actionClass)); app.executeSuspendingWriteAction(getProject(), "", () -> ReadAction.run(() -> { assertTrue(app.hasWriteAction(actionClass)); waitForFuture(app.executeOnPooledThread(() -> ReadAction.run(() -> assertTrue(app.hasWriteAction(actionClass))))); })); } }; assertFalse(app.hasWriteAction(runnable.getClass())); safeWrite(runnable); } public void testReadActionInImpatientModeShouldThrowWhenThereIsAPendingWrite() throws Throwable { AtomicBoolean stopRead = new AtomicBoolean(); AtomicBoolean readAcquired = new AtomicBoolean(); ApplicationImpl app = (ApplicationImpl)ApplicationManager.getApplication(); Future<?> readAction1 = app.executeOnPooledThread(() -> app.runReadAction(() -> { readAcquired.set(true); try { while (!stopRead.get()) checkTimeout(); } catch (Throwable e) { exception = e; } finally { readAcquired.set(false); } }) ); while (!readAcquired.get()) checkTimeout(); AtomicBoolean writeCompleted = new AtomicBoolean(); Future<?> readAction2 = app.executeOnPooledThread(() -> { try { // wait for write action attempt to start - i.e. app.myLock.writeLock() started to execute while (!app.myLock.writeRequested) checkTimeout(); app.executeByImpatientReader(() -> { try { assertFalse(app.isReadAccessAllowed()); app.runReadAction(EmptyRunnable.getInstance()); assertFalse(writeCompleted.get()); if (exception != null) throw new RuntimeException(exception); System.err.println(ThreadDumper.dumpThreadsToString()); fail("Must have been failed"); } catch (ApplicationUtil.CannotRunReadActionException ignored) { } catch (Throwable e) { exception = e; } finally { stopRead.set(true); } }); } catch (Throwable e) { exception = e; } }); app.runWriteAction(EmptyRunnable.getInstance()); writeCompleted.set(true); readAction2.get(); readAction1.get(); if (exception != null) throw exception; } public void testReadActionInImpatientModeMustNotThrowWhenThereIsAPendingWriteAndWeAreUnderNonCancelableSection() throws Throwable { AtomicBoolean stopRead = new AtomicBoolean(); AtomicBoolean readAcquired = new AtomicBoolean(); ApplicationImpl app = (ApplicationImpl)ApplicationManager.getApplication(); Future<?> readAction1 = app.executeOnPooledThread(() -> app.runReadAction(() -> { readAcquired.set(true); try { while (!stopRead.get()) checkTimeout(); } catch (Throwable e) { exception = e; } finally { readAcquired.set(false); } }) ); while (!readAcquired.get()) checkTimeout(); AtomicBoolean executingImpatientReader = new AtomicBoolean(); Future<?> readAction2 = app.executeOnPooledThread(() -> { // wait for write action attempt to start while (!app.myLock.writeRequested) { try { checkTimeout(); } catch (Throwable e) { throw new RuntimeException(e); } } ProgressManager.getInstance().executeNonCancelableSection(()-> app.executeByImpatientReader(() -> { executingImpatientReader.set(true); app.runReadAction(EmptyRunnable.getInstance()); // must not throw })); }); Future<?> readAction1Canceler = app.executeOnPooledThread(() -> { try { while (!executingImpatientReader.get()) checkTimeout(); // make sure readAction2 does call runReadAction() TimeoutUtil.sleep(300); stopRead.set(true); } catch (Throwable e) { exception = e; } }); app.runWriteAction(EmptyRunnable.getInstance()); readAction1Canceler.get(); readAction2.get(); readAction1.get(); if (exception != null) throw exception; } public void testPluginsHostProperty() { String host = "IntellijIdeaRulezzz"; String oldHost = System.setProperty(ApplicationInfoImpl.IDEA_PLUGINS_HOST_PROPERTY, host); try { ApplicationInfoImpl applicationInfo = new ApplicationInfoImpl(new Element("state")); Assert.assertThat(applicationInfo.getPluginManagerUrl(), containsString(host)); Assert.assertThat(applicationInfo.getPluginsListUrl(), containsString(host)); Assert.assertThat(applicationInfo.getPluginsDownloadUrl(), containsString(host)); Assert.assertThat(applicationInfo.getChannelsListUrl(), containsString(host)); Assert.assertThat(applicationInfo.getPluginManagerUrl(), not(containsString(ApplicationInfoImpl.DEFAULT_PLUGINS_HOST))); Assert.assertThat(applicationInfo.getPluginsListUrl(), not(containsString(ApplicationInfoImpl.DEFAULT_PLUGINS_HOST))); Assert.assertThat(applicationInfo.getPluginsDownloadUrl(), not(containsString(ApplicationInfoImpl.DEFAULT_PLUGINS_HOST))); Assert.assertThat(applicationInfo.getChannelsListUrl(), not(containsString(ApplicationInfoImpl.DEFAULT_PLUGINS_HOST))); } finally { if (oldHost == null) { System.clearProperty(ApplicationInfoImpl.IDEA_PLUGINS_HOST_PROPERTY); } else { System.setProperty(ApplicationInfoImpl.IDEA_PLUGINS_HOST_PROPERTY, oldHost); } } } }
package com.rtg.vcf; import static com.rtg.util.StringUtils.LS; import com.rtg.util.TestUtils; import com.rtg.util.io.MemoryPrintStream; import com.rtg.vcf.VcfFilterStatistics.Stat; import junit.framework.TestCase; @SuppressWarnings("fallthrough") public class VcfFilterStatisticsTest extends TestCase { public void test() { final VcfFilterStatistics stats = new VcfFilterStatistics(); final MemoryPrintStream stream = new MemoryPrintStream(); stats.printStatistics(stream.outputStream()); final String expected = "" + LS + "Total records : 0" + LS + "Remaining records : 0" + LS ; assertEquals(expected, stream.toString()); stream.reset(); stats.increment(Stat.TOTAL_COUNT); stats.incrementInfoTag("Bar"); stats.incrementFilterTag("Foo"); stats.printStatistics(stream.outputStream()); final String expected2 = "" + LS + "Total records : 1" + LS + "Filtered due to Foo : 1" + LS + "Filtered due to Bar : 1" + LS + "Remaining records : 0" + LS ; assertEquals(expected2, stream.toString()); stream.reset(); for (int i = 0; i < 15; i++) { for (VcfFilterStatistics.Stat s : Stat.values()) { if (s.ordinal() > i - 2) { stats.increment(s); } } } stats.incrementInfoTag("Bar"); stats.incrementFilterTag("Foo"); stats.printStatistics(stream.outputStream()); TestUtils.containsAll(stream.toString(), "Total records", "Filtered due to Foo", "Filtered due to Bar", "Filtered due to quality", "Filtered due to genotype quality", "Filtered due to AVR score", "Filtered due to sample read depth", "Filtered due to combined read depth", "Filtered due to ambiguity ratio", "Filtered due to allele balance", "Filtered due to same as reference", "Filtered due to all samples same as reference", "Filtered due to not a SNP", "Filtered due to simple SNP", "Filtered due to not in keep set", "Filtered due to overlap with previous", "Filtered due to density window", "Filtered due to include file", "Filtered due to exclude file", "Remaining records"); } }
package be.wegenenverkeer.atomium.store; import be.wegenenverkeer.atomium.api.Codec; import be.wegenenverkeer.atomium.api.Entry; import be.wegenenverkeer.atomium.format.AtomEntry; import be.wegenenverkeer.atomium.format.Content; import java.sql.*; import java.time.OffsetDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; public class PostgresDialect implements JdbcDialect { public static final PostgresDialect INSTANCE = new PostgresDialect(); final public static String CREATE_TABLE_SQL = "CREATE TABLE IF NOT EXISTS %s ( " + " %s SERIAL primary key, " + " %s INT, " + "%s VARCHAR(60), " + " %s TIMESTAMP, " + " %s TEXT )"; final public static String INSERT_STATEMENT = "INSERT INTO %s ( %s, %s, %s) VALUES (?, ?, ?)"; final public static String MAX_SEQNO_STATEMENT = "SELECT MAX( %s ) FROM %s"; final public static String SELECT_STATEMENT = "SELECT %s, %s, %s FROM %s WHERE %s >= ? ORDER BY %s LIMIT ?"; @Override public <T> GetEntriesOp createGetEntriesOp(final Connection conn, final Codec<T, String> codec, final JdbcEntryStoreMetadata meta) { return new GetEntriesOp<T>() { private long startNum; private long size; @Override public void setRange(long startNum, long size) { this.startNum = startNum; this.size = size; } final String sql = String.format( SELECT_STATEMENT, meta.getIdColumnName(), meta.getEntryValueColumnName(), meta.getUpdatedColumnName(), meta.getTableName(), meta.getSequenceNoColumnName(), meta.getSequenceNoColumnName()); @Override public List<Entry<T>> execute() throws SQLException { try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setLong(1, startNum); stmt.setLong(2, size); try (ResultSet res = stmt.executeQuery()) { List<Entry<T>> entries = new ArrayList<>(); while (res.next()) { String id = res.getString(1); String jsonEntityVal = res.getString(2); OffsetDateTime updated = (res.getTimestamp(3).toInstant().atZone(ZoneId.systemDefault()).toOffsetDateTime()); Content<T> content = new Content<T>(codec.decode(jsonEntityVal), ""); entries.add(new AtomEntry<>(id, updated, content)); } return entries; } } } }; } @Override public CreateTablesOp createEntryTable(final Connection conn, final JdbcEntryStoreMetadata meta) { return new CreateTablesOp() { String sql = String.format(CREATE_TABLE_SQL, meta.getTableName(), meta.getPrimaryKeyColumnName(), meta.getSequenceNoColumnName(), meta.getIdColumnName(), meta.getUpdatedColumnName(), meta.getEntryValueColumnName()); @Override public Boolean execute() throws SQLException { try (Statement stmt = conn.createStatement()) { return stmt.execute(sql); } } }; } @Override public TotalSizeOp createTotalSizeOp(final Connection conn, final JdbcEntryStoreMetadata meta) { final String sql = String.format( MAX_SEQNO_STATEMENT, meta.getSequenceNoColumnName(), meta.getTableName()) ; return new TotalSizeOp() { @Override public Long execute() throws SQLException { try (Statement stmt = conn.createStatement(); ResultSet resultSet = stmt.executeQuery(sql)) { if (resultSet.next()) { return resultSet.getLong(1) + 1; } } return 0L; } }; } @Override public <T> SaveEntryOp<T> createSaveEntryOp(final Connection conn, final Codec<T, String> codec, final JdbcEntryStoreMetadata meta) throws SQLException { final String sql = String.format(INSERT_STATEMENT, meta.getTableName(), meta.getIdColumnName(), meta.getUpdatedColumnName(), meta.getEntryValueColumnName()); final PreparedStatement stmt = conn.prepareStatement(sql); return new SaveEntryOp<T>() { @Override public void set(Entry<T> entry) throws SQLException { stmt.setString(1, entry.getId()); stmt.setTimestamp(2, new Timestamp(entry.getUpdated().toInstant().toEpochMilli())); stmt.setString(3, codec.encode(entry.getContent().getValue())); } @Override public Boolean execute() throws SQLException { return stmt.execute(); } @Override public void close() { close(stmt); } }; } }
package com.haulmont.cuba.gui.data.impl; import com.haulmont.bali.util.Preconditions; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.chile.core.model.MetaProperty; import com.haulmont.cuba.core.app.dynamicattributes.*; import com.haulmont.cuba.core.entity.*; import com.haulmont.cuba.core.global.*; import com.haulmont.cuba.core.sys.SetValueEntity; import com.haulmont.cuba.gui.data.*; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import javax.annotation.Nullable; import java.util.*; /** * Specific datasource for dynamic attributes. * It will be initialized only when main datasource will be valid. * * @author devyatkin * @version $Id$ */ public class RuntimePropsDatasourceImpl extends AbstractDatasource<DynamicAttributesEntity> implements RuntimePropsDatasource<DynamicAttributesEntity> { protected DsContext dsContext; protected DataSupplier dataSupplier; protected DynamicAttributesMetaClass metaClass; protected View view; protected Datasource mainDs; protected boolean initializedBefore = false; protected boolean categoryChanged = false; protected State state = State.NOT_INITIALIZED; protected DynamicAttributesEntity item; protected Category category; protected final Collection<CategoryAttribute> attributes; protected final View attributeValueView; public RuntimePropsDatasourceImpl(DsContext dsContext, DataSupplier dataSupplier, String id, String mainDsId) { this.id = id; this.dsContext = dsContext; this.dataSupplier = dataSupplier; this.metaClass = new DynamicAttributesMetaClass(); this.setMainDs(mainDsId); this.setCommitMode(CommitMode.DATASTORE); attributes = AppBeans.get(DynamicAttributesService.class).getAttributesForMetaClass(mainDs.getMetaClass()); for (CategoryAttribute attribute : attributes) { MetaProperty metaProperty = DynamicAttributesUtils.getMetaPropertyPath(mainDs.getMetaClass(), attribute).getMetaProperty(); this.metaClass.addProperty(metaProperty, attribute); } mainDs.addListener(new DsListenerAdapter() { @Override public void valueChanged(Entity source, String property, Object prevValue, Object value) { if (property.equals("category")) { categoryChanged = true; initMetaClass(); } } }); mainDs.setLoadDynamicAttributes(true); ViewRepository viewRepository = AppBeans.get(ViewRepository.NAME); View baseAttributeValueView = viewRepository.getView(CategoryAttributeValue.class, View.LOCAL); View baseAttributeView = viewRepository.getView(CategoryAttribute.class, View.LOCAL); attributeValueView = new View(baseAttributeValueView, null, false) .addProperty("categoryAttribute", new View(baseAttributeView, null, false).addProperty("category")); } @Override public void setup(DsContext dsContext, DataSupplier dataSupplier, String id, MetaClass metaClass, @Nullable View view) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } protected void initMetaClass() { Entity entity = mainDs.getItem(); if (!(entity instanceof BaseGenericIdEntity)) { throw new IllegalStateException("This datasource can contain only entity with subclass of BaseGenericIdEntity"); } BaseGenericIdEntity baseGenericIdEntity = (BaseGenericIdEntity) entity; if (PersistenceHelper.isNew(baseGenericIdEntity)) { baseGenericIdEntity.setDynamicAttributes(new HashMap<String, CategoryAttributeValue>()); } Map<String, CategoryAttributeValue> dynamicAttributes = baseGenericIdEntity.getDynamicAttributes(); Preconditions.checkNotNullArgument(dynamicAttributes, "Dynamic attributes should be loaded explicitly"); if (entity instanceof CategorizedEntity) { category = ((CategorizedEntity) entity).getCategory(); } if (!initializedBefore && category == null) { category = getDefaultCategory(entity); if (mainDs.getMetaClass().getProperty("category") != null) { entity.setValue("category", category); } } item = new DynamicAttributesEntity(metaClass); Collection<CategoryAttributeValue> entityValues = dynamicAttributes.values(); TimeSource timeSource = AppBeans.get(TimeSource.NAME); for (CategoryAttribute attribute : attributes) { CategoryAttributeValue attributeValue = getValue(attribute, entityValues); Object value; if (attributeValue == null) { attributeValue = new CategoryAttributeValue(); dynamicAttributes.put(attribute.getCode(), attributeValue); attributeValue.setCode(DynamicAttributesUtils.decodeAttributeCode(attribute.getCode())); attributeValue.setCategoryAttribute(attribute); attributeValue.setEntityId(entity.getUuid()); if (PersistenceHelper.isNew(entity) || categoryChanged) { attributeValue.setStringValue(StringUtils.trimToNull(attribute.getDefaultString())); attributeValue.setIntValue(attribute.getDefaultInt()); attributeValue.setDoubleValue(attribute.getDefaultDouble()); attributeValue.setBooleanValue(attribute.getDefaultBoolean()); attributeValue.setDateValue(BooleanUtils.isTrue(attribute.getDefaultDateIsCurrent()) ? timeSource.currentTimestamp() : attribute.getDefaultDate()); attributeValue.setEntityValue(attribute.getDefaultEntityId()); value = parseValue(attribute, attributeValue); } else { value = null; } } else { value = parseValue(attribute, attributeValue); } item.addAttributeValue(attribute, attributeValue, value); if (DynamicAttributesUtils.getAttributeClass(attribute).equals(SetValueEntity.class)) { createOptionsDatasource(attribute, (SetValueEntity) value); } } view = new View(DynamicAttributesEntity.class); Collection<MetaProperty> properties = metaClass.getProperties(); for (MetaProperty property : properties) { view.addProperty(property.getName()); } item.addListener(listener); item.addListener(new com.haulmont.chile.core.common.ValueListener() { @Override public void propertyChanged(Object item, String property, Object prevValue, Object value) { modified = true; //noinspection unchecked itemToUpdate.add(((DynamicAttributesEntity) item).getCategoryValue(property)); } }); this.valid(); initializedBefore = true; if (!itemToDelete.isEmpty()) { modified = true; } fireItemChanged(null); } protected void createOptionsDatasource(CategoryAttribute attribute, final SetValueEntity attributeValue) { final String property = attribute.getName(); final MetaClass metaClass = this.getMetaClass(); final MetaProperty metaProperty = metaClass.getProperty(property); if (metaProperty == null) { throw new DevelopmentException( String.format("Can't find property '%s' in datasource '%s'", property, this.getId())); } DsBuilder builder = new DsBuilder(getDsContext()); builder.reset().setMetaClass(metadata.getSession().getClass(SetValueEntity.class)).setId(id) .setViewName(View.MINIMAL).setSoftDeletion(false); CollectionDatasource datasource = builder .setRefreshMode(CollectionDatasource.RefreshMode.NEVER) .buildCollectionDatasource(); List<SetValueEntity> options = getOptions(attribute, attributeValue); for (SetValueEntity option : options) { datasource.includeItem(option); } ((DatasourceImpl) datasource).valid(); //datasource.setItem(attributeValue); } protected List<SetValueEntity> getOptions(CategoryAttribute attribute, SetValueEntity attributeValue) { String enumeration = attribute.getEnumeration(); String[] values = StringUtils.split(enumeration, ','); List<SetValueEntity> options = new LinkedList<>(); for (String value : values) { String trimmedValue = StringUtils.trimToNull(value); if (trimmedValue != null) { if (attributeValue != null && trimmedValue.equals(attributeValue.getValue())) options.add(attributeValue); else options.add(new SetValueEntity(trimmedValue)); } } return options; } protected CategoryAttributeValue getValue(CategoryAttribute attribute, Collection<CategoryAttributeValue> entityValues) { for (CategoryAttributeValue attrValue : entityValues) { if (attrValue.getCategoryAttribute().equals(attribute)) return attrValue; } return null; } protected Object parseValue(CategoryAttribute attribute, CategoryAttributeValue attrValue) { String dataType = attribute.getDataType(); if (BooleanUtils.isTrue(attribute.getIsEntity())) { if (attrValue != null) { UUID entityId = attrValue.getEntityValue(); return parseEntity(dataType, entityId); } else { UUID entityId = attribute.getDefaultEntityId(); return parseEntity(dataType, entityId); } } else { switch (PropertyType.valueOf(dataType)) { case STRING: if (attrValue != null) return attrValue.getStringValue(); else return attribute.getDefaultString(); case INTEGER: if (attrValue != null) return attrValue.getIntValue(); else return attribute.getDefaultInt(); case DOUBLE: if (attrValue != null) return attrValue.getDoubleValue(); else return attribute.getDefaultDouble(); case BOOLEAN: if (attrValue != null) return attrValue.getBooleanValue(); else return attribute.getDefaultBoolean(); case DATE: if (attrValue != null) return attrValue.getDateValue(); else return attribute.getDefaultDate(); case ENUMERATION: if (attrValue != null) { String stringValue = attrValue.getStringValue(); if (stringValue != null && !StringUtils.isBlank(stringValue)) return new SetValueEntity(stringValue); else return null; } else { String eValue = attribute.getDefaultString(); if (eValue != null) return new SetValueEntity(eValue); else return null; } } } return attrValue.getStringValue(); } protected Entity parseEntity(String entityType, UUID uuid) { Entity entity; try { Class clazz = Class.forName(entityType); LoadContext entitiesContext = new LoadContext(clazz); String entityClassName = metadata.getSession().getClassNN(clazz).getName(); LoadContext.Query query = entitiesContext.setQueryString("select a from " + entityClassName + " a where a.id =:e"); query.setParameter("e", uuid); entitiesContext.setView("_local"); entity = dataSupplier.load(entitiesContext); } catch (ClassNotFoundException e) { throw new RuntimeException("can't parse entity " + entityType + " " + uuid, e); } return entity; } @Override public DsContext getDsContext() { return dsContext; } @Override public DataSupplier getDataSupplier() { return dataSupplier; } @Override public void commit() { if (!allowCommit) return; if (Datasource.CommitMode.DATASTORE.equals(getCommitMode())) { Collection itemsToUpdate = getItemsToUpdate(); CommitContext cc = new CommitContext(itemsToUpdate); Set<Entity> entities = getDataSupplier().commit(cc); committed(entities); } else { throw new UnsupportedOperationException(); } } @Override public State getState() { return state; } @Override public DynamicAttributesEntity getItem() { if (State.VALID.equals(state)) return item; else throw new IllegalStateException("RuntimePropsDataSource state is " + state); } @Nullable @Override public DynamicAttributesEntity getItemIfValid() { return getState() == State.VALID ? getItem() : null; } @Override public void setItem(DynamicAttributesEntity item) { throw new UnsupportedOperationException(); } @Override public void invalidate() { if (State.NOT_INITIALIZED != this.state) { final State prevStatus = this.state; this.state = State.INVALID; fireStateChanged(prevStatus); } modified = false; clearCommitLists(); } @Override public void refresh() { initMetaClass(); } @Override public MetaClass getMetaClass() { return metaClass; } @Override public View getView() { return null; // null is correct } @Override public View getAttributeValueView() { return attributeValueView; } @Override public void initialized() { final State prev = state; state = State.INVALID; fireStateChanged(prev); } @Override public void valid() { final State prev = state; state = State.VALID; fireStateChanged(prev); } @Override public void committed(Set<Entity> entities) { if (!State.VALID.equals(state)) { return; } for (Entity entity : entities) { if (entity instanceof CategoryAttributeValue) { CategoryAttributeValue attributeValue = (CategoryAttributeValue) entity; item.updateAttributeValue(attributeValue); } } modified = false; clearCommitLists(); } protected void setMainDs(String name) { mainDs = dsContext.get(name); if (mainDs == null) { throw new DevelopmentException("runtimePropsDatasource initialization error: mainDs '" + name + "' does not exists"); } //noinspection unchecked mainDs.addListener( new DsListenerAdapter() { @Override public void stateChanged(Datasource ds, State prevState, State state) { if (State.VALID.equals(state)) { if (!State.VALID.equals(prevState)) initMetaClass(); else valid(); } } } ); } @Override public Datasource getMainDs() { return mainDs; } @Override public Collection<MetaProperty> getPropertiesFilteredByCategory() { return metaClass.getPropertiesFilteredByCategory(category); } @Nullable public Category getDefaultCategory(Entity entity) { MetaClass metaClass = metadata.getSession().getClassNN(entity.getClass()); Collection<Category> categoriesForMetaClass = AppBeans.get(DynamicAttributesService.class).getCategoriesForMetaClass(metaClass); for (Category category : categoriesForMetaClass) { if (Boolean.TRUE.equals(category.getIsDefault())) { return category; } } return null; } }
package org.eclipse.oomph.setup.ui.wizards; import org.eclipse.oomph.setup.Installation; import org.eclipse.oomph.setup.Trigger; import org.eclipse.oomph.setup.User; import org.eclipse.oomph.setup.Workspace; import org.eclipse.oomph.setup.internal.core.SetupTaskPerformer; import org.eclipse.oomph.setup.internal.core.util.CatalogManager; import org.eclipse.oomph.ui.HelpSupport.HelpProvider; import org.eclipse.oomph.ui.OomphWizardDialog; import org.eclipse.oomph.ui.PersistentButton; import org.eclipse.oomph.ui.UIUtil; import org.eclipse.oomph.util.StringUtil; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.edit.provider.ComposedAdapterFactory; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.wizard.IWizardContainer; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; /** * @author Eike Stepper */ public abstract class SetupWizardPage extends WizardPage implements HelpProvider { private static final String TOGGLE_COMMAND_PREFIX = "toggleCommand:"; private Composite checkComposite; public SetupWizardPage(String pageName) { super(pageName); } @Override public SetupWizard getWizard() { return (SetupWizard)super.getWizard(); } @Override protected IDialogSettings getDialogSettings() { IDialogSettings settings = super.getDialogSettings(); String sectionName = getName(); return UIUtil.getOrCreateSection(settings, sectionName); } public ComposedAdapterFactory getAdapterFactory() { return getWizard().getAdapterFactory(); } public String getHelpPath() { String id = "Doc" + getClass().getSimpleName(); return SetupWizard.HELP_FOLDER + id + ".html#" + id + "_1_table"; } public ResourceSet getResourceSet() { return getWizard().getResourceSet(); } public CatalogManager getCatalogManager() { return getWizard().getCatalogManager(); } public Trigger getTrigger() { return getWizard().getTrigger(); } public Installation getInstallation() { return getWizard().getInstallation(); } public Workspace getWorkspace() { return getWizard().getWorkspace(); } public User getUser() { return getWizard().getUser(); } public SetupTaskPerformer getPerformer() { return getWizard().getPerformer(); } public void setPerformer(SetupTaskPerformer performer) { getWizard().setPerformer(performer); } public boolean performCancel() { return true; } public void enterPage(boolean forward) { } public void leavePage(boolean forward) { } public final void advanceToNextPage() { IWizardPage nextPage = getNextPage(); getContainer().showPage(nextPage); } public final void createControl(Composite parent) { GridLayout layout = new GridLayout(); layout.marginWidth = 0; layout.marginHeight = 0; Composite pageControl = new Composite(parent, SWT.NONE); pageControl.setLayout(layout); super.setControl(pageControl); setPageComplete(false); Point sizeHint = getSizeHint(); GridData layoutData = new GridData(GridData.FILL_BOTH); layoutData.widthHint = sizeHint.x; layoutData.heightHint = sizeHint.y; final Control ui = createUI(pageControl); ui.setLayoutData(layoutData); createCheckButtons(); createFooter(pageControl); } protected void createCheckButtons() { } protected final Button addCheckButton(String text, String toolTip, boolean defaultSelection, String persistenceKey) { if (checkComposite == null) { GridLayout checkLayout = new GridLayout(); checkLayout.marginWidth = 5; checkLayout.marginHeight = 0; checkComposite = new Composite((Composite)getControl(), SWT.NONE); checkComposite.setLayout(checkLayout); checkComposite.setLayoutData(new GridData()); } else { GridLayout checkLayout = (GridLayout)checkComposite.getLayout(); ++checkLayout.numColumns; } Button button; if (persistenceKey != null) { boolean toggleCommand = false; if (persistenceKey.startsWith(TOGGLE_COMMAND_PREFIX)) { persistenceKey = persistenceKey.substring(TOGGLE_COMMAND_PREFIX.length()); toggleCommand = UIUtil.WORKBENCH != null; } PersistentButton.Persistence persistence; if (toggleCommand) { persistence = new PersistentButton.ToggleCommandPersistence(persistenceKey); } else { persistence = new PersistentButton.DialogSettingsPersistence(getDialogSettings(), persistenceKey); } button = new PersistentButton(checkComposite, SWT.CHECK, defaultSelection, persistence); } else { button = new Button(checkComposite, SWT.CHECK); button.setSelection(defaultSelection); } button.setLayoutData(new GridData()); button.setText(text); if (!StringUtil.isEmpty(toolTip)) { button.setToolTipText(toolTip); } return button; } protected final Composite getCheckComposite() { return checkComposite; } @Override protected final void setControl(Control newControl) { throw new UnsupportedOperationException(); } protected Point getSizeHint() { return new Point(800, 500); } protected abstract Control createUI(Composite parent); protected void createFooter(Composite parent) { } protected final void addHelpCallout(Control control, int number) { IWizardContainer container = getContainer(); if (container instanceof OomphWizardDialog) { OomphWizardDialog dialog = (OomphWizardDialog)container; dialog.getHelpSupport().addHelpCallout(control, number); } } }
package org.torquebox.services.as; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import org.jboss.as.controller.Extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ModelNodeRegistration; import org.jboss.logging.Logger; public class ServicesExtension implements Extension { @Override public void initialize(ExtensionContext context) { log.info( "Initializing TorqueBox Services Subsystem" ); final SubsystemRegistration registration = context.registerSubsystem( SUBSYSTEM_NAME ); final ModelNodeRegistration subsystem = registration.registerSubsystemModel( ServicesSubsystemProviders.SUBSYSTEM ); subsystem.registerOperationHandler( ADD, ServicesSubsystemAdd.ADD_INSTANCE, ServicesSubsystemProviders.SUBSYSTEM_ADD, false ); registration.registerXMLElementWriter(ServicesSubsystemParser.getInstance()); log.info( "Initialized TorqueBox Services Subsystem" ); } @Override public void initializeParsers(ExtensionParsingContext context) { context.setSubsystemXmlMapping(Namespace.CURRENT.getUriString(), ServicesSubsystemParser.getInstance()); } public static final String SUBSYSTEM_NAME = "torquebox-services"; static final Logger log = Logger.getLogger( "org.torquebox.services.as" ); }
package org.jkiss.dbeaver.ui.controls.vtabs; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.source.ISharedTextColors; import org.eclipse.swt.SWT; import org.eclipse.swt.accessibility.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.*; import org.jkiss.dbeaver.core.DBeaverUI; import org.jkiss.dbeaver.ui.UIUtils; /** * Shows the list of tabs in the tabbed property sheet page. * * @author Anthony Hunter * @author Serge Rieder */ public class TabbedPropertyList extends Composite { private static final ListElement[] ELEMENTS_EMPTY = new ListElement[0]; protected static final int NONE = -1; protected static final int INDENT = 7; public static final String LABEL_NA = "N/A"; private boolean focus = false; private ListElement[] elements; private int selectedElementIndex = NONE; private int topVisibleIndex = NONE; private int bottomVisibleIndex = NONE; private TopNavigationElement topNavigationElement; private BottomNavigationElement bottomNavigationElement; private int widestLabelIndex = NONE; private int tabsThatFitInComposite = NONE; private Color widgetForeground; private Color widgetBackground; private Color widgetNormalShadow; private Color widgetDarkShadow; private Color listBackground; private Color hoverGradientStart; private Color hoverGradientEnd; private Color defaultGradientStart; private Color defaultGradientEnd; private Color indentedDefaultBackground; private Color indentedHoverBackground; private Color navigationElementShadowStroke; private Color bottomNavigationElementShadowStroke1; private Color bottomNavigationElementShadowStroke2; /** * One of the tabs in the tabbed property list. */ public class ListElement extends Canvas { private ITabItem tab; private int index; private boolean selected; private boolean hover; /** * Constructor for ListElement. * * @param parent the parent Composite. * @param tab the tab item for the element. * @param index the index in the list. */ public ListElement(Composite parent, final ITabItem tab, int index) { super(parent, SWT.NO_FOCUS); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { paint(e); } }); addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent e) { if (!selected) { select(getIndex(ListElement.this)); /* * We set focus to the tabbed property composite so that * focus is moved to the appropriate widget in the * section. */ Composite tabbedPropertyComposite = getParent(); tabbedPropertyComposite.setFocus(); } } }); addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent e) { if (!hover) { hover = true; redraw(); } } }); addMouseTrackListener(new MouseTrackAdapter() { public void mouseExit(MouseEvent e) { hover = false; redraw(); } }); } /** * Set selected value for this element. * * @param selected the selected value. */ public void setSelected(boolean selected) { this.selected = selected; redraw(); } /** * Paint the element. * * @param e the paint event. */ private void paint(PaintEvent e) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds(); e.gc.setForeground(widgetNormalShadow); e.gc.drawLine(0, 0, bounds.width - 1, 0); e.gc.setForeground(listBackground); e.gc.drawLine(0, 1, bounds.width - 1, 1); /* draw the fill in the tab */ if (selected) { e.gc.setBackground(listBackground); e.gc.fillRectangle(0, 2, bounds.width, bounds.height - 1); } else if (hover && tab.isIndented()) { e.gc.setBackground(indentedHoverBackground); e.gc.fillRectangle(0, 2, bounds.width - 1, bounds.height - 1); } else if (hover) { e.gc.setForeground(hoverGradientStart); e.gc.setBackground(hoverGradientEnd); e.gc.fillGradientRectangle(0, 2, bounds.width - 1, bounds.height - 1, true); } else if (tab.isIndented()) { e.gc.setBackground(indentedDefaultBackground); e.gc.fillRectangle(0, 2, bounds.width - 1, bounds.height - 1); } else { e.gc.setForeground(defaultGradientStart); e.gc.setBackground(defaultGradientEnd); e.gc.fillGradientRectangle(0, 2, bounds.width - 1, bounds.height - 1, true); } if (!selected) { e.gc.setForeground(widgetNormalShadow); e.gc.drawLine(bounds.width - 1, 1, bounds.width - 1, bounds.height + 1); } /* * Add INDENT pixels to the left as a margin. */ int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics(); int height = fm.getHeight(); int textMiddle = (bounds.height - height) / 2; if (selected && tab.getImage() != null && !tab.getImage().isDisposed()) { /* draw the icon for the selected tab */ if (tab.isIndented()) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage(tab.getImage(), textIndent, textMiddle - 1); textIndent = textIndent + 16 + 4; } else if (tab.isIndented()) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground(widgetForeground); if (selected) { /* selected tab is bold font */ e.gc.setFont(JFaceResources.getFontRegistry().getBold(JFaceResources.DEFAULT_FONT)); } e.gc.drawText(tab.getText(), textIndent, textMiddle, true); if (((TabbedPropertyList) getParent()).focus && selected) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent(tab.getText()); e.gc.drawLine(textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4); } /* draw the bottom line on the tab for selected and default */ if (!hover) { e.gc.setForeground(listBackground); e.gc.drawLine(0, bounds.height - 1, bounds.width - 2, bounds.height - 1); } } /** * Get the tab item. * * @return the tab item. */ public ITabItem getTabItem() { return tab; } public String toString() { return tab.getText(); } } /** * The top navigation element in the tabbed property list. It looks like a * scroll button when scrolling is needed or is just a spacer when no * scrolling is required. */ public class TopNavigationElement extends Canvas { /** * Constructor for TopNavigationElement. * * @param parent the parent Composite. */ public TopNavigationElement(Composite parent) { super(parent, SWT.NO_FOCUS); addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { paint(e); } }); addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent e) { if (isUpScrollRequired()) { bottomVisibleIndex if (topVisibleIndex != 0) { topVisibleIndex } layoutTabs(); topNavigationElement.redraw(); bottomNavigationElement.redraw(); } } }); } /** * Paint the element. * * @param e the paint event. */ private void paint(PaintEvent e) { e.gc.setBackground(widgetBackground); e.gc.setForeground(widgetForeground); Rectangle bounds = getBounds(); if (elements.length != 0) { e.gc.fillRectangle(0, 0, bounds.width, bounds.height); e.gc.setForeground(widgetNormalShadow); e.gc.drawLine(bounds.width - 1, 0, bounds.width - 1, bounds.height - 1); } else { e.gc.setBackground(listBackground); e.gc.fillRectangle(0, 0, bounds.width, bounds.height); int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics(); int height = fm.getHeight(); int textMiddle = (bounds.height - height) / 2; e.gc.setForeground(widgetForeground); e.gc.drawText(LABEL_NA, textIndent, textMiddle); } if (isUpScrollRequired()) { e.gc.setForeground(widgetDarkShadow); int middle = bounds.width / 2; e.gc.drawLine(middle + 1, 3, middle + 5, 7); e.gc.drawLine(middle, 3, middle - 4, 7); e.gc.drawLine(middle - 3, 7, middle + 4, 7); e.gc.setForeground(listBackground); e.gc.drawLine(middle, 4, middle + 1, 4); e.gc.drawLine(middle - 1, 5, middle + 2, 5); e.gc.drawLine(middle - 2, 6, middle + 3, 6); e.gc.setForeground(widgetNormalShadow); e.gc.drawLine(0, 0, bounds.width - 2, 0); e.gc.setForeground(navigationElementShadowStroke); e.gc.drawLine(0, 1, bounds.width - 2, 1); e.gc.drawLine(0, bounds.height - 1, bounds.width - 2, bounds.height - 1); } } } /** * The top navigation element in the tabbed property list. It looks like a * scroll button when scrolling is needed or is just a spacer when no * scrolling is required. */ public class BottomNavigationElement extends Canvas { /** * Constructor for BottomNavigationElement. * * @param parent the parent Composite. */ public BottomNavigationElement(Composite parent) { super(parent, SWT.NO_FOCUS); addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { paint(e); } }); addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent e) { if (isDownScrollRequired()) { topVisibleIndex++; if (bottomVisibleIndex != elements.length - 1) { bottomVisibleIndex++; } layoutTabs(); topNavigationElement.redraw(); bottomNavigationElement.redraw(); } } }); } /** * Paint the element. * * @param e the paint event. */ private void paint(PaintEvent e) { e.gc.setBackground(widgetBackground); e.gc.setForeground(widgetForeground); Rectangle bounds = getBounds(); if (elements.length != 0) { e.gc.fillRectangle(0, 0, bounds.width, bounds.height); e.gc.setForeground(widgetNormalShadow); e.gc.drawLine(bounds.width - 1, 0, bounds.width - 1, bounds.height - 1); e.gc.drawLine(0, 0, bounds.width - 1, 0); e.gc.setForeground(bottomNavigationElementShadowStroke1); e.gc.drawLine(0, 1, bounds.width - 2, 1); e.gc.setForeground(bottomNavigationElementShadowStroke2); e.gc.drawLine(0, 2, bounds.width - 2, 2); } else { e.gc.setBackground(listBackground); e.gc.fillRectangle(0, 0, bounds.width, bounds.height); } if (isDownScrollRequired()) { e.gc.setForeground(widgetDarkShadow); int middle = bounds.width / 2; int bottom = bounds.height - 3; e.gc.drawLine(middle + 1, bottom, middle + 5, bottom - 4); e.gc.drawLine(middle, bottom, middle - 4, bottom - 4); e.gc.drawLine(middle - 3, bottom - 4, middle + 4, bottom - 4); e.gc.setForeground(listBackground); e.gc.drawLine(middle, bottom - 1, middle + 1, bottom - 1); e.gc.drawLine(middle - 1, bottom - 2, middle + 2, bottom - 2); e.gc.drawLine(middle - 2, bottom - 3, middle + 3, bottom - 3); e.gc.setForeground(widgetNormalShadow); e.gc.drawLine(0, bottom - 7, bounds.width - 2, bottom - 7); e.gc.setForeground(navigationElementShadowStroke); e.gc.drawLine(0, bottom + 2, bounds.width - 2, bottom + 2); e.gc.drawLine(0, bottom - 6, bounds.width - 2, bottom - 6); } } } public TabbedPropertyList(Composite parent) { super(parent, SWT.NO_FOCUS); removeAll(); setLayout(new FormLayout()); initColours(); initAccessible(); topNavigationElement = new TopNavigationElement(this); bottomNavigationElement = new BottomNavigationElement(this); this.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { focus = true; int i = getSelectionIndex(); if (i >= 0) { elements[i].redraw(); } } public void focusLost(FocusEvent e) { focus = false; int i = getSelectionIndex(); if (i >= 0) { elements[i].redraw(); } } }); this.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { computeTopAndBottomTab(); } }); this.addTraverseListener(new TraverseListener() { public void keyTraversed(TraverseEvent e) { if (e.detail == SWT.TRAVERSE_ARROW_PREVIOUS || e.detail == SWT.TRAVERSE_ARROW_NEXT) { int nMax = elements.length - 1; int nCurrent = getSelectionIndex(); if (e.detail == SWT.TRAVERSE_ARROW_PREVIOUS) { nCurrent -= 1; nCurrent = Math.max(0, nCurrent); } else { nCurrent += 1; nCurrent = Math.min(nCurrent, nMax); } select(nCurrent); redraw(); } else { e.doit = true; } } }); } /** * Calculate the number of tabs that will fit in the tab list composite. */ protected void computeTabsThatFitInComposite() { tabsThatFitInComposite = Math .round((getSize().y - 22) / getTabHeight()); if (tabsThatFitInComposite <= 0) { tabsThatFitInComposite = 1; } } /** * Returns the number of elements in this list viewer. * * @return number of elements */ public int getNumberOfElements() { return elements.length; } /** * Returns the element with the given index from this list viewer. Returns * <code>null</code> if the index is out of range. * * @param index the zero-based index * @return the element at the given index, or <code>null</code> if the * index is out of range */ public ListElement getElementAt(int index) { if (index >= 0 && index < elements.length) { return elements[index]; } return null; } /** * Returns the zero-relative index of the item which is currently selected * in the receiver, or -1 if no item is selected. * * @return the index of the selected item */ public int getSelectionIndex() { return selectedElementIndex; } /** * Removes all elements from this list. */ public void removeAll() { if (elements != null) { for (ListElement element : elements) { element.dispose(); } } elements = ELEMENTS_EMPTY; selectedElementIndex = NONE; widestLabelIndex = NONE; topVisibleIndex = NONE; bottomVisibleIndex = NONE; } /** * Sets the new list elements. */ public void setElements(ITabItem[] children) { if (elements != ELEMENTS_EMPTY) { removeAll(); } elements = new ListElement[children.length]; if (children.length == 0) { widestLabelIndex = NONE; } else { widestLabelIndex = 0; for (int i = 0; i < children.length; i++) { elements[i] = new ListElement(this, children[i], i); elements[i].setVisible(false); elements[i].setLayoutData(null); if (i != widestLabelIndex) { int width = getTabWidth(children[i]); if (width > getTabWidth(children[widestLabelIndex])) { widestLabelIndex = i; } } } } computeTopAndBottomTab(); } private int getTabWidth(ITabItem tabItem) { int width = getTextDimension(tabItem.getText()).x; /* * To anticipate for the icon placement we should always keep the * space available after the label. So when the active tab includes * an icon the width of the tab doesn't change. */ if (tabItem.getImage() != null) { width = width + tabItem.getImage().getBounds().x + 4; } if (tabItem.isIndented()) { width = width + INDENT; } return width; } /** * Selects one of the elements in the list. * * @param index the index of the element to select. */ protected void select(int index) { if (getSelectionIndex() == index) { /* * this index is already selected. */ return; } if (index >= 0 && index < elements.length) { int lastSelected = getSelectionIndex(); elements[index].setSelected(true); selectedElementIndex = index; if (lastSelected != NONE) { elements[lastSelected].setSelected(false); if (getSelectionIndex() != elements.length - 1) { /* * redraw the next tab to fix the border by calling * setSelected() */ elements[getSelectionIndex() + 1].setSelected(false); } } topNavigationElement.redraw(); bottomNavigationElement.redraw(); if (selectedElementIndex < topVisibleIndex || selectedElementIndex > bottomVisibleIndex) { computeTopAndBottomTab(); } } notifyListeners(SWT.Selection, new Event()); } /** * Deselects all the elements in the list. */ public void deselectAll() { if (getSelectionIndex() != NONE) { elements[getSelectionIndex()].setSelected(false); selectedElementIndex = NONE; } } private int getIndex(ListElement element) { return element.index; } public Point computeSize(int wHint, int hHint, boolean changed) { Point result = super.computeSize(hHint, wHint, changed); if (widestLabelIndex == -1) { result.x = getTextDimension(LABEL_NA).x + INDENT; } else { /* * Add INDENT pixels to the left of the longest tab as a margin. */ int width = getTabWidth(elements[widestLabelIndex].getTabItem()) + INDENT; /* * Add 10 pixels to the right of the longest tab as a margin. */ result.x = width + 10; } return result; } /** * Get the dimensions of the provided string. * * @param text the string. * @return the dimensions of the provided string. */ private Point getTextDimension(String text) { GC gc = new GC(this); gc.setFont(JFaceResources.getFontRegistry().getBold( JFaceResources.DEFAULT_FONT)); Point point = gc.textExtent(text); point.x++; gc.dispose(); return point; } /** * Initialize the colours used in the list. */ private void initColours() { Display display = Display.getCurrent(); ISharedTextColors sharedColors = DBeaverUI.getSharedTextColors(); listBackground = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); widgetBackground = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); widgetDarkShadow = display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW); widgetForeground = display.getSystemColor(SWT.COLOR_WIDGET_FOREGROUND); widgetNormalShadow = display.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW); RGB infoBackground = display.getSystemColor(SWT.COLOR_INFO_BACKGROUND).getRGB(); RGB white = display.getSystemColor(SWT.COLOR_WHITE).getRGB(); RGB black = display.getSystemColor(SWT.COLOR_BLACK).getRGB(); /* * gradient in the default tab: start colour WIDGET_NORMAL_SHADOW 100% + * white 20% + INFO_BACKGROUND 60% end colour WIDGET_NORMAL_SHADOW 100% + * INFO_BACKGROUND 40% */ defaultGradientStart = sharedColors.getColor( UIUtils.blend(infoBackground, UIUtils.blend(white, widgetNormalShadow.getRGB(), 20), 60) ); defaultGradientEnd = sharedColors.getColor(UIUtils.blend(infoBackground, widgetNormalShadow.getRGB(), 40)); navigationElementShadowStroke = sharedColors.getColor(UIUtils.blend(white, widgetNormalShadow.getRGB(), 55)); bottomNavigationElementShadowStroke1 = sharedColors.getColor(UIUtils.blend(black, widgetBackground.getRGB(), 10)); bottomNavigationElementShadowStroke2 = sharedColors.getColor(UIUtils.blend(black, widgetBackground.getRGB(), 5)); /* * gradient in the hover tab: start colour WIDGET_BACKGROUND 100% + * white 20% end colour WIDGET_BACKGROUND 100% + WIDGET_NORMAL_SHADOW * 10% */ hoverGradientStart = sharedColors.getColor(UIUtils.blend(white, widgetBackground.getRGB(), 20)); hoverGradientEnd = sharedColors.getColor(UIUtils.blend(widgetNormalShadow.getRGB(), widgetBackground.getRGB(), 10)); indentedDefaultBackground = sharedColors.getColor(UIUtils.blend(white, widgetBackground.getRGB(), 10)); indentedHoverBackground = sharedColors.getColor(UIUtils.blend(white, widgetBackground.getRGB(), 75)); } /** * Get the height of a tab. The height of the tab is the height of the text * plus buffer. * * @return the height of a tab. */ private int getTabHeight() { int tabHeight = getTextDimension("").y + INDENT; //$NON-NLS-1$ if (tabsThatFitInComposite == 1) { /* * if only one tab will fix, reduce the size of the tab height so * that the navigation elements fit. */ int ret = getBounds().height - 20; return (ret > tabHeight) ? tabHeight : (ret < 5) ? 5 : ret; } return tabHeight; } /** * Determine if a downward scrolling is required. * * @return true if downward scrolling is required. */ private boolean isDownScrollRequired() { return elements.length > tabsThatFitInComposite && bottomVisibleIndex != elements.length - 1; } /** * Determine if an upward scrolling is required. * * @return true if upward scrolling is required. */ private boolean isUpScrollRequired() { return elements.length > tabsThatFitInComposite && topVisibleIndex != 0; } /** * Based on available space, figure out the top and bottom tabs in the list. */ private void computeTopAndBottomTab() { computeTabsThatFitInComposite(); if (elements.length == 0) { /* * no tabs to display. */ topVisibleIndex = 0; bottomVisibleIndex = 0; } else if (tabsThatFitInComposite >= elements.length) { /* * all the tabs fit. */ topVisibleIndex = 0; bottomVisibleIndex = elements.length - 1; } else if (getSelectionIndex() == NONE) { /* * there is no selected tab yet, assume that tab one would * be selected for now. */ topVisibleIndex = 0; bottomVisibleIndex = tabsThatFitInComposite - 1; } else if (getSelectionIndex() + tabsThatFitInComposite > elements.length) { /* * the selected tab is near the bottom. */ bottomVisibleIndex = elements.length - 1; topVisibleIndex = bottomVisibleIndex - tabsThatFitInComposite + 1; } else { /* * the selected tab is near the top. */ topVisibleIndex = selectedElementIndex; bottomVisibleIndex = selectedElementIndex + tabsThatFitInComposite - 1; } layoutTabs(); } /** * Layout the tabs. */ private void layoutTabs() { if (tabsThatFitInComposite == NONE || elements.length == 0) { FormData formData = new FormData(); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.top = new FormAttachment(0, 0); formData.height = getTabHeight(); topNavigationElement.setLayoutData(formData); formData = new FormData(); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.top = new FormAttachment(topNavigationElement, 0); formData.bottom = new FormAttachment(100, 0); bottomNavigationElement.setLayoutData(formData); } else { FormData formData = new FormData(); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.top = new FormAttachment(0, 0); formData.height = 10; topNavigationElement.setLayoutData(formData); /* * use nextElement to attach the layout to the previous canvas * widget in the list. */ Canvas nextElement = topNavigationElement; for (int i = 0; i < elements.length; i++) { //System.out.print(i + " [" + elements[i].getText() + "]"); if (i < topVisibleIndex || i > bottomVisibleIndex) { /* * this tab is not visible */ elements[i].setLayoutData(null); elements[i].setVisible(false); } else { /* * this tab is visible. */ //System.out.print(" visible"); formData = new FormData(); formData.height = getTabHeight(); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.top = new FormAttachment(nextElement, 0); nextElement = elements[i]; elements[i].setLayoutData(formData); elements[i].setVisible(true); } //if (i == selectedElementIndex) { // System.out.print(" selected"); //System.out.println(""); } formData = new FormData(); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.top = new FormAttachment(nextElement, 0); formData.bottom = new FormAttachment(100, 0); formData.height = 10; bottomNavigationElement.setLayoutData(formData); } //System.out.println(""); // layout so that we have enough space for the new labels Composite grandparent = getParent().getParent(); grandparent.layout(true); layout(true); } /** * Initialize the accessibility adapter. */ private void initAccessible() { final Accessible accessible = getAccessible(); accessible.addAccessibleListener(new AccessibleAdapter() { public void getName(AccessibleEvent e) { if (getSelectionIndex() != NONE) { e.result = elements[getSelectionIndex()].getTabItem().getText(); } } public void getHelp(AccessibleEvent e) { if (getSelectionIndex() != NONE) { e.result = elements[getSelectionIndex()].getTabItem().getText(); } } }); accessible.addAccessibleControlListener(new AccessibleControlAdapter() { public void getChildAtPoint(AccessibleControlEvent e) { Point pt = toControl(new Point(e.x, e.y)); e.childID = (getBounds().contains(pt)) ? ACC.CHILDID_SELF : ACC.CHILDID_NONE; } public void getLocation(AccessibleControlEvent e) { if (getSelectionIndex() != NONE) { Rectangle location = elements[getSelectionIndex()].getBounds(); Point pt = toDisplay(new Point(location.x, location.y)); e.x = pt.x; e.y = pt.y; e.width = location.width; e.height = location.height; } } public void getChildCount(AccessibleControlEvent e) { e.detail = 0; } public void getRole(AccessibleControlEvent e) { e.detail = ACC.ROLE_TABITEM; } public void getState(AccessibleControlEvent e) { e.detail = ACC.STATE_SELECTABLE | ACC.STATE_SELECTED | ACC.STATE_FOCUSED | ACC.STATE_FOCUSABLE; } }); addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (isFocusControl()) { accessible.setFocus(ACC.CHILDID_SELF); } } }); addListener(SWT.FocusIn, new Listener() { public void handleEvent(Event event) { accessible.setFocus(ACC.CHILDID_SELF); } }); } }
package org.yakindu.sct.model.sgraph.resource; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.emf.ecore.xmi.XMLHelper; import org.eclipse.emf.ecore.xmi.XMLResource; import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; import org.eclipse.gmf.runtime.emf.core.resources.GMFLoad; /** * * @author andreas muelder - Initial contribution and API * */ public class SGraphLoad extends GMFLoad { private static final String NS_URI_TO_MIGRATE = "http: public SGraphLoad(XMLHelper helper) { super(helper); } @Override public void load(XMLResource r, InputStream s, @SuppressWarnings("rawtypes") Map o) throws IOException { IFile file = WorkspaceSynchronizer.getFile(r); if (file != null) { String osString = file.getLocation().makeAbsolute().toOSString(); String filecontent = readFileAsString(osString); // TODO: on check the first line for old ns uri, not neccessary to // read // the whole file content if (filecontent.contains(NS_URI_TO_MIGRATE)) { filecontent = migratePreM10Models(filecontent); BufferedWriter writer = new BufferedWriter(new FileWriter( osString)); writer.write(filecontent); writer.flush(); writer.close(); } } super.load(r, s, o); } private String migratePreM10Models(String content) { content = content.replace(NS_URI_TO_MIGRATE, "http: content = content.replaceAll("expression=\"", "specification=\""); content = content.replaceAll("<subRegions", "<regions"); content = content.replaceAll(" </subRegions", "</regions"); return content; } private String readFileAsString(String filePath) throws java.io.IOException { byte[] buffer = new byte[(int) new File(filePath).length()]; BufferedInputStream f = new BufferedInputStream(new FileInputStream( filePath)); f.read(buffer); return new String(buffer); } }
package com.opengamma.financial.aggregation; import com.opengamma.core.position.Position; import com.opengamma.financial.security.FinancialSecurityUtils; import com.opengamma.util.money.Currency; /** * Function to classify positions by Currency. * */ public class CurrencyAggregationFunction implements AggregationFunction<Currency> { private static final String NAME = "Currency"; @Override public Currency classifyPosition(Position position) { try { return FinancialSecurityUtils.getCurrency(position.getSecurity()); } catch (UnsupportedOperationException ex) { return "Unknown"; } } public String getName() { return NAME; } }
package org.jetbrains.plugins.coursecreator.actions; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.coursecreator.CCProjectService; import org.jetbrains.plugins.coursecreator.format.*; import org.jetbrains.plugins.coursecreator.ui.CreateTaskWindowDialog; import java.util.List; public class CCAddTaskWindow extends DumbAwareAction { private static final Logger LOG = Logger.getInstance(CCAddTaskWindow.class); public CCAddTaskWindow() { super("Add problem to solve", "Add problem to solve", null); } private static boolean areTaskWindowsIntersect(@NotNull final TaskFile taskFile, @NotNull final Document document, int start, int end) { List<TaskWindow> taskWindows = taskFile.getTaskWindows(); for (TaskWindow existingTaskWindow : taskWindows) { int twStart = existingTaskWindow.getRealStartOffset(document); int twEnd = existingTaskWindow.getReplacementLength() + twStart; if ((start >= twStart && start < twEnd) || (end > twStart && end <= twEnd) || (twStart >= start && twStart < end) || (twEnd > start && twEnd <= end)) { return true; } } return false; } @Override public void actionPerformed(@NotNull AnActionEvent e) { final Project project = e.getData(CommonDataKeys.PROJECT); if (project == null) { return; } final PsiFile file = CommonDataKeys.PSI_FILE.getData(e.getDataContext()); if (file == null) return; final Editor editor = CommonDataKeys.EDITOR.getData(e.getDataContext()); if (editor == null) return; final SelectionModel model = editor.getSelectionModel(); final Document document = PsiDocumentManager.getInstance(project).getDocument(file); if (document == null) return; final int start = model.getSelectionStart(); final int end = model.getSelectionEnd(); final int lineNumber = document.getLineNumber(start); final int length = end - start; int realStart = start - document.getLineStartOffset(lineNumber); final CCProjectService service = CCProjectService.getInstance(project); final Course course = service.getCourse(); final PsiDirectory taskDir = file.getContainingDirectory(); final PsiDirectory lessonDir = taskDir.getParent(); if (lessonDir == null) return; final Lesson lesson = course.getLesson(lessonDir.getName()); final Task task = lesson.getTask(taskDir.getName()); final TaskFile taskFile = task.getTaskFile(file.getName()); if (taskFile == null) { return; } if (areTaskWindowsIntersect(taskFile, document, start, end)) { return; } final TaskWindow taskWindow = new TaskWindow(lineNumber, realStart, length, model.getSelectedText()); CreateTaskWindowDialog dlg = new CreateTaskWindowDialog(project, taskWindow, lesson.getIndex(), task.getIndex(), file.getVirtualFile().getNameWithoutExtension(), taskFile.getTaskWindows().size() + 1); dlg.show(); if (dlg.getExitCode() != DialogWrapper.OK_EXIT_CODE) { return; } int index = taskFile.getTaskWindows().size() + 1; taskFile.addTaskWindow(taskWindow, index); taskWindow.drawHighlighter(editor, false); taskWindow.createGuardedBlocks(editor); } @Override public void update(@NotNull AnActionEvent event) { if (!CCProjectService.setCCActionAvailable(event)) { return; } final Presentation presentation = event.getPresentation(); final Project project = event.getData(CommonDataKeys.PROJECT); if (project == null) { presentation.setVisible(false); presentation.setEnabled(false); return; } final Editor editor = CommonDataKeys.EDITOR.getData(event.getDataContext()); final PsiFile file = CommonDataKeys.PSI_FILE.getData(event.getDataContext()); if (editor == null || file == null) { presentation.setVisible(false); presentation.setEnabled(false); return; } SelectionModel selectionModel = editor.getSelectionModel(); if (!selectionModel.hasSelection()) { presentation.setVisible(false); presentation.setEnabled(false); return; } int start = selectionModel.getSelectionStart(); int end = selectionModel.getSelectionEnd(); final CCProjectService service = CCProjectService.getInstance(project); final Course course = service.getCourse(); final PsiDirectory taskDir = file.getContainingDirectory(); final PsiDirectory lessonDir = taskDir.getParent(); if (lessonDir == null) return; final Lesson lesson = course.getLesson(lessonDir.getName()); if (lesson == null) { presentation.setVisible(false); presentation.setEnabled(false); return; } final Task task = lesson.getTask(taskDir.getName()); if (task == null) { presentation.setVisible(false); presentation.setEnabled(false); return; } TaskFile taskFile = task.getTaskFile(file.getName()); if (taskFile == null) { LOG.info("could not find task file"); presentation.setVisible(false); presentation.setEnabled(false); return; } if (areTaskWindowsIntersect(taskFile, editor.getDocument(), start, end)) { presentation.setVisible(false); presentation.setEnabled(false); return; } presentation.setVisible(true); presentation.setEnabled(true); } }
package com.ForgeEssentials.core.misc; import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntityChest; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.entity.player.PlayerDropsEvent; import com.ForgeEssentials.api.permissions.IPermRegisterEvent; import com.ForgeEssentials.api.permissions.PermRegister; import com.ForgeEssentials.api.permissions.PermissionsAPI; import com.ForgeEssentials.api.permissions.RegGroup; import com.ForgeEssentials.api.permissions.query.PermQueryPlayer; import com.ForgeEssentials.util.OutputHandler; public class DeathChest { private static final String PERM = "ForgeEssentials.DeathChest"; public static DeathChest instance; public static boolean enable; public DeathChest() { instance = this; } @ForgeSubscribe() public void deathEvent(PlayerDropsEvent e) { if(!enable) return; if(PermissionsAPI.checkPermAllowed(new PermQueryPlayer(e.entityPlayer, PERM))) { int X = (int) e.entityPlayer.posX, Y = (int) e.entityPlayer.posY, Z = (int) e.entityPlayer.posZ; int id = e.entityPlayer.worldObj.getBlockId(X, Y, Z); if(id == 0 || id == Block.snow.blockID || id == Block.tallGrass.blockID || id == Block.deadBush.blockID) { e.entityPlayer.worldObj.setBlock(X, Y, Z, Block.chest.blockID); TileEntityChest te = (TileEntityChest) Block.chest.createTileEntity(e.entityPlayer.worldObj, e.entityPlayer.worldObj.getBlockMetadata(X, Y, Z)); if(e.drops.size() > 27) { for(int i = 0; i < 27; i++) { te.setInventorySlotContents(i, e.drops.get(i).getEntityItem().copy()); } check2(e, X, Y, Z); } else { for(int i = 0; i < e.drops.size(); i++) { te.setInventorySlotContents(i, e.drops.get(i).getEntityItem().copy()); } } e.entityPlayer.worldObj.setBlockTileEntity(X, Y, Z, te); e.setCanceled(true); } } } private void check2(PlayerDropsEvent e, int X, int Y, int Z) { int X2 = X + 1, Y2 = Y, Z2 = Z; int id = e.entityPlayer.worldObj.getBlockId(X2, Y2, Z2); if(id == 0 || id == Block.snow.blockID || id == Block.tallGrass.blockID || id == Block.deadBush.blockID) { do2(e, X2, Y2, Z2); return; } X2 = X - 1; id = e.entityPlayer.worldObj.getBlockId(X2, Y2, Z2); if(id == 0 || id == Block.snow.blockID || id == Block.tallGrass.blockID || id == Block.deadBush.blockID) { do2(e, X2, Y2, Z2); return; } X2 = X; Y2 = Y + 1; id = e.entityPlayer.worldObj.getBlockId(X2, Y2, Z2); if(id == 0 || id == Block.snow.blockID || id == Block.tallGrass.blockID || id == Block.deadBush.blockID) { do2(e, X2, Y2, Z2); return; } Y2 = Y - 1; id = e.entityPlayer.worldObj.getBlockId(X2, Y2, Z2); if(id == 0 || id == Block.snow.blockID || id == Block.tallGrass.blockID || id == Block.deadBush.blockID) { do2(e, X2, Y2, Z2); return; } Y2 = Y; Z2 = Z + 1; id = e.entityPlayer.worldObj.getBlockId(X2, Y2, Z2); if(id == 0 || id == Block.snow.blockID || id == Block.tallGrass.blockID || id == Block.deadBush.blockID) { do2(e, X2, Y2, Z2); return; } Z2 = Z - 1; id = e.entityPlayer.worldObj.getBlockId(X2, Y2, Z2); if(id == 0 || id == Block.snow.blockID || id == Block.tallGrass.blockID || id == Block.deadBush.blockID) { do2(e, X2, Y2, Z2); return; } /* * If all else fails... */ for(int i = 27; i < e.drops.size(); i++) { e.entityPlayer.worldObj.spawnEntityInWorld(e.drops.get(i)); } } private void do2(PlayerDropsEvent e, int X2, int Y2, int Z2) { e.entityPlayer.worldObj.setBlock(X2, Y2, Z2, Block.chest.blockID); TileEntityChest te2 = (TileEntityChest) Block.chest.createTileEntity(e.entityPlayer.worldObj, e.entityPlayer.worldObj.getBlockMetadata(X2, Y2, Z2)); for(int i = 27; i < e.drops.size(); i++) { te2.setInventorySlotContents(i - 27, e.drops.get(i).getEntityItem().copy()); } e.entityPlayer.worldObj.setBlockTileEntity(X2, Y2, Z2, te2); } @PermRegister(ident = "FE-Core-bannedItems") public void registerPermissions(IPermRegisterEvent event) { event.registerPermissionLevel(PERM, RegGroup.MEMBERS); } }
package com.jme3.texture; import com.jme3.asset.Asset; import com.jme3.asset.AssetKey; import com.jme3.asset.TextureKey; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.InputCapsule; import com.jme3.export.OutputCapsule; import com.jme3.export.Savable; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * <code>Texture</code> defines a texture object to be used to display an * image on a piece of geometry. The image to be displayed is defined by the * <code>Image</code> class. All attributes required for texture mapping are * contained within this class. This includes mipmapping if desired, * magnificationFilter options, apply options and correction options. Default * values are as follows: minificationFilter - NearestNeighborNoMipMaps, * magnificationFilter - NearestNeighbor, wrap - EdgeClamp on S,T and R, apply - * Modulate, enivoronment - None. * * @see com.jme3.texture.Image * @author Mark Powell * @author Joshua Slack * @version $Id: Texture.java 4131 2009-03-19 20:15:28Z blaine.dev $ */ public abstract class Texture implements Asset, Savable, Cloneable { public enum Type { /** * Two dimensional texture (default). A rectangle. */ TwoDimensional, /** * An array of two dimensional textures. */ TwoDimensionalArray, /** * Three dimensional texture. (A cube) */ ThreeDimensional, /** * A set of 6 TwoDimensional textures arranged as faces of a cube facing * inwards. */ CubeMap; } public enum MinFilter { /** * Nearest neighbor interpolation is the fastest and crudest filtering * method - it simply uses the color of the texel closest to the pixel * center for the pixel color. While fast, this results in aliasing and * shimmering during minification. (GL equivalent: GL_NEAREST) */ NearestNoMipMaps(false), /** * In this method the four nearest texels to the pixel center are * sampled (at texture level 0), and their colors are combined by * weighted averages. Though smoother, without mipmaps it suffers the * same aliasing and shimmering problems as nearest * NearestNeighborNoMipMaps. (GL equivalent: GL_LINEAR) */ BilinearNoMipMaps(false), /** * Same as NearestNeighborNoMipMaps except that instead of using samples * from texture level 0, the closest mipmap level is chosen based on * distance. This reduces the aliasing and shimmering significantly, but * does not help with blockiness. (GL equivalent: * GL_NEAREST_MIPMAP_NEAREST) */ NearestNearestMipMap(true), /** * Same as BilinearNoMipMaps except that instead of using samples from * texture level 0, the closest mipmap level is chosen based on * distance. By using mipmapping we avoid the aliasing and shimmering * problems of BilinearNoMipMaps. (GL equivalent: * GL_LINEAR_MIPMAP_NEAREST) */ BilinearNearestMipMap(true), /** * Similar to NearestNeighborNoMipMaps except that instead of using * samples from texture level 0, a sample is chosen from each of the * closest (by distance) two mipmap levels. A weighted average of these * two samples is returned. (GL equivalent: GL_NEAREST_MIPMAP_LINEAR) */ NearestLinearMipMap(true), /** * Trilinear filtering is a remedy to a common artifact seen in * mipmapped bilinearly filtered images: an abrupt and very noticeable * change in quality at boundaries where the renderer switches from one * mipmap level to the next. Trilinear filtering solves this by doing a * texture lookup and bilinear filtering on the two closest mipmap * levels (one higher and one lower quality), and then linearly * interpolating the results. This results in a smooth degradation of * texture quality as distance from the viewer increases, rather than a * series of sudden drops. Of course, closer than Level 0 there is only * one mipmap level available, and the algorithm reverts to bilinear * filtering (GL equivalent: GL_LINEAR_MIPMAP_LINEAR) */ Trilinear(true); private boolean usesMipMapLevels; private MinFilter(boolean usesMipMapLevels) { this.usesMipMapLevels = usesMipMapLevels; } public boolean usesMipMapLevels() { return usesMipMapLevels; } } public enum MagFilter { /** * Nearest neighbor interpolation is the fastest and crudest filtering * mode - it simply uses the color of the texel closest to the pixel * center for the pixel color. While fast, this results in texture * 'blockiness' during magnification. (GL equivalent: GL_NEAREST) */ Nearest, /** * In this mode the four nearest texels to the pixel center are sampled * (at the closest mipmap level), and their colors are combined by * weighted average according to distance. This removes the 'blockiness' * seen during magnification, as there is now a smooth gradient of color * change from one texel to the next, instead of an abrupt jump as the * pixel center crosses the texel boundary. (GL equivalent: GL_LINEAR) */ Bilinear; } public enum WrapMode { /** * Only the fractional portion of the coordinate is considered. */ Repeat, /** * Only the fractional portion of the coordinate is considered, but if * the integer portion is odd, we'll use 1 - the fractional portion. * (Introduced around OpenGL1.4) Falls back on Repeat if not supported. */ MirroredRepeat, /** * coordinate will be clamped to [0,1] */ Clamp, /** * mirrors and clamps the texture coordinate, where mirroring and * clamping a value f computes: * <code>mirrorClamp(f) = min(1, max(1/(2*N), * abs(f)))</code> where N * is the size of the one-, two-, or three-dimensional texture image in * the direction of wrapping. (Introduced after OpenGL1.4) Falls back on * Clamp if not supported. */ MirrorClamp, /** * coordinate will be clamped to the range [-1/(2N), 1 + 1/(2N)] where N * is the size of the texture in the direction of clamping. Falls back * on Clamp if not supported. */ BorderClamp, /** * Wrap mode MIRROR_CLAMP_TO_BORDER_EXT mirrors and clamps to border the * texture coordinate, where mirroring and clamping to border a value f * computes: * <code>mirrorClampToBorder(f) = min(1+1/(2*N), max(1/(2*N), abs(f)))</code> * where N is the size of the one-, two-, or three-dimensional texture * image in the direction of wrapping." (Introduced after OpenGL1.4) * Falls back on BorderClamp if not supported. */ MirrorBorderClamp, /** * coordinate will be clamped to the range [1/(2N), 1 - 1/(2N)] where N * is the size of the texture in the direction of clamping. Falls back * on Clamp if not supported. */ EdgeClamp, /** * mirrors and clamps to edge the texture coordinate, where mirroring * and clamping to edge a value f computes: * <code>mirrorClampToEdge(f) = min(1-1/(2*N), max(1/(2*N), abs(f)))</code> * where N is the size of the one-, two-, or three-dimensional texture * image in the direction of wrapping. (Introduced after OpenGL1.4) * Falls back on EdgeClamp if not supported. */ MirrorEdgeClamp; } public enum WrapAxis { /** * S wrapping (u or "horizontal" wrap) */ S, /** * T wrapping (v or "vertical" wrap) */ T, /** * R wrapping (w or "depth" wrap) */ R; } /** * If this texture is a depth texture (the format is Depth*) then * this value may be used to compare the texture depth to the R texture * coordinate. */ public enum ShadowCompareMode { /** * Shadow comparison mode is disabled. * Texturing is done normally. */ Off, /** * Compares the 3rd texture coordinate R to the value * in this depth texture. If R <= texture value then result is 1.0, * otherwise, result is 0.0. If filtering is set to bilinear or trilinear * the implementation may sample the texture multiple times to provide * smoother results in the range [0, 1]. */ LessOrEqual, /** * Compares the 3rd texture coordinate R to the value * in this depth texture. If R >= texture value then result is 1.0, * otherwise, result is 0.0. If filtering is set to bilinear or trilinear * the implementation may sample the texture multiple times to provide * smoother results in the range [0, 1]. */ GreaterOrEqual } /** * The name of the texture (if loaded as a resource). */ private String name = null; /** * The image stored in the texture */ private Image image = null; /** * The texture key allows to reload a texture from a file * if needed. */ private TextureKey key = null; private MinFilter minificationFilter = MinFilter.BilinearNoMipMaps; private MagFilter magnificationFilter = MagFilter.Bilinear; private ShadowCompareMode shadowCompareMode = ShadowCompareMode.Off; private int anisotropicFilter; /** * @return */ @Override public Texture clone(){ try { return (Texture) super.clone(); } catch (CloneNotSupportedException ex) { throw new AssertionError(); } } /** * Constructor instantiates a new <code>Texture</code> object with default * attributes. */ public Texture() { } /** * @return the MinificationFilterMode of this texture. */ public MinFilter getMinFilter() { return minificationFilter; } public void setMinFilter(MinFilter minificationFilter) { if (minificationFilter == null) { throw new IllegalArgumentException( "minificationFilter can not be null."); } this.minificationFilter = minificationFilter; } /** * @return the MagnificationFilterMode of this texture. */ public MagFilter getMagFilter() { return magnificationFilter; } public void setMagFilter(MagFilter magnificationFilter) { if (magnificationFilter == null) { throw new IllegalArgumentException( "magnificationFilter can not be null."); } this.magnificationFilter = magnificationFilter; } /** * @return The ShadowCompareMode of this texture. * @see ShadowCompareMode */ public ShadowCompareMode getShadowCompareMode(){ return shadowCompareMode; } public void setShadowCompareMode(ShadowCompareMode compareMode){ if (compareMode == null){ throw new IllegalArgumentException( "compareMode can not be null."); } this.shadowCompareMode = compareMode; } /** * <code>setImage</code> sets the image object that defines the texture. * * @param image * the image that defines the texture. */ public void setImage(Image image) { this.image = image; } /** * @param key The texture key that was used to load this texture */ public void setKey(AssetKey key){ this.key = (TextureKey) key; } public AssetKey getKey(){ return this.key; } /** * <code>getImage</code> returns the image data that makes up this * texture. If no image data has been set, this will return null. * * @return the image data that makes up the texture. */ public Image getImage() { return image; } public abstract void setWrap(WrapAxis axis, WrapMode mode); public abstract void setWrap(WrapMode mode); public abstract WrapMode getWrap(WrapAxis axis); public abstract Type getType(); public String getName() { return name; } public void setName(String name) { this.name = name; } /** * @return the anisotropic filtering level for this texture. Default value * is 1 (no anisotrophy), 2 means x2, 4 is x4, etc. */ public int getAnisotropicFilter() { return anisotropicFilter; } /** * @param level * the anisotropic filtering level for this texture. */ public void setAnisotropicFilter(int level) { if (level < 1) anisotropicFilter = 1; else anisotropicFilter = level; } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append("[name=").append(name); if (image != null) sb.append(", image=").append(image.toString()); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Texture other = (Texture) obj; if (this.image != other.image && (this.image == null || !this.image.equals(other.image))) { return false; } if (this.minificationFilter != other.minificationFilter) { return false; } if (this.magnificationFilter != other.magnificationFilter) { return false; } if (this.shadowCompareMode != other.shadowCompareMode) { return false; } if (this.anisotropicFilter != other.anisotropicFilter) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 67 * hash + (this.image != null ? this.image.hashCode() : 0); hash = 67 * hash + (this.minificationFilter != null ? this.minificationFilter.hashCode() : 0); hash = 67 * hash + (this.magnificationFilter != null ? this.magnificationFilter.hashCode() : 0); hash = 67 * hash + (this.shadowCompareMode != null ? this.shadowCompareMode.hashCode() : 0); hash = 67 * hash + this.anisotropicFilter; return hash; } // public abstract Texture createSimpleClone(); /** Retreive a basic clone of this Texture (ie, clone everything but the * image data, which is shared) * * @return Texture */ public Texture createSimpleClone(Texture rVal) { rVal.setMinFilter(minificationFilter); rVal.setMagFilter(magnificationFilter); rVal.setShadowCompareMode(shadowCompareMode); // rVal.setHasBorder(hasBorder); rVal.setAnisotropicFilter(anisotropicFilter); rVal.setImage(image); // NOT CLONED. // rVal.memReq = memReq; rVal.setKey(key); rVal.setName(name); // rVal.setBlendColor(blendColor != null ? blendColor.clone() : null); // if (getTextureKey() != null) { // rVal.setTextureKey(getTextureKey()); return rVal; } public abstract Texture createSimpleClone(); public void write(JmeExporter e) throws IOException { OutputCapsule capsule = e.getCapsule(this); capsule.write(name, "name", null); if (key == null){ // no texture key is set, try to save image instead then capsule.write(image, "image", null); }else{ capsule.write(key, "key", null); } capsule.write(anisotropicFilter, "anisotropicFilter", 1); capsule.write(minificationFilter, "minificationFilter", MinFilter.BilinearNoMipMaps); capsule.write(magnificationFilter, "magnificationFilter", MagFilter.Bilinear); } public void read(JmeImporter e) throws IOException { InputCapsule capsule = e.getCapsule(this); name = capsule.readString("name", null); key = (TextureKey) capsule.readSavable("key", null); // load texture from key, if available if (key != null) { // key is available, so try the texture from there. Texture loadedTex = e.getAssetManager().loadTexture(key); if (loadedTex == null) { Logger.getLogger(Texture.class.getName()).log(Level.SEVERE, "Could not load texture: {0}", key.toString()); } else { image = loadedTex.getImage(); } }else{ // no key is set on the texture. Attempt to load an embedded image image = (Image) capsule.readSavable("image", null); if (image == null){ // TODO: what to print out here? the texture has no key or data, there's no useful information .. // assume texture.name is set even though the key is null Logger.getLogger(Texture.class.getName()).log(Level.SEVERE, "Could not load embedded image: {0}", toString() ); } } anisotropicFilter = capsule.readInt("anisotropicFilter", 1); minificationFilter = capsule.readEnum("minificationFilter", MinFilter.class, MinFilter.BilinearNoMipMaps); magnificationFilter = capsule.readEnum("magnificationFilter", MagFilter.class, MagFilter.Bilinear); } }
package com.speedment.runtime.compute; import com.speedment.runtime.compute.expression.Expression; import com.speedment.runtime.compute.expression.ExpressionType; import com.speedment.runtime.compute.internal.ToEnumImpl; import com.speedment.runtime.compute.internal.ToEnumNullableImpl; import com.speedment.runtime.compute.internal.expression.ComposedUtil; import com.speedment.runtime.compute.internal.expression.OrElseGetUtil; import com.speedment.runtime.compute.internal.expression.OrElseThrowUtil; import com.speedment.runtime.compute.internal.expression.OrElseUtil; import com.speedment.runtime.compute.trait.HasCompare; import com.speedment.runtime.compute.trait.HasHash; import com.speedment.runtime.compute.trait.ToNullable; import java.util.function.Function; import java.util.function.UnaryOperator; /** * Expression that given an entity returns an {@code enum} value, or * {@code null}. The expression also knows about the enum class and can * therefore not be implemented as a lambda like the other expressions in this * module. * * @param <T> type to extract from * @param <E> enum type * * @see Function * * @author Emil Forslund * @since 3.1.0 */ public interface ToEnumNullable<T, E extends Enum<E>> extends Expression<T>, ToNullable<T, E>, HasHash<T>, HasCompare<T> { static <T, E extends Enum<E>> ToEnumNullable<T, E> toEnumNullable(Class<E> enumClass, Function<T, E> getter) { return new ToEnumNullableImpl<>(enumClass, getter); } Class<E> enumClass(); @Override default ExpressionType expressionType() { return ExpressionType.ENUM_NULLABLE; } default ToIntNullable<T> asOrdinal() { return t -> isNotNull(t) ? apply(t).ordinal() : null; } default ToStringNullable<T> asName() { return t -> isNotNull(t) ? apply(t).name() : null; } default ToEnum<T, E> orThrow() { return OrElseThrowUtil.orElseThrow(this); } default ToEnum<T, E> orElseGet(ToEnum<T, E> getter) { return OrElseGetUtil.orElseGet(this, getter); } default ToEnum<T, E> orElse(E value) { return OrElseUtil.orElse(this, value); } default ToDoubleNullable<T> mapToDoubleIfPresent(ToDouble<E> mapper) { final ToEnumNullable<T, E> delegate = this; return new ToDoubleNullable<T>() { @Override public Double apply(T object) { return delegate.isNull(object) ? null : mapper.applyAsDouble(delegate.apply(object)); } @Override public double applyAsDouble(T object) throws NullPointerException { return mapper.applyAsDouble(delegate.apply(object)); } @Override public ToDouble<T> orElseGet(ToDouble<T> getter) { return object -> delegate.isNull(object) ? getter.applyAsDouble(object) : mapper.applyAsDouble(delegate.apply(object)); } @Override public ToDouble<T> orElse(double value) { return object -> delegate.isNull(object) ? value : mapper.applyAsDouble(delegate.apply(object)); } @Override public boolean isNull(T object) { return delegate.isNull(object); } @Override public boolean isNotNull(T object) { return delegate.isNotNull(object); } }; } default ToEnumNullable<T, E> mapIfPresent(UnaryOperator<E> mapper) { final ToEnumNullable<T, E> delegate = this; return new ToEnumNullable<T, E>() { @Override public Class<E> enumClass() { return delegate.enumClass(); } @Override public E apply(T object) { return delegate.isNull(object) ? null : mapper.apply(delegate.apply(object)); } @Override public ToEnum<T, E> orElseGet(ToEnum<T, E> getter) { return new ToEnumImpl<>( delegate.enumClass(), object -> delegate.isNull(object) ? getter.apply(object) : mapper.apply(delegate.apply(object)) ); } @Override public ToEnum<T, E> orElse(E value) { return new ToEnumImpl<>( delegate.enumClass(), object -> delegate.isNull(object) ? value : mapper.apply(delegate.apply(object)) ); } @Override public boolean isNull(T object) { return delegate.isNull(object); } @Override public boolean isNotNull(T object) { return delegate.isNotNull(object); } }; } @Override default long hash(T object) { final E e = apply(object); return e == null ? -1 : e.hashCode(); } @Override default int compare(T first, T second) { final E a = apply(first); final E b = apply(second); if (a == null) { return (b == null) ? -1 : 0; } else { return a.compareTo(b); } } @Override @SuppressWarnings("unchecked") default <V> ToEnumNullable<V, E> compose(Function<? super V, ? extends T> before) { return ComposedUtil.composeNullable((Function<V, T>) before, this); } }
package com.example.bot.spring; import java.io.IOException; import java.io.OutputStream; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import java.net.URISyntaxException; import java.net.URI; import java.sql.*; import javax.sql.DataSource;; import java.util.Timer; import java.util.TimerTask; import java.lang.Override; import com.heroku.sdk.jdbc.DatabaseUrl; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.google.common.io.ByteStreams; import com.linecorp.bot.client.LineMessagingClient; import com.linecorp.bot.client.MessageContentResponse; import com.linecorp.bot.model.ReplyMessage; import com.linecorp.bot.model.Multicast; import com.linecorp.bot.model.PushMessage; import com.linecorp.bot.model.action.MessageAction; import com.linecorp.bot.model.action.PostbackAction; import com.linecorp.bot.model.action.URIAction; import com.linecorp.bot.model.event.BeaconEvent; import com.linecorp.bot.model.event.Event; import com.linecorp.bot.model.event.FollowEvent; import com.linecorp.bot.model.event.JoinEvent; import com.linecorp.bot.model.event.MessageEvent; import com.linecorp.bot.model.event.PostbackEvent; import com.linecorp.bot.model.event.UnfollowEvent; import com.linecorp.bot.model.event.message.AudioMessageContent; import com.linecorp.bot.model.event.message.ImageMessageContent; import com.linecorp.bot.model.event.message.LocationMessageContent; import com.linecorp.bot.model.event.message.StickerMessageContent; import com.linecorp.bot.model.event.message.TextMessageContent; import com.linecorp.bot.model.event.message.VideoMessageContent; import com.linecorp.bot.model.event.source.GroupSource; import com.linecorp.bot.model.event.source.RoomSource; import com.linecorp.bot.model.event.source.Source; import com.linecorp.bot.model.message.AudioMessage; import com.linecorp.bot.model.message.ImageMessage; import com.linecorp.bot.model.message.ImagemapMessage; import com.linecorp.bot.model.message.LocationMessage; import com.linecorp.bot.model.message.Message; import com.linecorp.bot.model.message.StickerMessage; import com.linecorp.bot.model.message.TemplateMessage; import com.linecorp.bot.model.message.TextMessage; import com.linecorp.bot.model.message.VideoMessage; import com.linecorp.bot.model.message.imagemap.ImagemapArea; import com.linecorp.bot.model.message.imagemap.ImagemapBaseSize; import com.linecorp.bot.model.message.imagemap.MessageImagemapAction; import com.linecorp.bot.model.message.imagemap.URIImagemapAction; import com.linecorp.bot.model.message.template.ButtonsTemplate; import com.linecorp.bot.model.message.template.CarouselColumn; import com.linecorp.bot.model.message.template.CarouselTemplate; import com.linecorp.bot.model.message.template.ConfirmTemplate; import com.linecorp.bot.model.profile.UserProfileResponse; import com.linecorp.bot.model.response.BotApiResponse; import com.linecorp.bot.spring.boot.annotation.EventMapping; import com.linecorp.bot.spring.boot.annotation.LineMessageHandler; import lombok.NonNull; import lombok.Value; import lombok.extern.slf4j.Slf4j; @Slf4j @LineMessageHandler @RestController public class KitchenSinkController { @Autowired private LineMessagingClient lineMessagingClient; public Timer t0; public String TokenCallback1; @EventMapping public void handleTextMessageEvent(MessageEvent<TextMessageContent> event) throws Exception { TextMessageContent message = event.getMessage(); handleTextContent(event.getReplyToken(), event, message); } @EventMapping public void handleStickerMessageEvent(MessageEvent<StickerMessageContent> event) { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleLocationMessageEvent(MessageEvent<LocationMessageContent> event) { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleImageMessageEvent(MessageEvent<ImageMessageContent> event) throws IOException { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleAudioMessageEvent(MessageEvent<AudioMessageContent> event) throws IOException { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleVideoMessageEvent(MessageEvent<VideoMessageContent> event) throws IOException { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleUnfollowEvent(UnfollowEvent event) { log.info("unfollowed this bot: {}", event); } @EventMapping public void handleFollowEvent(FollowEvent event) { String replyToken = event.getReplyToken(); this.replyText(replyToken, "Anda mengikuti bot"); } @EventMapping public void handleJoinEvent(JoinEvent event) { String replyToken = event.getReplyToken(); this.replyText(replyToken, "Bot telah bergabung ke grup anda untuk info lebih lanjut /help" ); } @EventMapping public void handlePostbackEvent(PostbackEvent event) { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleBeaconEvent(BeaconEvent event) { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleOtherEvent(Event event) { log.info("Received message(Ignored): {}", event); } private void reply(@NonNull String replyToken, @NonNull Message message) { reply(replyToken, Collections.singletonList(message)); } private void reply(@NonNull String replyToken, @NonNull List<Message> messages) { try { BotApiResponse apiResponse = lineMessagingClient .replyMessage(new ReplyMessage(replyToken, messages)) .get(); log.info("Sent messages: {}", apiResponse); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } private void replyText(@NonNull String replyToken, @NonNull String message) { if (replyToken.isEmpty()) { throw new IllegalArgumentException("replyToken tidak boleh kosong"); } if (message.length() > 1000) { message = message.substring(0, 1000 - 2); } this.reply(replyToken, new TextMessage(message)); } private void push(@NonNull String To, @NonNull Message message) { push(To, Collections.singletonList(message)); } private void push(@NonNull String To, @NonNull List<Message> messages) { try { BotApiResponse apiResponse = lineMessagingClient .pushMessage(new PushMessage(To, messages)) .get(); log.info("Sent messages: {}", apiResponse); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } private void pushText(@NonNull String To, @NonNull String message) { if (To.isEmpty()) { throw new IllegalArgumentException("replyToken tidak boleh kosong"); } if (message.length() > 1000) { message = message.substring(0, 1000 - 2); } this.push(To, new TextMessage(message)); } private Timer startTimer(final String value) { Timer timer = new Timer("Timer" + value); return timer; } private void handleTextContent(String replyToken, Event event, TextMessageContent content) throws Exception { String text = content.getText(); log.info("Got text message from {}: {}", replyToken, text); if (text.indexOf("/create")>=0){ String userId = event.getSource().getUserId(); if (userId != null) { lineMessagingClient.getProfile(userId).whenComplete((profile, throwable) -> { if (throwable != null) { this.replyText(replyToken, throwable.getMessage()); return; } this.replyText(replyToken, profile.getDisplayName()+" Telah Membuat Game"); String imageUrl = createUri("/static/buttons/1040.jpg"); ButtonsTemplate buttonsTemplate = new ButtonsTemplate( imageUrl, "Klik join Untuk Bergabung dalam permainan", "Teka Teki Indonesia", Arrays.asList( new MessageAction("join", "/join") )); TemplateMessage templateMessage = new TemplateMessage("Teka Teki Indonesia", buttonsTemplate); this.reply(replyToken, templateMessage); Source source = event.getSource(); String groupid=""; String userid=""; this.TokenCallback1 = replyToken; if (source instanceof GroupSource) { groupid = ((GroupSource) source).getGroupId(); KitchenSinkController.this.t0 = startTimer(groupid); } if (groupid ==""){ userid = event.getSource().getUserId(); KitchenSinkController.this.t0 = startTimer(userid); } KitchenSinkController.this.t0.schedule( new TimerTask() { @Override public void run() { try{ Connection connection = KitchenSinkController.getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("DROP TABLE IF EXISTS ticks"); stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now() + INTERVAL '7 HOUR')"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); }catch(SQLException e){ KitchenSinkController.this.replyText(KitchenSinkController.this.TokenCallback1,e.getMessage()); }catch(URISyntaxException err){ KitchenSinkController.this.replyText(KitchenSinkController.this.TokenCallback1,err.getMessage()); } } }, 60000, 100); // Every second }); } else { this.replyText(replyToken, "Tolong izinkan Bot mengakses akun"); } }else if (text.indexOf("/leave")>=0){ Source source = event.getSource(); if (source instanceof GroupSource) { this.replyText(replyToken, "Bot meninggalkan grup"); lineMessagingClient.leaveGroup(((GroupSource) source).getGroupId()).get(); } else if (source instanceof RoomSource) { this.replyText(replyToken, "Bot meninggalkan ruangan"); lineMessagingClient.leaveRoom(((RoomSource) source).getRoomId()).get(); } else { this.replyText(replyToken, "ini room 1:1 tidak bisa menggunakan perintah /leave"); } }else if (text.indexOf("/join")>=0){ String userId = event.getSource().getUserId(); string profil = lineMessagingClient.getProfile(userId).getDisplayName(); this.reply(replyToken,"join", profil+" telah Bergabung ke dalam game"); }else if (text.indexOf("/help")>=0){ this.replyText(replyToken, "feature /help : bantuan\n"+"/imagemap:gambar yang dapat diklik\n"+"/buttons:tombol\n"+ "/question:pertanyaan\n"+"/carousel:carousel\n"+"/leave:keluar dari grup\n"+"/profile:user ID\n"); }else if(text.indexOf("/time")>=0){ try{ Connection connection = getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("DROP TABLE IF EXISTS ticks"); stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now() + INTERVAL '7 HOUR')"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); while (rs.next()) { this.replyText(replyToken,"Read from DB: " + rs.getTimestamp("tick")); } }catch(SQLException e){ this.replyText(replyToken,e.getMessage()); }catch(URISyntaxException err){ this.replyText(replyToken,err.getMessage()); } }else if(text.indexOf("/cancel")>=0){ Source source = event.getSource(); String groupid=""; String userid=""; if (source instanceof GroupSource) { groupid = ((GroupSource) source).getGroupId(); KitchenSinkController.this.t0 = startTimer(groupid); } if (groupid ==""){ userid = event.getSource().getUserId(); KitchenSinkController.this.t0 = startTimer(userid); } KitchenSinkController.this.t0.cancel(); }else{ log.info("Ignore message {}: {}", replyToken, text); } } private static Connection getConnection() throws URISyntaxException, SQLException { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath(); return DriverManager.getConnection(dbUrl, username, password); } private static String createUri(String path) { return ServletUriComponentsBuilder.fromCurrentContextPath() .path(path).build() .toUriString(); } private void system(String... args) { ProcessBuilder processBuilder = new ProcessBuilder(args); try { Process start = processBuilder.start(); int i = start.waitFor(); log.info("result: {} => {}", Arrays.toString(args), i); } catch (IOException e) { throw new UncheckedIOException(e); } catch (InterruptedException e) { log.info("Interrupted", e); Thread.currentThread().interrupt(); } } private static DownloadedContent saveContent(String ext, MessageContentResponse responseBody) { log.info("Got content-type: {}", responseBody); DownloadedContent tempFile = createTempFile(ext); try (OutputStream outputStream = Files.newOutputStream(tempFile.path)) { ByteStreams.copy(responseBody.getStream(), outputStream); log.info("Saved {}: {}", ext, tempFile); return tempFile; } catch (IOException e) { throw new UncheckedIOException(e); } } private static DownloadedContent createTempFile(String ext) { String fileName = LocalDateTime.now().toString() + '-' + UUID.randomUUID().toString() + '.' + ext; Path tempFile = KitchenSinkApplication.downloadedContentDir.resolve(fileName); tempFile.toFile().deleteOnExit(); return new DownloadedContent( tempFile, createUri("/downloaded/" + tempFile.getFileName())); } @Value public static class DownloadedContent { Path path; String uri; } @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="UserId", defaultValue="") String User,@RequestParam(value="message", defaultValue="") String message) { this.pushText(User, message); return new Greeting(User,message); } }
package org.orienteer.birt.orientdb.impl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.List; import java.util.Properties; import javax.xml.bind.DatatypeConverter; import org.eclipse.datatools.connectivity.oda.IParameterMetaData; import org.eclipse.datatools.connectivity.oda.IQuery; import org.eclipse.datatools.connectivity.oda.IResultSet; import org.eclipse.datatools.connectivity.oda.IResultSetMetaData; import org.eclipse.datatools.connectivity.oda.OdaException; import org.eclipse.datatools.connectivity.oda.SortSpec; import org.eclipse.datatools.connectivity.oda.spec.QuerySpecification; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.record.impl.ODocument; public class HttpQuery implements IQuery{ private ODocument dbResult; private ResultSetMetaData curMetaData; private ResultSet curResultSet; private int m_maxRows; private String queryText; private HttpConnection connection; public HttpQuery(HttpConnection connection){ this.connection = connection; } @Override public void prepare(String query) throws OdaException { Properties connProperties = connection.getProperties(); String url = connProperties.getProperty(Connection.DB_URI_PROPERTY);//"remote:127.0.0.1/Orienteer"; String username = connProperties.getProperty(Connection.DB_USER_PROPERTY);//"admin"; String password = connProperties.getProperty(Connection.DB_PASSWORD_PROPERTY);//"admin"; try { URL obj = new URL(url+URLEncoder.encode(query, "UTF-8")+"/"+(getMaxRows()==0?-1:getMaxRows())); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("accept", "application/json"); con.setRequestProperty("Authorization", "Basic " + DatatypeConverter.printBase64Binary((username + ":" + password).getBytes())); //int responseCode = con.getResponseCode(); BufferedReader in; in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String out = response.toString(); ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(); if (db==null){ //convert datetime to default format out = out.replaceAll("\\\"(\\d\\d\\d\\d\\-\\d\\d\\-\\d\\d\\s\\d\\d\\:\\d\\d\\:\\d\\d)\\\"", "\"$1:000\""); } dbResult = new ODocument(); dbResult.fromJSON(out); List<ODocument> resultList = dbResult.field("result"); curMetaData = new ResultSetMetaData(resultList.get(0)); curResultSet = new ResultSet(resultList,curMetaData); } catch (IOException e) { throw new OdaException(e); } } @Override public IResultSet executeQuery() throws OdaException { // TODO Auto-generated method stub return curResultSet; } @Override public void close() throws OdaException { // TODO Auto-generated method stub } @Override public void cancel() throws OdaException, UnsupportedOperationException { // TODO Auto-generated method stub } @Override public void clearInParameters() throws OdaException { // TODO Auto-generated method stub } @Override public int findInParameter(String arg0) throws OdaException { // TODO Auto-generated method stub return 0; } @Override public String getEffectiveQueryText() { return queryText; } @Override public int getMaxRows() throws OdaException { return m_maxRows; } @Override public IResultSetMetaData getMetaData() throws OdaException { // TODO Auto-generated method stub return curMetaData; } @Override public IParameterMetaData getParameterMetaData() throws OdaException { // TODO Auto-generated method stub return new ParameterMetaData(); } @Override public SortSpec getSortSpec() throws OdaException { // TODO Auto-generated method stub return null; } @Override public QuerySpecification getSpecification() { // TODO Auto-generated method stub return null; } @Override public void setAppContext(Object arg0) throws OdaException { // TODO Auto-generated method stub } @Override public void setBigDecimal(String arg0, BigDecimal arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setBigDecimal(int arg0, BigDecimal arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setBoolean(String arg0, boolean arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setBoolean(int arg0, boolean arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setDate(String arg0, Date arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setDate(int arg0, Date arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setDouble(String arg0, double arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setDouble(int arg0, double arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setInt(String arg0, int arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setInt(int arg0, int arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setMaxRows(int arg0) throws OdaException { m_maxRows = arg0; } @Override public void setNull(String arg0) throws OdaException { // TODO Auto-generated method stub } @Override public void setNull(int arg0) throws OdaException { // TODO Auto-generated method stub } @Override public void setObject(String arg0, Object arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setObject(int arg0, Object arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setProperty(String arg0, String arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setSortSpec(SortSpec arg0) throws OdaException { // TODO Auto-generated method stub } @Override public void setSpecification(QuerySpecification arg0) throws OdaException, UnsupportedOperationException { // TODO Auto-generated method stub } @Override public void setString(String arg0, String arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setString(int arg0, String arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setTime(String arg0, Time arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setTime(int arg0, Time arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setTimestamp(String arg0, Timestamp arg1) throws OdaException { // TODO Auto-generated method stub } @Override public void setTimestamp(int arg0, Timestamp arg1) throws OdaException { // TODO Auto-generated method stub } }
package com.vip.saturn.job.console.aop.aspect; import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import com.vip.saturn.job.console.aop.annotation.Audit; import com.vip.saturn.job.console.aop.annotation.AuditType; import com.vip.saturn.job.console.utils.AuditInfoContext; import com.vip.saturn.job.console.utils.DummyAppender; import com.vip.saturn.job.console.utils.SessionAttributeKeys; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.stereotype.Component; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpringContextAOP.class) public class AuditLogAspectTest { @Autowired private TestAspectClass testClass; @Mock private HttpServletRequest request; @Mock private HttpSession httpSession; private DummyAppender dummyAppender = new DummyAppender(); @Before public void before() { initAppender(); } @After public void after() { RequestContextHolder.resetRequestAttributes(); } @Test public void testRESTRequestAuditLog() { prepareRequest("192.168.1.1", "/home/path", null); testClass.method1(); assertEquals("log size should be 1", 1, dummyAppender.getEvents().size()); assertEquals("log content is not equal", "[INFO] REST API:[/home/path] is called by IP:[192.168.1.1], result is success. Context info:{jobName=jobA, namespace=www.abc.com}.", dummyAppender.getLastEvent().toString()); } @Test public void testWEBRequestAuditLog() { prepareRequest("192.168.1.2", "/home/path2", "usera"); testClass.method2(); assertEquals("log size should be 1", 1, dummyAppender.getEvents().size()); assertEquals("log content is not equal", "[INFO] GUI API:[/home/path2] is called by User:[usera] with IP:[192.168.1.2], result is success. Context info:{jobName=jobB, namespace=www.abc.com}.", dummyAppender.getLastEvent().toString()); } @Test public void testWebRequestAuditLogButFail() { prepareRequest("192.168.1.3", "/home/path3", "userb"); try { testClass.method3(); } catch (RuntimeException e) { // do nothing } assertEquals("log size should be 1", 1, dummyAppender.getEvents().size()); assertEquals("log content is not equal", "[INFO] GUI API:[/home/path3] is called by User:[userb] with IP:[192.168.1.3], result is failed. Context info:{jobName=jobC, namespace=www.abc.com}.", dummyAppender.getLastEvent().toString()); } private void prepareRequest(String ip, String uri, String username) { given(request.getHeader("X-FORWARDED-FOR")).willReturn(ip); given(request.getRequestURI()).willReturn(uri); given(httpSession.getAttribute(SessionAttributeKeys.LOGIN_USER_NAME)).willReturn(username); given(request.getSession()).willReturn(httpSession); ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(servletRequestAttributes); } private void initAppender() { ch.qos.logback.classic.Logger auditlog = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger("AUDITLOG"); if (dummyAppender != null) { dummyAppender.clear(); } auditlog.addAppender(dummyAppender); } } @Configuration @EnableAspectJAutoProxy @ComponentScan(basePackages = {"com.vip.saturn.job.console.aop.aspect"}) class SpringContextAOP { } @Component class TestAspectClass { @Audit(type = AuditType.REST) public void method1() { AuditInfoContext.putNamespace("www.abc.com"); AuditInfoContext.putJobName("jobA"); } @Audit(type = AuditType.WEB) public void method2() { AuditInfoContext.putNamespace("www.abc.com"); AuditInfoContext.putJobName("jobB"); } @Audit public void method3() { AuditInfoContext.putNamespace("www.abc.com"); AuditInfoContext.putJobName("jobC"); throw new RuntimeException("unexpected"); } }
package gov.nih.nci.system.web.struts.action; import gov.nih.nci.system.web.ajax.tree.Category; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.apache.struts2.ServletActionContext; public class Criteria extends BaseActionSupport { private static final long serialVersionUID = 1234567890L; private static Logger log = Logger.getLogger(Criteria.class.getName()); private long nodeId; private Category currentCategory; public void setNodeId(long nodeId) { this.nodeId = nodeId; } public long getNodeId() { return nodeId; } public String execute() throws Exception { currentCategory = Category.getById(nodeId); log.debug(currentCategory); HttpServletRequest request = ServletActionContext.getRequest(); // A Workaround for Criteria.jsp, which requires embedded JSP logic request.setAttribute("klassName", getSelectedDomain()); return SUCCESS; } public String getJavaDocsClassName() { return (getFullyQualClassName().replace('.','/')+".html"); } public String getFullyQualClassName() { return getPackage() + "." + getNodeName(); } public String getNodeName() { return currentCategory.getName(); } public String getPackage() { return currentCategory.getPackageName(); } public String getSelectedDomain() { return getPackage() + "." + getNodeName(); } }
package gov.nih.nci.caarray.platforms.affymetrix; import gov.nih.nci.caarray.application.arraydata.ArrayDataException; import gov.nih.nci.caarray.application.arraydata.ArrayDataIOException; import gov.nih.nci.caarray.domain.data.AbstractDataColumn; import gov.nih.nci.caarray.domain.data.ArrayDataTypeDescriptor; import gov.nih.nci.caarray.domain.data.FloatColumn; import gov.nih.nci.caarray.domain.data.IntegerColumn; import gov.nih.nci.caarray.domain.data.QuantitationType; import gov.nih.nci.caarray.domain.data.QuantitationTypeDescriptor; import gov.nih.nci.caarray.domain.data.ShortColumn; import gov.nih.nci.caarray.domain.data.StringColumn; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import affymetrix.calvin.data.ColumnInfo; import affymetrix.calvin.data.DataGroupHeader; import affymetrix.calvin.data.DataSetHeader; import affymetrix.calvin.data.FileHeader; import affymetrix.calvin.data.GenericDataHeader; import affymetrix.calvin.data.ProbeSetMultiDataCopyNumberData; import affymetrix.calvin.data.CHPMultiDataData.MultiDataType; import affymetrix.calvin.exception.UnsignedOutOfLimitsException; import affymetrix.calvin.parameter.ParameterNameValue; import affymetrix.fusion.chp.FusionCHPMultiDataData; /** * Supports Copy Number Affymetrix CHP file formats. * @author gax * @since 2.4.0 */ @SuppressWarnings("PMD.CyclomaticComplexity") // long switch statements class CnchpData extends AbstractCHPMultiData<ProbeSetMultiDataCopyNumberData> { private final Map<String, CopyNumberQuantitationType> qTypes; /** * @param fusionCHPMultiDataData */ public CnchpData(final FusionCHPMultiDataData fusionCHPMultiDataData, Map<String, CopyNumberQuantitationType> qTypes) { super(fusionCHPMultiDataData); this.qTypes = qTypes; } static final Map<String, CopyNumberQuantitationType> CN4_TYPE_MAP = getCN4Map(); static final Map<String, CopyNumberQuantitationType> CN5_TYPE_MAP = getCN5Map(); private static Map<String, CopyNumberQuantitationType> getCN4Map() { Map<String, CopyNumberQuantitationType> tmp = new HashMap<String, CopyNumberQuantitationType>(); // CN4 types addMap(tmp, CopyNumberQuantitationType.PROBE_SET_NAME); addMap(tmp, CopyNumberQuantitationType.CHROMOSOME); addMap(tmp, CopyNumberQuantitationType.POSITION); addMap(tmp, CopyNumberQuantitationType.CN4_CN_STATE); addMap(tmp, CopyNumberQuantitationType.LOG2RATIO); addMap(tmp, CopyNumberQuantitationType.HMM_MEDIAN_LOG2RATIO); addMap(tmp, CopyNumberQuantitationType.NEG_LOG10PVALUE); addMap(tmp, CopyNumberQuantitationType.CHIP_NUM); return Collections.unmodifiableMap(tmp); } private static Map<String, CopyNumberQuantitationType> getCN5Map() { Map<String, CopyNumberQuantitationType> tmp = new HashMap<String, CopyNumberQuantitationType>(); // CN5 types addMap(tmp, CopyNumberQuantitationType.PROBE_SET_NAME); addMap(tmp, CopyNumberQuantitationType.CHROMOSOME); addMap(tmp, CopyNumberQuantitationType.POSITION); addMap(tmp, CopyNumberQuantitationType.CN5_CN_STATE); addMap(tmp, CopyNumberQuantitationType.LOG2RATIO); addMap(tmp, CopyNumberQuantitationType.SMOOTH_SIGNAL); addMap(tmp, CopyNumberQuantitationType.LOH); addMap(tmp, CopyNumberQuantitationType.ALLELE_DIFFERENCE); return Collections.unmodifiableMap(tmp); } private static void addMap(Map<String, CopyNumberQuantitationType> map, CopyNumberQuantitationType qType) { map.put(qType.getName(), qType); } @SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.ExcessiveMethodLength" }) // long switch statement @Override protected void setExpressionValue(final AbstractDataColumn column, final int index, final ProbeSetMultiDataCopyNumberData entry) { final QuantitationType quantitationType = column.getQuantitationType(); final CopyNumberQuantitationType typeDescriptor = getExpressionTypeDescriptor(quantitationType); try { Map<String, ParameterNameValue> metricMap = getMetricMap(entry); switch (typeDescriptor) { case ALLELE_DIFFERENCE: ((FloatColumn) column).getValues()[index] = metricMap.get(CopyNumberQuantitationType.ALLELE_DIFFERENCE.getName()).getValueFloat(); break; case CHIP_NUM: ((ShortColumn) column).getValues()[index] = metricMap.get(CopyNumberQuantitationType.CHIP_NUM.getName()).getValueUInt8().toShort(); break; case CHROMOSOME: // CHECKSTYLE:OFF // 0xff is not really a magic number ((ShortColumn) column).getValues()[index] = (short) (0xff & entry.getChr()); // CHECKSTYLE:ON break; case CN4_CN_STATE: ((ShortColumn) column).getValues()[index] = metricMap.get(CopyNumberQuantitationType.CN4_CN_STATE.getName()).getValueUInt8().toShort(); break; case CN5_CN_STATE: ((FloatColumn) column).getValues()[index] = metricMap.get(CopyNumberQuantitationType.CN5_CN_STATE.getName()).getValueFloat(); break; case HMM_MEDIAN_LOG2RATIO: ((FloatColumn) column).getValues()[index] = metricMap.get(CopyNumberQuantitationType.HMM_MEDIAN_LOG2RATIO.getName()).getValueFloat(); break; case LOG2RATIO: ((FloatColumn) column).getValues()[index] = metricMap.get(CopyNumberQuantitationType.LOG2RATIO.getName()).getValueFloat(); break; case LOH: ((FloatColumn) column).getValues()[index] = metricMap.get(CopyNumberQuantitationType.LOH.getName()).getValueFloat(); break; case NEG_LOG10PVALUE: ((FloatColumn) column).getValues()[index] = metricMap.get(CopyNumberQuantitationType.NEG_LOG10PVALUE.getName()).getValueFloat(); break; case POSITION: ((IntegerColumn) column).getValues()[index] = entry.getPosition(); break; case PROBE_SET_NAME: ((StringColumn) column).getValues()[index] = entry.getName(); break; case SMOOTH_SIGNAL: ((FloatColumn) column).getValues()[index] = metricMap.get(CopyNumberQuantitationType.SMOOTH_SIGNAL.getName()).getValueFloat(); break; default: throw new IllegalArgumentException("Unsupported QuantitationType for CNCHP data: " + quantitationType); } } catch (UnsignedOutOfLimitsException e) { throw new ArrayDataException(e); } } /** * {@inheritDoc} */ @Override public String getChipType() { String key; FusionCHPMultiDataData d = getData(); if ("CN4".equals(d.getAlgName())) { key = "affymetrix-algorithm-param-ChipType1"; } else { key = "affymetrix-array-type"; } FileHeader h = d.getGenericData().getHeader(); GenericDataHeader gh = h.getGenericDataHdr(); for (ParameterNameValue nv : gh.getNameValParams()) { if (key.equals(nv.getName())) { return nv.getValueAscii(); } } return null; } private CopyNumberQuantitationType getExpressionTypeDescriptor( final QuantitationType quantitationType) { return getExpressionTypeMap().get(quantitationType.getName()); } public QuantitationTypeDescriptor[] getQuantitationTypeDescriptors() { DataSetHeader dsh = getDataSet(); int count = getDataSet().getColumnCnt(); ArrayList<CopyNumberQuantitationType> desc = new ArrayList<CopyNumberQuantitationType>(); for (int i = 0; i < count; i++) { ColumnInfo col = dsh.getColumnInfo(i); CopyNumberQuantitationType qt = getExpressionTypeMap().get(col.getName()); if (qt != null) { desc.add(qt); } } return desc.toArray(new CopyNumberQuantitationType[desc.size()]); } @Override protected DataSetHeader getDataSet() { DataGroupHeader hdr = getData().getGenericData().findDataGroupHeader("MultiData"); return hdr.findDataSetHeader("CopyNumber"); } public ArrayDataTypeDescriptor getArrayDataTypeDescriptor() { return AffymetrixArrayDataTypes.AFFYMETRIX_COPY_NUMBER_CHP; } private Map<String, CopyNumberQuantitationType> getExpressionTypeMap() { return qTypes; } @Override protected ProbeSetMultiDataCopyNumberData getEntry(int index) { try { return getData().getCopyNumberEntry(MultiDataType.CopyNumberMultiDataType, index); } catch (final IOException e) { throw new ArrayDataIOException(e); } catch (final UnsignedOutOfLimitsException e) { throw new ArrayDataException(e); } } }
package com.intellij.psi.impl.source.resolve.reference.impl.providers; import com.intellij.codeInsight.daemon.EmptyResolveMessageProvider; import com.intellij.codeInsight.daemon.QuickFixProvider; import com.intellij.codeInsight.daemon.XmlErrorMessages; import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.daemon.impl.quickfix.FetchExtResourceAction; import com.intellij.codeInsight.daemon.impl.quickfix.IgnoreExtResourceAction; import com.intellij.codeInsight.daemon.impl.quickfix.ManuallySetupExtResourceAction; import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixAction; import com.intellij.j2ee.openapi.ex.ExternalResourceManagerEx; import com.intellij.javaee.ExternalResourceManager; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.ElementManipulator; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.psi.filters.ElementFilter; import com.intellij.psi.impl.source.jsp.JspManager; import com.intellij.psi.impl.source.resolve.reference.PsiReferenceProvider; import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry; import com.intellij.psi.impl.source.resolve.reference.ReferenceType; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.Processor; import com.intellij.xml.XmlNSDescriptor; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * @by Maxim.Mossienko */ public class URIReferenceProvider implements PsiReferenceProvider { public ElementFilter getNamespaceAttributeFilter() { return new ElementFilter() { public boolean isAcceptable(Object element, PsiElement context) { final PsiElement parent = context.getParent(); if (parent instanceof XmlAttribute) { final XmlAttribute attribute = ((XmlAttribute)parent); return attribute.isNamespaceDeclaration(); } return false; } public boolean isClassAcceptable(Class hintClass) { return true; } }; } public static class URLReference implements PsiReference, QuickFixProvider, EmptyResolveMessageProvider { private PsiElement myElement; private TextRange myRange; private boolean mySoft; @NonNls private static final String TARGET_NAMESPACE_ATTR_NAME = "targetNamespace"; public URLReference(PsiElement element) { myElement = element; } public URLReference(PsiElement element, @Nullable TextRange range, boolean soft) { myElement = element; myRange = range; mySoft = soft; } public PsiElement getElement() { return myElement; } public TextRange getRangeInElement() { return myRange != null ? myRange : new TextRange(1,myElement.getTextLength()-1); } @Nullable public PsiElement resolve() { final String canonicalText = getCanonicalText(); if (canonicalText.length() == 0) { final XmlAttribute attr = PsiTreeUtil.getParentOfType(getElement(), XmlAttribute.class); if (attr != null && attr.isNamespaceDeclaration() && attr.getNamespacePrefix().length() == 0 ) { // Namespaces in XML 1.0 2nd edition, Section 6.2, last paragraph // The attribute value in a default namespace declaration MAY be empty. This has the same effect, within the scope of the declaration, // of there being no default namespace return myElement; } return null; } if (ExternalResourceManagerEx.getInstanceEx().isIgnoredResource(canonicalText)) return myElement; VirtualFile relativeFile = VfsUtil.findRelativeFile(canonicalText, myElement.getContainingFile().getVirtualFile()); if (relativeFile != null) return myElement.getManager().findFile(relativeFile); final XmlTag tag = PsiTreeUtil.getParentOfType(myElement, XmlTag.class); if (tag != null && canonicalText.equals(tag.getAttributeValue(TARGET_NAMESPACE_ATTR_NAME))) return tag; final PsiFile containingFile = myElement.getContainingFile(); if (containingFile instanceof XmlFile) { final XmlTag rootTag = ((XmlFile)containingFile).getDocument().getRootTag(); if (rootTag == null) return null; final XmlNSDescriptor nsDescriptor = rootTag.getNSDescriptor(canonicalText, true); if (nsDescriptor != null) return nsDescriptor.getDescriptorFile(); final PsiElement[] result = new PsiElement[1]; processWsdlSchemas(rootTag,new Processor<XmlTag>() { public boolean process(final XmlTag t) { if (canonicalText.equals(t.getAttributeValue(TARGET_NAMESPACE_ATTR_NAME))) { result[0] = t; return false; } return true; } }); return result[0]; } return null; } public String getCanonicalText() { final String text = myElement.getText(); if (text.length() > 1) { return myRange == null ? text.substring(1,text.length() - 1): text.substring(myRange.getStartOffset(),myRange.getEndOffset()); } return ""; } public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { final TextRange textRangeInElement = getRangeInElement(); final PsiElement elementToChange = myElement.findElementAt(textRangeInElement.getStartOffset()); final ElementManipulator<PsiElement> manipulator = ReferenceProvidersRegistry.getInstance(myElement.getProject()).getManipulator(elementToChange); assert manipulator != null; final int offsetFromStart = myElement.getTextRange().getStartOffset() + textRangeInElement.getStartOffset() - elementToChange.getTextOffset(); manipulator.handleContentChange(elementToChange, new TextRange(offsetFromStart, offsetFromStart + textRangeInElement.getLength()),newElementName); return myElement; } public PsiElement bindToElement(PsiElement element) throws IncorrectOperationException { assert element instanceof PsiFile; if (!isUrlText(getCanonicalText())) { // TODO: this should work! handleElementRename(VfsUtil.fixIDEAUrl(((PsiFile)element).getVirtualFile().getPresentableUrl())); } return myElement; } public boolean isReferenceTo(PsiElement element) { return myElement.getManager().areElementsEquivalent(resolve(),element); } public Object[] getVariants() { String[] resourceUrls = ExternalResourceManager.getInstance().getResourceUrls(null, true); final PsiFile containingFile = myElement.getContainingFile(); if (PsiUtil.isInJspFile(containingFile)) { final JspManager jspManager = JspManager.getInstance(containingFile.getProject()); if (jspManager != null) { final Object[] possibleTldUris = jspManager.getPossibleTldUris( PsiUtil.getJspFile(containingFile)); Object[] result = new Object[resourceUrls.length + possibleTldUris.length + 1]; System.arraycopy(resourceUrls, 0, result, 0, resourceUrls.length); System.arraycopy(possibleTldUris, 0, result, resourceUrls.length, possibleTldUris.length); result[result.length - 1] = JspManager.TAG_DIR_NS_PREFIX + "/WEB-INF/tags"; return result; } } else if (containingFile instanceof XmlFile) { XmlTag rootTag = ((XmlFile)containingFile).getDocument().getRootTag(); final ArrayList<String> additionalNs = new ArrayList<String>(); processWsdlSchemas(rootTag, new Processor<XmlTag>() { public boolean process(final XmlTag xmlTag) { final String s = xmlTag.getAttributeValue(TARGET_NAMESPACE_ATTR_NAME); if (s != null) { additionalNs.add(s); } return true; } }); resourceUrls = ArrayUtil.mergeArrays(resourceUrls, additionalNs.toArray(new String[additionalNs.size()]), String.class); } return resourceUrls; } public boolean isSoft() { return mySoft; } public void registerQuickfix(HighlightInfo info, PsiReference reference) { QuickFixAction.registerQuickFixAction(info, new FetchExtResourceAction()); QuickFixAction.registerQuickFixAction(info, new ManuallySetupExtResourceAction()); QuickFixAction.registerQuickFixAction(info, new IgnoreExtResourceAction()); } public String getUnresolvedMessagePattern() { return XmlErrorMessages.message("uri.is.not.registered"); } } public static void processWsdlSchemas(final XmlTag rootTag, Processor<XmlTag> processor) { if ("definitions".equals(rootTag.getLocalName())) { final XmlTag subTag = rootTag.findFirstSubTag(rootTag.getNamespacePrefix() + ":" + "types"); if (subTag != null) { final XmlTag[] tags = subTag.findSubTags("xsd:schema"); for(XmlTag t:tags) { if (!processor.process(t)) return; } } } } public static class DependentNSReference extends BasicAttributeValueReference implements QuickFixProvider { private final PsiReference myReference; public DependentNSReference(final PsiElement element, TextRange range, PsiReference ref) { super(element, range); myReference = ref; } @Nullable public PsiElement resolve() { return myReference.resolve(); } public Object[] getVariants() { return ArrayUtil.EMPTY_OBJECT_ARRAY; } public boolean isSoft() { return false; } public void registerQuickfix(HighlightInfo info, PsiReference reference) { QuickFixAction.registerQuickFixAction(info, new FetchExtResourceAction()); QuickFixAction.registerQuickFixAction(info, new ManuallySetupExtResourceAction()); QuickFixAction.registerQuickFixAction(info, new IgnoreExtResourceAction()); } } @NotNull @SuppressWarnings({"HardCodedStringLiteral"}) public PsiReference[] getReferencesByElement(PsiElement element) { final String text = element.getText(); String s = StringUtil.stripQuotesAroundValue(text); final PsiElement parent = element.getParent(); if (parent instanceof XmlAttribute && "xsi:schemaLocation".equals(((XmlAttribute)parent).getName())) { final List<PsiReference> refs = new ArrayList<PsiReference>(2); final StringTokenizer tokenizer = new StringTokenizer(s); while(tokenizer.hasMoreElements()) { final String namespace = tokenizer.nextToken(); int offset = text.indexOf(namespace); refs.add(new URLReference(element, new TextRange(offset,offset + namespace.length()), true)); if (!tokenizer.hasMoreElements()) break; String url = tokenizer.nextToken(); offset = text.indexOf(url); if (isUrlText(url)) refs.add(new DependentNSReference(element, new TextRange(offset,offset + url.length()), refs.get(refs.size() - 1))); else { for(PsiReference r : new FileReferenceSet(url, element, offset, this, false).getAllReferences()) { refs.add(r); } } } return refs.toArray(new PsiReference[refs.size()]); } if (isUrlText(s) || ( parent instanceof XmlAttribute && ((XmlAttribute)parent).isNamespaceDeclaration() ) ) { if (!s.startsWith(JspManager.TAG_DIR_NS_PREFIX)) { final boolean namespaceSoftRef = ( parent instanceof XmlAttribute && "namespace".equals(((XmlAttribute)parent).getName())) && ((XmlAttribute)parent).getParent().getAttributeValue("schemaLocation") != null; return getUrlReference(element, namespaceSoftRef); } else { final int offset = text.indexOf(s); s = s.substring(JspManager.TAG_DIR_NS_PREFIX.length()); return new FileReferenceSet( s, element, offset + JspManager.TAG_DIR_NS_PREFIX.length(), ReferenceType.FILE_TYPE, this, true ).getAllReferences(); } } else { if (s.startsWith("file:")) s = s.substring("file:".length()); return new FileReferenceSet(s,element,text.indexOf(s), ReferenceType.FILE_TYPE, this,true).getAllReferences(); } } static boolean isUrlText(final String s) { return s.startsWith("http: s.startsWith("urn:"); } private static PsiReference[] getUrlReference(final PsiElement element, boolean soft) { return new PsiReference[] { new URLReference(element, null, soft)}; } @NotNull public PsiReference[] getReferencesByElement(PsiElement element, ReferenceType type) { return PsiReference.EMPTY_ARRAY; } @NotNull public PsiReference[] getReferencesByString(String str, PsiElement position, ReferenceType type, int offsetInPosition) { return PsiReference.EMPTY_ARRAY; } public void handleEmptyContext(PsiScopeProcessor processor, PsiElement position) { } }
package ca.concordia.cssanalyser.cssmodel.declaration.value; import ca.concordia.cssanalyser.csshelper.ColorHelper; import ca.concordia.cssanalyser.csshelper.NamedColorsHelper; import ca.concordia.cssanalyser.cssmodel.declaration.Declaration; /** * This class is used to add equivalent values to a value. * The {@link #getDeclarationValue(String, String, ValueType)} method * returns either a {@link DeclarationValue} or {@link DeclarationEquivalentValue}. * @author Davood Mazinanian * */ public class DeclarationValueFactory { public static DeclarationValue getDeclarationValue(String forProperty, String value, ValueType type) { //return new DeclarationValue(value, type); forProperty = Declaration.getNonVendorProperty(Declaration.getNonHackedProperty(forProperty.toLowerCase())); value = value.trim(); switch (type) { case IDENT: { if (NamedColorsHelper.isNamedColor(value)) return new DeclarationEquivalentValue(value, NamedColorsHelper.getRGBAColor(value), ValueType.COLOR); switch (value.toLowerCase()) { case "currentcolor": return new DeclarationValue(value, ValueType.COLOR); case "none": return new DeclarationEquivalentValue(value, value, ValueType.IDENT); case "left": case "top": switch (forProperty) { case "background-position": case "background": case "perspective-origin": case "transform-origin": return new DeclarationEquivalentValue(value, "0px", ValueType.LENGTH); } break; case "right": case "bottom": switch (forProperty) { case "background-position": case "background": case "perspective-origin": case "transform-origin": return new DeclarationEquivalentValue(value, "100%", ValueType.LENGTH); } break; case "center": switch (forProperty) { case "background-position": case "background": case "perspective-origin": case "transform-origin": return new DeclarationEquivalentValue(value, "50%", ValueType.LENGTH); } break; case "bold": return new DeclarationEquivalentValue(value, "700", ValueType.INTEGER); case "normal": if (forProperty.equals("font-weight")) return new DeclarationEquivalentValue(value, "400", ValueType.INTEGER); // What should we do for font shorthand property?! } return new DeclarationValue(value, ValueType.IDENT); } case INTEGER: { if ("0".equals(value)) { switch (forProperty) { case "margin": case "margin-left": case "margin-right": case "margin-top": case "margin-bottom": case "padding": case "padding-left": case "padding-right": case "padding-bottom": case "padding-top": case "top": case "left": case "bottom": case "right": case "height": case "width": case "max-height": case "max-width": case "min-height": case "min-width": case "background-position": case "background-size": case "background": case "border": case "border-bottom": case "border-left": case "border-right": case "border-top": case "outline": case "border-top-width": case "border-bottom-width": case "border-left-width": case "border-right-width": case "border-width": case "outline-width": case "border-radius": case "border-bottom-left-radius": case "border-bottom-right-radius": case "border-top-left-radius": case "border-top-right-radius": case "column-width": case "column-rule-width": case "column-gap": case "perspective-origin": case "text-shadow": case "box-shadow": /* * Dangerous to do! * case "transform-origin": * case "-ms-transform-origin": * case "-webkit-transform-origin": */ return new DeclarationEquivalentValue("0", "0px", ValueType.LENGTH); } } } case PERCENTAGE: { if (value.startsWith(".")) value = "0" + value; String eqVal = value; if ("0".equals(value)) { switch (forProperty) { case "background-position": case "background-size": case "border-radius": case "-webkit-border-radius": case "-moz-border-radius": case "border-bottom-left-radius": case "border-bottom-right-radius": case "border-bottom-top-radius": case "border-bottom-bottom-radius": case "transform-origin": eqVal = "0px"; break; case "rgb": case "rgba": case "hsl": case "hsla": eqVal = "0"; } } return new DeclarationEquivalentValue(value, eqVal, ValueType.PERCENTAGE); } case COLOR: { String eqValue = ""; if (value.startsWith(" try { eqValue = ColorHelper.RGBAFromHEX(value.substring(1)); } catch (Exception e) { } } else if (value.startsWith("rgb")) { String[] values = getCommaSeparatedValueParts(value); float a = 1F; if (value.startsWith("rgba")) { if (values.length != 4) throw new RuntimeException("Invalid rgba color: " + value); a = Math.min(Float.valueOf(values[3]), 1); } else { if (values.length != 3) throw new RuntimeException("Invalid rgb color: " + value); } int r = getRgbComponentValue(values[0]); int g = getRgbComponentValue(values[1]); int b = getRgbComponentValue(values[2]); eqValue = ColorHelper.RGBA(r, g, b, a); } else if (value.startsWith("hsl")) { String[] values = getCommaSeparatedValueParts(value); float a = 1F; if (value.startsWith("hsla")) { if (values.length != 4) throw new RuntimeException("Invalid hsla color: " + value); a = Math.min(Float.valueOf(values[3]), 1); } else { if (values.length != 3) throw new RuntimeException("Invalid hsl color: " + value); } float h = Math.min(Integer.valueOf(values[0]), 360) / 360F; float s,l; try { s = getPercentageValue(values[1]); l = getPercentageValue(values[2]); } catch (IllegalArgumentException e) { throw new RuntimeException("Invalud percentage value in " + value); } eqValue = ColorHelper.RGBAFromHSLA(h, s, l, a); } return new DeclarationEquivalentValue(value, eqValue, ValueType.COLOR); } case LENGTH: { String postfix = value.substring(value.length() - 2); float floatVal = Float.valueOf(value.replace(postfix, "")); String eqVal = ""; if (value.startsWith(".")) { value = "0" + value; } switch(postfix) { case "pc": { // 1pc = 12pt = 16px eqVal = formatFloat(floatVal * 16) + "px"; break; } case "pt": { // 72pt is 96px eqVal = formatFloat(floatVal / 72F * 96F) + "px"; break; } case "in": { // Every inch is 96px eqVal = formatFloat(floatVal * 96F) + "px"; break; } case "cm": { // Every cm is (2.54^-1 * 96)px // In browser, every cm is about 38px eqVal = formatFloat(floatVal * 38F) + "px"; break; } case "mm": { //every mm is 0.01 cm eqVal = formatFloat(floatVal * 38F / 100F) + "px"; break; } case "px": { eqVal = value; break; } case "em": { // 1em = 100%, if we are talking about font if ("font".equals(forProperty) || "font-size".equals(forProperty) || "line-height".equals(forProperty)) { eqVal = formatFloat(floatVal * 100) + "%"; } else { return new DeclarationValue(value, ValueType.LENGTH); } break; } } if (!"".equals(eqVal)) return new DeclarationEquivalentValue(value, eqVal, ValueType.LENGTH); return new DeclarationValue(value, ValueType.LENGTH); } case ANGLE: { if (value.startsWith(".")) value = "0" + value; String eqVal = ""; if (value.endsWith("grad")) { // 1grad = 0.9deg eqVal = formatFloat(Float.valueOf(value.replace("grad", "")) * 0.9F) + "deg"; } else if (value.endsWith("rad")) { // 2pi rad = 360deg eqVal = formatFloat(Float.valueOf(value.replace("rad", "")) / (2 * 3.1415926F) * 360) + "deg"; } else if (value.endsWith("turn")) { // 1turn = 360deg eqVal = formatFloat(Float.valueOf(value.replace("turn", "")) * 360) + "deg"; } else if (value.endsWith("deg")) { eqVal = value; } return new DeclarationEquivalentValue(value, eqVal, type); } case FREQUENCY: { if (value.startsWith(".")) value = "0" + value; String eqVal = value; // 1KHz = 1000Hz if (value.endsWith("khz")) { eqVal = formatFloat(Float.valueOf(value.replace("khz", "")) * 1000) + "hz"; } return new DeclarationEquivalentValue(value, eqVal, ValueType.FREQUENCY); } case TIME: { // Each second is 1000 ms if (value.startsWith(".")) value = "0" + value; String eqVal = value; if (value.endsWith("ms")) { eqVal = formatFloat(Float.valueOf(value.replace("ms", "")) * 1000) + "ms"; } return new DeclarationEquivalentValue(value, eqVal, ValueType.TIME); } case URL: { if ("url('')".equals(value)) return new DeclarationEquivalentValue(value, "none", ValueType.URL); return new DeclarationValue(value, ValueType.URL); } default: return new DeclarationValue(value, type); } } protected static float getPercentageValue(String string) throws IllegalArgumentException { float s = 0; if (string.endsWith("%")) s = Math.min(Integer.valueOf(string.substring(0, string.length() - 1)), 100) / 100F; else if ("0".equals(string)) s = 0; else throw new IllegalArgumentException("Invalid percent value"); return s; } protected static String[] getCommaSeparatedValueParts(String value) { String[] values = value.substring(value.indexOf("(") + 1, value.indexOf(")")).split(","); for (int i = 0; i < values.length; i++) values[i] = values[i].trim(); return values; } /** * Returns a color component value (like red value) in 255 scale. * (it might be percent or integer, like rgb(100%, 50%, 40%) ) * @param color * @return */ private static int getRgbComponentValue(String value) { if (value.endsWith("%")) return (int) Math.min(Integer.valueOf(value.substring(0, value.length() - 1)) * 255, 255); else return Math.min(Integer.valueOf(value), 255); } public static String formatFloat(double f) { if(f == (long) f) return String.format("%d",(long)f); else return String.format("%s",f); } public static DeclarationValue getFontValue(String propertyName, float value, String unit) { String val = formatFloat(value) + unit; return getDeclarationValue(propertyName, val, ValueType.LENGTH); } }
package com.researchworx.cresco.plugins.gobjectIngestion.objectstorage; //import java.io.ByteArrayInputStream; import com.amazonaws.ClientConfiguration; import com.amazonaws.Protocol; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.S3ClientOptions; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.s3.transfer.*; import com.amazonaws.util.StringUtils; import com.researchworx.cresco.library.messaging.MsgEvent; import com.researchworx.cresco.library.utilities.CLogger; import com.researchworx.cresco.plugins.gobjectIngestion.Plugin; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //import java.io.InputStream; //import com.amazonaws.services.s3.model.ObjectMetadata; //import com.amazonaws.services.s3.model.PutObjectRequest; public class ObjectEngine { private static final int MAX_FILES_FOR_S3_DOWNLOAD = 5000; private static final int NUMBER_OF_THREADS_FOR_DOWNLOAD = 1; private CLogger logger; private static AmazonS3 conn; //private final static String FOLDER_SUFFIX = "/"; private MD5Tools md5t; private int partSize; private Plugin plugin; public ObjectEngine(Plugin plugin) { this.logger = new CLogger(plugin.getMsgOutQueue(), plugin.getRegion(), plugin.getAgent(), plugin.getPluginID(), CLogger.Level.Trace); //this.logger = new CLogger(plugin.getMsgOutQueue(), plugin.getRegion(), plugin.getAgent(), plugin.getPluginID()); this.plugin = plugin; //logger.trace("ObjectEngine instantiated [group = {}]", group); String accessKey = plugin.getConfig().getStringParam("accesskey"); logger.debug("\"accesskey\" from config [{}]", accessKey); String secretKey = plugin.getConfig().getStringParam("secretkey"); logger.debug("\"secretkey\" from config [{}]", secretKey); String endpoint = plugin.getConfig().getStringParam("endpoint"); logger.debug("\"endpoint\" from config [{}]", endpoint); this.partSize = plugin.getConfig().getIntegerParam("uploadpartsizemb"); logger.debug("\"uploadpartsizemb\" from config [{}]", this.partSize); //String accessKey = PluginEngine.config.getParam("s3","accesskey"); //String secretKey = PluginEngine.config.getParam("s3","secretkey"); //String endpoint = PluginEngine.config.getParam("s3","endpoint"); logger.trace("Building AWS Credentials"); AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); logger.trace("Building ClientConfiguration"); ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setProtocol(Protocol.HTTPS); clientConfig.setSignerOverride("S3SignerType"); //clientConfig.setMaxConnections(100); logger.trace("Connecting to Amazon S3"); conn = new AmazonS3Client(credentials, clientConfig); //conn.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true)); //S3ClientOptions(boolean pathStyleAccess, boolean chunkedEncodingDisabled, boolean accelerateModeEnabled, boolean payloadSigningEnabled) //conn.setS3ClientOptions(S3ClientOptions.); S3ClientOptions s3ops = S3ClientOptions.builder() .setAccelerateModeEnabled(false) .setPathStyleAccess(true) .setPayloadSigningEnabled(false) .build(); conn.setS3ClientOptions(s3ops); conn.setEndpoint(endpoint); logger.trace("Building new MD5Tools"); md5t = new MD5Tools(plugin); } public boolean uploadDirectory(String bucket, String inDir, String outDir) { logger.debug("Call to uploadDirectory [bucket = {}, inDir = {}, outDir = {}]", bucket, inDir, outDir); boolean wasTransfered = false; TransferManager tx = null; try { logger.trace("Building new TransferManager"); tx = new TransferManager(conn); logger.trace("Building new TransferManagerConfiguration"); TransferManagerConfiguration tmConfig = new TransferManagerConfiguration(); logger.trace("Setting up minimum part size"); // Sets the minimum part size for upload parts. tmConfig.setMinimumUploadPartSize(partSize * 1024 * 1024); logger.trace("Setting up size threshold for multipart uploads"); // Sets the size threshold in bytes for when to use multipart uploads. tmConfig.setMultipartUploadThreshold((long) partSize * 1024 * 1024); logger.trace("Setting configuration on TransferManager"); tx.setConfiguration(tmConfig); logger.trace("[uploadDir] set to [inDir]"); File uploadDir = new File(inDir); logger.trace("Starting timer"); long startUpload = System.currentTimeMillis(); logger.info("Beginning upload [bucket = {}, outDir = {}, uploadDir = {}]", bucket, outDir, uploadDir); MultipleFileUpload myUpload = tx.uploadDirectory(bucket, outDir, uploadDir, true); // You can poll your transfer's status to check its progress while (!myUpload.isDone()) { logger.debug("Transfer: " + myUpload.getDescription()); logger.debug(" - State: " + myUpload.getState()); logger.debug(" - Progress Bytes: " + myUpload.getProgress().getBytesTransferred()); //logger.trace("Calculating upload statistics"); float transferTime = (System.currentTimeMillis() - startUpload) / 1000; long bytesTransfered = myUpload.getProgress().getBytesTransferred(); float transferRate = (bytesTransfered / 1000000) / transferTime; logger.debug("Upload Transfer Desc: " + myUpload.getDescription()); logger.debug("\t- Transfered : " + myUpload.getProgress().getBytesTransferred() + " bytes"); logger.debug("\t- Elapsed time : " + transferTime + " seconds"); logger.debug("\t- Transfer rate : " + transferRate + " MB/sec"); MsgEvent me = plugin.genGMessage(MsgEvent.Type.INFO, "Transfer in progress (" + (int) myUpload.getProgress().getPercentTransferred() + "%)"); //me.setParam("pathstage",pathStage); me.setParam("indir", inDir); me.setParam("outdir", outDir); me.setParam("seq_id", outDir); me.setParam("pathstage", String.valueOf(plugin.pathStage)); me.setParam("sstep", "1"); me.setParam("xfer_rate", String.valueOf(transferRate)); me.setParam("xfer_bytes", String.valueOf(myUpload.getProgress().getBytesTransferred())); me.setParam("xfer_percent", String.valueOf(myUpload.getProgress().getPercentTransferred())); plugin.sendMsgEvent(me); Thread.sleep(5000); } /* System.out.println("Transfer: " + myUpload.getDescription()); System.out.println(" - State: " + myUpload.getState()); System.out.println(" - Progress: " + myUpload.getProgress().getBytesTransferred()); */ // Transfers also allow you to set a <code>ProgressListener</code> to receive // asynchronous notifications about your transfer's progress. //myUpload.addProgressListener(myProgressListener); // Or you can block the current thread and wait for your transfer to // to complete. If the transfer fails, this method will throw an // AmazonClientException or AmazonServiceException detailing the reason. //myUpload.waitForCompletion(); // After the upload is complete, call shutdownNow to release the resources. wasTransfered = true; } catch (Exception ex) { logger.error("uploadDirectory {}", ex.getMessage()); } finally { try { assert tx != null; tx.shutdownNow(); } catch (AssertionError e) { logger.error("uploadDirectory - TransferManager was pre-emptively shutdown"); } } return wasTransfered; } // downloadDirectory(String bucketName, String keyPrefix, File destinationDirectory) public boolean downloadDirectory(String bucketName, String keyPrefix, String destinationDirectory, String seqId, String sampleId) { logger.debug("Call to downloadDirectory [bucketName = {}, keyPrefix = {}, destinationDirectory = {}", bucketName, keyPrefix, destinationDirectory); boolean wasTransfered = false; TransferManager tx = null; if (!destinationDirectory.endsWith("/")) { destinationDirectory += "/"; } try { logger.trace("Building new TransferManager"); tx = new TransferManager(conn); logger.trace("Setting [downloadDir] to [desinationDirectory]"); File downloadDir = new File(destinationDirectory); if (!downloadDir.exists()) { if (!downloadDir.mkdirs()) { logger.error("Failed to create download directory!"); return false; } } Map<String, Long> dirList = getlistBucketContents(bucketName, keyPrefix); if (dirList.keySet().size() <= MAX_FILES_FOR_S3_DOWNLOAD) { logger.trace("Starting download timer"); long startDownload = System.currentTimeMillis(); logger.info("Beginning download [bucketName = {}, keyPrefix = {}, downloadDir = {}", bucketName, keyPrefix, downloadDir); MultipleFileDownload myDownload = tx.downloadDirectory(bucketName, keyPrefix, downloadDir); while (!myDownload.isDone()) { logger.debug("Transfer: " + myDownload.getDescription()); logger.debug(" - State: " + myDownload.getState()); logger.debug(" - Progress Bytes: " + myDownload.getProgress().getBytesTransferred()); float transferTime = (System.currentTimeMillis() - startDownload) / 1000; long bytesTransfered = myDownload.getProgress().getBytesTransferred(); float transferRate = (bytesTransfered / 1000000) / transferTime; logger.debug("Download Transfer Desc: " + myDownload.getDescription()); logger.debug("\t- Transfered : " + myDownload.getProgress().getBytesTransferred() + " bytes"); logger.debug("\t- Elapsed time : " + transferTime + " seconds"); logger.debug("\t- Transfer rate : " + transferRate + " MB/sec"); MsgEvent me = plugin.genGMessage(MsgEvent.Type.INFO, "Transfer in progress (" + (int) myDownload.getProgress().getPercentTransferred() + "%)"); if (seqId != null) me.setParam("seq_id", seqId); if (sampleId != null) me.setParam("sample_id", sampleId); me.setParam("pathstage", String.valueOf(plugin.pathStage)); me.setParam("sstep", "1"); me.setParam("xfer_rate", String.valueOf(transferRate)); me.setParam("xfer_bytes", String.valueOf(myDownload.getProgress().getBytesTransferred())); me.setParam("xfer_percent", String.valueOf(myDownload.getProgress().getPercentTransferred())); plugin.sendMsgEvent(me); Thread.sleep(5000); } logger.trace("Calculating download statistics"); float transferTime = (System.currentTimeMillis() - startDownload) / 1000; long bytesTransfered = myDownload.getProgress().getBytesTransferred(); float transferRate = (bytesTransfered / 1000000) / transferTime; logger.debug("Download Transfer Desc: " + myDownload.getDescription()); logger.debug("\t- Transfered : " + myDownload.getProgress().getBytesTransferred() + " bytes"); logger.debug("\t- Elapsed time : " + transferTime + " seconds"); logger.debug("\t- Transfer rate : " + transferRate + " MB/sec"); wasTransfered = true; } else { logger.trace("Beginning Large FileSet Download routine"); long startDownload = System.currentTimeMillis(); ExecutorService downloadExecutorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS_FOR_DOWNLOAD); long totalBytesToDownload = 0L; ConcurrentHashMap<String, Download> downloads = new ConcurrentHashMap<>(); for (Map.Entry<String, Long> entry : dirList.entrySet()) { String dir = entry.getKey(); String tdir = dir.substring(0, dir.lastIndexOf("/")); File directory = new File(destinationDirectory + tdir); File file = new File(destinationDirectory + dir); if (!directory.exists()) { if (createDir(directory)) { logger.trace("created directory : " + directory.getAbsolutePath()); } else { logger.error("failed creating directory : " + directory.getAbsolutePath()); } } totalBytesToDownload += entry.getValue(); downloadExecutorService.submit(new DownloadWorker(tx, bucketName, dir, file, downloads)); } logger.trace("All downloads have been generated"); downloadExecutorService.shutdown(); logger.trace("Entering Status while loop."); boolean done = false; while (!done && !downloadExecutorService.isTerminated()) { done = true; int downloadsWaiting = 0; int downloadsRunning = 0; int downloadsCompleted = 0; int downloadsFailed = 0; long totalBytesDownloaded = 0L; logger.trace("Calculating progress from {} active downloads.", downloads.size()); for (Map.Entry<String, Download> entry : downloads.entrySet()) { Download download = entry.getValue(); if (download.getState() == Transfer.TransferState.Waiting) { downloadsWaiting++; done = false; } if (download.getState() == Transfer.TransferState.InProgress) { downloadsRunning++; done = false; } if (download.getState() == Transfer.TransferState.Completed) { downloadsCompleted++; } if (download.getState() == Transfer.TransferState.Failed) { downloadsFailed++; } totalBytesDownloaded += download.getProgress().getBytesTransferred(); } logger.debug("\tWaiting: {}", downloadsWaiting); logger.debug("\tDownloading: {}", downloadsRunning); logger.debug("\tComplete: {}", downloadsCompleted); logger.debug("\tFailed: {}", downloadsFailed); logger.trace("Calculating download progress metrics."); float transferTime = (System.currentTimeMillis() - startDownload) / 1000; float transferRate = (totalBytesDownloaded / 1000000) / transferTime; double progress = 0; if (totalBytesToDownload > 0L) progress = ((double)totalBytesDownloaded/(double)totalBytesToDownload) * 100.0; logger.trace("Sending download progress metrics to controller"); logger.debug("\tTransferred: {} / {} ({}%)", humanReadableByteCount(totalBytesDownloaded, true), humanReadableByteCount(totalBytesToDownload, true), progress); logger.debug("\tElapsed time: {} seconds", transferTime); logger.debug("\tTransfer rate: {} MB/sec", transferRate); MsgEvent me = plugin.genGMessage(MsgEvent.Type.INFO, "Transfer in progress (" + progress + "%)"); if (seqId != null) me.setParam("seq_id", seqId); if (sampleId != null) me.setParam("sample_id", sampleId); me.setParam("pathstage", String.valueOf(plugin.pathStage)); me.setParam("sstep", "1"); me.setParam("xfer_rate", String.valueOf(transferRate)); me.setParam("xfer_bytes", String.valueOf(totalBytesDownloaded)); me.setParam("xfer_percent", String.valueOf(progress)); plugin.sendMsgEvent(me); Thread.sleep(60000); } wasTransfered = true; } } catch (Exception ex) { logger.error("downloadDirectory {}", ex.getMessage()); } finally { try { assert tx != null; tx.shutdownNow(); } catch (AssertionError e) { logger.error("downloadDirectory - TransferManager was pre-emptively shutdown"); } } return wasTransfered; } private Map<String, Long> getlistBucketContents(String bucket, String prefixKey) { logger.debug("Call to listBucketContents [bucket = {}, prefixKey = {}]", bucket, prefixKey); Map<String, Long> dirList = new HashMap<>(); try { if (doesBucketExist(bucket)) { logger.trace("Grabbing [objects] list from [bucket]"); ObjectListing objects = conn.listObjects(bucket); objects.setPrefix(prefixKey); do { for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) { dirList.put(objectSummary.getKey(), objectSummary.getSize()); } objects = conn.listNextBatchOfObjects(objects); } while (objects.isTruncated()); } else { logger.warn("Bucket :" + bucket + " does not exist!"); } } catch (Exception ex) { logger.error("getlistBucketContents {}", ex.getMessage()); } return dirList; } private class DownloadWorker implements Runnable { private TransferManager tx; private String keyPrefix; private String bucketName; private File file; private Map<String, Download> downloads; DownloadWorker(TransferManager tx, String bucketName, String keyPrefix, File file, Map<String, Download> downloads) { this.tx = tx; this.keyPrefix = keyPrefix; this.bucketName = bucketName; this.file = file; this.downloads = downloads; } @Override public void run() { try { Download download = tx.download(bucketName, keyPrefix, file); downloads.put(keyPrefix, download); while (!download.isDone()) { Thread.sleep(10); } } catch (Exception ex) { ex.printStackTrace(); } } } private static boolean createDir(File file) { boolean isCreated = false; try { //File file = new File(directories); // The mkdirs will create folder including any necessary but non existence // parent directories. This method returns true if and only if the directory // was created along with all necessary parent directories. isCreated = file.mkdirs(); } catch (Exception ex) { ex.printStackTrace(); } return isCreated; } /*public void createFolder(String bucket, String foldername) { // Create metadata for your folder & set content-length to 0 ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(0); // Create empty content InputStream emptyContent = new ByteArrayInputStream(new byte[0]); // Create a PutObjectRequest passing the foldername suffixed by / PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, foldername + FOLDER_SUFFIX, emptyContent, metadata); // Send request to S3 to create folder conn.putObject(putObjectRequest); }*/ public boolean isSyncDir(String bucket, String s3Dir, String localDir, List<String> ignoreList) { logger.debug("Call to isSyncDir [bucket = {}, s3Dir = {}, localDir = {}, ignoreList = {}", bucket, s3Dir, localDir, ignoreList.toString()); boolean isSync = true; Map<String, String> mdhp = new HashMap<>(); try { if (!s3Dir.endsWith("/")) { s3Dir = s3Dir + "/"; } //check if bucket exist if (doesBucketExist(bucket)) { logger.trace("isSync Grabbing [objects] from [bucket] [s3Dir]"); ObjectListing objects = conn.listObjects(bucket, s3Dir); do { for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) { if (!mdhp.containsKey(objectSummary.getKey())) { logger.trace("Adding from s3 [{} : {}]", objectSummary.getKey(), objectSummary.getETag()); mdhp.put(objectSummary.getKey(), objectSummary.getETag()); } } logger.trace("Grabbing next batch of [objects]"); objects = conn.listNextBatchOfObjects(objects); } while (objects.isTruncated()); //S3Object object = conn.getObject(new GetObjectRequest(bucketName, key)); logger.trace("Grabbing list of files from [localDir]"); File folder = new File(localDir); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles != null ? listOfFiles : new File[0]) { if ((file.isFile()) && (!ignoreList.contains(file.getName()))) { String bucket_key = s3Dir + file.getName(); logger.debug("[bucket_key = {}]", bucket_key); String md5hash; if (mdhp.containsKey(bucket_key)) { logger.trace("[mdhp] contains [bucket_key]"); String checkhash = mdhp.get(bucket_key); if (checkhash.contains("-")) { logger.trace("Grabbing multipart-checksum for large/multipart file"); md5hash = md5t.getMultiCheckSum(file.getAbsolutePath()); } else { logger.trace("Grabbing direct checksum for small/non-multipart file"); md5hash = md5t.getCheckSum(file.getAbsolutePath()); } if (!md5hash.equals(checkhash)) { isSync = false; logger.debug("Invalid Sync [bucket_key = {}, checkhash = {}] should be [md5hash = {}]", bucket_key, checkhash, md5hash); } } else { logger.debug("Missing Key [bucket_key = {}]", bucket_key); isSync = false; } } } } else { logger.warn("Bucket :" + bucket + " does not exist!"); } } catch (Exception ex) { logger.error("isSyncDir {}", ex.getMessage()); isSync = false; } mdhp.clear(); return isSync; } public Map<String, String> getDirMD5(String localDir, List<String> ignoreList) { logger.debug("Call to getDirMD5 [localDir = {}, ignoreList = {}]", localDir, ignoreList.toString()); Map<String, String> mdhp = new HashMap<>(); try { logger.trace("Grabbing [listOfFiles] from [localDir]"); File folder = new File(localDir); File[] listOfFiles = folder.listFiles(); logger.trace("Iterating [listOfFiles]"); for (File file : listOfFiles != null ? listOfFiles : new File[0]) { if ((file.isFile()) && (!ignoreList.contains(file.getName()))) { logger.trace("Processing [file = {}]", file.toString()); if (!ignoreList.contains(file.getName())) { logger.trace("Adding [file] to [mdhp]"); mdhp.put(file.getAbsolutePath(), md5t.getCheckSum(file.getAbsolutePath())); } } } } catch (Exception ex) { logger.error("isSyncDir {}", ex.getMessage()); } return mdhp; } public Map<String, String> listBucketContents(String bucket) { logger.debug("Call to listBucketContents [bucket = {}]", bucket); Map<String, String> fileMap = new HashMap<>(); try { if (doesBucketExist(bucket)) { logger.trace("Grabbing [objects] list from [bucket]"); ObjectListing objects = conn.listObjects(bucket); do { for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) { logger.debug("Found object {}\t{}\t{}\t{}", objectSummary.getKey(), objectSummary.getSize(), objectSummary.getETag(), StringUtils.fromDate(objectSummary.getLastModified())); fileMap.put(objectSummary.getKey(), objectSummary.getETag()); } logger.trace("Grabbing next batch of [objects]"); objects = conn.listNextBatchOfObjects(objects); } while (objects.isTruncated()); } else { logger.warn("Bucket :" + bucket + " does not exist!"); } } catch (Exception ex) { logger.error("listBucketContents {}", ex.getMessage()); fileMap = null; } return fileMap; } public List<String> listBucketDirs(String bucket) { logger.debug("Call to listBucketDirs [bucket = {}]", bucket); List<String> dirList = new ArrayList<>(); try { if (doesBucketExist(bucket)) { logger.trace("Instantiating new ListObjectsRequest"); ListObjectsRequest lor = new ListObjectsRequest(); lor.setBucketName(bucket); lor.setDelimiter("/"); logger.trace("Grabbing [objects] list from [lor]"); //if(doesBucketExist(bucket)) ObjectListing objects = conn.listObjects(lor); do { List<String> sublist = objects.getCommonPrefixes(); logger.trace("Adding all Common Prefixes from [objects]"); dirList.addAll(sublist); logger.trace("Grabbing next batch of [objects]"); objects = conn.listNextBatchOfObjects(objects); } while (objects.isTruncated()); } else { logger.warn("Bucket :" + bucket + " does not exist!"); } } catch (Exception ex) { logger.error("listBucketDirs {}", ex.getMessage()); dirList = null; } return dirList; } public Map<String, String> listBucketContents(String bucket, String searchName) { logger.debug("Call to listBucketContents [bucket = {}, searchName = {}]", bucket, searchName); Map<String, String> fileMap = new HashMap<>(); try { if (doesBucketExist(bucket)) { logger.trace("Grabbing [objects] list from [bucket]"); ObjectListing objects = conn.listObjects(bucket); do { for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) { if (objectSummary.getKey().contains(searchName)) { logger.debug("Found object {}\t{}\t{}\t{}", objectSummary.getKey(), objectSummary.getSize(), objectSummary.getETag(), StringUtils.fromDate(objectSummary.getLastModified())); fileMap.put(objectSummary.getKey(), objectSummary.getETag()); } } objects = conn.listNextBatchOfObjects(objects); } while (objects.isTruncated()); } else { logger.warn("Bucket :" + bucket + " does not exist!"); } } catch (Exception ex) { logger.error("listBucketContents {}", ex.getMessage()); fileMap = null; } return fileMap; } public boolean doesObjectExist(String bucket, String objectName) { logger.debug("Call to doesObjectExist [bucket = {}, objectName = {}]", bucket, objectName); return conn.doesObjectExist(bucket, objectName); } public boolean doesBucketExist(String bucket) { logger.debug("Call to doesBucketExist [bucket = {}]", bucket); return conn.doesBucketExist(bucket); } public void createBucket(String bucket) { logger.debug("Call to createBucket [bucket = {}]", bucket); try { if (!conn.doesBucketExist(bucket)) { Bucket mybucket = conn.createBucket(bucket); logger.debug("Created bucket [{}] ", bucket); } } catch (Exception ex) { logger.error("createBucket {}", ex.getMessage()); } } public void deleteBucketContents(String bucket) { logger.debug("Call to deleteBucketContents [bucket = {}]", bucket); logger.trace("Grabbing [objects] list from [bucket]"); ObjectListing objects = conn.listObjects(bucket); do { for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) { logger.trace("Deleting [{}] object from [{}] bucket", objectSummary.getKey(), bucket); conn.deleteObject(bucket, objectSummary.getKey()); logger.debug("Deleted {}\t{}\t{}\t{}", objectSummary.getKey(), objectSummary.getSize(), objectSummary.getETag(), StringUtils.fromDate(objectSummary.getLastModified())); } objects = conn.listNextBatchOfObjects(objects); } while (objects.isTruncated()); } public static String humanReadableByteCount(long bytes, boolean si) { int unit = si ? 1000 : 1024; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i"); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); } }
package com.thinkaurelius.titan.diskstorage.cassandra; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.cassandra.thrift.Cassandra; import org.apache.cassandra.thrift.CfDef; import org.apache.cassandra.thrift.ConsistencyLevel; import org.apache.cassandra.thrift.InvalidRequestException; import org.apache.cassandra.thrift.KsDef; import org.apache.cassandra.thrift.NotFoundException; import org.apache.cassandra.thrift.SchemaDisagreementException; import org.apache.commons.configuration.Configuration; import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thinkaurelius.titan.diskstorage.StorageManager; import com.thinkaurelius.titan.diskstorage.TransactionHandle; import com.thinkaurelius.titan.diskstorage.cassandra.thriftpool.CTConnection; import com.thinkaurelius.titan.diskstorage.cassandra.thriftpool.CTConnectionFactory; import com.thinkaurelius.titan.diskstorage.cassandra.thriftpool.CTConnectionPool; import com.thinkaurelius.titan.diskstorage.cassandra.thriftpool.UncheckedGenericKeyedObjectPool; import com.thinkaurelius.titan.diskstorage.util.ConfigHelper; import com.thinkaurelius.titan.diskstorage.util.OrderedKeyColumnValueIDManager; import com.thinkaurelius.titan.exceptions.GraphStorageException; import com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration; public class CassandraThriftStorageManager implements StorageManager { private static final Logger log = LoggerFactory.getLogger(CassandraThriftStorageManager.class); public static final String PROP_KEYSPACE = "keyspace"; public static final String PROP_HOSTNAME = "hostname"; public static final String PROP_PORT = "port"; public static final String PROP_SELF_HOSTNAME = "selfHostname"; public static final String PROP_TIMEOUT = "thrift_timeout"; public static final String PROP_ID_KEYSPACE = "id_keyspace"; public static Map<String, CassandraThriftOrderedKeyColumnValueStore> stores = new ConcurrentHashMap<String, CassandraThriftOrderedKeyColumnValueStore>(); /** * Default name for the Cassandra keyspace * <p> * Value = {@value} */ public static final String DEFAULT_KEYSPACE = "titantest00"; /** * Default hostname at which to attempt Cassandra Thrift connection. * <p> * Value = {@value} */ public static final String DEFAULT_HOSTNAME = null; /** * Default canonical hostname of the local machine. * <p> * Value = {@value} */ public static final String DEFAULT_SELF_HOSTNAME = null; /** * Default timeout for Thrift TSocket objects used to * connect to the Cassandra cluster. * <p> * Value = {@value} */ public static final int DEFAULT_THRIFT_TIMEOUT_MS = 10000; /** * Default port at which to attempt Cassandra Thrift connection. * <p> * Value = {@value} */ public static final int DEFAULT_PORT = 9160; /** * Default column family used for ID block management. * <p> * Value = {@value} */ public static final String idCfName = "id_allocations"; /** * Default keyspace to be used for ID block management. * <p> * Value = {@value} */ public static final String ID_KEYSPACE = "titan_ids"; public static final String READ_CONSISTENCY_LEVEL_KEY = "read_consistency_level"; public static final String READ_CONSISTENCY_LEVEL_DEFAULT = "QUORUM"; public static final String WRITE_CONSISTENCY_LEVEL_KEY = "write_consistency_level"; /* * Any operation attempted with ConsistencyLevel.TWO * against a single-node Cassandra cluster (like the one * we use in a lot of our test cases) will fail with * an UnavailableException. In other words, if you * set TWO here, Cassandra will require TWO nodes, even * if only one node has ever been a member of the * cluster in question. */ public static final String WRITE_CONSISTENCY_LEVEL_DEFAULT = "QUORUM"; private final String keyspace; private final UncheckedGenericKeyedObjectPool <String, CTConnection> pool; private final OrderedKeyColumnValueIDManager idmanager; private final int lockRetryCount; private final long lockWaitMS, lockExpireMS; private final ConsistencyLevel readConsistencyLevel; private final ConsistencyLevel writeConsistencyLevel; private final byte[] rid; public CassandraThriftStorageManager(Configuration config) { this.rid = ConfigHelper.getRid(config); this.keyspace = config.getString(PROP_KEYSPACE,DEFAULT_KEYSPACE); this.pool = CTConnectionPool.getPool( interpretHostname(config.getString(PROP_HOSTNAME,DEFAULT_HOSTNAME)), config.getInt(PROP_PORT,DEFAULT_PORT), config.getInt(PROP_TIMEOUT,DEFAULT_THRIFT_TIMEOUT_MS)); this.lockRetryCount = config.getInt( GraphDatabaseConfiguration.LOCK_RETRY_COUNT, GraphDatabaseConfiguration.LOCK_RETRY_COUNT_DEFAULT); this.lockWaitMS = config.getLong( GraphDatabaseConfiguration.LOCK_WAIT_MS, GraphDatabaseConfiguration.LOCK_WAIT_MS_DEFAULT); this.lockExpireMS = config.getLong( GraphDatabaseConfiguration.LOCK_EXPIRE_MS, GraphDatabaseConfiguration.LOCK_EXPIRE_MS_DEFAULT); this.readConsistencyLevel = ConsistencyLevel.valueOf( config.getString( READ_CONSISTENCY_LEVEL_KEY, READ_CONSISTENCY_LEVEL_DEFAULT)); log.debug("Set read consistency level to {}", this.readConsistencyLevel); this.writeConsistencyLevel = ConsistencyLevel.valueOf( config.getString( WRITE_CONSISTENCY_LEVEL_KEY, WRITE_CONSISTENCY_LEVEL_DEFAULT)); log.debug("Set write consistency level to {}", this.writeConsistencyLevel); idmanager = new OrderedKeyColumnValueIDManager( openDatabase("blocks_allocated", ID_KEYSPACE, true), rid, config); } @Override public long[] getIDBlock(int partition, int blockSize) { return idmanager.getIDBlock(partition,blockSize); } @Override public TransactionHandle beginTransaction() { return new CassandraTransaction(this, rid, lockRetryCount, lockWaitMS, lockExpireMS); } @Override public void close() { //Do nothing } @Override public CassandraThriftOrderedKeyColumnValueStore openDatabase(final String name) throws GraphStorageException { return openDatabase(name, keyspace, false); } private CassandraThriftOrderedKeyColumnValueStore openDatabase(final String name, final String ksoverride, boolean forceCfCheck) throws GraphStorageException { String storeKey = ksoverride + ":" + name; CassandraThriftOrderedKeyColumnValueStore store = stores.get(storeKey); if (null != store && !forceCfCheck) { return store; } CTConnection conn = null; try { conn = pool.genericBorrowObject(ksoverride); Cassandra.Client client = conn.getClient(); log.debug("Looking up metadata on keyspace {}...", ksoverride); KsDef keyspaceDef = client.describe_keyspace(ksoverride); boolean foundColumnFamily = false; for (CfDef cfDef : keyspaceDef.getCf_defs()) { String curCfName = cfDef.getName(); if (curCfName.equals(name)) { foundColumnFamily = true; } } if (!foundColumnFamily) { log.debug("Keyspace {} not found, about to create it", ksoverride); createColumnFamily(client, ksoverride, name); } else { log.debug("Found keyspace: {}", ksoverride); } } catch (TException e) { throw new GraphStorageException(e); } catch (InvalidRequestException e) { throw new GraphStorageException(e); } catch (NotFoundException e) { throw new GraphStorageException(e); } finally { if (null != conn) pool.genericReturnObject(ksoverride, conn); } if (null != store) { return store; } store = new CassandraThriftOrderedKeyColumnValueStore( ksoverride, name, pool, this, readConsistencyLevel, writeConsistencyLevel); stores.put(storeKey, store); log.debug("Created {}", store); return store; } String getLockColumnFamilyName(String cfName) { return cfName + "_locks"; } /** * Drop the named keyspace if it exists. Otherwise, do nothing. * * @throws GraphStorageException wrapping any unexpected Exception or * subclass of Exception * @returns true if the keyspace was dropped, false if it was not present */ public boolean dropKeyspace(String keyspace) throws GraphStorageException { CTConnection conn = null; try { conn = pool.genericBorrowObject(keyspace); Cassandra.Client client = conn.getClient(); try { client.describe_keyspace(keyspace); // Keyspace must exist log.debug("Dropping keyspace {}...", keyspace); String schemaVer = client.system_drop_keyspace(keyspace); // Try to let Cassandra converge on the new column family CTConnectionFactory.validateSchemaIsSettled(client, schemaVer); pool.clear(keyspace); } catch (NotFoundException e) { // Keyspace doesn't exist yet: return immediately log.debug("Keyspace {} does not exist, not attempting to drop", keyspace); return false; } stores.clear(); return true; } catch (Exception e) { throw new GraphStorageException(e); } finally { if (null != conn) pool.genericReturnObject(keyspace, conn); } } /** * Connect to Cassandra via Thrift on the specified host and * port and attempt to drop the named keyspace. * * This is a utility method intended mainly for testing. It is * equivalent to issuing "drop keyspace {@code <keyspace>};" in * the cassandra-cli tool. * * @param keyspace the keyspace to drop * @throws RuntimeException if any checked Thrift or UnknownHostException * is thrown in the body of this method */ public static void dropKeyspace(String keyspace, String hostname, int port) throws GraphStorageException { CTConnection conn = null; try { conn = CTConnectionPool.getFactory(hostname, port, DEFAULT_THRIFT_TIMEOUT_MS).makeRawConnection(); Cassandra.Client client = conn.getClient(); try { client.describe_keyspace(keyspace); // Keyspace must exist log.debug("Dropping keyspace {}...", keyspace); String schemaVer = client.system_drop_keyspace(keyspace); // Try to let Cassandra converge on the new column family CTConnectionFactory.validateSchemaIsSettled(client, schemaVer); CTConnectionPool.getPool(hostname, port, DEFAULT_THRIFT_TIMEOUT_MS).clear(keyspace); stores.clear(); } catch (NotFoundException e) { // Keyspace doesn't exist yet: return immediately log.debug("Keyspace {} does not exist, not attempting to drop", keyspace); } } catch (Exception e) { throw new GraphStorageException(e); } finally { if (null != conn && conn.getTransport().isOpen()) conn.getTransport().close(); } } /** * If hostname is non-null, returns hostname. * * If hostname is null, returns the result of calling * InetAddress.getLocalHost().getCanonicalHostName(). * Any exceptions generated during said call are rethrown as * RuntimeException. * * @throws RuntimeException in case of UnknownHostException for localhost * @return sanitized hostname */ private static String interpretHostname(String hostname) { if (null == hostname) { try { return InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { throw new RuntimeException(e); } } else { return hostname; } } private void createColumnFamily(Cassandra.Client client, String ksname, String cfName) throws InvalidRequestException, TException { CfDef createColumnFamily = new CfDef(); createColumnFamily.setName(cfName); createColumnFamily.setKeyspace(ksname); createColumnFamily.setComparator_type("org.apache.cassandra.db.marshal.BytesType"); log.debug("Adding column family {} to keyspace {}...", cfName, ksname); String schemaVer = null; try { schemaVer = client.system_add_column_family(createColumnFamily); } catch (SchemaDisagreementException e) { throw new GraphStorageException("Error in setting up column family",e); } log.debug("Added column family {} to keyspace {}.", cfName, ksname); // Try to let Cassandra converge on the new column family try { CTConnectionFactory.validateSchemaIsSettled(client, schemaVer); } catch (InterruptedException e) { throw new GraphStorageException(e); } } @Override public String toString() { return "CassandraThriftStorageManager[ks=" + keyspace + "]"; } }
package com.whizzosoftware.hobson.bootstrap.api.plugin; import com.whizzosoftware.hobson.api.HobsonRuntimeException; import com.whizzosoftware.hobson.api.device.DeviceContext; import com.whizzosoftware.hobson.api.device.DeviceManager; import com.whizzosoftware.hobson.api.disco.DiscoManager; import com.whizzosoftware.hobson.api.event.*; import com.whizzosoftware.hobson.api.hub.HubContext; import com.whizzosoftware.hobson.api.hub.HubManager; import com.whizzosoftware.hobson.api.plugin.*; import com.whizzosoftware.hobson.api.property.PropertyContainerClass; import com.whizzosoftware.hobson.api.task.TaskManager; import com.whizzosoftware.hobson.api.variable.VariableManager; import com.whizzosoftware.hobson.api.variable.VariableUpdate; import io.netty.util.concurrent.Future; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; /** * A class that encapsulates a Hobson plugin class in order to handle OSGi lifecycle events and provide * the plugin event loop. This implements HobsonPlugin so it can will appear to the OSGi runtime as * an actual plugin while it intercepts the OSGi lifecycle callbacks. * * @author Dan Noguerol */ public class HobsonPluginEventLoopWrapper implements HobsonPlugin, EventListener, ServiceListener { private final Logger logger = LoggerFactory.getLogger(getClass()); // these will be dependency injected by the OSGi runtime private volatile DeviceManager deviceManager; private volatile DiscoManager discoManager; private volatile EventManager eventManager; private volatile ExecutorService executorService; private volatile HubManager hubManager; private volatile PluginManager pluginManager; private volatile TaskManager taskManager; private volatile VariableManager variableManager; private HobsonPlugin plugin; /** * Constructor. * * @param plugin the plugin to wrapper */ public HobsonPluginEventLoopWrapper(HobsonPlugin plugin) { if (plugin != null) { this.plugin = plugin; } else { throw new HobsonRuntimeException("Passed a null plugin to HobsonPluginEventLoopWrapper"); } } /** * Called when the OSGi service is started. This performs plugin dependency injection and gets the * plugin event loop started. */ public void start() { logger.debug("Starting plugin: {}", plugin.getContext()); // inject manager dependencies getRuntime().setDeviceManager(deviceManager); getRuntime().setDiscoManager(discoManager); getRuntime().setEventManager(eventManager); getRuntime().setHubManager(hubManager); getRuntime().setPluginManager(pluginManager); getRuntime().setTaskManager(taskManager); getRuntime().setVariableManager(variableManager); // wait for service to become registered before performing final initialization try { String filter = "(&(objectclass=" + HobsonPlugin.class.getName() + ")(pluginId=" + getContext().getPluginId() + "))"; FrameworkUtil.getBundle(getClass()).getBundleContext().addServiceListener(this, filter); } catch (InvalidSyntaxException e) { logger.error("Error registering service listener for plugin " + getContext(), e); } } /** * Called when the OSGi service is stopped. This will stop the plugin event loop. */ public void stop() { logger.debug("Stopping plugin: {}", plugin.getContext()); final long now = System.currentTimeMillis(); // remove the service listener FrameworkUtil.getBundle(getClass()).getBundleContext().removeServiceListener(this); final HubContext ctx = HubContext.createLocal(); final PluginContext pctx = plugin.getContext(); final Object mutex = new Object(); // stop listening for all events eventManager.removeListenerFromAllTopics(ctx, HobsonPluginEventLoopWrapper.this); // unpublish all variables published by this plugin's devices variableManager.unpublishAllVariables(plugin.getContext()); // stop all devices deviceManager.unpublishAllDevices(pctx, plugin.getRuntime().getEventLoopExecutor()); // queue a task for final cleanup logger.trace("Queuing final cleanup task"); plugin.getRuntime().getEventLoopExecutor().executeInEventLoop(new Runnable() { @Override public void run() { logger.trace("All devices have shut down; performing final cleanup"); // shut down the plugin getRuntime().onShutdown(); // post plugin stopped event eventManager.postEvent(ctx, new PluginStoppedEvent(now, getContext())); // release reference plugin = null; // notify thread that kicked off the stop that the plugin shutdown is complete synchronized (mutex) { mutex.notify(); } } }); // wait for the async task to complete so that the OSGi framework knows that we've really stopped synchronized (mutex) { try { logger.trace("Waiting for final cleanup"); long start = System.currentTimeMillis(); mutex.wait(5000); if (System.currentTimeMillis() - start >= 5000) { logger.error("Plugin " + getName() + " failed to stop gracefully"); } } catch (InterruptedException ignored) {} } logger.debug("Shutdown complete for plugin: {}", pctx); } /* * EventManagerListener methods */ @Override public void onHobsonEvent(final HobsonEvent event) { plugin.getRuntime().submitInEventLoop(new Runnable() { @Override public void run() { try { // ignore the event if the plugin has been stopped if (plugin != null && plugin.getContext() != null && plugin.getContext().getPluginId() != null) { String pluginId = plugin.getContext().getPluginId(); if (event instanceof PluginConfigurationUpdateEvent && pluginId.equals(((PluginConfigurationUpdateEvent)event).getPluginId())) { PluginConfigurationUpdateEvent pcue = (PluginConfigurationUpdateEvent)event; logger.trace("Dispatching device config update for {} to runtime", pcue.getPluginId()); plugin.getRuntime().onPluginConfigurationUpdate(pcue.getConfiguration()); } else if (event instanceof DeviceConfigurationUpdateEvent && pluginId.equals(((DeviceConfigurationUpdateEvent)event).getPluginId())) { DeviceConfigurationUpdateEvent dcue = (DeviceConfigurationUpdateEvent)event; logger.trace("Dispatching device config update for {}:{} to runtime", dcue.getPluginId(), dcue.getDeviceId()); plugin.getRuntime().onDeviceConfigurationUpdate(DeviceContext.create(plugin.getContext(), dcue.getDeviceId()), dcue.getConfiguration()); } else if (event instanceof VariableUpdateRequestEvent) { VariableUpdateRequestEvent dcue = (VariableUpdateRequestEvent)event; for (VariableUpdate update : dcue.getUpdates()) { if (pluginId.equals(update.getPluginId())) { logger.trace("Dispatching variable update request for {}:{} to runtime", update.getPluginId(), update.getDeviceId()); plugin.getRuntime().onSetDeviceVariable(DeviceContext.create(plugin.getContext(), update.getDeviceId()), update.getName(), update.getValue()); } } } else { logger.trace("Dispatching event to plugin {}: {}", pluginId, event); plugin.getRuntime().onHobsonEvent(event); } } else { logger.error("Error processing event for plugin " + plugin + ": " + event); } } catch (Throwable e) { logger.error("An error occurred processing an event", e); } } }); } /* * Hobson plugin interface methods -- these all pass-through to the real plugin implementation */ @Override public PluginContext getContext() { return plugin.getContext(); } @Override public String getName() { return plugin.getName(); } @Override public String getVersion() { return plugin.getVersion(); } @Override public PluginStatus getStatus() { return plugin.getStatus(); } @Override public PropertyContainerClass getConfigurationClass() { return plugin.getConfigurationClass(); } @Override public PluginType getType() { return plugin.getType(); } @Override public boolean isConfigurable() { return plugin.isConfigurable(); } @Override public HobsonPluginRuntime getRuntime() { return plugin.getRuntime(); } @Override public void serviceChanged(ServiceEvent serviceEvent) { if (serviceEvent.getType() == ServiceEvent.REGISTERED) { // register plugin for necessary event topics int otherTopicsCount = 0; String[] otherTopics = plugin.getRuntime().getEventTopics(); if (otherTopics != null) { otherTopicsCount = otherTopics.length; } String[] topics = new String[otherTopicsCount + 1]; topics[0] = EventTopics.STATE_TOPIC; // all plugins need to listen for state events if (otherTopicsCount > 0) { System.arraycopy(otherTopics, 0, topics, 1, otherTopicsCount); } eventManager.addListener(plugin.getContext().getHubContext(), this, topics); // start the event loop Future f = getRuntime().submitInEventLoop(new Runnable() { @Override public void run() { // start the plugin getRuntime().onStartup(pluginManager.getLocalPluginConfiguration(plugin.getContext())); // post plugin started event eventManager.postEvent(plugin.getContext().getHubContext(), new PluginStartedEvent(System.currentTimeMillis(), getContext())); // schedule the refresh callback if the plugin's refresh interval > 0 if (plugin.getRuntime().getRefreshInterval() > 0) { getRuntime().scheduleAtFixedRateInEventLoop(new Runnable() { @Override public void run() { try { getRuntime().onRefresh(); } catch (Throwable e) { logger.error("Error refreshing plugin: " + plugin.getContext(), e); } } }, 0, plugin.getRuntime().getRefreshInterval(), TimeUnit.SECONDS); } logger.debug("Startup complete for plugin: {}", plugin.getContext()); } }); // wait for the async task to complete so that the OSGi framework knows that we've really started try { f.get(); } catch (Throwable e) { logger.error("Error waiting for plugin to start", e); } } } public HobsonPlugin getPlugin() { return plugin; } }
package org.projectspinoza.twitterswissarmyknife.command; import java.io.BufferedWriter; import java.io.IOException; import org.projectspinoza.twitterswissarmyknife.util.TsakResponse; import twitter4j.AccountSettings; import twitter4j.Twitter; import twitter4j.TwitterException; import com.beust.jcommander.Parameters; import com.google.gson.Gson; @Parameters(commandNames = "dumpAccountSettings", commandDescription = "Account Setting") public class CommandDumpAccountSettings extends BaseCommand { @Override public TsakResponse execute(Twitter twitter) throws TwitterException { AccountSettings settings = twitter.getAccountSettings(); int remApiLimits = settings.getRateLimitStatus().getRemaining(); TsakResponse tsakResponse = new TsakResponse(remApiLimits, settings); tsakResponse.setCommandDetails(this.toString()); return tsakResponse; } @Override public void write(TsakResponse tsakResponse, BufferedWriter writer) throws IOException { String jsonSettings = new Gson().toJson(tsakResponse.getResponseData()); writer.append(jsonSettings); writer.newLine(); } @Override public String toString() { return "CommandDumpAccountSettings []"; } }
package org.realityforge.replicant.example.server.service.tyrell; import java.util.ArrayList; import javax.annotation.Nonnull; import javax.ejb.EJB; import javax.ejb.Stateless; import org.realityforge.replicant.example.server.entity.tyrell.Building; import org.realityforge.replicant.example.server.entity.tyrell.Room; import org.realityforge.replicant.example.server.entity.tyrell.dao.BuildingRepository; import org.realityforge.replicant.example.server.entity.tyrell.dao.RoomRepository; @Stateless public class BuildingServiceEJB implements BuildingService { @EJB private BuildingRepository _buildingRepository; @EJB private RoomRepository _roomRepository; @Nonnull @Override public Building createBuilding( @Nonnull final String name ) { final Building building = new Building(); building.setName( name ); _buildingRepository.persist( building ); return building; } @Override public void removeBuilding( @Nonnull final Building building ) { final ArrayList<Room> rooms = new ArrayList<>( building.getRooms() ); for ( final Room room : rooms ) { removeRoom( room ); } _buildingRepository.remove( building ); } @Override public void setBuildingName( @Nonnull final Building building, @Nonnull final String name ) { building.setName( name ); } @Nonnull @Override public Room createRoom( @Nonnull final Building building, final int floor, final int localNumber, @Nonnull final String name, final boolean active ) { final Room room = new Room( building, floor ); room.setLocalNumber( localNumber ); room.setName( name ); room.setActive( active ); _roomRepository.persist( room ); return room; } @Override public void removeRoom( @Nonnull final Room room ) { _roomRepository.remove( room ); } @Override public void setRoomName( @Nonnull final Room room, @Nonnull final String name ) { room.setName( name ); } @Override public void setRoomLocalNumber( @Nonnull final Room room, final int localNumber ) { room.setLocalNumber( localNumber ); } @Override public void setRoomActivity( @Nonnull final Room room, final boolean active ) { room.setActive( active ); } }
package com.github.davidmoten.fsm.persistence; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Queue; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Function; import com.github.davidmoten.fsm.runtime.CancelTimedSignal; import com.github.davidmoten.fsm.runtime.Clock; import com.github.davidmoten.fsm.runtime.ClockDefault; import com.github.davidmoten.fsm.runtime.Create; import com.github.davidmoten.fsm.runtime.EntityBehaviour; import com.github.davidmoten.fsm.runtime.EntityState; import com.github.davidmoten.fsm.runtime.EntityStateMachine; import com.github.davidmoten.fsm.runtime.Event; import com.github.davidmoten.fsm.runtime.Signal; import com.github.davidmoten.guavamini.Preconditions; public final class Persistence { private final ScheduledExecutorService executor; private final Clock clock; private final Serializer entitySerializer; private final Serializer eventSerializer; private final Sql sql; private final Callable<Connection> connectionFactory; private final Function<Class<?>, EntityBehaviour<?, String>> behaviourFactory; private final Queue<NumberedSignal<?, ?>> queue = new LinkedList<>(); private final AtomicInteger wip = new AtomicInteger(); private final boolean storeSignals; private final Consumer<Throwable> errorHandler; private final long retryIntervalMs; private Persistence(ScheduledExecutorService executor, Clock clock, Serializer entitySerializer, Serializer eventSerializer, Function<Class<?>, EntityBehaviour<?, String>> behaviourFactory, Sql sql, Callable<Connection> connectionFactory, boolean storeSignals, Consumer<Throwable> errorHandler, long retryIntervalMs) { this.executor = executor; this.clock = clock; this.entitySerializer = entitySerializer; this.eventSerializer = eventSerializer; this.behaviourFactory = behaviourFactory; this.sql = sql; this.connectionFactory = connectionFactory; this.storeSignals = storeSignals; this.errorHandler = errorHandler; this.retryIntervalMs = retryIntervalMs; } public static Builder connectionFactory(Callable<Connection> connectionFactory) { return new Builder().connectionFactory(connectionFactory); } public static final class Builder { private static final int DEFAULT_RETRY_INTERVAL_MS = 30000; private static final Consumer<Throwable> PRINT_STACK_TRACE_AND_THROW = t -> { t.printStackTrace(); throw new RuntimeException(t); }; private static final Consumer<Throwable> PRINT_STACK_TRACE = t -> { t.printStackTrace(); }; private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); private Clock clock = ClockDefault.instance(); private Serializer entitySerializer = Serializer.JSON; private Serializer eventSerializer = Serializer.JSON; private Function<Class<?>, EntityBehaviour<?, String>> behaviourFactory; private Sql sql = Sql.DEFAULT; private Callable<Connection> connectionFactory; private boolean storeSignals = true; private Consumer<Throwable> errorHandler = PRINT_STACK_TRACE; private long retryIntervalMs = DEFAULT_RETRY_INTERVAL_MS; private Builder() { // do nothing } public Builder executor(ScheduledExecutorService executor) { this.executor = executor; return this; } public Builder clock(Clock clock) { this.clock = clock; return this; } public Builder entitySerializer(Serializer serializer) { this.entitySerializer = serializer; return this; } public Builder eventSerializer(Serializer serializer) { this.eventSerializer = serializer; return this; } public Builder behaviourFactory(Function<Class<?>, EntityBehaviour<?, String>> behaviourFactory) { this.behaviourFactory = behaviourFactory; return this; } public Builder sql(Sql sql) { this.sql = sql; return this; } public Builder connectionFactory(Callable<Connection> connectionFactory) { this.connectionFactory = connectionFactory; return this; } public Builder storeSignals(boolean storeSignals) { this.storeSignals = storeSignals; return this; } public Builder errorHandler(Consumer<Throwable> errorHandler) { this.errorHandler = errorHandler; return this; } /** * This method designed for use with TestExecutor in unit tests. Best * not to use this outside of unit tests because throwing shuts down the * drain loop and no further signals will be processed. */ public Builder errorHandlerPrintStackTraceAndThrow() { return errorHandler(PRINT_STACK_TRACE_AND_THROW); } public Builder retryIntervalMs(long retryIntervalMs) { this.retryIntervalMs = retryIntervalMs; return this; } public Persistence build() { return new Persistence(executor, clock, entitySerializer, eventSerializer, behaviourFactory, sql, connectionFactory, storeSignals, errorHandler, retryIntervalMs); } } public void create() { String sql = new String(readAll(Persistence.class.getResourceAsStream("/create-h2.sql")), StandardCharsets.UTF_8); create(sql); } public void create(String sql) { try (Connection con = createConnection()) { con.setAutoCommit(true); String[] commands = sql.split(";"); for (String command : commands) { con.prepareStatement(command).execute(); } con.commit(); } catch (SQLException e) { throw new SQLRuntimeException(e); } } public <T> void signal(Class<T> cls, String id, Event<? super T> event) { signal(Signal.create(cls, id, event)); } public void signal(Signal<?, String> signal) { if (!signal.time().isPresent()) { try ( Connection con = createConnection(); PreparedStatement ps = con.prepareStatement(sql.addToSignalQueue())) { ps.setString(1, signal.cls().getName()); ps.setString(2, signal.id()); ps.setString(3, signal.event().getClass().getName()); ps.setBlob(4, new ByteArrayInputStream(eventSerializer.serialize(signal.event()))); ps.executeUpdate(); try (ResultSet rs = ps.getGeneratedKeys()) { rs.next(); long number = rs.getLong(1); offer(new NumberedSignal<>(signal, number)); } } catch (SQLException e) { throw new SQLRuntimeException(e); } } else { } } @SuppressWarnings("unchecked") public void initialize() { List<NumberedSignal<?, ?>> list = new ArrayList<NumberedSignal<?, ?>>(); try ( Connection con = createConnection(); PreparedStatement ps = con.prepareStatement(sql.selectDelayedSignals())) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { long number = rs.getLong("seq_num"); String className = rs.getString("cls"); String id = rs.getString("id"); byte[] eventBytes = readAll(rs.getBlob("event_bytes").getBinaryStream()); String eventClsName = rs.getString("event_cls"); Class<?> eventClass = Class.forName(eventClsName); Object event = eventSerializer.deserialize(eventClass, eventBytes); Class<?> cls = Class.forName(className); long time = rs.getTimestamp("times").getTime(); Signal<Object, String> signal = Signal.create((Class<Object>) cls, id, (Event<Object>) event, Optional.of(time)); list.add(new NumberedSignal<Object, String>(signal, number)); } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } catch (SQLException e) { throw new SQLRuntimeException(e); } for (NumberedSignal<?, ?> sig : list) { schedule(sig); } } @SuppressWarnings("unchecked") private void schedule(NumberedSignal<?, ?> sig) { Preconditions.checkArgument(sig.signal.time().isPresent()); long now = clock.now(); long delayMs = Math.max(0, sig.signal.time().get() - now); executor.schedule(() -> offer((NumberedSignal<?, String>) sig), delayMs, TimeUnit.MILLISECONDS); } public static final class EntityAndState<T> { final T entity; final EntityState<T> state; EntityAndState(T entity, EntityState<T> state) { this.entity = entity; this.state = state; } static <T> EntityAndState<T> create(T entity, EntityState<T> state) { return new EntityAndState<T>(entity, state); } } @SuppressWarnings("unchecked") private boolean process(NumberedSignal<?, String> signal) { List<NumberedSignal<?, ?>> numberedSignalsToOther; List<NumberedSignal<?, ?>> delayedNumberedSignalsToOther; try (Connection con = createConnection()) { // start a transaction con.setAutoCommit(false); // if signal does not exist in queue anymore then ignore if (!signalExists(con, signal)) { return true; } // if is cancellation then remove signal from delayed queue and // return if (handleCancellationSignal(con, signal)) { return true; } // get behaviour EntityBehaviour<Object, String> behaviour = (EntityBehaviour<Object, String>) behaviourFactory .apply(signal.signal.cls()); // read entity Optional<EntityAndState<Object>> entity = readEntity(con, (Class<Object>) signal.signal.cls(), signal.signal.id(), (EntityBehaviour<Object, String>) behaviour); // initialize state machine final EntityStateMachine<?, String> esm = getStateMachine(signal, behaviour, entity); // apend signal to signal_store (optional) if (storeSignals) { insertIntoSignalStore(con, esm, signal.signal.event(), eventSerializer); } Signals<String> signals = new Signals<String>(); signals.signalsToSelf.offerFirst(signal.signal.event()); // push signal through state machine which will immediately process // non-delayed signals to self and accumulate signals to others EntityStateMachine<?, String> esm2 = pushSignalThroughStateMachine(esm, signals); Deque<Signal<?, String>> signalsToOther = signals.signalsToOther; // add signals to others to signal_queue numberedSignalsToOther = insertSignalsToOther(con, eventSerializer, signalsToOther); // add delayed signals to other to delayed_signal_queue delayedNumberedSignalsToOther = insertDelayedSignalsToOther(con, esm2.cls(), esm.id(), eventSerializer, signalsToOther); // remove signal from signal_queue removeSignal(con, signal); // update/create the entity bytes and state to entity table saveEntity(con, esm2); // commit the transaction con.commit(); } catch (Throwable e) { errorHandler.accept(e); scheduleRetry(); return false; } for (NumberedSignal<?, ?> signalToOther : numberedSignalsToOther) { offer((NumberedSignal<?, String>) signalToOther); } for (NumberedSignal<?, ?> signalToOther : delayedNumberedSignalsToOther) { schedule(signalToOther); } return true; } private void scheduleRetry() { if (retryIntervalMs > 0) { executor.schedule(() -> drain(), retryIntervalMs, TimeUnit.MILLISECONDS); } } @SuppressWarnings("unchecked") private EntityStateMachine<?, String> pushSignalThroughStateMachine(final EntityStateMachine<?, String> esm, Signals<String> signals) { EntityStateMachine<?, String> esm2 = esm; Event<?> event; while ((event = signals.signalsToSelf.poll()) != null) { esm2 = esm2.signal((Event<Object>) event); List<Event<Object>> list = (List<Event<Object>>) (List<?>) esm2.signalsToSelf(); for (int i = list.size() - 1; i >= 0; i signals.signalsToSelf.offerLast(list.get(i)); } for (Signal<?, ?> s : esm2.signalsToOther()) { signals.signalsToOther.offerFirst((Signal<?, String>) s); } } return esm2; } private static final class Signals<Id> { final Deque<Event<?>> signalsToSelf = new ArrayDeque<>(); final Deque<Signal<?, Id>> signalsToOther = new ArrayDeque<>(); } private boolean handleCancellationSignal(Connection con, NumberedSignal<?, String> signal) throws SQLException { if (signal.signal.event() instanceof CancelTimedSignal) { @SuppressWarnings("unchecked") CancelTimedSignal<String> c = (CancelTimedSignal<String>) signal.signal.event(); removeDelayedSignal(con, c.fromClass(), c.fromId(), signal.signal.cls(), signal.signal.id()); return true; } else { return false; } } private boolean signalExists(Connection con, NumberedSignal<?, String> signal) throws SQLException { if (signal.signal.time().isPresent()) { try (PreparedStatement ps = con.prepareStatement(sql.delayedSignalExists())) { ps.setLong(1, signal.number); try (ResultSet rs = ps.executeQuery()) { return rs.next(); } } } else { try (PreparedStatement ps = con.prepareStatement(sql.signalExists())) { ps.setLong(1, signal.number); try (ResultSet rs = ps.executeQuery()) { return rs.next(); } } } } private EntityStateMachine<?, String> getStateMachine(NumberedSignal<?, String> signal, EntityBehaviour<Object, String> behaviour, Optional<EntityAndState<Object>> entity) { if (!entity.isPresent()) { return behaviour.create(signal.signal.id()).signal(new Create()); } else { return behaviour.create(signal.signal.id(), entity.get().entity, entity.get().state); } } private <T> Optional<EntityAndState<T>> readEntity(Connection con, Class<T> cls, String id, EntityBehaviour<T, String> behaviour) throws SQLException { try (PreparedStatement ps = con.prepareStatement(sql.readEntityAndState())) { ps.setString(1, cls.getName()); ps.setString(2, id); try (ResultSet rs = ps.executeQuery()) { if (!rs.next()) { return Optional.empty(); } else { byte[] bytes = readAll(rs.getBlob("bytes").getBinaryStream()); T entity = (T) entitySerializer.deserialize(cls, bytes); EntityState<T> state = behaviour.from(rs.getString("state")); return Optional.of(EntityAndState.create(entity, state)); } } } } private void insertIntoSignalStore(Connection con, EntityStateMachine<?, String> esm, Event<?> event, Serializer eventSerializer) throws SQLException { try (PreparedStatement ps = con.prepareStatement(sql.addToSignalStore())) { ps.setString(1, esm.cls().getName()); ps.setString(2, esm.id()); ps.setString(3, event.getClass().getName()); ps.setBlob(4, new ByteArrayInputStream(eventSerializer.serialize(event))); ps.executeUpdate(); } } @SuppressWarnings("unchecked") private List<NumberedSignal<?, ?>> insertSignalsToOther(Connection con, Serializer eventSerializer, Collection<Signal<?, String>> signalsToOther) throws SQLException { List<NumberedSignal<?, ?>> list = new ArrayList<>(); try (PreparedStatement ps = con.prepareStatement(sql.addToSignalQueue())) { for (Signal<?, ?> signal : signalsToOther) { if (!signal.time().isPresent()) { Signal<?, String> sig = (Signal<?, String>) signal; ps.setString(1, sig.cls().getName()); ps.setString(2, sig.id()); ps.setString(3, sig.event().getClass().getName()); ps.setBlob(4, new ByteArrayInputStream(eventSerializer.serialize(sig.event()))); ps.executeUpdate(); // add the generated primary key for the signal to the list try (ResultSet rs = ps.getGeneratedKeys()) { rs.next(); list.add(new NumberedSignal<Object, String>((Signal<Object, String>) signal, rs.getLong(1))); } } } } return list; } @SuppressWarnings("unchecked") private List<NumberedSignal<?, ?>> insertDelayedSignalsToOther(Connection con, Class<?> fromCls, String fromId, Serializer eventSerializer, Collection<Signal<?, String>> signalsToOther) throws SQLException { List<NumberedSignal<?, ?>> list = new ArrayList<NumberedSignal<?, ?>>(); try ( PreparedStatement del = con.prepareStatement(sql.deleteDelayedSignal()); PreparedStatement ps = con.prepareStatement(sql.addDelayedSignal())) { for (Signal<?, ?> signal : signalsToOther) { if (signal.time().isPresent()) { Signal<?, String> sig = (Signal<?, String>) signal; del.setString(1, fromCls.getName()); del.setString(2, fromId); del.setString(3, sig.cls().getName()); del.setString(4, sig.id()); del.executeUpdate(); ps.setString(1, fromCls.getName()); ps.setString(2, fromId); ps.setString(3, sig.cls().getName()); ps.setString(4, sig.id()); ps.setString(5, sig.event().getClass().getName()); ps.setBlob(6, new ByteArrayInputStream(eventSerializer.serialize(sig.event()))); ps.setTimestamp(7, new Timestamp(sig.time().get())); ps.executeUpdate(); try (ResultSet rs = ps.getGeneratedKeys()) { rs.next(); list.add(new NumberedSignal<Object, String>((Signal<Object, String>) signal, rs.getLong(1))); } } } } return list; } private void removeSignal(Connection con, NumberedSignal<?, String> signal) throws SQLException { if (signal.signal.time().isPresent()) { removeNonDelayedSignal(con, signal.number); } else { removeDelayedSignal(con, signal.number); } } private void removeNonDelayedSignal(Connection con, long number) throws SQLException { try (PreparedStatement ps = con.prepareStatement(sql.deleteNumberedSignal())) { ps.setLong(1, number); ps.executeUpdate(); } } private void removeDelayedSignal(Connection con, long number) throws SQLException { try (PreparedStatement ps = con.prepareStatement(sql.deleteNumberedDelayedSignal())) { ps.setLong(1, number); ps.executeUpdate(); } } private void removeDelayedSignal(Connection con, Class<?> fromClass, String fromId, Class<?> cls, String id) throws SQLException { try (PreparedStatement ps = con.prepareStatement(sql.deleteDelayedSignal())) { ps.setString(1, fromClass.getName()); ps.setString(2, fromId); ps.setString(3, cls.getName()); ps.setString(4, id); ps.executeUpdate(); } } private void saveEntity(Connection con, EntityStateMachine<?, String> esm) throws SQLException { final boolean updated; try (PreparedStatement ps = con.prepareStatement(sql.updateEntity())) { byte[] bytes = entitySerializer.serialize(esm.get().get()); ps.setBlob(1, new ByteArrayInputStream(bytes)); ps.setString(2, esm.state().toString()); ps.setString(3, esm.cls().getName()); ps.setString(4, esm.id()); updated = ps.executeUpdate() > 0; } if (!updated) { try (PreparedStatement ps = con.prepareStatement(sql.insertEntity())) { byte[] bytes = entitySerializer.serialize(esm.get().get()); ps.setString(1, esm.cls().getName()); ps.setString(2, esm.id()); ps.setBlob(3, new ByteArrayInputStream(bytes)); ps.setString(4, esm.state().toString()); ps.executeUpdate(); } } } public void replay(Class<?> cls, String id) { try (Connection con = createConnection()) { return; } catch (SQLException e) { throw new SQLRuntimeException(e); } } private Connection createConnection() { try { return connectionFactory.call(); } catch (SQLException e) { throw new SQLRuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") public <T> Optional<EntityAndState<T>> getWithState(Class<T> cls, String id) { try ( Connection con = createConnection(); PreparedStatement ps = con.prepareStatement(sql.readEntityAndState())) { ps.setString(1, cls.getName()); ps.setString(2, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { String stateName = rs.getString(1); T t = (T) entitySerializer.deserialize(cls, readAll(rs.getBlob(2).getBinaryStream())); EntityBehaviour<?, String> behaviour = behaviourFactory.apply(cls); EntityState<?> state = behaviour.from(stateName); return Optional.of(EntityAndState.create(t, (EntityState<T>) state)); } else { return Optional.empty(); } } } catch (SQLException e) { throw new SQLRuntimeException(e); } } public <T> Optional<T> get(Class<T> cls, String id) { try ( Connection con = createConnection(); PreparedStatement ps = con.prepareStatement(sql.readEntity())) { ps.setString(1, cls.getName()); ps.setString(2, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { T t = (T) entitySerializer.deserialize(cls, readAll(rs.getBlob(1).getBinaryStream())); return Optional.of(t); } else { return Optional.empty(); } } } catch (SQLException e) { throw new SQLRuntimeException(e); } } private void offer(NumberedSignal<?, String> signal) { queue.offer(signal); drain(); } @SuppressWarnings("unchecked") private void drain() { // non-blocking drain loop for the signal queue if (wip.getAndIncrement() == 0) { executor.execute(() -> { int missed = 1; while (true) { while (true) { NumberedSignal<?, ?> signal = queue.peek(); if (signal == null) { break; } else { if (process((NumberedSignal<?, String>) signal)) { queue.poll(); } else { break; } } } missed = wip.addAndGet(-missed); if (missed == 0) { return; } } }); } } private static byte[] readAll(InputStream is) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int count; try { while ((count = is.read(buffer)) != -1) { bytes.write(buffer, 0, count); } } catch (IOException e) { throw new RuntimeException(e); } return bytes.toByteArray(); } }
package com.github.davidmoten.fsm.example.aws; import java.util.Base64; import java.util.List; import java.util.Map; import com.amazonaws.regions.Regions; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.ItemCollection; import com.amazonaws.services.dynamodbv2.document.QueryOutcome; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.internal.IteratorSupport; import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec; import com.amazonaws.services.dynamodbv2.document.utils.ValueMap; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.amazonaws.services.sqs.model.Message; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import com.amazonaws.services.sqs.model.ReceiveMessageResult; import com.amazonaws.services.sqs.model.SendMessageRequest; import com.github.davidmoten.fsm.example.generated.MicrowaveBehaviour; import com.github.davidmoten.fsm.example.generated.MicrowaveStateMachine; import com.github.davidmoten.fsm.example.generated.MicrowaveStateMachine.State; import com.github.davidmoten.fsm.example.microwave.Microwave; import com.github.davidmoten.fsm.example.microwave.event.DoorOpened; import com.github.davidmoten.fsm.runtime.Signal; import com.github.davidmoten.fsm.runtime.rx.ClassId; public class Handler { public String submitSignal(Map<String, Object> input, Context context) { LambdaLogger log = context.getLogger(); String body = (String) input.get("body"); log.log("body=" + body); return "ok"; } public String process(Map<String, Object> input, Context context) { // use fifo sqs queue with groupId equal to Class+Id // to support fifo deduplication every signal needs to include a from // Class+Id, eventId pair in the serialized signal // get the latest state bytes from the item in Entity table identified // by the msg entityId // deserialize the bytes into an an entity object and its state enum // create an EntityStateMachine object intialized with entity object and // its state // apply the Event object to the EntityStateMachine object // serialize the new state to bytes // fifo queue regions still limited so use a US region AmazonSQS sqs = AmazonSQSClientBuilder .standard() .withRegion(Regions.US_WEST_2) .build(); String signalQueueUrl = sqs .getQueueUrl("signal-queue.fifo") .getQueueUrl(); List<Message> msgs = readQueue(sqs, signalQueueUrl); if (msgs.isEmpty()) { return "none"; } else { AmazonDynamoDB dbClient = AmazonDynamoDBClientBuilder .standard() .withRegion(Regions.AP_SOUTHEAST_2) .build(); DynamoDB db = new DynamoDB(dbClient); Table entityTable = db.getTable("Entity"); for (Message msg : msgs) { Signal<Microwave, String> signal = parseSignal(msg.getBody()); String entityId = signal.cls().getCanonicalName() + ":" + signal.id(); Item item = entityTable.getItem("EntityId", entityId); MicrowaveBehaviour<String> behaviour = createMicrowaveBehaviour(); Microwave m = Microwave.fromId(signal.id()); String id = null; State state = MicrowaveStateMachine.State.COOKING; MicrowaveStateMachine<String> sm = MicrowaveStateMachine.create(m, id, behaviour, state); sm.signal(signal.event()); // send signals to others for (Signal<?, ?> sig : sm.signalsToOther()) { // serialize sig to bytes // put bytes on queue String serialized = Base64.getEncoder().encodeToString(serialize(sig)); SendMessageRequest req = new SendMessageRequest() .withQueueUrl(signalQueueUrl) .withMessageBody(serialized) .withMessageGroupId(toGroupId(sig)); sqs.sendMessage(req); } Microwave m2 = sm.get().get(); // TODO serialize m2 and save in entityTable item byte[] bytes = serialize(m2); Item item2 = new Item() .with("EntityId", entityId) .withBinary("entityBytes", bytes); entityTable.putItem(item2); } } return "ok"; } private byte[] serialize(Microwave m2) { // TODO return new byte[] { 1, 2, 3 }; } private static String toGroupId(Signal<?, ?> sig) { return sig.cls().getCanonicalName() + ":" + sig.id(); } private static byte[] serialize(Signal<?, ?> sig) { return new byte[] { 1, 2, 3 }; } private static Signal<Microwave, String> parseSignal(String body) { return Signal.create(ClassId.create(Microwave.class, "1"), new DoorOpened()); } private MicrowaveBehaviour<String> createMicrowaveBehaviour() { // TODO Auto-generated method stub return null; } private void updateStuff(DynamoDB db, String entityId) { } private void replay(DynamoDB db, String entityId) { Table entityEvent = db.getTable("EntityEvent"); QuerySpec spec = new QuerySpec() .withKeyConditionExpression("EntityId = :entityId") .withValueMap(new ValueMap().withString("entityId", entityId)); ItemCollection<QueryOutcome> items = entityEvent.query(spec); IteratorSupport<Item, QueryOutcome> it = items.iterator(); while (it.hasNext()) { Item item = it.next(); // TODO push through Processor } } private static List<Message> readQueue(AmazonSQS sqs, String signalQueueUrl) { ReceiveMessageRequest req = new ReceiveMessageRequest() .withQueueUrl(signalQueueUrl) .withMaxNumberOfMessages(1); ReceiveMessageResult resp = sqs.receiveMessage(req); List<Message> msgs = resp.getMessages(); return msgs; } }
package cz.hobrasoft.pdfmu.signature; import com.itextpdf.text.pdf.AcroFields; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.security.CertificateInfo; import com.itextpdf.text.pdf.security.CertificateInfo.X500Name; import com.itextpdf.text.pdf.security.PdfPKCS7; import cz.hobrasoft.pdfmu.Console; import cz.hobrasoft.pdfmu.Operation; import cz.hobrasoft.pdfmu.OperationException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import net.sourceforge.argparse4j.impl.Arguments; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser; import org.apache.commons.lang3.StringUtils; /** * Displays signatures of a PDF document * * @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a> */ public class OperationSignatureDisplay implements Operation { @Override public String getCommandName() { return "display"; } @Override public Subparser configureSubparser(Subparser subparser) { String help = "Display signatures of a PDF document"; String metavarIn = "IN.pdf"; // Configure the subparser subparser.help(help) .description(help) .defaultHelp(true) .setDefault("command", this.getClass()); // Add arguments to the subparser // Positional arguments are required by default subparser.addArgument("in") .help("input PDF document") .metavar(metavarIn) .type(Arguments.fileType().acceptSystemIn().verifyCanRead()) .required(true); return subparser; } @Override public void execute(Namespace namespace) throws OperationException { // Input file File inFile = namespace.get("in"); assert inFile != null; // Required argument display(inFile); } private static void display(File inFile) throws OperationException { assert inFile != null; Console.println(String.format("Input PDF document: %s", inFile)); // Open the input stream FileInputStream inStream; try { inStream = new FileInputStream(inFile); } catch (FileNotFoundException ex) { throw new OperationException("Input file not found.", ex); } display(inStream); // Close the input stream try { inStream.close(); } catch (IOException ex) { throw new OperationException("Could not close the input file.", ex); } } private static void display(InputStream inStream) throws OperationException { // Open the PDF reader // PdfReader parses a PDF document. PdfReader pdfReader; try { pdfReader = new PdfReader(inStream); } catch (IOException ex) { throw new OperationException("Could not open the input PDF document.", ex); } display(pdfReader); // Close the PDF reader pdfReader.close(); } private static void display(PdfReader pdfReader) throws OperationException { // digitalsignatures20130304.pdf : Code sample 5.1 AcroFields fields = pdfReader.getAcroFields(); display(fields); } private static void display(AcroFields fields) throws OperationException { // digitalsignatures20130304.pdf : Code sample 5.1 ArrayList<String> names = fields.getSignatureNames(); // Print number of signatures Console.println(String.format("Number of signatures: %d", names.size())); Console.println(String.format("Number of document revisions: %d", fields.getTotalRevisions())); if (names.size() > 0) { Console.println(""); // Precede the first signature with an empty line } for (String name : names) { Console.println(String.format("Signature field name: %s", name)); Console.indentMore(); try { display(fields, name); // May throw OperationException } finally { Console.indentLess(); Console.println(""); // Follow each signature with an empty line } } } private static PdfPKCS7 display(AcroFields fields, String name) throws OperationException { // digitalsignatures20130304.pdf : Code sample 5.2 Console.println(String.format("Signature covers the whole document: %b", fields.signatureCoversWholeDocument(name))); Console.println(String.format("Document revision: %d of %d", fields.getRevision(name), fields.getTotalRevisions())); PdfPKCS7 pkcs7 = fields.verifySignature(name); display(pkcs7); return pkcs7; } private static PdfPKCS7 display(PdfPKCS7 pkcs7) throws OperationException { // digitalsignatures20130304.pdf : Code sample 5.3 Console.println("Signature metadata:"); { Console.indentMore(); // Only name may be null. // The values are set in {@link PdfPKCS7#verifySignature}. { // name String name = pkcs7.getSignName(); // May be null if (name == null) { name = "N/A"; } Console.println(String.format("Name: %s", name)); } // TODO?: Print "N/A" if the value is an empty string // TODO?: Determine whether the value is set in the signature Console.println(String.format("Reason: %s", pkcs7.getReason())); Console.println(String.format("Location: %s", pkcs7.getLocation())); Console.indentLess(); } // TODO: Format date X509Certificate cert = pkcs7.getSigningCertificate(); { // Signing certificate Console.indentMore("Signing certificate:"); showCertInfo(cert); Console.indentLess(); } // Various signature properties can be extracted by calling `pkcs7` getters. return pkcs7; } private static void showCertInfo(X509Certificate cert) { { // Issuer Console.indentMore("Issuer:"); showX500Name(CertificateInfo.getIssuerFields(cert)); Console.indentLess(); } { // Subject Console.indentMore("Subject:"); showX500Name(CertificateInfo.getSubjectFields(cert)); Console.indentLess(); } } private static void showX500Name(X500Name name) { Map<String, ArrayList<String>> fields = name.getFields(); // TODO?: Sort (show known attributes first in a pre-defined order) for (Entry<String, ArrayList<String>> field : fields.entrySet()) { String type = field.getKey(); type = niceX500AttributeType(type); ArrayList<String> values = field.getValue(); String valuesString = StringUtils.join(values, ", "); Console.println(String.format("%s: %s", type, valuesString)); } } private static final Map<String, String> attributeTypeAliases = new HashMap<>(); static { // Alias sources: attributeTypeAliases.put("CN", "Common name"); attributeTypeAliases.put("L", "Locality"); attributeTypeAliases.put("ST", "State or province"); attributeTypeAliases.put("O", "Organization"); attributeTypeAliases.put("OU", "Organizational unit"); attributeTypeAliases.put("C", "Country code"); attributeTypeAliases.put("STREET", "Street address"); attributeTypeAliases.put("DC", "Domain component"); attributeTypeAliases.put("UID", "User ID"); attributeTypeAliases.put("E", "Email address"); attributeTypeAliases.put("SN", "Device serial number"); attributeTypeAliases.put("T", "Title"); } private static String niceX500AttributeType(String type) { String nice = attributeTypeAliases.get(type); if (nice != null) { type = nice; } else { return String.format("<%s>", type); } return type; } }
package org.jboss.forge.arquillian.maven; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequestPopulator; import org.apache.maven.model.Build; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.model.building.DefaultModelBuilderFactory; import org.apache.maven.model.building.DefaultModelBuildingRequest; import org.apache.maven.model.building.ModelBuilder; import org.apache.maven.model.building.ModelBuildingException; import org.apache.maven.model.building.ModelBuildingResult; import org.apache.maven.model.building.ModelProblem; import org.apache.maven.project.ProjectBuilder; import org.apache.maven.project.ProjectBuildingRequest; import org.apache.maven.project.ProjectBuildingResult; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.apache.maven.settings.Mirror; import org.apache.maven.settings.Profile; import org.apache.maven.settings.Proxy; import org.apache.maven.settings.Repository; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.util.repository.AuthenticationBuilder; import org.eclipse.aether.util.repository.DefaultMirrorSelector; import org.eclipse.aether.util.repository.DefaultProxySelector; import org.jboss.forge.furnace.manager.maven.MavenContainer; import org.jboss.forge.furnace.manager.maven.addon.MavenAddonDependencyResolver; public class ProjectHelper { private final MavenContainer mavenContainer; private ProjectBuildingRequest request; public ProjectHelper() { this.mavenContainer = new MavenContainer(); } public Model loadPomFromFile(File pomFile, String... profiles) { RepositorySystem system = mavenContainer.getRepositorySystem(); Settings settings = mavenContainer.getSettings(); DefaultRepositorySystemSession session = mavenContainer.setupRepoSession(system, settings); final DefaultModelBuildingRequest request = new DefaultModelBuildingRequest() .setSystemProperties(System.getProperties()) .setPomFile(pomFile) .setActiveProfileIds(settings.getActiveProfiles()); ModelBuilder builder = new DefaultModelBuilderFactory().newInstance(); ModelBuildingResult result; try { request.setModelResolver(new MavenModelResolver(system, session, mavenContainer .getEnabledRepositoriesFromProfile(settings))); result = builder.build(request); } // wrap exception message catch (ModelBuildingException e) { String pomPath = request.getPomFile().getAbsolutePath(); StringBuilder sb = new StringBuilder("Found ").append(e.getProblems().size()) .append(" problems while building POM model from ").append(pomPath).append("\n"); int counter = 1; for (ModelProblem problem : e.getProblems()) { sb.append(counter++).append("/ ").append(problem).append("\n"); } throw new RuntimeException(sb.toString()); } return result.getEffectiveModel(); } public List<Dependency> resolveDependenciesFromPOM(File pomFile) throws Exception { PlexusContainer plexus = new PlexusContainer(); List<Dependency> result; try { ProjectBuildingRequest request = getBuildingRequest(plexus); request.setResolveDependencies(true); ProjectBuilder builder = plexus.lookup(ProjectBuilder.class); ProjectBuildingResult build = builder.build(pomFile, request); result = build.getDependencyResolutionResult().getDependencies(); } finally { plexus.shutdown(); } return result; } private ProjectBuildingRequest getBuildingRequest(PlexusContainer plexus) { if (this.request == null) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Settings settings = mavenContainer.getSettings(); // TODO this needs to be configurable via .forge // TODO this reference to the M2_REPO should probably be centralized MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest(); RepositorySystem repositorySystem = plexus.lookup(RepositorySystem.class); MavenExecutionRequestPopulator requestPopulator = plexus.lookup(MavenExecutionRequestPopulator.class); requestPopulator.populateFromSettings(executionRequest, settings); requestPopulator.populateDefaults(executionRequest); ProjectBuildingRequest request = executionRequest.getProjectBuildingRequest(); org.apache.maven.artifact.repository.ArtifactRepository localRepository = RepositoryUtils .toArtifactRepository("local", new File(settings.getLocalRepository()).toURI().toURL().toString(), null, true, true); request.setLocalRepository(localRepository); List<org.apache.maven.artifact.repository.ArtifactRepository> settingsRepos = new ArrayList<org.apache.maven.artifact.repository.ArtifactRepository>( request.getRemoteRepositories()); List<String> activeProfiles = settings.getActiveProfiles(); Map<String, Profile> profiles = settings.getProfilesAsMap(); for (String id : activeProfiles) { Profile profile = profiles.get(id); if (profile != null) { List<Repository> repositories = profile.getRepositories(); for (Repository repository : repositories) { settingsRepos.add(RepositoryUtils.convertFromMavenSettingsRepository(repository)); } } } request.setRemoteRepositories(settingsRepos); request.setSystemProperties(System.getProperties()); DefaultRepositorySystemSession repositorySession = MavenRepositorySystemUtils.newSession(); Proxy activeProxy = settings.getActiveProxy(); if (activeProxy != null) { DefaultProxySelector dps = new DefaultProxySelector(); dps.add(RepositoryUtils.convertFromMavenProxy(activeProxy), activeProxy.getNonProxyHosts()); repositorySession.setProxySelector(dps); } LocalRepository localRepo = new LocalRepository(settings.getLocalRepository()); repositorySession.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager(repositorySession, localRepo)); repositorySession.setOffline(settings.isOffline()); List<Mirror> mirrors = executionRequest.getMirrors(); DefaultMirrorSelector mirrorSelector = new DefaultMirrorSelector(); if (mirrors != null) { for (Mirror mirror : mirrors) { mirrorSelector.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(), mirror.getMirrorOfLayouts()); } } repositorySession.setMirrorSelector(mirrorSelector); LazyAuthenticationSelector authSelector = new LazyAuthenticationSelector(mirrorSelector); for (Server server : settings.getServers()) { authSelector.add( server.getId(), new AuthenticationBuilder().addUsername(server.getUsername()).addPassword(server.getPassword()) .addPrivateKey(server.getPrivateKey(), server.getPassphrase()).build()); } repositorySession.setAuthenticationSelector(authSelector); request.setRepositorySession(repositorySession); request.setProcessPlugins(false); request.setResolveDependencies(false); this.request = request; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException( "Could not create Maven project building request", e); } finally { /* * We reset the classloader to prevent potential modules bugs if Classwords container changes classloaders * on us */ Thread.currentThread().setContextClassLoader(cl); } } return request; } /** * Returns <code>true</code> if this model is a single-project addon */ public boolean isAddon(Model model) { boolean result = false; Build build = model.getBuild(); if (build != null) { PLUGIN_LOOP: for (Plugin plugin : build.getPlugins()) { if ("maven-jar-plugin".equals(plugin.getArtifactId())) { for (PluginExecution execution : plugin.getExecutions()) { Xpp3Dom config = (Xpp3Dom) execution.getConfiguration(); if (config!= null) { Xpp3Dom classifierNode = config.getChild("classifier"); if (classifierNode != null && MavenAddonDependencyResolver.FORGE_ADDON_CLASSIFIER.equals(classifierNode.getValue())) { result = true; break PLUGIN_LOOP; } } } } } } return result; } }
package org.motechproject.nms.testing.it.region; import org.apache.commons.httpclient.HttpStatus; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.motechproject.nms.csv.domain.CsvAuditRecord; import org.motechproject.nms.csv.exception.CsvImportDataException; import org.motechproject.nms.csv.repository.CsvAuditRecordDataService; import org.motechproject.nms.region.csv.CircleImportService; import org.motechproject.nms.region.domain.Circle; import org.motechproject.nms.region.domain.State; import org.motechproject.nms.region.repository.CircleDataService; import org.motechproject.nms.region.repository.StateDataService; import org.motechproject.nms.testing.it.api.utils.RequestBuilder; import org.motechproject.nms.testing.service.TestingService; import org.motechproject.testing.osgi.BasePaxIT; import org.motechproject.testing.osgi.container.MotechNativeTestContainerFactory; import org.motechproject.testing.osgi.http.SimpleHttpClient; import org.motechproject.testing.utils.TestContext; import org.ops4j.pax.exam.ExamFactory; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerSuite; import javax.inject.Inject; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @RunWith(PaxExam.class) @ExamReactorStrategy(PerSuite.class) @ExamFactory(MotechNativeTestContainerFactory.class) public class CircleImportServiceBundleIT extends BasePaxIT { @Inject TestingService testingService; @Inject CircleDataService circleDataService; @Inject StateDataService stateDataService; @Inject CircleImportService circleImportService; private String headers = "Circle,State"; private State Gujarat; private State Daman; private State Dadra; private State Haryana; private State Pradesh; private State Uttarakhand; @Inject private CsvAuditRecordDataService csvAuditRecordDataService; public static final String SUCCESS = "Success"; public static final String FAILURE = "Failure: "; @Before public void setUp() { testingService.clearDatabase(); Gujarat = stateDataService.create(new State("Gujarat", 1L)); Daman = stateDataService.create(new State("Daman & Diu", 2L)); Dadra = stateDataService.create(new State("Dadra & Nagar Haveli", 3L)); Haryana = stateDataService.create(new State("Haryana", 4L)); Pradesh = stateDataService.create(new State("Uttar Pradesh", 5L)); Uttarakhand = stateDataService.create(new State("Uttarakhand", 6L)); } // Test missing circle name @Test(expected = CsvImportDataException.class) public void testMissingCircleName() throws Exception { Reader reader = createReaderWithHeaders(headers, ",Haryana"); circleImportService.importData(reader); } // Test missing state @Test(expected = CsvImportDataException.class) public void testMissingStateName() throws Exception { Reader reader = createReaderWithHeaders(headers, "Haryana,"); circleImportService.importData(reader); } // Test no state for code in csv file @Test(expected = CsvImportDataException.class) public void testNoStateForName() throws Exception { Reader reader = createReaderWithHeaders(headers, "Haryana,BlahBlah"); circleImportService.importData(reader); } // Test file import @Test public void testFileImport() throws Exception { State state; circleImportService.importData(read("csv/circles.csv")); // What to assert? Circle circle = circleDataService.findByName("Gujarat & Daman & Diu"); assertNotNull(circle); assertEquals(3, circle.getStates().size()); assertTrue(circle.getStates().contains(Gujarat)); assertTrue(circle.getStates().contains(Daman)); assertTrue(circle.getStates().contains(Dadra)); state = stateDataService.findByName("Gujarat"); assertNotNull(state); assertEquals(1, state.getCircles().size()); assertTrue(state.getCircles().contains(circle)); state = stateDataService.findByName("Daman & Diu"); assertNotNull(state); assertEquals(1, state.getCircles().size()); assertTrue(state.getCircles().contains(circle)); state = stateDataService.findByName("Dadra & Nagar Haveli"); assertNotNull(state); assertEquals(1, state.getCircles().size()); assertTrue(state.getCircles().contains(circle)); circle = circleDataService.findByName("Haryana"); assertNotNull(circle); assertEquals(1, circle.getStates().size()); assertTrue(circle.getStates().contains(Haryana)); state = stateDataService.findByName("Haryana"); assertNotNull(state); assertEquals(1, state.getCircles().size()); assertTrue(state.getCircles().contains(circle)); circle = circleDataService.findByName("Uttar Pradesh(East)"); assertNotNull(circle); assertEquals(1, circle.getStates().size()); assertTrue(circle.getStates().contains(Pradesh)); state = stateDataService.findByName("Uttar Pradesh"); assertNotNull(state); assertEquals(2, state.getCircles().size()); assertTrue(state.getCircles().contains(circle)); circle = circleDataService.findByName("Uttar Pradesh(West) & Uttarakhand"); assertNotNull(circle); assertEquals(2, circle.getStates().size()); assertTrue(circle.getStates().contains(Pradesh)); assertTrue(circle.getStates().contains(Uttarakhand)); state = stateDataService.findByName("Uttar Pradesh"); assertNotNull(state); assertEquals(2, state.getCircles().size()); assertTrue(state.getCircles().contains(circle)); state = stateDataService.findByName("Uttarakhand"); assertNotNull(state); assertEquals(1, state.getCircles().size()); assertTrue(state.getCircles().contains(circle)); } private Reader createReaderWithHeaders(String header, String... lines) { StringBuilder builder = new StringBuilder(); builder.append(header); builder.append("\r\n"); for (String line : lines) { builder.append(line).append("\r\n"); } return new StringReader(builder.toString()); } private Reader read(String resource) { return new InputStreamReader(getClass().getClassLoader().getResourceAsStream(resource)); } /** * Method used to import CSV File For Location Data */ private void importCsvFileForLocationData(String location, String fileName) throws InterruptedException, IOException { HttpPost httpPost = new HttpPost(String.format( "http://localhost:%d/region/data/import/%s", TestContext.getJettyPort(), location)); FileBody fileBody = new FileBody(new File(String.format( "src/test/resources/csv/%s", fileName))); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("csvFile", fileBody); httpPost.setEntity(builder.build()); HttpResponse response = SimpleHttpClient.httpRequestAndResponse( httpPost, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } /** * To verify circle location data is uploaded successfully. */ @Test public void verifyFT262() throws InterruptedException, IOException { importCsvFileForLocationData("circle", "circles.csv"); // assert circle data Circle circle = circleDataService.findByName("Gujarat & Daman & Diu"); assertNotNull(circle); assertEquals(3, circle.getStates().size()); assertTrue(circle.getStates().contains(Gujarat)); assertTrue(circle.getStates().contains(Daman)); assertTrue(circle.getStates().contains(Dadra)); // Assert audit trail log CsvAuditRecord csvAuditRecord = csvAuditRecordDataService.retrieveAll() .get(0); assertEquals("region/data/import/circle", csvAuditRecord.getEndpoint()); assertEquals(SUCCESS, csvAuditRecord.getOutcome()); assertEquals("circles.csv", csvAuditRecord.getFile()); } }
package uk.ac.ebi.biosamples.accession; import java.sql.ResultSet; import java.sql.SQLException; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.stereotype.Component; import uk.ac.ebi.biosamples.PipelinesProperties; import uk.ac.ebi.biosamples.client.BioSamplesClient; import uk.ac.ebi.biosamples.model.Attribute; import uk.ac.ebi.biosamples.model.Sample; import uk.ac.ebi.biosamples.utils.AdaptiveThreadPoolExecutor; import uk.ac.ebi.biosamples.utils.ThreadUtils; @Component public class Accession implements ApplicationRunner{ private Logger log = LoggerFactory.getLogger(getClass()); @Autowired private PipelinesProperties pipelinesProperties; @Autowired private AccessionDao accessionDao; @Autowired private BioSamplesClient bioSamplesClient; @Override public void run(ApplicationArguments args) throws Exception { log.info("Processing Accession pipeline..."); try (AdaptiveThreadPoolExecutor executorService = AdaptiveThreadPoolExecutor.create(100, 10000, true, pipelinesProperties.getThreadCount(), pipelinesProperties.getThreadCountMax())) { Map<String, Future<Void>> futures = new HashMap<>(); accessionDao.doAssayAccessionCallback(new AccessionCallbackHandler(executorService, futures, "SAMEA")); accessionDao.doReferenceAccessionCallback(new AccessionCallbackHandler(executorService, futures, "SAME")); accessionDao.doGroupAccessionCallback(new AccessionCallbackHandler(executorService, futures, "SAMEG")); //wait for everything to finish ThreadUtils.checkFutures(futures, 0); } } private class AccessionCallbackHandler implements RowCallbackHandler { private final ThreadPoolExecutor executor; private final Map<String, Future<Void>> futures; private final String prefix; public AccessionCallbackHandler(ThreadPoolExecutor executor, Map<String, Future<Void>> futures, String prefix) { this.executor = executor; this.futures = futures; this.prefix = prefix; } @Override public void processRow(ResultSet rs) throws SQLException { int accessionNo = rs.getInt("ACCESSION"); String userAccession = rs.getString("USER_ACCESSION"); String submissionAccession = rs.getString("SUBMISSION_ACCESSION"); Date dateAssigned = rs.getDate("DATE_ASSIGNED"); boolean deleted = rs.getBoolean("IS_DELETED"); String accession = prefix+accessionNo; log.trace(""+accessionNo+" "+userAccession+" "+submissionAccession+" "+dateAssigned+" "+deleted); Callable<Void> callable = new AccessionCallable(accession, userAccession, submissionAccession, dateAssigned, deleted); Future<Void> future = executor.submit(callable); futures.put(accession, future); try { ThreadUtils.checkFutures(futures, 100); } catch (InterruptedException e) { log.warn("Interupted while checking for futures", e); } catch (ExecutionException e) { throw new RuntimeException(e); } } } private class AccessionCallable implements Callable<Void> { private final String accession; private final String userAccession; private final String submissionAccession; private final Date dateAssigned; private final boolean deleted; public AccessionCallable(String accession, String userAccession, String submissionAccession, Date dateAssigned, boolean deleted) { this.accession = accession; this.userAccession = userAccession; this.submissionAccession = submissionAccession; this.dateAssigned = dateAssigned; this.deleted = deleted; } @Override public Void call() throws Exception { String name = userAccession; LocalDateTime release = LocalDateTime.now().plusYears(100); LocalDateTime update = LocalDateTime.ofInstant(Instant.ofEpochMilli(dateAssigned.getTime()), ZoneId.systemDefault()); SortedSet<Attribute> attributes = new TreeSet<>(); //commented out, this makes loading into neo4j slow attributes.add(Attribute.build("other", "migrated from accession database at "+LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME))); attributes.add(Attribute.build("user accession", userAccession)); attributes.add(Attribute.build("submission accession", submissionAccession)); attributes.add(Attribute.build("deleted", Boolean.toString(deleted))); Sample sample = Sample.build(name, accession, release, update, attributes, null, null); bioSamplesClient.persistSample(sample); return null; } } }
package algorithms.compGeometry.convexHull; import algorithms.compGeometry.convexHull.GrahamScanLong.CH; /** * finds the pair of points most distant from one another a.k.a. the * furthest pair problem. * one can imagine a rough estimate by fitting an ellipse around the given points * and determining the major axis of the points. * even more precisely, one can fit a convex hull around the points and * determine which pair of points has the largest distance between them. * Note that the convex hull returns points ordered in a counter-clockwise manner * so is suitable for ordered traversal already. * An efficient way of comparing the point distances on the hull is to start * with the first point and determine its distance to the next point i, continuing * with increasing i and increasing distance. that comparison should be * roughly h/2 comparisons where h is the number of points in the hull. * then for the i points just used in the calculation, do the same analysis * to find their most distant point (these points are called antipodal points). * the total number of "i" visited are roughly h/2 and each antipodal search is * h/2 = O(h^2). * The algorithm total runtime complexity is O(convex hull) + O(h^2). * * If one uses Graham Scan for the convex hull algorithm, * O(convex hull) = O(N*log_2(N)) where N is the number of points given. * If one instead uses Jarvis March for the convex hull algorithm, * O(convex hull) = O(N*log_2(h)) where N is the number of points given and * h is the number of points in the resulting convex hull. * * If N is greater than h, the total runtime complexity is * O(N*log_2(N)) if use the Graham Scan. * If N is equal to h, the total runtime complexity is * O(N^2) = O(h^2). * * We can speculate about the size of the hull from information in Cormen * et al. Introduction to Algorithms, Exercise 33-5 * for sparse-hulled distributions of a unit-radius disk, a convex polygon with k sides, * and a 2-D normal distribution respectively as n^(1/3), log_2(n), sqrt(log_2(n)). * * @author nichole */ public class LargestDistancePair { /** * find the largest distance between the given pairs of points. * The runtime complexity is <em>O(N*log_2(N))</em>, * worse case runtime complexity is if the number of hull points * is equivalent to the number of points, O(N^2) = O(h^2). * * NOTE: one could make an O(N) version of this algorithm assuming h^2 is * less than N, by rewriting the bottleneck of the algorithm, the sorting. * For the polar angle counter-clockwise sorting of points, one could * use counting sort and integer degree bands for the angles. * Counting sort runtime complexity is O(max(N, range of data)), so * if the range of data were constrained to 0 to 359 for N >= 360, * the sort could be done in less than O(N) * and the remaining hull and largest pair algorithm runtime complexity is still O(N). * For the counting sort, if N were less than 360, and O(N) were more appealing than accuracy, * the 0 to 359 intervals could be made into a smaller number than 360 of evenly * sized bands. * * @param x input array of x coordinates. note that this method modifies the order of x * upon CCW sorting of x and y, so copy the arrays in if need to kep the * original order. * @param y x input array of x coordinates. note that this method modifies the order of x * upon CCW sorting of x and y, so copy the arrays in if need to kep the * original order. * @return an array of the pair of points furthest from one another. the * format in the return array is [xa, ya, yb, yb]. * If there are more than one points with same maximum distance, * only one is returned, and that one is the lastest point in roughly the 1st half of the * convex hull and it last pairing in terms of CCW ordering of the hull points. * @throws algorithms.compGeometry.convexHull.GrahamScanTooFewPointsException * if the unique polar angles w.r.t. the smallest y point in the arrays * are fewer than 3 in number. */ public static long[] findLargestDistancePair(long[] x, long[] y) throws GrahamScanTooFewPointsException { // x and y CH ch = GrahamScanLong.computeHull(x, y); long maxDist = Long.MIN_VALUE; int iMaxDist = 0; long distSq; long xd; long yd; long x0 = ch.getXH()[0]; long y0 = ch.getYH()[0]; int i0 = 0; // find furthest point from the first point. that will be the scan range; int i; // scan to the 2nd to last point because the last point in the hull is the same as the first point for (i = 1; i < ch.getXH().length - 1; ++i) { xd = ch.getXH()[i] - x0; yd = ch.getYH()[i] - y0; distSq = xd * xd + yd * yd; if (distSq >= maxDist) { maxDist = distSq; iMaxDist = i; } else { // because the hull points are sorted in CCW order, the max dist // will increase or stay the same and then decrease. break; } } int nScan = i; int j; // try pairs i0: [2, nScan) to see if an i1 pairing has dist > maxDist for (i = 1; i < nScan; ++i) { x0 = ch.getXH()[i]; y0 = ch.getYH()[i]; for (j = i + 1; j < ch.getXH().length - 1; ++j) { xd = ch.getXH()[j] - x0; yd = ch.getYH()[j] - y0; distSq = xd * xd + yd * yd; if (distSq >= maxDist) { i0 = i; maxDist = distSq; iMaxDist = j; } else if (j > (i + nScan)) { //TODO: consider letting the scan continue further than this along the hull break; } } } assert(maxDist > Long.MIN_VALUE); return new long[]{x[i0], y[i0], x[iMaxDist], y[iMaxDist]}; } }
package edu.tamu.tcat.oss.account.test.mock; import java.util.UUID; import javax.ws.rs.BeanParam; import javax.ws.rs.ForbiddenException; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import edu.tamu.tcat.account.Account; import edu.tamu.tcat.account.AccountException; import edu.tamu.tcat.account.db.login.DatabaseLoginProvider; import edu.tamu.tcat.account.jaxrs.bean.ContextBean; import edu.tamu.tcat.account.jaxrs.bean.TokenProviding; import edu.tamu.tcat.account.jaxrs.bean.TokenSecured; import edu.tamu.tcat.account.login.AccountLoginException; import edu.tamu.tcat.account.login.LoginData; import edu.tamu.tcat.account.login.LoginProvider; import edu.tamu.tcat.account.store.AccountNotFoundException; import edu.tamu.tcat.account.store.AccountStore; import edu.tamu.tcat.crypto.CryptoProvider; import edu.tamu.tcat.crypto.bouncycastle.BouncyCastleCryptoProvider; import edu.tamu.tcat.osgi.services.util.ServiceHelper; import edu.tamu.tcat.oss.account.test.internal.Activator; import edu.tamu.tcat.oss.db.DbExecutor; @Path("/mock") public class MockResource { private static final String LOGIN_PROVIDER_DB = "db.basic"; @POST @TokenSecured(payloadType=UUID.class) public String doPost(@BeanParam ContextBean bean) throws AccountException { System.out.println("post"); UUID uuid = bean.get(UUID.class); return "posted: " + uuid; } @POST @Path ("/authenticate") @Produces (MediaType.APPLICATION_JSON) @TokenProviding(payloadType=UUID.class) public AccountSDV authenticate(@FormParam("username") String username, @FormParam("password") String password, @BeanParam ContextBean bean) throws AccountException { if (username == null || username.length() == 0) throw new AccountException("Username not specified\n"); if (password == null || password.length() == 0) throw new AccountException("Password not specified\n"); //TODO: later, allow the user to select a Login Provider String providerId = LOGIN_PROVIDER_DB; CryptoProvider crypto = getCryptoProvider(); DbExecutor dbExec = getDbExecutor(); LoginProvider loginProvider = getLoginProvider(providerId, username, password, crypto, dbExec); try { // provider encapsulates everything, so try to log in (or fail) LoginData data = loginProvider.login(); Account account = getAccountStore().lookup(data); bean.set(account.getId()); return new AccountSDV(account);//, getAccountUri(account)); } catch (AccountLoginException | AccountNotFoundException ae) { throw new ForbiddenException(); } } /** a serialization data vehicl for {@link Account} */ static class AccountSDV { public UUID uuid; public AccountSDV(Account acct) { uuid = acct.getId(); } } @GET @Path ("/reAuthenticate") @Produces (MediaType.APPLICATION_JSON) //@SignatureSecured(duration = 14)//, unit = ChronoUnit.DAYS) @TokenProviding(payloadType=UUID.class) public String reAuthenticate(@BeanParam ContextBean bean) throws AccountException { Account account = bean.get(Account.class); //SignatureContext signatureContext = ContextContainingPrincipal.requireContext(context, SignatureContext.class); //Account account = Objects.requireNonNull(signatureContext.account); // final UUID uuid = UUID.randomUUID(); // // would be looked up // Account account = new Account(){ // @Override // public UUID getId() // return uuid; bean.set(account.getId()); return account.toString(); } private static AccountStore getAccountStore() { return new MockAccountStore(); } private static CryptoProvider getCryptoProvider() { return new BouncyCastleCryptoProvider(); } private static DbExecutor getDbExecutor() { try (ServiceHelper sh = new ServiceHelper(Activator.getDefault().getContext())) { DbExecutor exec = sh.waitForService(DbExecutor.class, 5_000); return exec; } catch (Exception e) { throw new IllegalStateException("Failed accessing database executor", e); } } private static LoginProvider getLoginProvider(String providerId, String username, String password, CryptoProvider cp, DbExecutor dbExec) { if (providerId.equals(LOGIN_PROVIDER_DB)) { DatabaseLoginProvider db = new DatabaseLoginProvider(); db.init(providerId, username, password, cp, dbExec); return db; } throw new IllegalStateException("Unknown provider id: " + providerId); } }
package io.spine.testing.server.blackbox; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.truth.IterableSubject; import io.spine.client.Query; import io.spine.client.QueryFactory; import io.spine.client.Topic; import io.spine.client.TopicFactory; import io.spine.core.UserId; import io.spine.server.BoundedContextBuilder; import io.spine.server.DefaultRepository; import io.spine.server.ServerEnvironment; import io.spine.server.commandbus.CommandDispatcher; import io.spine.server.delivery.Delivery; import io.spine.server.entity.Repository; import io.spine.server.event.EventDispatcher; import io.spine.server.event.EventEnricher; import io.spine.server.projection.ProjectionRepository; import io.spine.server.type.CommandClass; import io.spine.testing.server.VerifyingCounter; import io.spine.testing.server.blackbox.command.BbCreateProject; import io.spine.testing.server.blackbox.command.BbFinalizeProject; import io.spine.testing.server.blackbox.command.BbRegisterCommandDispatcher; import io.spine.testing.server.blackbox.event.BbAssigneeAdded; import io.spine.testing.server.blackbox.event.BbAssigneeRemoved; import io.spine.testing.server.blackbox.event.BbProjectCreated; import io.spine.testing.server.blackbox.event.BbProjectDone; import io.spine.testing.server.blackbox.event.BbReportCreated; import io.spine.testing.server.blackbox.event.BbTaskAdded; import io.spine.testing.server.blackbox.event.BbTaskAddedToReport; import io.spine.testing.server.blackbox.given.BbCommandDispatcher; import io.spine.testing.server.blackbox.given.BbDuplicateCommandDispatcher; import io.spine.testing.server.blackbox.given.BbEventDispatcher; import io.spine.testing.server.blackbox.given.BbInitProcess; import io.spine.testing.server.blackbox.given.BbProjectRepository; import io.spine.testing.server.blackbox.given.BbProjectViewProjection; import io.spine.testing.server.blackbox.given.BbReportRepository; import io.spine.testing.server.blackbox.given.BbTaskViewProjection; import io.spine.testing.server.blackbox.given.RepositoryThrowingExceptionOnClose; import io.spine.testing.server.blackbox.rejection.Rejections; import io.spine.testing.server.entity.EntitySubject; import io.spine.type.TypeName; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.util.Set; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static io.spine.core.BoundedContextNames.newName; import static io.spine.testing.client.blackbox.Count.count; import static io.spine.testing.client.blackbox.Count.once; import static io.spine.testing.client.blackbox.Count.thrice; import static io.spine.testing.client.blackbox.Count.twice; import static io.spine.testing.client.blackbox.VerifyAcknowledgements.acked; import static io.spine.testing.core.given.GivenUserId.newUuid; import static io.spine.testing.server.blackbox.VerifyEvents.emittedEvent; import static io.spine.testing.server.blackbox.given.Given.addProjectAssignee; import static io.spine.testing.server.blackbox.given.Given.addTask; import static io.spine.testing.server.blackbox.given.Given.createProject; import static io.spine.testing.server.blackbox.given.Given.createReport; import static io.spine.testing.server.blackbox.given.Given.createdProjectState; import static io.spine.testing.server.blackbox.given.Given.eventDispatcherRegistered; import static io.spine.testing.server.blackbox.given.Given.finalizeProject; import static io.spine.testing.server.blackbox.given.Given.initProject; import static io.spine.testing.server.blackbox.given.Given.newProjectId; import static io.spine.testing.server.blackbox.given.Given.projectDone; import static io.spine.testing.server.blackbox.given.Given.registerCommandDispatcher; import static io.spine.testing.server.blackbox.given.Given.startProject; import static io.spine.testing.server.blackbox.given.Given.taskAdded; import static io.spine.testing.server.blackbox.given.Given.userDeleted; import static io.spine.testing.server.blackbox.verify.state.VerifyState.exactly; import static io.spine.testing.server.blackbox.verify.state.VerifyState.exactlyOne; import static org.junit.jupiter.api.Assertions.assertThrows; /** * An abstract base for integration testing of Bounded Contexts with {@link BlackBoxBoundedContext}. * * @param <T> * the type of the {@code BlackBoxBoundedContext} */ abstract class BlackBoxBoundedContextTest<T extends BlackBoxBoundedContext<T>> { private T context; @BeforeEach void setUp() { context = newInstance().with(new BbProjectRepository(), DefaultRepository.of(BbProjectViewProjection.class), DefaultRepository.of(BbInitProcess.class)); } @AfterEach void tearDown() { context.close(); } /** * Creates a new instance of a bounded context to be used in this test suite. */ abstract BlackBoxBoundedContext<T> newInstance(); T boundedContext() { return context; } @Test @DisplayName("register command dispatchers") void registerCommandDispatchers() { CommandClass commandTypeToDispatch = CommandClass.from(BbRegisterCommandDispatcher.class); BbCommandDispatcher dispatcher = new BbCommandDispatcher(commandTypeToDispatch); context.withHandlers(dispatcher); context.receivesCommand(registerCommandDispatcher(dispatcher.getClass())); assertThat(dispatcher.commandsDispatched()).isEqualTo(1); } @Test @DisplayName("throw on an attempt to register duplicate command dispatchers") void throwOnDuplicateCommandDispatchers() { CommandClass commandTypeToDispatch = CommandClass.from(BbRegisterCommandDispatcher.class); BbCommandDispatcher dispatcher = new BbCommandDispatcher(commandTypeToDispatch); context.withHandlers(dispatcher); BbDuplicateCommandDispatcher duplicateDispatcher = new BbDuplicateCommandDispatcher(commandTypeToDispatch); assertThrows(IllegalArgumentException.class, () -> context.withHandlers(duplicateDispatcher)); } @Test @DisplayName("throw on an attempt to register a null command dispatcher") void throwOnNullCommandDispatcher() { assertThrows(NullPointerException.class, () -> context.withHandlers((CommandDispatcher) null)); } @Test @DisplayName("throw on an attempt to register several command dispatchers one of which is null") void throwOnOneOfNull() { CommandClass commandTypeToDispatch = CommandClass.from(BbRegisterCommandDispatcher.class); BbCommandDispatcher dispatcher = new BbCommandDispatcher(commandTypeToDispatch); assertThrows(NullPointerException.class, () -> context.withHandlers(dispatcher, null)); } @Test @DisplayName("register a repository if it's passed as command dispatcher") void registerRepoAsCommandDispatcher() { BbReportRepository repository = new BbReportRepository(); context.withHandlers(repository); assertThat(context.allStateTypes()).contains(TypeName.of(BbReport.class)); } @Test @DisplayName("register event dispatcher") void registerEventDispatcher() { BbEventDispatcher dispatcher = new BbEventDispatcher(); context.withEventDispatchers(dispatcher); context.receivesEvent(eventDispatcherRegistered(dispatcher.getClass())); assertThat(dispatcher.eventsReceived()).isEqualTo(1); } @Test @DisplayName("throw on an attempt to register a null event dispatcher") void throwOnNullEventDispatcher() { assertThrows(NullPointerException.class, () -> context.withEventDispatchers((EventDispatcher) null)); } @Test @DisplayName("throw on an attempt to register several event dispatchers if one of them is null") void throwOnOneOfEventDispatchersIsNull() { BbEventDispatcher validDispatcher = new BbEventDispatcher(); assertThrows(NullPointerException.class, () -> context.withEventDispatchers(validDispatcher, null)); } @Test @DisplayName("register a repository if it's passed as event dispatcher") void registerRepoAsEventDispatcher() { ProjectionRepository<?, ?, ?> repository = (ProjectionRepository<?, ?, ?>) DefaultRepository.of(BbTaskViewProjection.class); context.withEventDispatchers(repository); assertThat(context.allStateTypes()).contains(TypeName.of(BbTaskView.class)); } @Test @DisplayName("ignore sent events in emitted") void ignoreSentEvents() { BbProjectId id = newProjectId(); context.receivesCommand(createProject(id)) .receivesEvent(taskAdded(id)) .assertThat(emittedEvent(once())) .assertThat(emittedEvent(BbProjectCreated.class, once())); } @Nested @DisplayName("verify state of") class VerifyStateOf { @Test @DisplayName("a single aggregate") void aggregate() { BbCreateProject createProject = createProject(); BbProject expectedProject = createdProjectState(createProject); context.receivesCommand(createProject) .assertThat(exactlyOne(expectedProject)); } @Test @DisplayName("several aggregates") void aggregates() { BbCreateProject cmd1 = createProject(); BbCreateProject cmd2 = createProject(); BbProject expectedProject1 = createdProjectState(cmd1); BbProject expectedProject2 = createdProjectState(cmd2); context.receivesCommands(cmd1, cmd2) .assertThat(exactly(BbProject.class, ImmutableSet.of(expectedProject1, expectedProject2))); } @Test @DisplayName("a single projection") void projection() { BbCreateProject createProject = createProject(); BbProjectView expectedProject = createProjectView(createProject); context.receivesCommand(createProject) .assertThat(exactlyOne(expectedProject)); } @Test @DisplayName("several projections") void projections() { BbCreateProject cmd1 = createProject(); BbCreateProject cmd2 = createProject(); BbProjectView expectedProject1 = createProjectView(cmd1); BbProjectView expectedProject2 = createProjectView(cmd2); context.receivesCommands(cmd1, cmd2) .assertThat(exactly(BbProjectView.class, ImmutableSet.of(expectedProject1, expectedProject2))); } private BbProjectView createProjectView(BbCreateProject createProject) { return BbProjectView.newBuilder() .setId(createProject.getProjectId()) .build(); } } @Test @DisplayName("receive and handle a single command") void receivesACommand() { context.receivesCommand(createProject()) .assertThat(acked(once()).withoutErrorsOrRejections()) .assertThat(emittedEvent(BbProjectCreated.class, once())); } @Test @DisplayName("verifiers emitting one event") void eventOnCommand() { context.receivesCommand(createProject()) .assertEmitted(BbProjectCreated.class); } @Test @DisplayName("receive and handle multiple commands") void receivesCommands() { BbProjectId projectId = newProjectId(); context.receivesCommand(createProject(projectId)) .receivesCommands(addTask(projectId), addTask(projectId), addTask(projectId)) .assertThat(acked(count(4)).withoutErrorsOrRejections()) .assertThat(emittedEvent(count(4))) .assertThat(emittedEvent(BbProjectCreated.class, once())) .assertThat(emittedEvent(BbTaskAdded.class, thrice())); } @Test @DisplayName("reject a command") void rejectsCommand() { BbProjectId projectId = newProjectId(); // Create and start the project. context.receivesCommands(createProject(projectId), startProject(projectId)); // Attempt to start the project again. context.receivesCommand(startProject(projectId)) .assertRejectedWith(Rejections.BbProjectAlreadyStarted.class); } @Nested @DisplayName("throw `AssertionError` on receiving an unsupported command") class FailOnUnsupportedCommand { @AfterEach void cleanInbox() { ServerEnvironment.instance() .configureDelivery(Delivery.local()); } @Test @DisplayName("directly from the caller") void fromCaller() { BbFinalizeProject command = finalizeProject(newProjectId()); assertThrows(AssertionError.class, () -> context.receivesCommand(command)); } @Test @DisplayName("generated as a response to some other signal") void generatedWithinModel() { BbProjectDone event = projectDone(newProjectId()); assertThrows(AssertionError.class, () -> context.receivesEvent(event)); } } @Test @DisplayName("receive and react on single event") void receivesEvent() { BbProjectId projectId = newProjectId(); context.with(new BbReportRepository()) .receivesCommand(createReport(projectId)) .receivesEvent(taskAdded(projectId)) .assertThat(acked(twice()).withoutErrorsOrRejections()) .assertThat(emittedEvent(twice())) .assertThat(emittedEvent(BbReportCreated.class, once())) .assertThat(emittedEvent(BbTaskAddedToReport.class, once())); } @Test @DisplayName("receive and react on multiple events") void receivesEvents() { BbProjectId projectId = newProjectId(); context.with(new BbReportRepository()) .receivesCommand(createReport(projectId)) .receivesEvents(taskAdded(projectId), taskAdded(projectId), taskAdded(projectId)) .assertThat(acked(count(4)).withoutErrorsOrRejections()) .assertThat(emittedEvent(count(4))) .assertThat(emittedEvent(BbReportCreated.class, once())) .assertThat(emittedEvent(BbTaskAddedToReport.class, thrice())); } @Nested class SendExternalEvents { @Test @DisplayName("sends an external event") void single() { BbProjectId projectId = newProjectId(); UserId user = newUuid(); context.receivesCommand(createProject(projectId)) .receivesCommand(addProjectAssignee(projectId, user)) .receivesExternalEvent(newName("Users"), userDeleted(user, projectId)) .assertThat(acked(count(3)).withoutErrorsOrRejections()) .assertThat(emittedEvent(count(3))) .assertThat(emittedEvent(BbProjectCreated.class, once())) .assertThat(emittedEvent(BbAssigneeAdded.class, once())) .assertThat(emittedEvent(BbAssigneeRemoved.class, once())); } @Test @DisplayName("sends multiple external events") void multiple() { BbProjectId projectId = newProjectId(); UserId user1 = newUuid(); UserId user2 = newUuid(); UserId user3 = newUuid(); context.receivesCommand(createProject(projectId)) .receivesCommands(addProjectAssignee(projectId, user1), addProjectAssignee(projectId, user2), addProjectAssignee(projectId, user3)) .receivesExternalEvents(newName("Users"), userDeleted(user1, projectId), userDeleted(user2, projectId), userDeleted(user3, projectId)) .assertThat(acked(count(7)).withoutErrorsOrRejections()) .assertThat(emittedEvent(count(7))) .assertThat(emittedEvent(BbProjectCreated.class, once())) .assertThat(emittedEvent(BbAssigneeAdded.class, thrice())) .assertThat(emittedEvent(BbAssigneeRemoved.class, thrice())); } } @Test @DisplayName("throw Illegal State Exception on Bounded Context close error") void throwIllegalStateExceptionOnClose() { assertThrows(IllegalStateException.class, () -> newInstance() .with(new RepositoryThrowingExceptionOnClose() { @Override protected void throwException() { throw new RuntimeException("Expected error"); } }) .close()); } @Nested @DisplayName("create an instance by BoundedContextBuilder") class CreateByBuilder { private final ImmutableList<Repository<?, ?>> repositories = ImmutableList.of( new BbProjectRepository(), DefaultRepository.of(BbProjectViewProjection.class) ); private final CommandClass commandClass = CommandClass.from(BbRegisterCommandDispatcher.class); private CommandDispatcher commandDispatcher; private EventDispatcher eventDispatcher; private final Set<TypeName> types = toTypes(repositories); private BlackBoxBoundedContext<?> blackBox; private EventEnricher enricher; @BeforeEach void setUp() { enricher = EventEnricher .newBuilder() .build(); commandDispatcher = new BbCommandDispatcher(commandClass); eventDispatcher = new BbEventDispatcher(); } @Test void singleTenant() { BoundedContextBuilder builder = BoundedContextBuilder .assumingTests(false) .enrichEventsUsing(enricher); repositories.forEach(builder::add); builder.addCommandDispatcher(commandDispatcher); builder.addEventDispatcher(eventDispatcher); blackBox = BlackBoxBoundedContext.from(builder); assertThat(blackBox).isInstanceOf(SingleTenantBlackBoxContext.class); assertEntityTypes(); assertDispatchers(); assertEnricher(); } private void assertEntityTypes() { assertThat(blackBox.allStateTypes()).containsAtLeastElementsIn(types); } private void assertDispatchers() { assertThat(blackBox.commandBus().registeredCommandClasses()).contains(commandClass); assertThat(blackBox.eventBus().registeredEventClasses()) .containsAtLeastElementsIn(eventDispatcher.eventClasses()); } private void assertEnricher() { assertThat(blackBox.eventBus().enricher()).hasValue(enricher); } @Test void multiTenant() { BoundedContextBuilder builder = BoundedContextBuilder .assumingTests(true) .enrichEventsUsing(enricher); repositories.forEach(builder::add); builder.addCommandDispatcher(commandDispatcher); builder.addEventDispatcher(eventDispatcher); blackBox = BlackBoxBoundedContext.from(builder); assertThat(blackBox).isInstanceOf(MultitenantBlackBoxContext.class); assertEntityTypes(); assertDispatchers(); assertEnricher(); } /** * Obtains the set of entity state types from the passed repositories. */ private Set<TypeName> toTypes(Iterable<Repository<?, ?>> repos) { ImmutableSet.Builder<TypeName> builder = ImmutableSet.builder(); repos.forEach(repository -> builder.add(repository.entityStateType() .toTypeName())); return builder.build(); } } @Nested @DisplayName("obtain `EntitySubject`") class ObtainEntitySubject { private BbProjectId id; @BeforeEach void getSubject() { id = newProjectId(); context.receivesCommand(initProject(id, false)); } @Test @DisplayName("via entity class") void entityClass() { EntitySubject subject = context.assertEntity(BbInitProcess.class, id); assertThat(subject) .isNotNull(); subject.isInstanceOf(BbInitProcess.class); } @Test @DisplayName("via entity state class") void entityStateClass() { EntitySubject subject = context.assertEntityWithState(BbInit.class, id); assertThat(subject) .isNotNull(); subject.hasStateThat() .isInstanceOf(BbInit.class); } @Nested @DisplayName("with") class NestedSubjects { private EntitySubject assertProcessManager; @BeforeEach void getSubj() { assertProcessManager = context.assertEntity(BbInitProcess.class, id); } @Test @DisplayName("archived flag subject") void archivedFlag() { assertProcessManager.archivedFlag() .isFalse(); } @Test @DisplayName("deleted flag subject") void deletedFlag() { assertProcessManager.deletedFlag() .isTrue(); } @Test @DisplayName("state subject") void stateSubject() { BbInit expectedState = BbInit .newBuilder() .setId(id) .setInitialized(true) .build(); assertProcessManager.hasStateThat() .isEqualTo(expectedState); } } } @Nested @DisplayName("Provide `Subject` for generated messages") class MessageSubjects { @BeforeEach void sendCommand() { BbProjectId id = newProjectId(); context.receivesCommand(createProject(id)); } @Test @DisplayName("`CommandSubject`") void commandSubject() { assertThat(context.assertCommands()) .isNotNull(); } @Test @DisplayName("`EventSubject`") void eventSubject() { assertThat(context.assertEvents()) .isNotNull(); } } @Test @DisplayName("provide `Subject` for a specified `Query` result") void obtainQueryResultSubject() { BbProjectId id = newProjectId(); context.receivesCommand(createProject(id)); QueryFactory queryFactory = context.requestFactory() .query(); Query query = queryFactory.all(BbProject.class); BbProject expected = BbProject .newBuilder() .setId(id) .build(); context.assertQueryResult(query) .comparingExpectedFieldsOnly() .containsExactly(expected); } @Test @DisplayName("provide a method for `Subscription` updates verification") void assertSubscriptionUpdates() { BbProjectId id = newProjectId(); TopicFactory topicFactory = context.requestFactory() .topic(); Topic topic = topicFactory.allOf(BbProject.class); BbProject expected = BbProject .newBuilder() .setId(id) .build(); VerifyingCounter updateCounter = context.assertSubscriptionUpdates( topic, assertEachReceived -> assertEachReceived.comparingExpectedFieldsOnly() .isEqualTo(expected) ); context.receivesCommand(createProject(id)); updateCounter.verifyEquals(1); } @Nested @DisplayName("Provide generated") class Generated { @BeforeEach void postCommands() { BbProjectId id = newProjectId(); context.receivesCommand(createProject(id)) .receivesCommand(initProject(id, true)) ; } @Test @DisplayName("event messages") void eventMessages() { IterableSubject assertEventMessages = assertThat(context.eventMessages()); assertEventMessages.isNotEmpty(); assertEventMessages.hasSize(context.events() .size()); } @Test @DisplayName("command messages") void commandMessages() { IterableSubject assertCommandMessages = assertThat(context.commandMessages()); assertCommandMessages.isNotEmpty(); assertCommandMessages.hasSize(context.commands() .size()); } } }
package com.dmdirc.addons.ui_swing.framemanager.windowmenu; import com.dmdirc.ClientModule; import com.dmdirc.DMDircMBassador; import com.dmdirc.addons.ui_swing.EdtHandlerInvocation; import com.dmdirc.addons.ui_swing.events.SwingWindowAddedEvent; import com.dmdirc.addons.ui_swing.events.SwingWindowDeletedEvent; import com.dmdirc.addons.ui_swing.injection.SwingEventBus; import com.dmdirc.addons.ui_swing.interfaces.ActiveFrameManager; import com.dmdirc.addons.ui_swing.wizard.SwingWindowManager; import com.dmdirc.ui.IconManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.inject.Inject; import javax.swing.JMenuItem; import net.engio.mbassy.listener.Handler; /** * A Menu item that closes the active window when triggered. */ public class CloseActiveWindowMenuItem extends JMenuItem implements ActionListener { private final ActiveFrameManager activeFrameManager; private final DMDircMBassador eventBus; private final SwingWindowManager windowManager; @Inject public CloseActiveWindowMenuItem(final ActiveFrameManager activeFrameManager, @ClientModule.GlobalConfig final IconManager iconManager, @SwingEventBus final DMDircMBassador eventBus, final SwingWindowManager windowManager) { super(iconManager.getIcon("close")); this.activeFrameManager = activeFrameManager; this.eventBus = eventBus; this.windowManager = windowManager; setMnemonic('c'); setText("Close"); setActionCommand("Close"); } /** * Initialises the menu item adding listeners as required. */ public void init() { addActionListener(this); eventBus.subscribe(this); } @Override public void actionPerformed(final ActionEvent e) { activeFrameManager.getActiveFrame().getContainer().close(); } @Handler(invocation = EdtHandlerInvocation.class) public void windowAdded(final SwingWindowAddedEvent event) { setEnabled(true); } @Handler(invocation = EdtHandlerInvocation.class) public void windowDeleted(final SwingWindowDeletedEvent event) { setEnabled(!windowManager.getTopLevelWindows().isEmpty()); } }
package org.openoffice.xmerge.converter.xml.sxc.pexcel.records.formula; import java.io.*; public interface TokenConstants { // Unary Operator Tokens public static final int TUPLUS = 0x12; public static final int TUMINUS = 0x13; public static final int TPERCENT = 0x14; public static final int TPAREN = 0x15; // Binary Operator Tokens public static final int TADD = 0x03; public static final int TSUB = 0x04; public static final int TMUL = 0x05; public static final int TDIV = 0x06; public static final int TPOWER = 0x07; public static final int TCONCAT = 0x08; //Logical operators public static final int TLESS = 0x09; public static final int TLESSEQUALS = 0x0A; public static final int TEQUALS = 0x0B; public static final int TGTEQUALS = 0x0C; public static final int TGREATER = 0x0D; public static final int TNEQUALS = 0x0E; // Function Operator Tokens public static final int TFUNC = 0x41; public static final int TFUNCVAR = 0x42; // Constant Operand Tokens public static final int TSTRING = 0x17; public static final int TINT = 0x1E; public static final int TNUM = 0x1F; // Operand Tokens public static final int TREF = 0x44; public static final int TAREA = 0x25; public static final int TNAME = 0x23; public static final int TREF3D = 0x3A; public static final int TAREA3D = 0x3B; public static final int TARGSEP = 0x1001; public static final int TCLOSEPAREN = 0x1002; // Variable argument Functions // Math and Trig public static final int TSUM = 0x04; public static final int TPRODUCT = 0xB7; public static final int TSUMIF = 0x0159; public static final int TLOG = 0x6D; public static final int TRUNC = 0xC5; // Financial public static final int TDDB = 0x90; public static final int TFV = 0x39; public static final int TIRR = 0x3E; public static final int TNPER = 0x3A; public static final int TNPV = 0x0B; public static final int TPMT = 0x3B; public static final int TPV = 0x38; public static final int TRATE = 0x3C; // Statistical public static final int TAVERAGE = 0x05; public static final int TCOUNT = 0x00; public static final int TCOUNTA = 0xA9; public static final int TMAX = 0x07; public static final int TMIN = 0x06; public static final int TSTDEV = 0x0C; public static final int TSTDEVP = 0xC1; public static final int TVAR = 0x2E; public static final int TVARP = 0xC2; // Lookup public static final int TCHOOSE = 0x64; public static final int THLOOKUP = 0x65; public static final int TINDEX = 0x1D; public static final int TMATCH = 0x40; public static final int TVLOOKUP = 0x66; // Text public static final int TRIGHT = 0x74; public static final int TSUBSTITUTE = 0x78; public static final int TFIND = 0x7c; public static final int TLEFT = 0x73; // Logical public static final int TAND = 0x24; public static final int TIF = 0x01; public static final int TOR = 0x25; // Fixed argument Functions // Math and Trig public static final int TABS = 0x18; public static final int TACOS = 0x63; public static final int TASIN = 0x62; public static final int TATAN = 0x12; public static final int TATAN2 = 0x61; public static final int TCOS = 0x10; public static final int TSIN = 0x0F; public static final int TCOUNTIF = 0x015A; public static final int TDEGREES = 0x0157; public static final int TEXP = 0x15; public static final int TFACT = 0xB8; public static final int TINTE = 0x19; public static final int TLN = 0x16; public static final int TLOG10 = 0x17; public static final int TMOD = 0x27; public static final int TPI = 0x13; public static final int TPOWERF = 0x0151; public static final int TRADIANS = 0x0156; public static final int TRAND = 0x3F; public static final int TROUND = 0x1B; public static final int TSQRT = 0x14; public static final int TTAN = 0x11; public static final int TSLN = 0x8E; public static final int TSYD = 0x8F; // Date and Time public static final int TDATE = 0x41; public static final int TDATEVALUE = 0x8C; public static final int TDAY = 0x43; public static final int THOUR = 0x47; public static final int TMINUTE = 0x48; public static final int TMONTH = 0x44; public static final int TNOW = 0x4A; public static final int TSECOND = 0x49; public static final int TTIME = 0x42; public static final int TTIMEVALUE = 0x8D; public static final int TYEAR = 0x45; // Statistical public static final int TCOUNTBLANK = 0x015B ; // lookup public static final int TCOLUMNS = 0x4D; public static final int TROWS = 0x4C; // Database public static final int TDAVAERAGE = 0x2A; public static final int TDCOUNT = 0x28; public static final int TDCOUNTA = 0xC7; public static final int TDGET = 0xEB; public static final int TDMAX = 0x2C; public static final int TDMIN = 0x2B; public static final int TDPRODUCT = 0xBD; public static final int TDSTDEV = 0x2D; public static final int TDSTDEVP = 0xC3; public static final int TDSUM = 0x29; public static final int TDVAR = 0x2F; public static final int TDVARP = 0xC4; // Text public static final int TEXACT = 0x75; public static final int TLEN = 0x20; public static final int TLOWER = 0x70; public static final int TMID = 0x1F; public static final int TPROPER = 0x72; public static final int TREPLACE = 0x77; public static final int TREPT = 0x1E; public static final int TT = 0x82; public static final int TRIM = 0x76; public static final int TUPPER = 0x71; public static final int TVALUE = 0x21; // Logical public static final int TFALSE = 0x23; public static final int TNOT = 0x26; public static final int TTRUE = 0x22; // Informational public static final int TERRORTYPE = 0x05; public static final int TISBLANK = 0x81; public static final int TISERR = 0x7E; public static final int TISERROR = 0x03; public static final int TISLOGICAL = 0xC6; public static final int TISNA = 0x02; public static final int TISNONTEXT = 0xBE; public static final int TISNUMBER = 0x80; public static final int TISTEXT = 0x7F; public static final int TN = 0x83; public static final int TNA = 0x0A; }
package beginner; import com.sandwich.koan.Koan; import static com.sandwich.koan.constant.KoanConstants.__; import static com.sandwich.util.Assert.assertEquals; public class AboutConstructors { class A { String someString = "a"; public A() { someString += "x"; } } class B extends A { public B() { someString += "g"; }; } @Koan public void simpleConstructorOrder(){ assertEquals(new B().someString, __); } class Aa { String someString = "a"; public Aa() { someString += "x"; } public Aa(String s) { someString += s; } } class Bb extends Aa { public Bb() { super("Boo"); someString += "g"; }; } @Koan public void complexConstructorOrder(){ assertEquals(new Bb().someString, __); } }
package com.xpn.xwiki.web; import java.util.Arrays; import java.util.List; import java.util.Locale; import org.apache.commons.lang3.StringUtils; import org.xwiki.job.Job; import org.xwiki.job.JobException; import org.xwiki.job.JobExecutor; import org.xwiki.refactoring.job.RefactoringJobs; import org.xwiki.refactoring.job.RestoreRequest; import org.xwiki.refactoring.script.RefactoringScriptService; import org.xwiki.script.service.ScriptService; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiDeletedDocument; import com.xpn.xwiki.doc.XWikiDocument; /** * Action for restoring documents from the recycle bin. * * @version $Id$ * @since 1.2M1 */ public class UndeleteAction extends XWikiAction { private static final String ID_PARAMETER = "id"; private static final String SHOW_BATCH_PARAMETER = "showBatch"; private static final String INCLUDE_BATCH_PARAMETER = "includeBatch"; private static final String CONFIRM_PARAMETER = "confirm"; private static final String ASYNC_PARAM = "async"; private static final String TRUE = "true"; private static final String VIEW_ACTION = "view"; @Override public boolean action(XWikiContext context) throws XWikiException { XWikiRequest request = context.getRequest(); // If showBatch=true and confirm=true then restore the page w/o the batch. If not, the render action will go to // the "restore" UI so that the user can confirm. That "restore" UI will then call the action again with // confirm=true. if (TRUE.equals(request.get(SHOW_BATCH_PARAMETER)) && !TRUE.equals(request.get(CONFIRM_PARAMETER))) { return true; } // CSRF prevention if (!csrfTokenCheck(context)) { return false; } XWikiResponse response = context.getResponse(); XWikiDocument doc = context.getDoc(); XWikiDeletedDocument deletedDocument = getDeletedDocument(context); boolean redirected = false; if (deletedDocument != null) { redirected = restoreDocument(deletedDocument, context); } // Redirect to the undeleted document. Make sure to redirect to the proper translation. if (!redirected) { String queryString = getRedirectQueryString(context, deletedDocument.getLocale()); sendRedirect(response, doc.getURL(VIEW_ACTION, queryString, context)); redirected = true; } return redirected; } private XWikiDeletedDocument getDeletedDocument(XWikiContext context) throws XWikiException { XWikiDeletedDocument result = null; XWikiRequest request = context.getRequest(); XWiki xwiki = context.getWiki(); String sindex = request.getParameter(ID_PARAMETER); if (StringUtils.isNotBlank(sindex)) { long index = Long.parseLong(sindex); result = xwiki.getDeletedDocument(index, context); } return result; } private String getRedirectQueryString(XWikiContext context, Locale deletedDocumentLocale) { String result = null; XWiki xwiki = context.getWiki(); if (deletedDocumentLocale != null && xwiki.isMultiLingual(context)) { result = String.format("language=%s", deletedDocumentLocale); } return result; } @Override public String render(XWikiContext context) throws XWikiException { String result = null; XWikiRequest request = context.getRequest(); // If showBatch=true and user confirmation is required, display the "restore" UI. if (TRUE.equals(request.get(SHOW_BATCH_PARAMETER)) && !TRUE.equals(request.get(CONFIRM_PARAMETER))) { result = "restore"; } return result; } private boolean restoreDocument(XWikiDeletedDocument deletedDocument, XWikiContext context) throws XWikiException { Job restoreJob = startRestoreJob(deletedDocument, context); // If the user asked for an asynchronous action... if (isAsync(context.getRequest())) { List<String> jobId = restoreJob.getRequest().getId(); // We redirect to the view action and accept the edge case when the restored document's rights might prevent // the restoring user to view the result. In that case, an admin must be contacted to fix the rights. sendRedirect(context.getResponse(), Utils.getRedirect(VIEW_ACTION, "xpage=restore&jobId=" + serializeJobId(jobId), context)); // A redirect has been performed. return true; } // Otherwise... try { restoreJob.join(); } catch (InterruptedException e) { throw new XWikiException(String.format("Failed to restore [%s] from batch [%s]", deletedDocument.getFullName(), deletedDocument.getBatchId()), e); } // No redirect has been performed. return false; } private String serializeJobId(List<String> jobId) { return StringUtils.join(jobId, "/"); } private Job startRestoreJob(XWikiDeletedDocument deletedDocument, XWikiContext context) throws XWikiException { XWikiRequest request = context.getRequest(); RefactoringScriptService refactoring = (RefactoringScriptService) Utils.getComponent(ScriptService.class, "refactoring"); RestoreRequest restoreRequest = null; if (TRUE.equals(request.getParameter(INCLUDE_BATCH_PARAMETER))) { // Restore the entire batch, including the current document. String batchId = deletedDocument.getBatchId(); restoreRequest = refactoring.createRestoreRequest(batchId); } else { // Restore just the current document. restoreRequest = refactoring.createRestoreRequest(Arrays.asList(deletedDocument.getId())); } restoreRequest.setInteractive(isAsync(request)); try { JobExecutor jobExecutor = Utils.getComponent(JobExecutor.class); return jobExecutor.execute(RefactoringJobs.RESTORE, restoreRequest); } catch (JobException e) { throw new XWikiException( String.format("Failed to schedule the restore job for deleted document [%s], id [%s] of batch [%s]", deletedDocument.getFullName(), deletedDocument.getId(), deletedDocument.getBatchId()), e); } } private boolean isAsync(XWikiRequest request) { return TRUE.equals(request.get(ASYNC_PARAM)); } }
package fundamentals.string.convert.lc012_integertoroman; /** * Given an integer, convert it to a roman numeral. * Input is guaranteed to be within the range from 1 to 3999. */ public class Solution { public String intToRoman(int num) { int[] ints = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; String[] rom = { "M", "CM", "D", "CD", "C", "XC", "L", "LX", "X", "IX", "V", "IV", "I" }; StringBuilder ret = new StringBuilder(); for (int i = 0; i < ints.length && num > 0; i++) { // terminate early while (num >= ints[i]) { ret.append(rom[i]); num -= ints[i]; } } return ret.toString(); } // Extremely simple and straightforward solution public String intToRoman3(int num) { String[] ones = " I II III IV V VI VII VIII IX".split(" "); String[] tens = " X XX XXX XL L LX LXX LXXX XC".split(" "); String[] hund = " C CC CCC CD D DC DCC DCCC CM".split(" "); String[] thou = " M MM MMM".split(" "); return thou[num / 1000] + hund[num % 1000 / 100] + tens[num % 100 / 10] + ones[num % 10]; } private String[] syms = { "I", "V", "X", "L", "C", "D", "M", "", "" // avoid outofbound error }; // My 2AC: divide into 3 groups 1~10,10~100,100~1000,1000~... // A little better but same thought as 1AC public String intToRoman2(int num) { StringBuilder roman = new StringBuilder(); for (int i = 0, j = 0; num > 0; i++, j += 2, num /= 10) { roman.insert(0, int2ro(num % 10, syms[j], syms[j + 1], syms[j + 2])); } return roman.toString(); } private String int2ro(int digit, String i, String v, String x) { switch (digit) { case 1: return i; case 2: return i + i; case 3: return i + i + i; case 4: return i + v; case 5: return v; case 6: return v + i; case 7: return v + i + i; case 8: return v + i + i + i; case 9: return i + x; default: return ""; /* digit=0 */ } } // My 1AC public String intToRoman1(int num) { StringBuilder str = new StringBuilder(); String[][] base = { {"I", "V", "X"}, {"X", "L", "C"}, {"C", "D", "M"}, {"M", "-", "-"}, }; int i = 0; while (num > 0) { str.insert(0, parse(num % 10, base[i][0], base[i][1], base[i][2])); num /= 10; i++; } return str.toString(); } // num: [0,9] private String parse(int num, String one, String five, String ten) { int mod = num % 5; if (mod <= 3) { // [0,3] => 0~3, 5~8 String str = ""; while (mod str += one; } return num >= 5 ? five + str : str; } else { // [4] => 4,9 return num > 5 ? one + ten : one + five; } } }
package hu.itkodex.litest.template; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.ParameterizedType; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.jdom.Document; import org.jdom.transform.JDOMResult; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import com.processpuzzle.commons.xml.ClasspathResourceResolver; import com.processpuzzle.fundamental_types.domain.ServiceMessage; import com.processpuzzle.litest.fixture.GenericTestFixture; import com.processpuzzle.litest.fixture.TransientFreshFixture; public abstract class ServiceMessageTestFixture<S extends ServiceMessage> extends GenericTestFixture<S> implements TransientFreshFixture<S> { protected static final String CONTEXT_PATH = "com.cahoot"; protected Class<S> messageClass; protected S messageAsObject; protected Document messageAsXml; protected String messagePath; protected Resource messageResource; protected Schema messageSchema; protected ResourceLoader resourceLoader; protected String schemaPath; protected ServiceMessageTestFixture( String messagePath, String schemaPath ) { this.messagePath = messagePath; this.schemaPath = schemaPath; } // Properties public Document getMessageAsXml() { return messageAsXml; } // Protected, private helper methods @Override protected void configureBeforeSutInstantiation() { resourceLoader = new DefaultResourceLoader(); determineMessageClass(); loadSchema(); } @Override protected S instantiateSUT() { messageAsObject = setUpMessageObject(); sut = transformXmlToObject(); messageAsXml = transformObjectToXml(); return sut; } protected <T> Document marshall( Class<T> marshalledObjectClass, String schemaPath, ServiceMessage message ) { JDOMResult marshallResult = new JDOMResult(); try{ JAXBContext jaxbContext = JAXBContext.newInstance( marshalledObjectClass ); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); //SchemaFactory sf = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI ); //Schema schema = sf.newSchema( new URL( SCHEMA_PATH ) ); //jaxbMarshaller.setSchema( schema ); jaxbMarshaller.marshal( messageAsObject, marshallResult ); }catch( Exception e ){ throw new RuntimeException( e ); } return marshallResult.getDocument(); } protected abstract S setUpMessageObject(); protected <T> T unmarshall( Class<T> docClass, String resourceName ) throws JAXBException, IOException { messageResource = resourceLoader.getResource( resourceName ); return unmarshal( docClass, messageResource.getInputStream() ); } @SuppressWarnings( "unchecked" ) protected <T> T unmarshal( Class<T> unmarshalledObjectClass, InputStream inputStream ) throws JAXBException, IOException { JAXBContext jaxbContext = JAXBContext.newInstance( unmarshalledObjectClass ); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setSchema( messageSchema ); T unmarshalledObject = (T) unmarshaller.unmarshal( inputStream ); inputStream.close(); return unmarshalledObject; } @SuppressWarnings( "unchecked" ) private void determineMessageClass() { messageClass = (Class<S>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } private void loadSchema() { SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI ); try{ schemaFactory.setResourceResolver( new ClasspathResourceResolver() ); Resource schemaResource = resourceLoader.getResource( schemaPath ); messageSchema = schemaFactory.newSchema( schemaResource.getFile() ); }catch( Exception e ){ throw new RuntimeException( e ); } } private Document transformObjectToXml() { return marshall( messageClass, schemaPath, messageAsObject ); } private S transformXmlToObject() { try{ sut = unmarshall( messageClass, messagePath ); }catch( JAXBException e ){ e.printStackTrace(); }catch( IOException e ){ e.printStackTrace(); } return sut; } }
package com.devewm.passwordstrength; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.TreeSet; import com.devewm.passwordstrength.exception.MaximumPasswordLengthExceededException; /** * @author eric * */ public class PasswordStrengthMeter { public static final int PASSWORD_LENGTH_LIMIT = 256; public static final BigInteger check(String passwordPlaintext) { return PasswordStrengthMeter.check(passwordPlaintext, false); } public static final BigInteger check(String passwordPlaintext, boolean bypassMemoryLimitCheck) { if(null == passwordPlaintext || passwordPlaintext.length() < 1) { return new BigInteger("0"); } if(!bypassMemoryLimitCheck && passwordPlaintext.length() > PASSWORD_LENGTH_LIMIT) { throw new MaximumPasswordLengthExceededException(); } TreeSet<PasswordCharacterRange> ranges = new TreeSet<PasswordCharacterRange>(); for(int i = 0; i < passwordPlaintext.length(); i++) { char c = passwordPlaintext.charAt(i); for(PasswordCharacterRange range : PasswordCharacterRange.values()) { if(range.contains(c)) { ranges.add(range); break; } } } BigInteger rangeSize = new BigInteger("0"); for(PasswordCharacterRange range : ranges) { rangeSize = rangeSize.add(new BigInteger(Long.toString(range.size()))); } // determine number of iterations required for brute force attack // within this character range BigInteger result = new BigInteger("0"); for(int i = 1; i < passwordPlaintext.length(); i++) { BigInteger iteration = rangeSize.pow(i); result = result.add(iteration); } for(int i = 1; i <= passwordPlaintext.length(); i++) { int power = passwordPlaintext.length() - i; long placeValue = getCharacterPositionInRangeSet(passwordPlaintext.charAt(i - 1), ranges);; if(power == 0 && placeValue == 0) { continue; } // 8 = 8 * 10^0, 80 = 8 * 10^1 BigInteger multiplier = rangeSize.pow(power); BigInteger iteration = new BigInteger(Long.toString(placeValue)).multiply(multiplier); result = result.add(iteration); } return result.add(new BigInteger("1")); } private static long getCharacterPositionInRangeSet(char character, TreeSet<PasswordCharacterRange> ranges) { long position = 0; for(PasswordCharacterRange range : ranges) { long rangePosition = range.position(character); if(rangePosition < 0) { position += range.size(); } else { return position + rangePosition; } } return -1; } public static void main(String[] args) { if(args.length < 1) { printUsage(); return; } StringBuffer password = new StringBuffer(); for(int i = 0; i < args.length; i++) { password.append(args[i] + " "); } password.setLength(password.length() - 1); DecimalFormat number = new DecimalFormat(); number.setGroupingUsed(true); BigInteger result = PasswordStrengthMeter.check(password.toString(), true); System.out.println(password + ": " + number.format(result)); } private static void printUsage() { String className = PasswordStrengthMeter.class.getName(); System.out.println(); System.out.println(className); System.out.println("http://devewm.com/projects/passwordstrength\n"); System.out.println("Usage:"); System.out.println(" java <password>"); System.out.println("example:\n java " + className + " chickeN\n"); System.out.println(); } }
package de.hska.iwi.microservice.product.adaptor; import de.hska.iwi.microservice.product.domain.ProductDAO; import de.hska.iwi.microservice.product.entity.Product; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; public class ProductAdapter { private static final Logger logger = Logger.getLogger(ProductAdapter.class); public Product convertProductDAOToProduct(ProductDAO productDAO) { if (productDAO instanceof ProductDAO) { logger.info(String.format("Wandle Datenbank-Objekt in Produkt: %s", productDAO.toString())); return new Product(productDAO.getId(), productDAO.getName(), productDAO.getPrice(), productDAO.getDetails(), productDAO.getCategoryId()); } return null; } public ProductDAO convertProductToProductDAO(Product product) { if (product instanceof Product) { logger.info(String.format("Wandle Produkt in Datenbank-Objekt: %s", product.toString())); return new ProductDAO(product.getId(), product.getName(), product.getPrice(), product.getDetails(), product.getCategoryId()); } return null; } public List<Product> convertListProductDAOToListProduct(List<ProductDAO> listProductDAO) { if (listProductDAO instanceof List) { logger.info("Wandle Datenbank-Objekt-Liste in Produkt-Liste"); List<Product> resultList = new ArrayList<>(); for (ProductDAO productDAO : listProductDAO) { logger.info(productDAO.toString()); resultList.add(this.convertProductDAOToProduct(productDAO)); } return resultList; } return null; } }
package com.example.iavanish.popularmovies.activities; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import com.example.iavanish.popularmovies.R; public class MovieDetails extends AppCompatActivity { private MovieDetailsFragment movieDetailsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_details); FragmentManager fragmentManager = getSupportFragmentManager(); Fragment fragment = fragmentManager.findFragmentByTag("movieDetailsFragment"); if(fragment != null) { // ensures app doesn't crash on device rotation by re-assigning the previous instance of fragment movieDetailsFragment = (MovieDetailsFragment) fragment; } else { Intent intent = getIntent(); Bundle args = intent.getExtras(); movieDetailsFragment = new MovieDetailsFragment(); movieDetailsFragment.setArguments(args); getSupportFragmentManager().beginTransaction().replace(R.id.movie_details_container, movieDetailsFragment, "movieDetailsFragment").commit(); } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); // Nothing to save } }
package ca.ualberta.cs.cmput301t02project.test; import java.util.ArrayList; import java.util.Date; import java.util.Random; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.location.Location; import android.test.ActivityInstrumentationTestCase2; import android.test.UiThreadTest; import android.test.ViewAsserts; import android.widget.ArrayAdapter; import android.widget.ListView; import ca.ualberta.cs.cmput301t02project.R; import ca.ualberta.cs.cmput301t02project.activity.BrowseFavoritesActivity; import ca.ualberta.cs.cmput301t02project.activity.CreateCommentActivity; import ca.ualberta.cs.cmput301t02project.activity.LoginActivity; import ca.ualberta.cs.cmput301t02project.activity.MainMenuActivity; import ca.ualberta.cs.cmput301t02project.controller.TopLevelListController; import ca.ualberta.cs.cmput301t02project.model.CommentListModel; import ca.ualberta.cs.cmput301t02project.model.CommentModel; import ca.ualberta.cs.cmput301t02project.model.CommentServer; import ca.ualberta.cs.cmput301t02project.model.FavoritesListModel; import ca.ualberta.cs.cmput301t02project.model.Server; import ca.ualberta.cs.cmput301t02project.model.StoredCommentListAbstraction; import ca.ualberta.cs.cmput301t02project.model.TopLevelCommentList; import ca.ualberta.cs.cmput301t02project.model.User; import ca.ualberta.cs.cmput301t02project.view.CommentListAdapter; public class BrowseFavoritesActivityTest extends ActivityInstrumentationTestCase2<BrowseFavoritesActivity> { public BrowseFavoritesActivityTest() { super(BrowseFavoritesActivity.class); } private Context context; // for unique username Date date = new Date(); @Override public void setUp() { context = getInstrumentation().getTargetContext(); // unique username User.login(new Random(date.getSeconds()).toString(), context); } // not a test, used in test below -SB public CommentModel initializeComment() { String loc = "Location Intialization"; Location currentLocation; currentLocation = new Location(loc); //unique username CommentModel comment = new CommentModel("sasha", currentLocation, new Random(date.getSeconds()).toString()); comment.setId("for testing, no need to push"); return comment; } /* Test for Use Case 11 */ public void testVisibleListView(){ // Check if the ListView shows up on the BrowseFavoritesActivity page BrowseFavoritesActivity activity = getActivity(); ListView view = (ListView) activity.findViewById(R.id.commentListView); ViewAsserts.assertOnScreen(activity.getWindow().getDecorView(), view); } /* Test for Use Case 11 */ @UiThreadTest public void testAddFavorite(){ BrowseFavoritesActivity activity = getActivity(); CommentModel comment = initializeComment(); User.getUser().getFavorites().add(comment); ListView view = (ListView) activity.findViewById(R.id.commentListView); assertEquals("should be one comment in faves", User.getUser().getFavorites().getList().size(), 1); assertEquals("one fave should be displayed on the listview", view.getAdapter().getCount(), 1); assertEquals("displayed fave should match the saved fave", view.getAdapter().getItem(0).toString(), User.getUser().getFavorites().getList().get(0).toString()); } /* * TESTS FOR SORTING */ /* * Test for Use Case 1 */ public void testSortByLocation (){ Location currentLocation = new Location("Location Initialization"); currentLocation.setLatitude(0); currentLocation.setLongitude(0); Location l1 = new Location("Location Initialization"); l1.setLatitude(1); l1.setLongitude(1); Location l2 = new Location("Location Initialization"); l2.setLatitude(20); l2.setLongitude(20); Location l3 = new Location("Location Initialization"); l3.setLatitude(300); l3.setLongitude(300); CommentModel comment1 = new CommentModel("post 1", l1, "schmoop"); comment1.setId("1"); CommentModel comment2 = new CommentModel("post 2", l2, "schmoop"); comment2.setId("2"); CommentModel comment3 = new CommentModel("post 3", l3, "schmoop"); comment3.setId("3"); FavoritesListModel inOrder = new FavoritesListModel(context); inOrder.add(comment3); inOrder.add(comment2); inOrder.add(comment1); FavoritesListModel outOfOrder = new FavoritesListModel(context); outOfOrder.add(comment1); outOfOrder.add(comment2); outOfOrder.add(comment3); CommentListAdapter adapter1; CommentListAdapter adapter2; adapter1 = new CommentListAdapter(context, R.layout.list_item, inOrder); adapter2 = new CommentListAdapter(context, R.layout.list_item, outOfOrder); adapter1.sortByLocation(); adapter2.sortByLocation(); assertEquals("First items should be in same place", adapter1.getItem(0), adapter2.getItem(0)); assertEquals("Second items should be in same place", adapter1.getItem(1), adapter2.getItem(1)); assertEquals("Third items should be in same place", adapter1.getItem(2), adapter2.getItem(2)); assertEquals("First item's locations should be equal", adapter1.getItem(0).getLocation().toString(), adapter2.getItem(0).getLocation().toString()); assertEquals("Second item's locations should be equal", adapter1.getItem(1).getLocation().toString(), adapter2.getItem(1).getLocation().toString()); assertEquals("Third item's locations should be equal", adapter1.getItem(2).getLocation().toString(), adapter2.getItem(2).getLocation().toString()); } /* Test for Use Case 2 */ /* Test for Use Case 8 */ public void testSortByPicture (){ // retrived April 6th 2014. Bitmap.Config conf = Bitmap.Config.ARGB_4444; Bitmap pic = Bitmap.createBitmap(10, 10, conf); // Has picture -SB CommentModel comment1 = new CommentModel("post 1", pic, null, "schmoop"); comment1.setId("1"); // Does not have picture -SB CommentModel comment2 = new CommentModel("post 2", null, "schmoop"); comment2.setId("2"); // Has picture -SB CommentModel comment3 = new CommentModel("post 3", pic, null, "schmoop"); comment3.setId("3"); // Does not have picture -SB CommentModel comment4 = new CommentModel("post 4", null, "schmoop"); comment4.setId("4"); FavoritesListModel outOfOrderComments = new FavoritesListModel(context); outOfOrderComments.add(comment1); outOfOrderComments.add(comment2); outOfOrderComments.add(comment3); outOfOrderComments.add(comment4); FavoritesListModel inOrderComments = new FavoritesListModel(context); inOrderComments.add(comment1); inOrderComments.add(comment3); inOrderComments.add(comment2); inOrderComments.add(comment4); CommentListAdapter adapter1; CommentListAdapter adapter2; adapter1 = new CommentListAdapter(context, 0, outOfOrderComments); adapter2 = new CommentListAdapter(context, 0, inOrderComments); adapter1.sortByPicture(); adapter2.sortByPicture(); // 2 comments with pictures, 2 without. top 2 should have pictures, bottom two should not. Don't have to be exactly the same order. assertTrue("First item should have a picture", adapter1.getItem(0).hasPicture()); assertEquals("First items should have pictures", adapter1.getItem(0).hasPicture(), adapter2.getItem(0).hasPicture()); assertTrue("Second item should have a picture", adapter1.getItem(1).hasPicture()); assertEquals("Second items should have pictures", adapter1.getItem(1).hasPicture(), adapter2.getItem(1).hasPicture()); assertFalse("Third item should not have a picture", adapter1.getItem(2).hasPicture()); assertEquals("Third items should not have pictures", adapter1.getItem(2).hasPicture(), adapter2.getItem(2).hasPicture()); assertFalse("Forth item should not have a picture", adapter1.getItem(3).hasPicture()); assertEquals("Forth items should not have pictures", adapter1.getItem(3).hasPicture(), adapter2.getItem(3).hasPicture()); } /* Test for Use Case 9 */ public void testSortByDate(){ CommentModel comment1 = new CommentModel("post 1", null, "schmoop"); comment1.setDate(new Date(1)); comment1.setId("1"); CommentModel comment2 = new CommentModel("post 2", null, "schmoop"); comment2.setDate(new Date(20000)); comment2.setId("2"); CommentModel comment3 = new CommentModel("post 3", null, "schmoop"); comment3.setDate(new Date(300000000)); comment3.setId("3"); FavoritesListModel outOfOrderComments = new FavoritesListModel(context); outOfOrderComments.add(comment1); outOfOrderComments.add(comment2); outOfOrderComments.add(comment3); FavoritesListModel inOrderComments = new FavoritesListModel(context); inOrderComments.add(comment3); inOrderComments.add(comment2); inOrderComments.add(comment1); CommentListAdapter adapter1; CommentListAdapter adapter2; adapter1 = new CommentListAdapter(context, 0, outOfOrderComments); adapter2 = new CommentListAdapter(context, 0, inOrderComments); adapter1.sortByDate(); adapter2.sortByDate(); assertEquals("First items should be in same place", adapter1.getItem(0), adapter2.getItem(0)); assertEquals("Second items should be in same place", adapter1.getItem(1), adapter2.getItem(1)); assertEquals("Third items should be in same place", adapter1.getItem(2), adapter2.getItem(2)); assertEquals("First item's dates should be equal", adapter1.getItem(0).getDate(), adapter2.getItem(0).getDate()); assertEquals("Second item's dates should be equal", adapter1.getItem(1).getDate(), adapter2.getItem(1).getDate()); assertEquals("Third item's dates should be equal", adapter1.getItem(2).getDate(), adapter2.getItem(2).getDate()); } /* * Use Case 15 */ public void testSortByFaves (){ CommentModel comment1 = new CommentModel("post 1", null, "schmoop"); comment1.setRating(0); comment1.setId("1"); CommentModel comment2 = new CommentModel("post 2", null, "schmoop"); comment2.setRating(2); comment2.setId("2"); CommentModel comment3 = new CommentModel("post 3", null, "schmoop"); comment3.setRating(6); comment3.setId("3"); FavoritesListModel outOfOrderComments = new FavoritesListModel(context); outOfOrderComments.add(comment3); outOfOrderComments.add(comment2); outOfOrderComments.add(comment1); FavoritesListModel inOrderComments = new FavoritesListModel(context); inOrderComments.add(comment1); inOrderComments.add(comment2); inOrderComments.add(comment3); CommentListAdapter adapter1; CommentListAdapter adapter2; adapter1 = new CommentListAdapter(context, R.layout.list_item, outOfOrderComments); adapter2 = new CommentListAdapter(context, R.layout.list_item, inOrderComments); adapter1.sortByFaves(); adapter2.sortByFaves(); assertEquals("First items should be in same place", adapter1.getItem(0), adapter2.getItem(0)); assertEquals("Second items should be in same place", adapter1.getItem(1), adapter2.getItem(1)); assertEquals("Third items should be in same place", adapter1.getItem(2), adapter2.getItem(2)); assertEquals("First item's ratings should be equal", adapter1.getItem(0).getRating(), adapter2.getItem(0).getRating()); assertEquals("Second item's ratings should be equal", adapter1.getItem(1).getRating(), adapter2.getItem(1).getRating()); assertEquals("Third item's ratings should be equal", adapter1.getItem(2).getRating(), adapter2.getItem(2).getRating()); } /* Test for Use Case 16 */ public void testSortByDefault (){ Location currentLocation = new Location("Location Initialization"); currentLocation.setLatitude(0); currentLocation.setLongitude(0); Location l1 = new Location("Location Initialization"); l1.setLatitude(0.01); l1.setLongitude(0); Location l2 = new Location("Location Initialization"); l2.setLatitude(10); l2.setLongitude(10); Location l3 = new Location("Location Initialization"); l3.setLatitude(120); l3.setLongitude(120); CommentModel comment1 = new CommentModel("post 1", l1, "schmoop"); comment1.setDate(new Date(1)); comment1.setId("1"); CommentModel comment2 = new CommentModel("post 2", l1, "schmoop"); comment2.setDate(new Date(20000)); comment2.setId("2"); CommentModel comment3 = new CommentModel("post 3", l1, "schmoop"); comment3.setDate(new Date(300000000)); comment3.setId("3"); CommentModel comment4 = new CommentModel("post 4", l2, "schmoop"); comment4.setDate(new Date(1)); comment4.setId("4"); CommentModel comment5 = new CommentModel("post 5", l2, "schmoop"); comment5.setDate(new Date(20000)); comment5.setId("5"); CommentModel comment6 = new CommentModel("post 6", l2, "schmoop"); comment6.setDate(new Date(300000000)); comment6.setId("6"); CommentModel comment7 = new CommentModel("post 7", l3, "schmoop"); comment7.setDate(new Date(1)); comment7.setId("7"); CommentModel comment8 = new CommentModel("post 8", l3, "schmoop"); comment8.setDate(new Date(20000)); comment8.setId("8"); CommentModel comment9 = new CommentModel("post 9", l3, "schmoop"); comment9.setDate(new Date(300000000)); comment9.setId("9"); FavoritesListModel outOfOrderComments = new FavoritesListModel(context); outOfOrderComments.add(comment1); outOfOrderComments.add(comment2); outOfOrderComments.add(comment3); outOfOrderComments.add(comment4); outOfOrderComments.add(comment5); outOfOrderComments.add(comment6); outOfOrderComments.add(comment7); outOfOrderComments.add(comment8); outOfOrderComments.add(comment9); /*outOfOrderComments.add(comment9); outOfOrderComments.add(comment5); outOfOrderComments.add(comment4); outOfOrderComments.add(comment3); outOfOrderComments.add(comment8); outOfOrderComments.add(comment6); outOfOrderComments.add(comment1); outOfOrderComments.add(comment2); outOfOrderComments.add(comment7);*/ FavoritesListModel inOrderComments = new FavoritesListModel(context); inOrderComments.add(comment1); inOrderComments.add(comment2); inOrderComments.add(comment3); inOrderComments.add(comment4); inOrderComments.add(comment5); inOrderComments.add(comment6); inOrderComments.add(comment7); inOrderComments.add(comment8); inOrderComments.add(comment9); /* * * inOrderComments.add(comment3); inOrderComments.add(comment2); inOrderComments.add(comment1); inOrderComments.add(comment6); inOrderComments.add(comment5); inOrderComments.add(comment4); inOrderComments.add(comment9); inOrderComments.add(comment8); inOrderComments.add(comment7); */ CommentListAdapter adapter1; CommentListAdapter adapter2; // this isn't even working!!! adapter1 = new CommentListAdapter(context, R.layout.list_item, inOrderComments); adapter2 = new CommentListAdapter(context, R.layout.list_item, inOrderComments); assertEquals("First items should be in same place", adapter1.getItem(0), adapter2.getItem(0)); assertEquals("Second items should be in same place", adapter1.getItem(1), adapter2.getItem(1)); assertEquals("Third items should be in same place", adapter1.getItem(2), adapter2.getItem(2)); /* assertEquals("First items should be in same place", adapter1.getItem(0), adapter2.getItem(0)); assertEquals("Second items should be in same place", adapter1.getItem(1), adapter2.getItem(1)); assertEquals("Third items should be in same place", adapter1.getItem(2), adapter2.getItem(2)); assertEquals("Fourth items should be in same place", adapter1.getItem(3), adapter2.getItem(3)); assertEquals("Fifth items should be in same place", adapter1.getItem(4), adapter2.getItem(4)); assertEquals("Sixth items should be in same place", adapter1.getItem(5), adapter2.getItem(5)); assertEquals("Seventh items should be in same place", adapter1.getItem(6), adapter2.getItem(6)); assertEquals("Eighth items should be in same place", adapter1.getItem(7), adapter2.getItem(7)); assertEquals("Ninth items should be in same place", adapter1.getItem(8), adapter2.getItem(8)); assertEquals("First items' dates should be equal", adapter1.getItem(0).getDate(), adapter2.getItem(0).getDate()); assertEquals("Second items' dates should be equal", adapter1.getItem(1).getDate(), adapter2.getItem(1).getDate()); assertEquals("Third items' dates should be equal", adapter1.getItem(2).getDate(), adapter2.getItem(2).getDate()); assertEquals("Fourth items' dates should be equal", adapter1.getItem(3).getDate(), adapter2.getItem(3).getDate()); assertEquals("Fifth items' dates should be equal", adapter1.getItem(4).getDate(), adapter2.getItem(4).getDate()); assertEquals("Sixth items' dates should be equal", adapter1.getItem(5).getDate(), adapter2.getItem(5).getDate()); assertEquals("Seventh items' dates should be equal", adapter1.getItem(6).getDate(), adapter2.getItem(6).getDate()); assertEquals("Eighth items' dates should be equal", adapter1.getItem(7).getDate(), adapter2.getItem(7).getDate()); assertEquals("Ninth items' dates should be equal", adapter1.getItem(8).getDate(), adapter2.getItem(8).getDate()); assertEquals("First items' locations should be equal", adapter1.getItem(0).getLocation(), adapter2.getItem(0).getLocation()); assertEquals("Second items' locations should be equal", adapter1.getItem(1).getLocation(), adapter2.getItem(1).getLocation()); assertEquals("Third items' locations should be equal", adapter1.getItem(2).getLocation(), adapter2.getItem(2).getLocation()); assertEquals("Fourth items' locations should be equal", adapter1.getItem(3).getLocation(), adapter2.getItem(3).getLocation()); assertEquals("Fifth items' locations should be equal", adapter1.getItem(4).getLocation(), adapter2.getItem(4).getLocation()); assertEquals("Sixth items' locations should be equal", adapter1.getItem(5).getLocation(), adapter2.getItem(5).getLocation()); assertEquals("Seventh items' locations should be equal", adapter1.getItem(6).getLocation(), adapter2.getItem(6).getLocation()); assertEquals("Eighth items' locations should be equal", adapter1.getItem(7).getLocation(), adapter2.getItem(7).getLocation()); assertEquals("Ninth items' locations should be equal", adapter1.getItem(8).getLocation(), adapter2.getItem(8).getLocation()); */ } }
package com.mopub.mobileads.dfp.adapters; import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.format.DateFormat; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.formats.NativeAdOptions; import com.google.android.gms.ads.mediation.MediationAdRequest; import com.google.android.gms.ads.mediation.MediationBannerAdapter; import com.google.android.gms.ads.mediation.MediationBannerListener; import com.google.android.gms.ads.mediation.MediationInterstitialAdapter; import com.google.android.gms.ads.mediation.MediationInterstitialListener; import com.google.android.gms.ads.mediation.MediationNativeAdapter; import com.google.android.gms.ads.mediation.MediationNativeListener; import com.google.android.gms.ads.mediation.NativeMediationAdRequest; import com.mopub.common.MoPub; import com.mopub.common.SdkConfiguration; import com.mopub.common.SdkInitializationListener; import com.mopub.common.logging.MoPubLog; import com.mopub.mobileads.MoPubErrorCode; import com.mopub.mobileads.MoPubInterstitial; import com.mopub.mobileads.MoPubView; import com.mopub.nativeads.BaseNativeAd; import com.mopub.nativeads.MoPubNative; import com.mopub.nativeads.MoPubStaticNativeAdRenderer; import com.mopub.nativeads.NativeAd; import com.mopub.nativeads.NativeErrorCode; import com.mopub.nativeads.RequestParameters; import com.mopub.nativeads.StaticNativeAd; import com.mopub.nativeads.ViewBinder; import java.net.MalformedURLException; import java.net.URL; import java.util.Calendar; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import static com.google.android.gms.ads.AdRequest.GENDER_FEMALE; import static com.google.android.gms.ads.AdRequest.GENDER_MALE; import static com.mopub.mobileads.dfp.adapters.DownloadDrawablesAsync.KEY_IMAGE; /** * A {@link com.google.android.gms.ads.mediation.MediationAdapter} used to mediate banner ads, * interstitial ads and native ads from MoPub. */ public class MoPubAdapter implements MediationNativeAdapter, MediationBannerAdapter, MediationInterstitialAdapter { public static final String TAG = MoPubAdapter.class.getSimpleName(); private MoPubView mMoPubView; private AdSize mAdSize; private MoPubInterstitial mMoPubInterstitial; private static final String MOPUB_NATIVE_CEVENT_VERSION = "gmext"; public static final double DEFAULT_MOPUB_IMAGE_SCALE = 1; private static final String MOPUB_AD_UNIT_KEY = "adUnitId"; private int privacyIconPlacement; private int mPrivacyIconSize; private static final int MINIMUM_MOPUB_PRIVACY_ICON_SIZE_DP = 10; private static final int DEFAULT_MOPUB_PRIVACY_ICON_SIZE_DP = 20; private static final int MAXIMUM_MOPUB_PRIVACY_ICON_SIZE_DP = 30; private NativeAd.MoPubNativeEventListener mMoPubNativeEventListener; @Override public void onDestroy() { if (mMoPubInterstitial != null) { mMoPubInterstitial.destroy(); mMoPubInterstitial = null; } if (mMoPubView != null) { mMoPubView.destroy(); mMoPubView = null; } } @Override public void onPause() { } @Override public void onResume() { } @Override public void requestNativeAd(final Context context, final MediationNativeListener listener, Bundle serverParameters, NativeMediationAdRequest mediationAdRequest, Bundle mediationExtras) { String adunit = serverParameters.getString(MOPUB_AD_UNIT_KEY); initializeMoPub(context, adunit); final NativeAdOptions options = mediationAdRequest.getNativeAdOptions(); if (options != null) privacyIconPlacement = options.getAdChoicesPlacement(); else privacyIconPlacement = NativeAdOptions.ADCHOICES_TOP_RIGHT; if (!mediationAdRequest.isAppInstallAdRequested() && mediationAdRequest .isContentAdRequested()) { Log.d(TAG, "Currently, MoPub only serves native app install ads. Apps requesting " + "content ads alone will not receive ads from this adapter."); listener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); return; } if (mediationExtras != null) { int iconSizeExtra = mediationExtras.getInt(BundleBuilder.ARG_PRIVACY_ICON_SIZE_DP); if (iconSizeExtra < MINIMUM_MOPUB_PRIVACY_ICON_SIZE_DP) { mPrivacyIconSize = MINIMUM_MOPUB_PRIVACY_ICON_SIZE_DP; } else if (iconSizeExtra > MAXIMUM_MOPUB_PRIVACY_ICON_SIZE_DP) { mPrivacyIconSize = MAXIMUM_MOPUB_PRIVACY_ICON_SIZE_DP; } else { mPrivacyIconSize = iconSizeExtra; } } else { mPrivacyIconSize = DEFAULT_MOPUB_PRIVACY_ICON_SIZE_DP; } MoPubNative.MoPubNativeNetworkListener moPubNativeNetworkListener = new MoPubNative.MoPubNativeNetworkListener() { @Override public void onNativeLoad(NativeAd nativeAd) { // Setting a native event listener for MoPub's impression & click events. nativeAd.setMoPubNativeEventListener(mMoPubNativeEventListener); BaseNativeAd adData = nativeAd.getBaseNativeAd(); if (adData instanceof StaticNativeAd) { final StaticNativeAd staticNativeAd = (StaticNativeAd) adData; try { HashMap<String, URL> map = new HashMap<>(); try { map.put(DownloadDrawablesAsync.KEY_ICON, new URL(staticNativeAd.getIconImageUrl())); map.put(KEY_IMAGE, new URL(staticNativeAd.getMainImageUrl())); } catch (MalformedURLException e) { Log.d(TAG, "Invalid ad response received from MoPub. Image URLs" + " are invalid"); listener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_INTERNAL_ERROR); } new DownloadDrawablesAsync(new DrawableDownloadListener() { @Override public void onDownloadSuccess( HashMap<String, Drawable> drawableMap) { try { final MoPubNativeAppInstallAdMapper moPubNativeAppInstallAdMapper = new MoPubNativeAppInstallAdMapper( staticNativeAd, drawableMap, privacyIconPlacement, mPrivacyIconSize); // Returning the ImageView containing the main image via // AdMob's MediaView. ImageView imageView = new ImageView(context); imageView.setImageDrawable(drawableMap.get(KEY_IMAGE)); moPubNativeAppInstallAdMapper.setMediaView(imageView); listener.onAdLoaded(MoPubAdapter.this, moPubNativeAppInstallAdMapper); } catch (Exception e) { Log.d(TAG, "Exception trying to download native ad " + "drawables"); listener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_INTERNAL_ERROR); } } @Override public void onDownloadFailure() { // Failed to download images, send failure callback. listener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_INTERNAL_ERROR); } }).execute(map); } catch (Exception e) { Log.d(TAG, "Exception constructing the native ad"); listener.onAdFailedToLoad( MoPubAdapter.this, AdRequest.ERROR_CODE_INTERNAL_ERROR); } } } @Override public void onNativeFail(NativeErrorCode errorCode) { switch (errorCode) { case EMPTY_AD_RESPONSE: listener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_NO_FILL); break; case INVALID_REQUEST_URL: listener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); break; case CONNECTION_ERROR: listener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); break; case UNSPECIFIED: listener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_INTERNAL_ERROR); break; default: listener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_INTERNAL_ERROR); break; } } }; if (adunit == null) { Log.d(TAG, "Ad unit id is invalid. So failing the request."); listener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); return; } MoPubNative moPubNative = new MoPubNative(context, adunit, moPubNativeNetworkListener); ViewBinder viewbinder = new ViewBinder.Builder(0).build(); MoPubStaticNativeAdRenderer moPubStaticNativeAdRenderer = new MoPubStaticNativeAdRenderer(viewbinder); moPubNative.registerAdRenderer(moPubStaticNativeAdRenderer); EnumSet<RequestParameters.NativeAdAsset> assetsSet = EnumSet.of(RequestParameters.NativeAdAsset.TITLE, RequestParameters.NativeAdAsset.TEXT, RequestParameters.NativeAdAsset.CALL_TO_ACTION_TEXT, RequestParameters.NativeAdAsset.MAIN_IMAGE, RequestParameters.NativeAdAsset.ICON_IMAGE); RequestParameters requestParameters = new RequestParameters.Builder() .keywords(getKeywords(mediationAdRequest, false)) .userDataKeywords(getKeywords(mediationAdRequest, true)) .location(mediationAdRequest.getLocation()) .desiredAssets(assetsSet) .build(); moPubNative.makeRequest(requestParameters); // Forwarding MoPub's impression and click events to AdMob. mMoPubNativeEventListener = new NativeAd.MoPubNativeEventListener() { @Override public void onImpression(View view) { listener.onAdImpression(MoPubAdapter.this); Log.d(TAG, "onImpression"); } @Override public void onClick(View view) { listener.onAdClicked(MoPubAdapter.this); listener.onAdOpened(MoPubAdapter.this); listener.onAdLeftApplication(MoPubAdapter.this); Log.d(TAG, "onClick"); } }; } @Override public void requestBannerAd(Context context, MediationBannerListener mediationBannerListener, Bundle bundle, AdSize adSize, MediationAdRequest mediationAdRequest, Bundle bundle1) { String adunit = bundle.getString(MOPUB_AD_UNIT_KEY); initializeMoPub(context, adunit); mAdSize = adSize; mMoPubView = new MoPubView(context); mMoPubView.setBannerAdListener(new MBannerListener(mediationBannerListener)); mMoPubView.setAdUnitId(adunit); //If test mode is enabled if (mediationAdRequest.isTesting()) { mMoPubView.setTesting(true); } //If location is available if (mediationAdRequest.getLocation() != null) { mMoPubView.setLocation(mediationAdRequest.getLocation()); } mMoPubView.setKeywords(getKeywords(mediationAdRequest, false)); mMoPubView.setUserDataKeywords(getKeywords(mediationAdRequest, true)); mMoPubView.loadAd(); } @Override public View getBannerView() { return mMoPubView; } /* Keywords passed from AdMob are separated into 1) personally identifiable, and 2) non-personally identifiable categories before they are forwarded to MoPub due to GDPR. */ private String getKeywords(MediationAdRequest mediationAdRequest, boolean intendedForPII) { Date birthday = mediationAdRequest.getBirthday(); String ageString = ""; if (birthday != null) { int ageInt = getAge(birthday); ageString = "m_age:" + Integer.toString(ageInt); } int gender = mediationAdRequest.getGender(); String genderString = ""; if (gender != -1) { if (gender == GENDER_FEMALE) { genderString = "m_gender:f"; } else if (gender == GENDER_MALE) { genderString = "m_gender:m"; } } StringBuilder keywordsBuilder = new StringBuilder(); keywordsBuilder = keywordsBuilder.append(MOPUB_NATIVE_CEVENT_VERSION) .append(",").append(ageString) .append(",").append(genderString); if (intendedForPII) { return keywordsContainPII(mediationAdRequest) ? keywordsBuilder.toString() : ""; } else { return keywordsContainPII(mediationAdRequest) ? "" : keywordsBuilder.toString(); } } // Check whether passed keywords contain personally-identifiable information private boolean keywordsContainPII(MediationAdRequest mediationAdRequest) { return mediationAdRequest.getBirthday() != null || mediationAdRequest.getGender() != -1 || mediationAdRequest.getLocation() != null; } private static int getAge(Date birthday) { int givenYear = Integer.parseInt((String) DateFormat.format("yyyy", birthday)); int currentYear = Calendar.getInstance().get(Calendar.YEAR); return currentYear - givenYear; } private class MBannerListener implements MoPubView.BannerAdListener { private MediationBannerListener mMediationBannerListener; public MBannerListener(MediationBannerListener bannerListener) { mMediationBannerListener = bannerListener; } @Override public void onBannerClicked(MoPubView moPubView) { mMediationBannerListener.onAdClicked(MoPubAdapter.this); } @Override public void onBannerCollapsed(MoPubView moPubView) { mMediationBannerListener.onAdClosed(MoPubAdapter.this); } @Override public void onBannerExpanded(MoPubView moPubView) { mMediationBannerListener.onAdOpened(MoPubAdapter.this); } @Override public void onBannerFailed(MoPubView moPubView, MoPubErrorCode moPubErrorCode) { switch (moPubErrorCode) { case NO_FILL: mMediationBannerListener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_NO_FILL); break; case NETWORK_TIMEOUT: mMediationBannerListener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_NETWORK_ERROR); break; case SERVER_ERROR: mMediationBannerListener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); break; default: mMediationBannerListener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_INTERNAL_ERROR); break; } } @Override public void onBannerLoaded(MoPubView moPubView) { if (!(mAdSize.getWidth() == moPubView.getAdWidth() && mAdSize.getHeight() == moPubView.getAdHeight())) { Log.w(TAG, "The banner ad size loaded does not match the request size. Update the" + " ad size on your MoPub UI to match the request size."); } mMediationBannerListener.onAdLoaded(MoPubAdapter.this); } } @Override public void requestInterstitialAd(Context context, MediationInterstitialListener mediationInterstitialListener, Bundle bundle, MediationAdRequest mediationAdRequest, Bundle bundle1) { String adunit = bundle.getString(MOPUB_AD_UNIT_KEY); initializeMoPub(context, adunit); mMoPubInterstitial = new MoPubInterstitial((Activity) context, adunit); mMoPubInterstitial.setInterstitialAdListener( new mMediationInterstitialListener(mediationInterstitialListener)); //If test mode is enabled if (mediationAdRequest.isTesting()) { mMoPubInterstitial.setTesting(true); } mMoPubInterstitial.setKeywords(getKeywords(mediationAdRequest, false)); mMoPubInterstitial.setKeywords(getKeywords(mediationAdRequest, true)); mMoPubInterstitial.load(); } @Override public void showInterstitial() { if (mMoPubInterstitial.isReady()) { mMoPubInterstitial.show(); } else { MoPubLog.i("Interstitial was not ready. Unable to load the interstitial"); } } private class mMediationInterstitialListener implements MoPubInterstitial.InterstitialAdListener { private MediationInterstitialListener mMediationInterstitialListener; public mMediationInterstitialListener(MediationInterstitialListener interstitialListener) { mMediationInterstitialListener = interstitialListener; } @Override public void onInterstitialClicked(MoPubInterstitial moPubInterstitial) { mMediationInterstitialListener.onAdClicked(MoPubAdapter.this); } @Override public void onInterstitialDismissed(MoPubInterstitial moPubInterstitial) { mMediationInterstitialListener.onAdClosed(MoPubAdapter.this); } @Override public void onInterstitialFailed(MoPubInterstitial moPubInterstitial, MoPubErrorCode moPubErrorCode) { switch (moPubErrorCode) { case NO_FILL: mMediationInterstitialListener.onAdFailedToLoad(MoPubAdapter.this, AdRequest.ERROR_CODE_NO_FILL); break; case NETWORK_TIMEOUT: mMediationInterstitialListener.onAdFailedToLoad(MoPubAdapter.this, AdRequest .ERROR_CODE_NETWORK_ERROR); break; case SERVER_ERROR: mMediationInterstitialListener.onAdFailedToLoad(MoPubAdapter.this, AdRequest .ERROR_CODE_INVALID_REQUEST); break; default: mMediationInterstitialListener.onAdFailedToLoad(MoPubAdapter.this, AdRequest .ERROR_CODE_INTERNAL_ERROR); break; } } @Override public void onInterstitialLoaded(MoPubInterstitial moPubInterstitial) { mMediationInterstitialListener.onAdLoaded(MoPubAdapter.this); } @Override public void onInterstitialShown(MoPubInterstitial moPubInterstitial) { mMediationInterstitialListener.onAdOpened(MoPubAdapter.this); } } // Initializing the MoPub SDK. Required as of 5.0.0 private void initializeMoPub(Context context, String adUnitId) { if (!MoPub.isSdkInitialized()) { SdkConfiguration sdkConfiguration = new SdkConfiguration.Builder(adUnitId) .build(); MoPub.initializeSdk(context, sdkConfiguration, initSdkListener()); } } private SdkInitializationListener initSdkListener() { return new SdkInitializationListener() { @Override public void onInitializationFinished() { MoPubLog.d("MoPub SDK initialized."); } }; } /** * The {@link BundleBuilder} class is used to create a NetworkExtras bundle which can be passed * to the adapter to make network-specific customizations. */ public static final class BundleBuilder { /** * Key to add and obtain {@link #mPrivacyIconSizeDp}. */ private static final String ARG_PRIVACY_ICON_SIZE_DP = "privacy_icon_size_dp"; /** * MoPub's privacy icon size in dp. */ private int mPrivacyIconSizeDp; /** * Sets the privacy icon size in dp. */ public BundleBuilder setPrivacyIconSize(int iconSizeDp) { mPrivacyIconSizeDp = iconSizeDp; return BundleBuilder.this; } /** * Constructs a Bundle with the specified extras. * * @return a {@link Bundle} containing the specified extras. */ public Bundle build() { Bundle bundle = new Bundle(); bundle.putInt(ARG_PRIVACY_ICON_SIZE_DP, mPrivacyIconSizeDp); return bundle; } } }
package com.github.ambry.messageformat; import com.codahale.metrics.Histogram; import com.codahale.metrics.MetricRegistry; import com.github.ambry.store.MessageInfo; import com.github.ambry.store.StoreKey; import com.github.ambry.store.StoreKeyFactory; import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Utils; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * InputStream that skips invalid blobs based on some validation criteria. * For now, the check only supports detection of message corruption */ public class MessageSievingInputStream extends InputStream { private int validSize; private final Logger logger; private ByteBuffer byteBuffer; private boolean hasInvalidMessages; private List<MessageInfo> validMessageInfoList; //metrics public Histogram messageFormatValidationTime; public Histogram messageFormatBatchValidationTime; /** * @param stream The stream from which bytes need to be read. If the underlying stream is SocketInputStream, it needs * to be blocking * @param messageInfoList List of MessageInfo which contains details about the messages in the stream * @param storeKeyFactory factory which is used to read the key from the stream * @param metricRegistry Metric register to register metrics * @throws java.io.IOException */ public MessageSievingInputStream(InputStream stream, List<MessageInfo> messageInfoList, StoreKeyFactory storeKeyFactory, MetricRegistry metricRegistry) throws IOException { this.logger = LoggerFactory.getLogger(getClass()); messageFormatValidationTime = metricRegistry.histogram(MetricRegistry.name(MessageSievingInputStream.class, "MessageFormatValidationTime")); messageFormatBatchValidationTime = metricRegistry .histogram(MetricRegistry.name(MessageSievingInputStream.class, "MessageFormatBatchValidationTime")); validSize = 0; hasInvalidMessages = false; validMessageInfoList = new ArrayList<MessageInfo>(); // check for empty list if (messageInfoList.size() == 0) { byteBuffer = ByteBuffer.allocate(0); return; } int totalMessageListSize = 0; for (MessageInfo info : messageInfoList) { totalMessageListSize += info.getSize(); } int bytesRead = 0; byte[] data = new byte[totalMessageListSize]; long startTime = SystemTime.getInstance().milliseconds(); logger.trace("Starting to validate message stream "); int offset = 0; for (MessageInfo msgInfo : messageInfoList) { int msgSize = (int) msgInfo.getSize(); Utils.readBytesFromStream(stream, data, offset, msgSize); logger.trace("Read stream for message info " + msgInfo + " into memory"); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data, offset, msgSize); if (checkForMessageValidity(byteArrayInputStream, offset, msgSize, storeKeyFactory, msgInfo)) { offset += msgSize; validMessageInfoList.add(msgInfo); } else { logger.error("Error reading the message at " + bytesRead + " with messageInfo " + msgInfo + " and hence skipping the message"); hasInvalidMessages = true; } bytesRead += msgSize; } if (bytesRead != totalMessageListSize) { logger.error( "Failed to read intended size from stream. Expected " + totalMessageListSize + ", actual " + bytesRead); } if (validMessageInfoList.size() == 0) { logger.error("All messages are invalidated in this message stream "); } messageFormatBatchValidationTime.update(SystemTime.getInstance().milliseconds() - startTime); this.validSize = offset; byteBuffer = ByteBuffer.wrap(data, 0, validSize); logger.trace("Completed validation of message stream "); } /** * Returns the total size of all valid messages that could be read from the stream * @return validSize */ public int getSize() { return validSize; } @Override public int read() throws IOException { if (!byteBuffer.hasRemaining()) { return -1; } return byteBuffer.get() & 0xFF; } @Override public int read(byte[] bytes, int offset, int length) throws IOException { if (bytes == null) { throw new IllegalArgumentException("Byte array cannot be null"); } else if (offset < 0 || length < 0 || length > bytes.length - offset) { throw new IndexOutOfBoundsException(); } else if (length == 0) { return 0; } int count = Math.min(byteBuffer.remaining(), length); if (count == 0) { return -1; } byteBuffer.get(bytes, offset, count); return count; } /** * Whether the stream has invalid messages or not * @return */ public boolean hasInvalidMessages() { return hasInvalidMessages; } public List<MessageInfo> getValidMessageInfoList() { return validMessageInfoList; } /** * Ensures blob validity in the given input stream. For now, blobs are checked for message corruption * @param byteArrayInputStream stream against which validation has to be done * @param size total size of the message expected * @param currentOffset Current offset at which the data has to be read from the given byte array * @param storeKeyFactory StoreKeyFactory used to get store key * @return true if message is valid and false otherwise * @throws IOException */ private boolean checkForMessageValidity(ByteArrayInputStream byteArrayInputStream, int currentOffset, long size, StoreKeyFactory storeKeyFactory, MessageInfo msgInfo) throws IOException { boolean isValid = false; BlobProperties props = null; ByteBuffer metadata = null; BlobOutput output = null; long startTime = SystemTime.getInstance().milliseconds(); try { int availableBeforeParsing = byteArrayInputStream.available(); byte[] headerVersionInBytes = new byte[MessageFormatRecord.Version_Field_Size_In_Bytes]; byteArrayInputStream.read(headerVersionInBytes, 0, MessageFormatRecord.Version_Field_Size_In_Bytes); ByteBuffer headerVersion = ByteBuffer.wrap(headerVersionInBytes); short version = headerVersion.getShort(); if (version == 1) { ByteBuffer headerBuffer = ByteBuffer.allocate(MessageFormatRecord.MessageHeader_Format_V1.getHeaderSize()); headerBuffer.putShort(version); byteArrayInputStream.read(headerBuffer.array(), 2, headerBuffer.capacity() - 2); headerBuffer.position(headerBuffer.capacity()); headerBuffer.flip(); MessageFormatRecord.MessageHeader_Format_V1 header = new MessageFormatRecord.MessageHeader_Format_V1(headerBuffer); StoreKey storeKey = storeKeyFactory.getStoreKey(new DataInputStream(byteArrayInputStream)); if (header.getBlobPropertiesRecordRelativeOffset() != MessageFormatRecord.Message_Header_Invalid_Relative_Offset) { props = MessageFormatRecord.deserializeBlobProperties(byteArrayInputStream); metadata = MessageFormatRecord.deserializeUserMetadata(byteArrayInputStream); output = MessageFormatRecord.deserializeBlob(byteArrayInputStream); } else { throw new IllegalStateException("Message cannot be a deleted record "); } if (byteArrayInputStream.available() != 0) { logger.error("Parsed message size " + (availableBeforeParsing + byteArrayInputStream.available()) + " is not equivalent to the size in message info " + availableBeforeParsing); isValid = false; } if (logger.isTraceEnabled()) { logger.trace("Message Successfully read"); logger.trace( "Header - version {} Message Size {} Starting offset of the blob {} BlobPropertiesRelativeOffset {}" + " UserMetadataRelativeOffset {} DataRelativeOffset {} DeleteRecordRelativeOffset {} Crc {}", header.getVersion(), header.getMessageSize(), currentOffset, header.getBlobPropertiesRecordRelativeOffset(), header.getUserMetadataRecordRelativeOffset(), header.getBlobRecordRelativeOffset(), header.getDeleteRecordRelativeOffset(), header.getCrc()); logger.trace("Id {} Blob Properties - blobSize {} Metadata - size {} Blob - size {} ", storeKey.getID(), props.getBlobSize(), metadata.capacity(), output.getSize()); } if(msgInfo.getStoreKey().equals(storeKey)){ isValid = true; } else{ logger.error("StoreKey in log " + storeKey +" failed to match store key from Index " + msgInfo.getStoreKey()); } } else { throw new MessageFormatException("Header version not supported " + version, MessageFormatErrorCodes.Data_Corrupt); } } catch (MessageFormatException e) { logger .error("MessageFormat exception thrown for a blob starting at offset " + currentOffset + " with exception: ", e); } finally { messageFormatValidationTime.update(SystemTime.getInstance().milliseconds() - startTime); } return isValid; } }
package com.it_nomads.fluttersecurestorage.ciphers; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import android.security.keystore.StrongBoxUnavailableException; import android.util.Log; import java.math.BigInteger; import java.security.Key; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.Certificate; import java.security.spec.AlgorithmParameterSpec; import java.util.Calendar; import java.util.Locale; import javax.crypto.Cipher; import javax.security.auth.x500.X500Principal; class RSACipher18Implementation { private final String KEY_ALIAS; private static final String KEYSTORE_PROVIDER_ANDROID = "AndroidKeyStore"; private static final String TYPE_RSA = "RSA"; private Context context; public RSACipher18Implementation(Context context) throws Exception { KEY_ALIAS = context.getPackageName() + ".FlutterSecureStoragePluginKey"; this.context = context; createRSAKeysIfNeeded(context); } public byte[] wrap(Key key) throws Exception { PublicKey publicKey = getPublicKey(); Cipher cipher = getRSACipher(); cipher.init(Cipher.WRAP_MODE, publicKey); return cipher.wrap(key); } public Key unwrap(byte[] wrappedKey, String algorithm) throws Exception { PrivateKey privateKey = getPrivateKey(); Cipher cipher = getRSACipher(); cipher.init(Cipher.UNWRAP_MODE, privateKey); return cipher.unwrap(wrappedKey, algorithm, Cipher.SECRET_KEY); } public byte[] encrypt(byte[] input) throws Exception { PublicKey publicKey = getPublicKey(); Cipher cipher = getRSACipher(); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(input); } public byte[] decrypt(byte[] input) throws Exception { PrivateKey privateKey = getPrivateKey(); Cipher cipher = getRSACipher(); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(input); } private PrivateKey getPrivateKey() throws Exception { KeyStore ks = KeyStore.getInstance(KEYSTORE_PROVIDER_ANDROID); ks.load(null); Key key = ks.getKey(KEY_ALIAS, null); if (key == null) { throw new Exception("No key found under alias: " + KEY_ALIAS); } if (!(key instanceof PrivateKey)) { throw new Exception("Not an instance of a PrivateKey"); } return (PrivateKey) key; } private PublicKey getPublicKey() throws Exception { KeyStore ks = KeyStore.getInstance(KEYSTORE_PROVIDER_ANDROID); ks.load(null); Certificate cert = ks.getCertificate(KEY_ALIAS); if (cert == null) { throw new Exception("No certificate found under alias: " + KEY_ALIAS); } PublicKey key = cert.getPublicKey(); if (key == null) { throw new Exception("No key found under alias: " + KEY_ALIAS); } return key; } private Cipher getRSACipher() throws Exception { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL"); // error in android 6: InvalidKeyException: Need RSA private or public key } else { return Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidKeyStoreBCWorkaround"); // error in android 5: NoSuchProviderException: Provider not available: AndroidKeyStoreBCWorkaround } } private void createRSAKeysIfNeeded(Context context) throws Exception { KeyStore ks = KeyStore.getInstance(KEYSTORE_PROVIDER_ANDROID); ks.load(null); Key privateKey = ks.getKey(KEY_ALIAS, null); if (privateKey == null) { createKeys(context); } } /** * Sets default locale. */ private void setLocale(Locale locale) { Locale.setDefault(locale); Resources resources = context.getResources(); Configuration config = resources.getConfiguration(); config.locale = locale; resources.updateConfiguration(config, resources.getDisplayMetrics()); } @SuppressLint("NewApi") private void createKeys(Context context) throws Exception { Log.i("fluttersecurestorage", "Creating keys!"); final Locale localeBeforeFakingEnglishLocale = Locale.getDefault(); try { setLocale(Locale.ENGLISH); Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); end.add(Calendar.YEAR, 25); KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(TYPE_RSA, KEYSTORE_PROVIDER_ANDROID); AlgorithmParameterSpec spec; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { spec = new android.security.KeyPairGeneratorSpec.Builder(context) .setAlias(KEY_ALIAS) .setSubject(new X500Principal("CN=" + KEY_ALIAS)) .setSerialNumber(BigInteger.valueOf(1)) .setStartDate(start.getTime()) .setEndDate(end.getTime()) .build(); } else { KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT) .setCertificateSubject(new X500Principal("CN=" + KEY_ALIAS)) .setDigests(KeyProperties.DIGEST_SHA256) .setBlockModes(KeyProperties.BLOCK_MODE_ECB) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1) .setCertificateSerialNumber(BigInteger.valueOf(1)) .setCertificateNotBefore(start.getTime()) .setCertificateNotAfter(end.getTime()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { builder.setIsStrongBoxBacked(true); } spec = builder.build(); } try { Log.i("fluttersecurestorage", "Initializing"); kpGenerator.initialize(spec); Log.i("fluttersecurestorage", "Generating key pair"); kpGenerator.generateKeyPair(); } catch (StrongBoxUnavailableException se) { spec = new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT) .setCertificateSubject(new X500Principal("CN=" + KEY_ALIAS)) .setDigests(KeyProperties.DIGEST_SHA256) .setBlockModes(KeyProperties.BLOCK_MODE_ECB) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1) .setCertificateSerialNumber(BigInteger.valueOf(1)) .setCertificateNotBefore(start.getTime()) .setCertificateNotAfter(end.getTime()) .build(); kpGenerator.initialize(spec); kpGenerator.generateKeyPair(); } } finally { setLocale(localeBeforeFakingEnglishLocale); } } }
package com.thebluealliance.androidclient.background.firstlaunch; import android.content.SharedPreferences; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.util.Log; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.thebluealliance.androidclient.Constants; import com.thebluealliance.androidclient.R; import com.thebluealliance.androidclient.Utilities; import com.thebluealliance.androidclient.activities.LaunchActivity; import com.thebluealliance.androidclient.datafeed.CSVManager; import com.thebluealliance.androidclient.datafeed.DataManager; import com.thebluealliance.androidclient.datafeed.Database; import com.thebluealliance.androidclient.datafeed.JSONManager; import com.thebluealliance.androidclient.datafeed.TBAv2; import com.thebluealliance.androidclient.datatypes.APIResponse; import com.thebluealliance.androidclient.models.SimpleEvent; import com.thebluealliance.androidclient.models.SimpleTeam; import java.util.ArrayList; import java.util.Calendar; public class LoadAllData extends AsyncTask<Void, LoadAllData.LoadProgressInfo, Void> { private LaunchActivity activity; public LoadAllData(LaunchActivity activity) { this.activity = activity; } @Override protected Void doInBackground(Void... params) { if (activity == null) { throw new IllegalArgumentException("Activity must not be null!"); } /* We need to download and cache every team and event into the database. To avoid * unexpected behavior caused by changes in network connectivity, we will load all * teams into memory first. Once we have loaded everything, only then will we wipe the * database and insert all the new teams and events. * */ try { ArrayList<SimpleTeam> teams = new ArrayList(); ArrayList<SimpleEvent> events = new ArrayList(); int maxPageNum = 0; // First we will load all the teams for (int pageNum = 0; pageNum < 20; pageNum++) { // limit to 20 pages to prevent potential infinite loop int start = pageNum * Constants.API_TEAM_LIST_PAGE_SIZE; int end = start + Constants.API_TEAM_LIST_PAGE_SIZE - 1; start = start == 0 ? 1 : start; publishProgress(new LoadProgressInfo(LoadProgressInfo.STATE_LOADING, String.format(activity.getString(R.string.loading_teams), start, end))); APIResponse<String> teamListResponse; teamListResponse = TBAv2.getResponseFromURLOrThrow(activity, String.format(TBAv2.API_URL.get(TBAv2.QUERY.TEAM_LIST), pageNum), true); JsonArray responseObject = JSONManager.getasJsonArray(teamListResponse.getData()); if (responseObject instanceof JsonArray) { if (responseObject.size() == 0) { // No teams found for a page; we are done break; } } maxPageNum = Math.max(maxPageNum, pageNum); ArrayList<SimpleTeam> pageTeams = TBAv2.getTeamList(teamListResponse.getData()); teams.addAll(pageTeams); } // Now we load all events for (int year = Constants.FIRST_COMP_YEAR; year < Calendar.getInstance().get(Calendar.YEAR) + 1; year++) { publishProgress(new LoadProgressInfo(LoadProgressInfo.STATE_LOADING, String.format(activity.getString(R.string.loading_events), Integer.toString(year)))); APIResponse<String> eventListResponse; eventListResponse = TBAv2.getResponseFromURLOrThrow(activity, "http://thebluealliance.com/api/v2/events/" + year, true); JsonElement responseObject = new JsonParser().parse(eventListResponse.getData()); if (responseObject instanceof JsonObject) { if (((JsonObject) responseObject).has("404")) { // No events found for that year; skip it continue; } } ArrayList<SimpleEvent> yearEvents = TBAv2.getEventList(eventListResponse.getData()); events.addAll(yearEvents); } // If no exception has been thrown at this point, we have all the data. We can now // insert it into the database. Database.getInstance(activity).storeTeams(teams); Database.getInstance(activity).storeEvents(events); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(activity).edit(); // Loop through all pages for (int pageNum = 0; pageNum <= maxPageNum; pageNum++) { editor.putBoolean(DataManager.ALL_TEAMS_LOADED_TO_DATABASE_FOR_PAGE + pageNum, true); } // Loop through all years for (int year = Constants.FIRST_COMP_YEAR; year < Calendar.getInstance().get(Calendar.YEAR) + 1; year++) { editor.putBoolean(DataManager.ALL_EVENTS_LOADED_TO_DATABASE_FOR_YEAR + year, true); } editor.commit(); publishProgress(new LoadProgressInfo(LoadProgressInfo.STATE_FINISHED, activity.getString(R.string.loading_finished))); } catch (DataManager.NoDataException e) { e.printStackTrace(); publishProgress(new LoadProgressInfo(LoadProgressInfo.STATE_NO_CONNECTION, activity.getString(R.string.connection_lost))); // Wipe any partially cached responses Database.getInstance(activity).deleteAllResponses(); } catch (Exception e) { // This is bad, probably an error in the response from the server e.printStackTrace(); // Wipe any partially cached responses Database.getInstance(activity).deleteAllResponses(); // Alert the user that there was a problem publishProgress(new LoadProgressInfo(LoadProgressInfo.STATE_ERROR, Utilities.exceptionStacktraceToString(e))); } return null; } @Override protected void onProgressUpdate(LoadProgressInfo... values) { activity.onLoadingProgressUpdate(values[0]); } public class LoadProgressInfo { public static final int STATE_LOADING = 0; public static final int STATE_FINISHED = 1; public static final int STATE_NO_CONNECTION = 2; public static final int STATE_ERROR = 3; public int state = -1; public String message = ""; public LoadProgressInfo(int state, String message) { this.state = state; this.message = message; } } }
package uk.ac.ebi.quickgo.annotation.controller; import uk.ac.ebi.quickgo.annotation.download.header.HeaderContent; import uk.ac.ebi.quickgo.annotation.download.header.HeaderCreator; import uk.ac.ebi.quickgo.annotation.download.header.HeaderCreatorFactory; import uk.ac.ebi.quickgo.annotation.download.header.HeaderUri; import uk.ac.ebi.quickgo.annotation.download.http.MediaTypeFactory; import uk.ac.ebi.quickgo.annotation.download.model.DownloadContent; import uk.ac.ebi.quickgo.annotation.model.Annotation; import uk.ac.ebi.quickgo.annotation.model.AnnotationRequest; import uk.ac.ebi.quickgo.annotation.model.StatisticsGroup; import uk.ac.ebi.quickgo.annotation.service.search.SearchServiceConfig; import uk.ac.ebi.quickgo.annotation.service.statistics.StatisticsService; import uk.ac.ebi.quickgo.rest.ParameterBindingException; import uk.ac.ebi.quickgo.rest.ResponseExceptionHandler; import uk.ac.ebi.quickgo.rest.comm.FilterContext; import uk.ac.ebi.quickgo.rest.metadata.MetaData; import uk.ac.ebi.quickgo.rest.metadata.MetaDataProvider; import uk.ac.ebi.quickgo.rest.search.DefaultSearchQueryTemplate; import uk.ac.ebi.quickgo.rest.search.SearchService; import uk.ac.ebi.quickgo.rest.search.query.QueryRequest; import uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery; import uk.ac.ebi.quickgo.rest.search.query.RegularPage; import uk.ac.ebi.quickgo.rest.search.request.FilterRequest; import uk.ac.ebi.quickgo.rest.search.request.converter.FilterConverterFactory; import uk.ac.ebi.quickgo.rest.search.results.QueryResult; import uk.ac.ebi.quickgo.rest.search.results.transformer.ResultTransformationRequests; import uk.ac.ebi.quickgo.rest.search.results.transformer.ResultTransformerChain; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.function.Function; import java.util.stream.Stream; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.task.TaskExecutor; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter; import static com.google.common.base.Preconditions.checkArgument; import static java.util.stream.Collectors.toList; import static org.slf4j.LoggerFactory.getLogger; import static org.springframework.http.HttpHeaders.ACCEPT; import static org.springframework.http.HttpHeaders.VARY; import static uk.ac.ebi.quickgo.annotation.download.http.MediaTypeFactory.*; import static uk.ac.ebi.quickgo.rest.search.SearchDispatcher.searchAndTransform; import static uk.ac.ebi.quickgo.rest.search.SearchDispatcher.streamSearchResults; import static uk.ac.ebi.quickgo.rest.search.query.CursorPage.createFirstCursorPage; @RestController @RequestMapping(value = "/annotation") public class AnnotationController { private static final Logger LOGGER = getLogger(AnnotationController.class); private static final DateTimeFormatter DOWNLOAD_FILE_NAME_DATE_FORMATTER = DateTimeFormatter.ofPattern("-N-yyyyMMdd"); private static final String DOWNLOAD_FILE_NAME_PREFIX = "QuickGO-annotations"; private static final String GO_USAGE_SLIM = "goUsage=slim"; private static final String DOWNLOAD_STATISTICS_FILE_NAME = "annotation_statistics"; private static final Function<MediaType, String> TO_DOWNLOAD_STATISTICS_FILENAME = mt -> String.format("%s.%s", DOWNLOAD_STATISTICS_FILE_NAME, MediaTypeFactory.MEDIA_TYPE_TO_FILE_EXTENSIONS .get(mt)); private static final Function<MediaType, String> TO_DOWNLOAD_FILENAME = mt -> String.format("%s%s.%s", DOWNLOAD_FILE_NAME_PREFIX, formattedDateStringForNow(), MediaTypeFactory.MEDIA_TYPE_TO_FILE_EXTENSIONS .get(mt)); private final MetaDataProvider metaDataProvider; private final SearchService<Annotation> annotationSearchService; private final SearchServiceConfig.AnnotationCompositeRetrievalConfig annotationRetrievalConfig; private final DefaultSearchQueryTemplate queryTemplate; private final DefaultSearchQueryTemplate downloadQueryTemplate; private final FilterConverterFactory converterFactory; private final ResultTransformerChain<QueryResult<Annotation>> resultTransformerChain; private final StatisticsService statsService; private final TaskExecutor taskExecutor; private final HeaderCreatorFactory headerCreatorFactory; @Autowired public AnnotationController(SearchService<Annotation> annotationSearchService, SearchServiceConfig.AnnotationCompositeRetrievalConfig annotationRetrievalConfig, FilterConverterFactory converterFactory, ResultTransformerChain<QueryResult<Annotation>> resultTransformerChain, StatisticsService statsService, TaskExecutor taskExecutor, HeaderCreatorFactory headerCreatorFactory, MetaDataProvider metaDataProvider) { checkArgument(annotationSearchService != null, "The SearchService<Annotation> instance passed " + "to the constructor of AnnotationController should not be null."); checkArgument(annotationRetrievalConfig != null, "The SearchServiceConfig" + ".AnnotationCompositeRetrievalConfig instance passed to the constructor of AnnotationController " + "should not be null."); checkArgument(converterFactory != null, "The FilterConverterFactory cannot be null."); checkArgument(resultTransformerChain != null, "The ResultTransformerChain<QueryResult<Annotation>> cannot be null."); checkArgument(statsService != null, "Annotation stats service cannot be null."); checkArgument(taskExecutor != null, "TaskExecutor cannot be null."); checkArgument(headerCreatorFactory != null, "HeaderCreatorFactory cannot be null."); checkArgument(metaDataProvider != null, "Metadata provider cannot be null."); this.annotationSearchService = annotationSearchService; this.converterFactory = converterFactory; this.statsService = statsService; this.resultTransformerChain = resultTransformerChain; this.annotationRetrievalConfig = annotationRetrievalConfig; this.queryTemplate = createSearchQueryTemplate(annotationRetrievalConfig); this.downloadQueryTemplate = createDownloadSearchQueryTemplate(annotationRetrievalConfig); this.taskExecutor = taskExecutor; this.headerCreatorFactory = headerCreatorFactory; this.metaDataProvider = metaDataProvider; } /** * Search for an Annotations based on their attributes * @return a {@link QueryResult} instance containing the results of the search */ @ApiResponses(value = { @ApiResponse(code = 200, message = "Annotation result set has been filtered according to " + "the provided attribute values"), @ApiResponse(code = 500, message = "Internal server error occurred whilst searching for " + "matching annotations", response = ResponseExceptionHandler.ErrorInfo.class), @ApiResponse(code = 400, message = "Bad request due to a validation issue encountered in one of the " + "filters", response = ResponseExceptionHandler.ErrorInfo.class)}) @ApiOperation(value = "Search for all annotations that match the filter criteria provided by the client.") @RequestMapping(value = "/search", method = {RequestMethod.GET}, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<Annotation>> annotationLookup( @Valid @ModelAttribute AnnotationRequest request, BindingResult bindingResult) { checkBindingErrors(bindingResult); FilterQueryInfo filterQueryInfo = extractFilterQueryInfo(request); QueryRequest queryRequest = queryTemplate.newBuilder() .setQuery(QuickGOQuery.createAllQuery()) .addFilters(filterQueryInfo.getFilterQueries()) .setPage(new RegularPage(request.getPage(), request.getLimit())) .build(); return searchAndTransform(queryRequest, annotationSearchService, resultTransformerChain, filterQueryInfo.getFilterContext()); } /** * Return statistics based on the search result. * * The statistics are subdivided into two areas, each with * @return a {@link QueryResult} instance containing the results of the search */ @ApiResponses(value = { @ApiResponse(code = 200, message = "Statistics have been calculated for the annotation result set " + "obtained from the application of the filter parameters"), @ApiResponse(code = 500, message = "Internal server error occurred whilst producing statistics", response = ResponseExceptionHandler.ErrorInfo.class), @ApiResponse(code = 400, message = "Bad request due to a validation issue encountered in one of the " + "filters", response = ResponseExceptionHandler.ErrorInfo.class)}) @ApiOperation(value = "Generate statistic on the annotation result set obtained from applying the filters.") @RequestMapping(value = "/stats", method = {RequestMethod.GET}, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<StatisticsGroup>> annotationStats( @Valid @ModelAttribute AnnotationRequest request, BindingResult bindingResult) { checkBindingErrors(bindingResult); QueryResult<StatisticsGroup> stats = statsService.calculate(request); return new ResponseEntity<>(stats, HttpStatus.OK); } @RequestMapping(value = "/downloadSearch", method = {RequestMethod.GET}, produces = {GPAD_MEDIA_TYPE_STRING, GAF_MEDIA_TYPE_STRING, TSV_MEDIA_TYPE_STRING}) public ResponseEntity<ResponseBodyEmitter> downloadLookup( @Valid @ModelAttribute AnnotationRequest request, BindingResult bindingResult, @RequestHeader(ACCEPT) MediaType mediaTypeAcceptHeader, HttpServletRequest servletRequest) { LOGGER.info("Download Request:: " + request + ", " + mediaTypeAcceptHeader); checkBindingErrors(bindingResult); FilterQueryInfo filterQueryInfo = extractFilterQueryInfo(request); final int pageLimit = request.getDownloadLimit() < this.annotationRetrievalConfig.getDownloadPageSize()? request.getDownloadLimit() : this.annotationRetrievalConfig.getDownloadPageSize(); QueryRequest queryRequest = downloadQueryTemplate.newBuilder() .setQuery(QuickGOQuery.createAllQuery()) .addFilters(filterQueryInfo.getFilterQueries()) .setPage(createFirstCursorPage(pageLimit)) .build(); ResponseBodyEmitter emitter = new ResponseBodyEmitter(); HeaderCreator headerCreator = headerCreatorFactory.provide(mediaTypeAcceptHeader.getSubtype()); final List<String> selectedFields = selectedFieldList(request); HeaderContent headerContent = buildHeaderContent(servletRequest, selectedFields); headerCreator.write(emitter, headerContent); taskExecutor.execute(() -> { final Stream<QueryResult<Annotation>> annotationResultStream = getQueryResultStream(request, filterQueryInfo, queryRequest); DownloadContent downloadContent = new DownloadContent(annotationResultStream, selectedFields); emitDownloadWithMediaType(emitter, downloadContent, mediaTypeAcceptHeader); }); return ResponseEntity .ok() .headers(addHttpFileAttachmentHeader(mediaTypeAcceptHeader, TO_DOWNLOAD_FILENAME)) .body(emitter); } @RequestMapping(value = "/downloadStats", method = {RequestMethod.GET}, produces = {EXCEL_MEDIA_TYPE_STRING,JSON_MEDIA_TYPE_STRING}) public ResponseEntity<ResponseBodyEmitter> downloadStats( @Valid @ModelAttribute AnnotationRequest request, BindingResult bindingResult, @RequestHeader(ACCEPT) MediaType mediaTypeAcceptHeader) throws IOException { checkBindingErrors(bindingResult); QueryResult<StatisticsGroup> stats = statsService.calculate(request); ResponseBodyEmitter emitter = new ResponseBodyEmitter(); try { emitter.send(stats, mediaTypeAcceptHeader); } catch (IOException e) { LOGGER.error("Failed to stream annotation results", e); emitter.completeWithError(e); } emitter.complete(); LOGGER.info("Emitted response stream -- which will be written by the HTTP message converter for: " + mediaTypeAcceptHeader); return ResponseEntity .ok() .headers(addHttpFileAttachmentHeader(mediaTypeAcceptHeader, TO_DOWNLOAD_STATISTICS_FILENAME)) .body(emitter); } private static String formattedDateStringForNow() { LocalDateTime now = LocalDateTime.now(); return now.format(DOWNLOAD_FILE_NAME_DATE_FORMATTER); } private HeaderContent buildHeaderContent(HttpServletRequest servletRequest, List<String> selectedFields) { HeaderContent.Builder contentBuilder = new HeaderContent.Builder(); return contentBuilder.setIsSlimmed(isSlimmed(servletRequest)) .setUri(HeaderUri.uri(servletRequest)) .setDate(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE)) .setSelectedFields(selectedFields) .build(); } private List<String> selectedFieldList(AnnotationRequest annotationRequest) { if(annotationRequest.getSelectedFields() != null){ return Arrays.stream(annotationRequest.getSelectedFields()) .map(String::toLowerCase) .collect(toList()); } return Collections.emptyList(); } private boolean isSlimmed(HttpServletRequest servletRequest) { return Objects.nonNull(servletRequest.getQueryString()) && servletRequest.getQueryString().contains(GO_USAGE_SLIM); } private Stream<QueryResult<Annotation>> getQueryResultStream(@Valid @ModelAttribute AnnotationRequest request, FilterQueryInfo filterQueryInfo, QueryRequest queryRequest) { LOGGER.info("Creating stream of search results. With limit " + request.getDownloadLimit()); Stream<QueryResult<Annotation>> resultStream = streamSearchResults(queryRequest, queryTemplate, annotationSearchService, resultTransformerChain, filterQueryInfo.getFilterContext(), request.getDownloadLimit()); LOGGER.info("Finished creating stream of search results."); return resultStream; } /** * Get meta data information about the Annotation service * * @return response with metadata information. */ @ApiOperation(value = "Get meta data information about the Annotation service", notes = "Annotations creation date.") @RequestMapping(value = "/about", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<MetaData> provideMetaData() { return new ResponseEntity<>(metaDataProvider.lookupMetaData(), HttpStatus.OK); } private DefaultSearchQueryTemplate createSearchQueryTemplate( SearchServiceConfig.AnnotationCompositeRetrievalConfig retrievalConfig) { DefaultSearchQueryTemplate template = new DefaultSearchQueryTemplate(); template.setReturnedFields(retrievalConfig.getSearchReturnedFields()); return template; } private DefaultSearchQueryTemplate createDownloadSearchQueryTemplate( SearchServiceConfig.AnnotationCompositeRetrievalConfig retrievalConfig) { DefaultSearchQueryTemplate template = new DefaultSearchQueryTemplate(); template.setReturnedFields(retrievalConfig.getSearchReturnedFields()); template.setPage(createFirstCursorPage(retrievalConfig.getDownloadPageSize())); retrievalConfig.getDownloadSortCriteria() .forEach(criterion -> template.addSortCriterion(criterion.getSortField().getField(), criterion.getSortOrder())); return template; } private FilterQueryInfo extractFilterQueryInfo(AnnotationRequest request) { Set<QuickGOQuery> filterQueries = new HashSet<>(); Set<FilterContext> filterContexts = new HashSet<>(); convertFilterRequests(request, filterQueries, filterContexts); convertResultTransformationRequests(request, filterContexts); return new FilterQueryInfo() { @Override public Set<QuickGOQuery> getFilterQueries() { return filterQueries; } @Override public FilterContext getFilterContext() { return filterContexts.stream().reduce(new FilterContext(), FilterContext::merge); } }; } /** * Processes the list of {@link FilterRequest}s from the {@link AnnotationRequest} and * adds corresponding {@link QuickGOQuery}s to the {@code filterQueries}, and {@link FilterContext}s * to the {@code filterContext}s. * @param request the annotation request * @param filterQueries the {@link QuickGOQuery} list to append to * @param filterContexts the {@link FilterContext} list to append to */ private void convertFilterRequests(AnnotationRequest request, Set<QuickGOQuery> filterQueries, Set<FilterContext> filterContexts) { request.createFilterRequests().stream() .map(converterFactory::convert) .forEach(convertedFilter -> { filterQueries.add(convertedFilter.getConvertedValue()); convertedFilter.getFilterContext().ifPresent(filterContexts::add); }); } /** * Processes the {@link ResultTransformationRequests} instance from the {@link AnnotationRequest} and * adds corresponding {@link FilterContext}s to the {@code filterContext}s. * @param request the annotation request * @param filterContexts the {@link FilterContext} list to append to */ private void convertResultTransformationRequests( AnnotationRequest request, Set<FilterContext> filterContexts) { ResultTransformationRequests transformationRequests = request.createResultTransformationRequests(); if (!transformationRequests.getRequests().isEmpty()) { FilterContext transformationContext = new FilterContext(); transformationContext.save(ResultTransformationRequests.class, transformationRequests); filterContexts.add(transformationContext); } } private void checkBindingErrors(BindingResult bindingResult) { if (bindingResult.hasErrors()) { throw new ParameterBindingException(bindingResult); } } private HttpHeaders addHttpFileAttachmentHeader(MediaType mediaType, Function<MediaType, String> toFileName) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentDispositionFormData("attachment", toFileName.apply(mediaType)); httpHeaders.setContentType(mediaType); httpHeaders.add(VARY, ACCEPT); return httpHeaders; } private void emitDownloadWithMediaType( ResponseBodyEmitter emitter, DownloadContent downloadContent, MediaType mediaType) { try { emitter.send(downloadContent, mediaType); } catch (IOException e) { LOGGER.error("Failed to stream annotation results", e); emitter.completeWithError(e); } emitter.complete(); LOGGER.info("Emitted response stream -- which will be written by the HTTP message converter for: " + mediaType); } private interface FilterQueryInfo { Set<QuickGOQuery> getFilterQueries(); FilterContext getFilterContext(); } }