lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
JavaScript
|
mit
|
9d698f3014c1ce112e0dd137bcc6c2bb827b9091
| 0 |
kolach/loopback-component-cloudinary
|
var IncomingForm = require('formidable');
var fs = require('fs');
var path = require('path');
exports.upload = function(cloudinary, req, res, options, cb) {
var uploadOpts = Object.assign({}, options.upload);
if (!cb && 'function' === typeof options) {
cb = options;
options = {};
}
var form = new IncomingForm(options);
// we do not support multiple files upload currently
// more tests and more smart work with streams needed
form.multiples = false;
var files = [];
// list of files to upload
form.on('file', function(name, file) {
files.push(file);
});
form.on('field', function(name, value) {
switch (name) {
case 'folder':
uploadOpts.folder = uploadOpts.folder ? path.join(uploadOpts.folder, value) : value;
break;
case 'tags':
uploadOpts.tags = uploadOpts.tags ? [value, uploadOpts.tags].join() : value;
break;
default:
uploadOpts[name] = value;
}
});
// end request processing and retrun result
var done = function(error, result) {
cb && cb(error, result);
};
form.parse(req, function(error, fields, _files) {
if (error) {
done(error, null);
} else if (files.length === 0) {
done(new Error('No files supplied to request'), null);
} else {
// create writer with given options
var writer = cloudinary.v2.uploader.upload_stream(uploadOpts, done);
var reader = fs.createReadStream(files[0].path);
reader.pipe(writer);
}
});
};
|
lib/cloudinary-handler.js
|
var IncomingForm = require('formidable');
var fs = require('fs');
var path = require('path');
exports.upload = function(cloudinary, req, res, options, cb) {
var uploadOpts = options.upload || {};
if (!cb && 'function' === typeof options) {
cb = options;
options = {};
}
var form = new IncomingForm(options);
// we do not support multiple files upload currently
// more tests and more smart work with streams needed
form.multiples = false;
var files = [];
// list of files to upload
form.on('file', function(name, file) {
files.push(file);
});
form.on('field', function(name, value) {
switch (name) {
case 'folder':
uploadOpts.folder = uploadOpts.folder ? path.join(uploadOpts.folder, value) : value;
break;
case 'tags':
uploadOpts.tags = uploadOpts.tags ? [value, uploadOpts.tags].join() : value;
break;
default:
uploadOpts[name] = value;
}
});
// end request processing and retrun result
var done = function(error, result) {
cb && cb(error, result);
};
form.parse(req, function(error, fields, _files) {
if (error) {
done(error, null);
} else if (files.length === 0) {
done(new Error('No files supplied to request'), null);
} else {
// create writer with given options
var writer = cloudinary.v2.uploader.upload_stream(uploadOpts, done);
var reader = fs.createReadStream(files[0].path);
reader.pipe(writer);
}
});
};
|
fixed upload folder copied bug
|
lib/cloudinary-handler.js
|
fixed upload folder copied bug
|
<ide><path>ib/cloudinary-handler.js
<ide>
<ide> exports.upload = function(cloudinary, req, res, options, cb) {
<ide>
<del> var uploadOpts = options.upload || {};
<add> var uploadOpts = Object.assign({}, options.upload);
<ide>
<ide> if (!cb && 'function' === typeof options) {
<ide> cb = options;
|
|
Java
|
apache-2.0
|
8655815e86c86f182e55eb8fd1007070554ad252
| 0 |
jenkinsci/kubernetes-plugin,jenkinsci/kubernetes-plugin,jenkinsci/kubernetes-plugin
|
/*
* The MIT License
*
* Copyright (c) 2016, Carlos Sanchez
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.csanchez.jenkins.plugins.kubernetes.pipeline;
import static org.csanchez.jenkins.plugins.kubernetes.KubernetesTestUtil.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.junit.Assume.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import hudson.model.Computer;
import com.gargoylesoftware.htmlunit.html.DomNodeUtil;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.slaves.SlaveComputer;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodList;
import io.fabric8.kubernetes.client.KubernetesClientException;
import jenkins.model.Jenkins;
import org.csanchez.jenkins.plugins.kubernetes.KubernetesSlave;
import org.csanchez.jenkins.plugins.kubernetes.PodAnnotation;
import org.csanchez.jenkins.plugins.kubernetes.PodTemplate;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution;
import org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRuleNonLocalhost;
import org.jvnet.hudson.test.LoggerRule;
import hudson.model.Result;
import java.util.Locale;
import org.jenkinsci.plugins.workflow.flow.FlowDurabilityHint;
import org.jenkinsci.plugins.workflow.flow.GlobalDefaultFlowDurabilityLevel;
import org.junit.Ignore;
import org.jvnet.hudson.test.MockAuthorizationStrategy;
public class KubernetesPipelineTest extends AbstractKubernetesPipelineTest {
private static final Logger LOGGER = Logger.getLogger(KubernetesPipelineTest.class.getName());
@Rule
public TemporaryFolder tmp = new TemporaryFolder();
@Rule
public LoggerRule warnings = new LoggerRule();
@Before
public void setUp() throws Exception {
// Had some problems with FileChannel.close hangs from WorkflowRun.save:
r.jenkins.getDescriptorByType(GlobalDefaultFlowDurabilityLevel.DescriptorImpl.class).setDurabilityHint(FlowDurabilityHint.PERFORMANCE_OPTIMIZED);
deletePods(cloud.connect(), getLabels(cloud, this, name), false);
warnings.record("", Level.WARNING).capture(1000);
assertNotNull(createJobThenScheduleRun());
}
/**
* Ensure all builds are complete by the end of the test.
*/
@After
public void allDead() throws Exception {
if (b != null && b.isLogUpdated()) {
LOGGER.warning(() -> "Had to interrupt " + b);
b.getExecutor().interrupt();
}
for (int i = 0; i < 100 && r.isSomethingHappening(); i++) {
Thread.sleep(100);
}
}
@Issue("JENKINS-57993")
@Test
public void runInPod() throws Exception {
SemaphoreStep.waitForStart("podTemplate/1", b);
List<PodTemplate> templates = podTemplatesWithLabel(name.getMethodName(), cloud.getAllTemplates());
assertThat(templates, hasSize(1));
SemaphoreStep.success("podTemplate/1", null);
// check if build failed
assertTrue("Build has failed early: " + b.getResult(), b.isBuilding() || Result.SUCCESS.equals(b.getResult()));
LOGGER.log(Level.INFO, "Found templates with label runInPod: {0}", templates);
for (PodTemplate template : cloud.getAllTemplates()) {
LOGGER.log(Level.INFO, "Cloud template \"{0}\" labels: {1}",
new Object[] { template.getName(), template.getLabelSet() });
}
Map<String, String> labels = getLabels(cloud, this, name);
SemaphoreStep.waitForStart("pod/1", b);
for (Computer c : r.jenkins.getComputers()) { // TODO perhaps this should be built into JenkinsRule via ComputerListener.preLaunch?
new Thread(() -> {
long pos = 0;
try {
while (Jenkins.getInstanceOrNull() != null) { // otherwise get NPE from Computer.getLogDir
if (c.getLogFile().isFile()) { // TODO should LargeText.FileSession handle this?
pos = c.getLogText().writeLogTo(pos, System.out);
}
Thread.sleep(100);
}
} catch (Exception x) {
x.printStackTrace();
}
}, "watching logs for " + c.getDisplayName()).start();
System.out.println(c.getLog());
}
PodList pods = cloud.connect().pods().withLabels(labels).list();
assertThat(
"Expected one pod with labels " + labels + " but got: "
+ pods.getItems().stream().map(pod -> pod.getMetadata()).collect(Collectors.toList()),
pods.getItems(), hasSize(1));
SemaphoreStep.success("pod/1", null);
PodTemplate template = templates.get(0);
List<PodAnnotation> annotations = template.getAnnotations();
assertNotNull(annotations);
boolean foundBuildUrl=false;
for(PodAnnotation pd : annotations)
{
if(pd.getKey().equals("buildUrl"))
{
assertTrue(pd.getValue().contains(p.getUrl()));
foundBuildUrl=true;
}
}
assertTrue(foundBuildUrl);
assertEquals(Integer.MAX_VALUE, template.getInstanceCap());
assertThat(template.getLabelsMap(), hasEntry("jenkins/" + name.getMethodName(), "true"));
Pod pod = pods.getItems().get(0);
LOGGER.log(Level.INFO, "One pod found: {0}", pod);
assertThat(pod.getMetadata().getLabels(), hasEntry("jenkins", "slave"));
assertThat("Pod labels are wrong: " + pod, pod.getMetadata().getLabels(), hasEntry("jenkins/" + name.getMethodName(), "true"));
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("script file contents: ", b);
assertFalse("There are pods leftover after test execution, see previous logs",
deletePods(cloud.connect(), getLabels(cloud, this, name), true));
assertThat("routine build should not issue warnings",
warnings.getRecords().stream().
filter(lr -> lr.getLevel().intValue() >= Level.WARNING.intValue()). // TODO .record(…, WARNING) does not accomplish this
map(lr -> lr.getSourceClassName() + "." + lr.getSourceMethodName() + ": " + lr.getMessage()).collect(Collectors.toList()), // LogRecord does not override toString
emptyIterable());
}
@Test
public void runIn2Pods() throws Exception {
SemaphoreStep.waitForStart("podTemplate1/1", b);
String label1 = name.getMethodName() + "-1";
PodTemplate template1 = podTemplatesWithLabel(label1, cloud.getAllTemplates()).get(0);
SemaphoreStep.success("podTemplate1/1", null);
assertEquals(Integer.MAX_VALUE, template1.getInstanceCap());
assertThat(template1.getLabelsMap(), hasEntry("jenkins/" + label1, "true"));
SemaphoreStep.waitForStart("pod1/1", b);
Map<String, String> labels1 = getLabels(cloud, this, name);
labels1.put("jenkins/"+label1, "true");
PodList pods = cloud.connect().pods().withLabels(labels1).list();
assertTrue(!pods.getItems().isEmpty());
SemaphoreStep.success("pod1/1", null);
SemaphoreStep.waitForStart("podTemplate2/1", b);
String label2 = name.getMethodName() + "-2";
PodTemplate template2 = podTemplatesWithLabel(label2, cloud.getAllTemplates()).get(0);
SemaphoreStep.success("podTemplate2/1", null);
assertEquals(Integer.MAX_VALUE, template2.getInstanceCap());
assertThat(template2.getLabelsMap(), hasEntry("jenkins/" + label2, "true"));
assertNull(label2 + " should not inherit from anything", template2.getInheritFrom());
SemaphoreStep.waitForStart("pod2/1", b);
Map<String, String> labels2 = getLabels(cloud, this, name);
labels1.put("jenkins/" + label2, "true");
PodList pods2 = cloud.connect().pods().withLabels(labels2).list();
assertTrue(!pods2.getItems().isEmpty());
SemaphoreStep.success("pod2/1", null);
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("script file contents: ", b);
assertFalse("There are pods leftover after test execution, see previous logs",
deletePods(cloud.connect(), getLabels(cloud, this, name), true));
}
private List<PodTemplate> podTemplatesWithLabel(String label, List<PodTemplate> templates) {
return templates.stream().filter(t -> label.equals(t.getLabel())).collect(Collectors.toList());
}
@Issue("JENKINS-57893")
@Test
public void runInPodFromYaml() throws Exception {
List<PodTemplate> templates = cloud.getTemplates();
while (templates.isEmpty()) {
LOGGER.log(Level.INFO, "Waiting for template to be created");
templates = cloud.getTemplates();
Thread.sleep(1000);
}
assertFalse(templates.isEmpty());
PodTemplate template = templates.get(0);
assertEquals(Integer.MAX_VALUE, template.getInstanceCap());
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("script file contents: ", b);
r.assertLogNotContains(CONTAINER_ENV_VAR_FROM_SECRET_VALUE, b);
r.assertLogContains("INSIDE_CONTAINER_ENV_VAR_FROM_SECRET = ******** or " + CONTAINER_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b);
assertFalse("There are pods leftover after test execution, see previous logs",
deletePods(cloud.connect(), getLabels(cloud, this, name), true));
}
@Test
public void runInPodWithDifferentShell() throws Exception {
r.assertBuildStatus(Result.FAILURE,r.waitForCompletion(b));
/* TODO instead the program fails with a IOException: Pipe closed from ContainerExecDecorator.doExec:
r.assertLogContains("/bin/bash: no such file or directory", b);
*/
}
@Test
public void bourneShellElsewhereInPath() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("/kaniko:/busybox", b);
}
@Test
public void runInPodWithMultipleContainers() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("image: \"jenkins/jnlp-slave:3.35-5-alpine\"", b);
r.assertLogContains("image: \"maven:3.3.9-jdk-8-alpine\"", b);
r.assertLogContains("image: \"golang:1.6.3-alpine\"", b);
r.assertLogContains("My Kubernetes Pipeline", b);
r.assertLogContains("my-mount", b);
r.assertLogContains("Apache Maven 3.3.9", b);
}
@Test
public void runInPodNested() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("image: \"maven:3.3.9-jdk-8-alpine\"", b);
r.assertLogContains("image: \"golang:1.6.3-alpine\"", b);
r.assertLogContains("Apache Maven 3.3.9", b);
r.assertLogContains("go version go1.6.3", b);
}
@Issue("JENKINS-57548")
@Test
public void runInPodNestedExplicitInherit() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("image: \"maven:3.3.9-jdk-8-alpine\"", b);
r.assertLogNotContains("image: \"golang:1.6.3-alpine\"", b);
r.assertLogContains("Apache Maven 3.3.9", b);
r.assertLogNotContains("go version go1.6.3", b);
}
@Issue({"JENKINS-57893", "JENKINS-58540"})
@Test
public void runInPodWithExistingTemplate() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("outside container", b);
r.assertLogContains("inside container", b);
assertEnvVars(r, b);
}
@Issue({"JENKINS-57893", "JENKINS-58540"})
@Test
public void runWithEnvVariables() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
assertEnvVars(r, b);
r.assertLogContains("OUTSIDE_CONTAINER_BUILD_NUMBER = 1\n", b);
r.assertLogContains("INSIDE_CONTAINER_BUILD_NUMBER = 1\n", b);
r.assertLogContains("OUTSIDE_CONTAINER_JOB_NAME = " + getProjectName() + "\n", b);
r.assertLogContains("INSIDE_CONTAINER_JOB_NAME = " + getProjectName() +"\n", b);
// check that we are getting the correct java home
r.assertLogContains("INSIDE_JAVA_HOME =\n", b);
r.assertLogContains("JNLP_JAVA_HOME = /usr/lib/jvm/java-1.8-openjdk\n", b);
r.assertLogContains("JAVA7_HOME = /usr/lib/jvm/java-1.7-openjdk/jre\n", b);
r.assertLogContains("JAVA8_HOME = /usr/lib/jvm/java-1.8-openjdk/jre\n", b);
// check that we are not filtering too much
r.assertLogContains("INSIDE_JAVA_HOME_X = java-home-x\n", b);
r.assertLogContains("OUTSIDE_JAVA_HOME_X = java-home-x\n", b);
r.assertLogContains("JNLP_JAVA_HOME_X = java-home-x\n", b);
r.assertLogContains("JAVA7_HOME_X = java-home-x\n", b);
r.assertLogContains("JAVA8_HOME_X = java-home-x\n", b);
}
@Test
public void runWithEnvVariablesInContext() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("The initial value of POD_ENV_VAR is pod-env-var-value", b);
r.assertLogContains("The value of POD_ENV_VAR outside container is /bin/mvn:pod-env-var-value", b);
r.assertLogContains("The value of FROM_ENV_DEFINITION is ABC", b);
r.assertLogContains("The value of FROM_WITHENV_DEFINITION is DEF", b);
r.assertLogContains("The value of WITH_QUOTE is \"WITH_QUOTE", b);
r.assertLogContains("The value of AFTER_QUOTE is AFTER_QUOTE\"", b);
r.assertLogContains("The value of ESCAPED_QUOTE is \\\"ESCAPED_QUOTE", b);
r.assertLogContains("The value of AFTER_ESCAPED_QUOTE is AFTER_ESCAPED_QUOTE\\\"", b);
r.assertLogContains("The value of SINGLE_QUOTE is BEFORE'AFTER", b);
r.assertLogContains("The value of WITH_NEWLINE is before newline\nafter newline", b);
r.assertLogContains("The value of POD_ENV_VAR is /bin/mvn:pod-env-var-value", b);
r.assertLogContains("The value of WILL.NOT is ", b);
}
private void assertEnvVars(JenkinsRuleNonLocalhost r2, WorkflowRun b) throws Exception {
r.assertLogNotContains(POD_ENV_VAR_FROM_SECRET_VALUE, b);
r.assertLogNotContains(CONTAINER_ENV_VAR_FROM_SECRET_VALUE, b);
r.assertLogContains("INSIDE_CONTAINER_ENV_VAR = " + CONTAINER_ENV_VAR_VALUE + "\n", b);
r.assertLogContains("INSIDE_CONTAINER_ENV_VAR_LEGACY = " + CONTAINER_ENV_VAR_VALUE + "\n", b);
r.assertLogContains("INSIDE_CONTAINER_ENV_VAR_FROM_SECRET = ******** or " + CONTAINER_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b);
r.assertLogContains("INSIDE_POD_ENV_VAR = " + POD_ENV_VAR_VALUE + "\n", b);
r.assertLogContains("INSIDE_POD_ENV_VAR_FROM_SECRET = ******** or " + POD_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b);
r.assertLogContains("INSIDE_EMPTY_POD_ENV_VAR_FROM_SECRET = ''", b);
r.assertLogContains("INSIDE_GLOBAL = " + GLOBAL + "\n", b);
r.assertLogContains("OUTSIDE_CONTAINER_ENV_VAR =\n", b);
r.assertLogContains("OUTSIDE_CONTAINER_ENV_VAR_LEGACY =\n", b);
r.assertLogContains("OUTSIDE_CONTAINER_ENV_VAR_FROM_SECRET = or\n", b);
r.assertLogContains("OUTSIDE_POD_ENV_VAR = " + POD_ENV_VAR_VALUE + "\n", b);
r.assertLogContains("OUTSIDE_POD_ENV_VAR_FROM_SECRET = ******** or " + POD_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b);
r.assertLogContains("OUTSIDE_EMPTY_POD_ENV_VAR_FROM_SECRET = ''", b);
r.assertLogContains("OUTSIDE_GLOBAL = " + GLOBAL + "\n", b);
}
@Test
public void runWithOverriddenEnvVariables() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("OUTSIDE_CONTAINER_HOME_ENV_VAR = /home/jenkins\n", b);
r.assertLogContains("INSIDE_CONTAINER_HOME_ENV_VAR = /root\n",b);
r.assertLogContains("OUTSIDE_CONTAINER_POD_ENV_VAR = " + POD_ENV_VAR_VALUE + "\n", b);
r.assertLogContains("INSIDE_CONTAINER_POD_ENV_VAR = " + CONTAINER_ENV_VAR_VALUE + "\n",b);
}
@Test
public void supportComputerEnvVars() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("OPENJDK_BUILD_NUMBER: 1\n", b);
r.assertLogContains("JNLP_BUILD_NUMBER: 1\n", b);
r.assertLogContains("DEFAULT_BUILD_NUMBER: 1\n", b);
}
@Test
public void runDirContext() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
String workspace = "/home/jenkins/agent/workspace/" + getProjectName();
r.assertLogContains("initpwd is -" + workspace + "-", b);
r.assertLogContains("dirpwd is -" + workspace + "/hz-", b);
r.assertLogContains("postpwd is -" + workspace + "-", b);
}
@Test
public void runInPodWithLivenessProbe() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("Still alive", b);
}
@Test
public void runWithActiveDeadlineSeconds() throws Exception {
SemaphoreStep.waitForStart("podTemplate/1", b);
PodTemplate deadlineTemplate = cloud.getAllTemplates().stream().filter(x -> name.getMethodName().equals(x.getLabel())).findAny().orElse(null);
assertNotNull(deadlineTemplate);
SemaphoreStep.success("podTemplate/1", null);
assertEquals(10, deadlineTemplate.getActiveDeadlineSeconds());
b.getExecutor().interrupt();
r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b));
}
@Test
public void runInPodWithRetention() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
assertTrue(deletePods(cloud.connect(), getLabels(this, name), true));
}
@Issue("JENKINS-49707")
@Test
public void terminatedPod() throws Exception {
r.waitForMessage("+ sleep", b);
deletePods(cloud.connect(), getLabels(this, name), false);
r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b));
r.waitForMessage(new ExecutorStepExecution.RemovedNodeCause().getShortDescription(), b);
}
@Test
public void interruptedPod() throws Exception {
r.waitForMessage("starting to sleep", b);
b.getExecutor().interrupt();
r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b));
r.assertLogContains("shut down gracefully", b);
}
@Issue("JENKINS-58306")
@Test
public void cascadingDelete() throws Exception {
try {
cloud.connect().apps().deployments().withName("cascading-delete").delete();
} catch (KubernetesClientException x) {
// Failure executing: DELETE at: https://…/apis/apps/v1/namespaces/kubernetes-plugin-test/deployments/cascading-delete. Message: Forbidden!Configured service account doesn't have access. Service account may have been revoked. deployments.apps "cascading-delete" is forbidden: User "system:serviceaccount:…:…" cannot delete resource "deployments" in API group "apps" in the namespace "kubernetes-plugin-test".
assumeNoException("was not permitted to clean up any previous deployment, so presumably cannot run test either", x);
}
cloud.connect().apps().replicaSets().withLabel("app", "cascading-delete").delete();
cloud.connect().pods().withLabel("app", "cascading-delete").delete();
r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
@Test
public void computerCantBeConfigured() throws Exception {
r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().
grant(Jenkins.ADMINISTER).everywhere().to("admin"));
SemaphoreStep.waitForStart("pod/1", b);
Optional<KubernetesSlave> optionalNode = r.jenkins.getNodes().stream().filter(KubernetesSlave.class::isInstance).map(KubernetesSlave.class::cast).findAny();
assertTrue(optionalNode.isPresent());
KubernetesSlave node = optionalNode.get();
JenkinsRule.WebClient wc = r.createWebClient().login("admin");
wc.getOptions().setPrintContentOnFailingStatusCode(false);
HtmlPage nodeIndex = wc.getPage(node);
assertNotXPath(nodeIndex, "//*[text() = 'configure']");
wc.assertFails(node.toComputer().getUrl()+"configure", 403);
SemaphoreStep.success("pod/1", null);
}
private void assertNotXPath(HtmlPage page, String xpath) {
HtmlElement documentElement = page.getDocumentElement();
assertNull("There should not be an object that matches XPath:" + xpath, DomNodeUtil.selectSingleNode(documentElement, xpath));
}
@Issue("JENKINS-57717")
@Test
public void runInPodWithShowRawYamlFalse() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogNotContains("value: \"container-env-var-value\"", b);
}
@Issue("JENKINS-58574")
@Test
public void showRawYamlFalseInherited() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogNotContains("value: \"container-env-var-value\"", b);
}
@Test
@Issue("JENKINS-58405")
public void overrideYaml() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
@Test
@Issue("JENKINS-58405")
public void mergeYaml() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
@Test
@Issue("JENKINS-58602")
public void jenkinsSecretHidden() throws Exception {
SemaphoreStep.waitForStart("pod/1", b);
Optional<SlaveComputer> scOptional = Arrays.stream(r.jenkins.getComputers())
.filter(SlaveComputer.class::isInstance)
.map(SlaveComputer.class::cast)
.findAny();
assertTrue(scOptional.isPresent());
String jnlpMac = scOptional.get().getJnlpMac();
SemaphoreStep.success("pod/1", b);
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogNotContains(jnlpMac, b);
}
@Test
public void jnlpWorkingDir() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
@Issue("JENKINS-57256")
@Test
public void basicWindows() throws Exception {
assumeWindows();
cloud.setDirectConnection(false); // not yet supported by https://github.com/jenkinsci/docker-jnlp-slave/blob/517ccd68fd1ce420e7526ca6a40320c9a47a2c18/jenkins-agent.ps1
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("Directory of C:\\home\\jenkins\\agent\\workspace\\basic Windows", b); // bat
r.assertLogContains("C:\\Program Files (x86)", b); // powershell
}
@Issue("JENKINS-53500")
@Test
public void windowsContainer() throws Exception {
assumeWindows();
cloud.setDirectConnection(false);
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("Directory of C:\\home\\jenkins\\agent\\workspace\\windows Container\\subdir", b);
r.assertLogContains("C:\\Users\\ContainerAdministrator", b);
r.assertLogContains("got stuff: some value", b);
}
@Ignore("TODO aborts, but with “kill finished with exit code 9009” and “After 20s process did not stop” and no graceful shutdown")
@Test
public void interruptedPodWindows() throws Exception {
assumeWindows();
cloud.setDirectConnection(false);
r.waitForMessage("starting to sleep", b);
b.getExecutor().interrupt();
r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b));
r.assertLogContains("shut down gracefully", b);
}
@Test
public void secretMaskingWindows() throws Exception {
assumeWindows();
cloud.setDirectConnection(false);
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("INSIDE_POD_ENV_VAR_FROM_SECRET = ******** or " + POD_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT), b);
r.assertLogContains("INSIDE_CONTAINER_ENV_VAR_FROM_SECRET = ******** or " + CONTAINER_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT), b);
r.assertLogNotContains(POD_ENV_VAR_FROM_SECRET_VALUE, b);
r.assertLogNotContains(CONTAINER_ENV_VAR_FROM_SECRET_VALUE, b);
}
@Test
public void dynamicPVC() throws Exception {
try {
cloud.connect().persistentVolumeClaims().list();
} catch (KubernetesClientException x) {
// Error from server (Forbidden): persistentvolumeclaims is forbidden: User "system:serviceaccount:kubernetes-plugin-test:default" cannot list resource "persistentvolumeclaims" in API group "" in the namespace "kubernetes-plugin-test"
assumeNoException("was not permitted to list pvcs, so presumably cannot run test either", x);
}
r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
}
|
src/test/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/KubernetesPipelineTest.java
|
/*
* The MIT License
*
* Copyright (c) 2016, Carlos Sanchez
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.csanchez.jenkins.plugins.kubernetes.pipeline;
import static org.csanchez.jenkins.plugins.kubernetes.KubernetesTestUtil.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.junit.Assume.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import hudson.model.Computer;
import com.gargoylesoftware.htmlunit.html.DomNodeUtil;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.slaves.SlaveComputer;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodList;
import io.fabric8.kubernetes.client.KubernetesClientException;
import jenkins.model.Jenkins;
import org.csanchez.jenkins.plugins.kubernetes.KubernetesSlave;
import org.csanchez.jenkins.plugins.kubernetes.PodAnnotation;
import org.csanchez.jenkins.plugins.kubernetes.PodTemplate;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution;
import org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRuleNonLocalhost;
import org.jvnet.hudson.test.LoggerRule;
import hudson.model.Result;
import java.util.Locale;
import org.jenkinsci.plugins.workflow.flow.FlowDurabilityHint;
import org.jenkinsci.plugins.workflow.flow.GlobalDefaultFlowDurabilityLevel;
import org.junit.Ignore;
import org.jvnet.hudson.test.MockAuthorizationStrategy;
public class KubernetesPipelineTest extends AbstractKubernetesPipelineTest {
private static final Logger LOGGER = Logger.getLogger(KubernetesPipelineTest.class.getName());
@Rule
public TemporaryFolder tmp = new TemporaryFolder();
@Rule
public LoggerRule warnings = new LoggerRule();
@Before
public void setUp() throws Exception {
// Had some problems with FileChannel.close hangs from WorkflowRun.save:
r.jenkins.getDescriptorByType(GlobalDefaultFlowDurabilityLevel.DescriptorImpl.class).setDurabilityHint(FlowDurabilityHint.PERFORMANCE_OPTIMIZED);
deletePods(cloud.connect(), getLabels(cloud, this, name), false);
warnings.record("", Level.WARNING).capture(1000);
assertNotNull(createJobThenScheduleRun());
}
/**
* Ensure all builds are complete by the end of the test.
*/
@After
public void allDead() throws Exception {
if (b != null && b.isLogUpdated()) {
LOGGER.warning(() -> "Had to interrupt " + b);
b.getExecutor().interrupt();
}
r.waitUntilNoActivityUpTo(9999);
}
@Issue("JENKINS-57993")
@Test
public void runInPod() throws Exception {
SemaphoreStep.waitForStart("podTemplate/1", b);
List<PodTemplate> templates = podTemplatesWithLabel(name.getMethodName(), cloud.getAllTemplates());
assertThat(templates, hasSize(1));
SemaphoreStep.success("podTemplate/1", null);
// check if build failed
assertTrue("Build has failed early: " + b.getResult(), b.isBuilding() || Result.SUCCESS.equals(b.getResult()));
LOGGER.log(Level.INFO, "Found templates with label runInPod: {0}", templates);
for (PodTemplate template : cloud.getAllTemplates()) {
LOGGER.log(Level.INFO, "Cloud template \"{0}\" labels: {1}",
new Object[] { template.getName(), template.getLabelSet() });
}
Map<String, String> labels = getLabels(cloud, this, name);
SemaphoreStep.waitForStart("pod/1", b);
for (Computer c : r.jenkins.getComputers()) { // TODO perhaps this should be built into JenkinsRule via ComputerListener.preLaunch?
new Thread(() -> {
long pos = 0;
try {
while (Jenkins.getInstanceOrNull() != null) { // otherwise get NPE from Computer.getLogDir
if (c.getLogFile().isFile()) { // TODO should LargeText.FileSession handle this?
pos = c.getLogText().writeLogTo(pos, System.out);
}
Thread.sleep(100);
}
} catch (Exception x) {
x.printStackTrace();
}
}, "watching logs for " + c.getDisplayName()).start();
System.out.println(c.getLog());
}
PodList pods = cloud.connect().pods().withLabels(labels).list();
assertThat(
"Expected one pod with labels " + labels + " but got: "
+ pods.getItems().stream().map(pod -> pod.getMetadata()).collect(Collectors.toList()),
pods.getItems(), hasSize(1));
SemaphoreStep.success("pod/1", null);
PodTemplate template = templates.get(0);
List<PodAnnotation> annotations = template.getAnnotations();
assertNotNull(annotations);
boolean foundBuildUrl=false;
for(PodAnnotation pd : annotations)
{
if(pd.getKey().equals("buildUrl"))
{
assertTrue(pd.getValue().contains(p.getUrl()));
foundBuildUrl=true;
}
}
assertTrue(foundBuildUrl);
assertEquals(Integer.MAX_VALUE, template.getInstanceCap());
assertThat(template.getLabelsMap(), hasEntry("jenkins/" + name.getMethodName(), "true"));
Pod pod = pods.getItems().get(0);
LOGGER.log(Level.INFO, "One pod found: {0}", pod);
assertThat(pod.getMetadata().getLabels(), hasEntry("jenkins", "slave"));
assertThat("Pod labels are wrong: " + pod, pod.getMetadata().getLabels(), hasEntry("jenkins/" + name.getMethodName(), "true"));
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("script file contents: ", b);
assertFalse("There are pods leftover after test execution, see previous logs",
deletePods(cloud.connect(), getLabels(cloud, this, name), true));
assertThat("routine build should not issue warnings",
warnings.getRecords().stream().
filter(lr -> lr.getLevel().intValue() >= Level.WARNING.intValue()). // TODO .record(…, WARNING) does not accomplish this
map(lr -> lr.getSourceClassName() + "." + lr.getSourceMethodName() + ": " + lr.getMessage()).collect(Collectors.toList()), // LogRecord does not override toString
emptyIterable());
}
@Test
public void runIn2Pods() throws Exception {
SemaphoreStep.waitForStart("podTemplate1/1", b);
String label1 = name.getMethodName() + "-1";
PodTemplate template1 = podTemplatesWithLabel(label1, cloud.getAllTemplates()).get(0);
SemaphoreStep.success("podTemplate1/1", null);
assertEquals(Integer.MAX_VALUE, template1.getInstanceCap());
assertThat(template1.getLabelsMap(), hasEntry("jenkins/" + label1, "true"));
SemaphoreStep.waitForStart("pod1/1", b);
Map<String, String> labels1 = getLabels(cloud, this, name);
labels1.put("jenkins/"+label1, "true");
PodList pods = cloud.connect().pods().withLabels(labels1).list();
assertTrue(!pods.getItems().isEmpty());
SemaphoreStep.success("pod1/1", null);
SemaphoreStep.waitForStart("podTemplate2/1", b);
String label2 = name.getMethodName() + "-2";
PodTemplate template2 = podTemplatesWithLabel(label2, cloud.getAllTemplates()).get(0);
SemaphoreStep.success("podTemplate2/1", null);
assertEquals(Integer.MAX_VALUE, template2.getInstanceCap());
assertThat(template2.getLabelsMap(), hasEntry("jenkins/" + label2, "true"));
assertNull(label2 + " should not inherit from anything", template2.getInheritFrom());
SemaphoreStep.waitForStart("pod2/1", b);
Map<String, String> labels2 = getLabels(cloud, this, name);
labels1.put("jenkins/" + label2, "true");
PodList pods2 = cloud.connect().pods().withLabels(labels2).list();
assertTrue(!pods2.getItems().isEmpty());
SemaphoreStep.success("pod2/1", null);
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("script file contents: ", b);
assertFalse("There are pods leftover after test execution, see previous logs",
deletePods(cloud.connect(), getLabels(cloud, this, name), true));
}
private List<PodTemplate> podTemplatesWithLabel(String label, List<PodTemplate> templates) {
return templates.stream().filter(t -> label.equals(t.getLabel())).collect(Collectors.toList());
}
@Issue("JENKINS-57893")
@Test
public void runInPodFromYaml() throws Exception {
List<PodTemplate> templates = cloud.getTemplates();
while (templates.isEmpty()) {
LOGGER.log(Level.INFO, "Waiting for template to be created");
templates = cloud.getTemplates();
Thread.sleep(1000);
}
assertFalse(templates.isEmpty());
PodTemplate template = templates.get(0);
assertEquals(Integer.MAX_VALUE, template.getInstanceCap());
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("script file contents: ", b);
r.assertLogNotContains(CONTAINER_ENV_VAR_FROM_SECRET_VALUE, b);
r.assertLogContains("INSIDE_CONTAINER_ENV_VAR_FROM_SECRET = ******** or " + CONTAINER_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b);
assertFalse("There are pods leftover after test execution, see previous logs",
deletePods(cloud.connect(), getLabels(cloud, this, name), true));
}
@Test
public void runInPodWithDifferentShell() throws Exception {
r.assertBuildStatus(Result.FAILURE,r.waitForCompletion(b));
/* TODO instead the program fails with a IOException: Pipe closed from ContainerExecDecorator.doExec:
r.assertLogContains("/bin/bash: no such file or directory", b);
*/
}
@Test
public void bourneShellElsewhereInPath() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("/kaniko:/busybox", b);
}
@Test
public void runInPodWithMultipleContainers() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("image: \"jenkins/jnlp-slave:3.35-5-alpine\"", b);
r.assertLogContains("image: \"maven:3.3.9-jdk-8-alpine\"", b);
r.assertLogContains("image: \"golang:1.6.3-alpine\"", b);
r.assertLogContains("My Kubernetes Pipeline", b);
r.assertLogContains("my-mount", b);
r.assertLogContains("Apache Maven 3.3.9", b);
}
@Test
public void runInPodNested() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("image: \"maven:3.3.9-jdk-8-alpine\"", b);
r.assertLogContains("image: \"golang:1.6.3-alpine\"", b);
r.assertLogContains("Apache Maven 3.3.9", b);
r.assertLogContains("go version go1.6.3", b);
}
@Issue("JENKINS-57548")
@Test
public void runInPodNestedExplicitInherit() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("image: \"maven:3.3.9-jdk-8-alpine\"", b);
r.assertLogNotContains("image: \"golang:1.6.3-alpine\"", b);
r.assertLogContains("Apache Maven 3.3.9", b);
r.assertLogNotContains("go version go1.6.3", b);
}
@Issue({"JENKINS-57893", "JENKINS-58540"})
@Test
public void runInPodWithExistingTemplate() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("outside container", b);
r.assertLogContains("inside container", b);
assertEnvVars(r, b);
}
@Issue({"JENKINS-57893", "JENKINS-58540"})
@Test
public void runWithEnvVariables() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
assertEnvVars(r, b);
r.assertLogContains("OUTSIDE_CONTAINER_BUILD_NUMBER = 1\n", b);
r.assertLogContains("INSIDE_CONTAINER_BUILD_NUMBER = 1\n", b);
r.assertLogContains("OUTSIDE_CONTAINER_JOB_NAME = " + getProjectName() + "\n", b);
r.assertLogContains("INSIDE_CONTAINER_JOB_NAME = " + getProjectName() +"\n", b);
// check that we are getting the correct java home
r.assertLogContains("INSIDE_JAVA_HOME =\n", b);
r.assertLogContains("JNLP_JAVA_HOME = /usr/lib/jvm/java-1.8-openjdk\n", b);
r.assertLogContains("JAVA7_HOME = /usr/lib/jvm/java-1.7-openjdk/jre\n", b);
r.assertLogContains("JAVA8_HOME = /usr/lib/jvm/java-1.8-openjdk/jre\n", b);
// check that we are not filtering too much
r.assertLogContains("INSIDE_JAVA_HOME_X = java-home-x\n", b);
r.assertLogContains("OUTSIDE_JAVA_HOME_X = java-home-x\n", b);
r.assertLogContains("JNLP_JAVA_HOME_X = java-home-x\n", b);
r.assertLogContains("JAVA7_HOME_X = java-home-x\n", b);
r.assertLogContains("JAVA8_HOME_X = java-home-x\n", b);
}
@Test
public void runWithEnvVariablesInContext() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("The initial value of POD_ENV_VAR is pod-env-var-value", b);
r.assertLogContains("The value of POD_ENV_VAR outside container is /bin/mvn:pod-env-var-value", b);
r.assertLogContains("The value of FROM_ENV_DEFINITION is ABC", b);
r.assertLogContains("The value of FROM_WITHENV_DEFINITION is DEF", b);
r.assertLogContains("The value of WITH_QUOTE is \"WITH_QUOTE", b);
r.assertLogContains("The value of AFTER_QUOTE is AFTER_QUOTE\"", b);
r.assertLogContains("The value of ESCAPED_QUOTE is \\\"ESCAPED_QUOTE", b);
r.assertLogContains("The value of AFTER_ESCAPED_QUOTE is AFTER_ESCAPED_QUOTE\\\"", b);
r.assertLogContains("The value of SINGLE_QUOTE is BEFORE'AFTER", b);
r.assertLogContains("The value of WITH_NEWLINE is before newline\nafter newline", b);
r.assertLogContains("The value of POD_ENV_VAR is /bin/mvn:pod-env-var-value", b);
r.assertLogContains("The value of WILL.NOT is ", b);
}
private void assertEnvVars(JenkinsRuleNonLocalhost r2, WorkflowRun b) throws Exception {
r.assertLogNotContains(POD_ENV_VAR_FROM_SECRET_VALUE, b);
r.assertLogNotContains(CONTAINER_ENV_VAR_FROM_SECRET_VALUE, b);
r.assertLogContains("INSIDE_CONTAINER_ENV_VAR = " + CONTAINER_ENV_VAR_VALUE + "\n", b);
r.assertLogContains("INSIDE_CONTAINER_ENV_VAR_LEGACY = " + CONTAINER_ENV_VAR_VALUE + "\n", b);
r.assertLogContains("INSIDE_CONTAINER_ENV_VAR_FROM_SECRET = ******** or " + CONTAINER_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b);
r.assertLogContains("INSIDE_POD_ENV_VAR = " + POD_ENV_VAR_VALUE + "\n", b);
r.assertLogContains("INSIDE_POD_ENV_VAR_FROM_SECRET = ******** or " + POD_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b);
r.assertLogContains("INSIDE_EMPTY_POD_ENV_VAR_FROM_SECRET = ''", b);
r.assertLogContains("INSIDE_GLOBAL = " + GLOBAL + "\n", b);
r.assertLogContains("OUTSIDE_CONTAINER_ENV_VAR =\n", b);
r.assertLogContains("OUTSIDE_CONTAINER_ENV_VAR_LEGACY =\n", b);
r.assertLogContains("OUTSIDE_CONTAINER_ENV_VAR_FROM_SECRET = or\n", b);
r.assertLogContains("OUTSIDE_POD_ENV_VAR = " + POD_ENV_VAR_VALUE + "\n", b);
r.assertLogContains("OUTSIDE_POD_ENV_VAR_FROM_SECRET = ******** or " + POD_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b);
r.assertLogContains("OUTSIDE_EMPTY_POD_ENV_VAR_FROM_SECRET = ''", b);
r.assertLogContains("OUTSIDE_GLOBAL = " + GLOBAL + "\n", b);
}
@Test
public void runWithOverriddenEnvVariables() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("OUTSIDE_CONTAINER_HOME_ENV_VAR = /home/jenkins\n", b);
r.assertLogContains("INSIDE_CONTAINER_HOME_ENV_VAR = /root\n",b);
r.assertLogContains("OUTSIDE_CONTAINER_POD_ENV_VAR = " + POD_ENV_VAR_VALUE + "\n", b);
r.assertLogContains("INSIDE_CONTAINER_POD_ENV_VAR = " + CONTAINER_ENV_VAR_VALUE + "\n",b);
}
@Test
public void supportComputerEnvVars() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("OPENJDK_BUILD_NUMBER: 1\n", b);
r.assertLogContains("JNLP_BUILD_NUMBER: 1\n", b);
r.assertLogContains("DEFAULT_BUILD_NUMBER: 1\n", b);
}
@Test
public void runDirContext() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
String workspace = "/home/jenkins/agent/workspace/" + getProjectName();
r.assertLogContains("initpwd is -" + workspace + "-", b);
r.assertLogContains("dirpwd is -" + workspace + "/hz-", b);
r.assertLogContains("postpwd is -" + workspace + "-", b);
}
@Test
public void runInPodWithLivenessProbe() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("Still alive", b);
}
@Test
public void runWithActiveDeadlineSeconds() throws Exception {
SemaphoreStep.waitForStart("podTemplate/1", b);
PodTemplate deadlineTemplate = cloud.getAllTemplates().stream().filter(x -> name.getMethodName().equals(x.getLabel())).findAny().orElse(null);
assertNotNull(deadlineTemplate);
SemaphoreStep.success("podTemplate/1", null);
assertEquals(10, deadlineTemplate.getActiveDeadlineSeconds());
b.getExecutor().interrupt();
r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b));
}
@Test
public void runInPodWithRetention() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
assertTrue(deletePods(cloud.connect(), getLabels(this, name), true));
}
@Issue("JENKINS-49707")
@Test
public void terminatedPod() throws Exception {
r.waitForMessage("+ sleep", b);
deletePods(cloud.connect(), getLabels(this, name), false);
r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b));
r.waitForMessage(new ExecutorStepExecution.RemovedNodeCause().getShortDescription(), b);
}
@Test
public void interruptedPod() throws Exception {
r.waitForMessage("starting to sleep", b);
b.getExecutor().interrupt();
r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b));
r.assertLogContains("shut down gracefully", b);
}
@Issue("JENKINS-58306")
@Test
public void cascadingDelete() throws Exception {
try {
cloud.connect().apps().deployments().withName("cascading-delete").delete();
} catch (KubernetesClientException x) {
// Failure executing: DELETE at: https://…/apis/apps/v1/namespaces/kubernetes-plugin-test/deployments/cascading-delete. Message: Forbidden!Configured service account doesn't have access. Service account may have been revoked. deployments.apps "cascading-delete" is forbidden: User "system:serviceaccount:…:…" cannot delete resource "deployments" in API group "apps" in the namespace "kubernetes-plugin-test".
assumeNoException("was not permitted to clean up any previous deployment, so presumably cannot run test either", x);
}
cloud.connect().apps().replicaSets().withLabel("app", "cascading-delete").delete();
cloud.connect().pods().withLabel("app", "cascading-delete").delete();
r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
@Test
public void computerCantBeConfigured() throws Exception {
r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().
grant(Jenkins.ADMINISTER).everywhere().to("admin"));
SemaphoreStep.waitForStart("pod/1", b);
Optional<KubernetesSlave> optionalNode = r.jenkins.getNodes().stream().filter(KubernetesSlave.class::isInstance).map(KubernetesSlave.class::cast).findAny();
assertTrue(optionalNode.isPresent());
KubernetesSlave node = optionalNode.get();
JenkinsRule.WebClient wc = r.createWebClient().login("admin");
wc.getOptions().setPrintContentOnFailingStatusCode(false);
HtmlPage nodeIndex = wc.getPage(node);
assertNotXPath(nodeIndex, "//*[text() = 'configure']");
wc.assertFails(node.toComputer().getUrl()+"configure", 403);
SemaphoreStep.success("pod/1", null);
}
private void assertNotXPath(HtmlPage page, String xpath) {
HtmlElement documentElement = page.getDocumentElement();
assertNull("There should not be an object that matches XPath:" + xpath, DomNodeUtil.selectSingleNode(documentElement, xpath));
}
@Issue("JENKINS-57717")
@Test
public void runInPodWithShowRawYamlFalse() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogNotContains("value: \"container-env-var-value\"", b);
}
@Issue("JENKINS-58574")
@Test
public void showRawYamlFalseInherited() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogNotContains("value: \"container-env-var-value\"", b);
}
@Test
@Issue("JENKINS-58405")
public void overrideYaml() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
@Test
@Issue("JENKINS-58405")
public void mergeYaml() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
@Test
@Issue("JENKINS-58602")
public void jenkinsSecretHidden() throws Exception {
SemaphoreStep.waitForStart("pod/1", b);
Optional<SlaveComputer> scOptional = Arrays.stream(r.jenkins.getComputers())
.filter(SlaveComputer.class::isInstance)
.map(SlaveComputer.class::cast)
.findAny();
assertTrue(scOptional.isPresent());
String jnlpMac = scOptional.get().getJnlpMac();
SemaphoreStep.success("pod/1", b);
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogNotContains(jnlpMac, b);
}
@Test
public void jnlpWorkingDir() throws Exception {
r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
@Issue("JENKINS-57256")
@Test
public void basicWindows() throws Exception {
assumeWindows();
cloud.setDirectConnection(false); // not yet supported by https://github.com/jenkinsci/docker-jnlp-slave/blob/517ccd68fd1ce420e7526ca6a40320c9a47a2c18/jenkins-agent.ps1
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("Directory of C:\\home\\jenkins\\agent\\workspace\\basic Windows", b); // bat
r.assertLogContains("C:\\Program Files (x86)", b); // powershell
}
@Issue("JENKINS-53500")
@Test
public void windowsContainer() throws Exception {
assumeWindows();
cloud.setDirectConnection(false);
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("Directory of C:\\home\\jenkins\\agent\\workspace\\windows Container\\subdir", b);
r.assertLogContains("C:\\Users\\ContainerAdministrator", b);
r.assertLogContains("got stuff: some value", b);
}
@Ignore("TODO aborts, but with “kill finished with exit code 9009” and “After 20s process did not stop” and no graceful shutdown")
@Test
public void interruptedPodWindows() throws Exception {
assumeWindows();
cloud.setDirectConnection(false);
r.waitForMessage("starting to sleep", b);
b.getExecutor().interrupt();
r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b));
r.assertLogContains("shut down gracefully", b);
}
@Test
public void secretMaskingWindows() throws Exception {
assumeWindows();
cloud.setDirectConnection(false);
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("INSIDE_POD_ENV_VAR_FROM_SECRET = ******** or " + POD_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT), b);
r.assertLogContains("INSIDE_CONTAINER_ENV_VAR_FROM_SECRET = ******** or " + CONTAINER_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT), b);
r.assertLogNotContains(POD_ENV_VAR_FROM_SECRET_VALUE, b);
r.assertLogNotContains(CONTAINER_ENV_VAR_FROM_SECRET_VALUE, b);
}
@Test
public void dynamicPVC() throws Exception {
try {
cloud.connect().persistentVolumeClaims().list();
} catch (KubernetesClientException x) {
// Error from server (Forbidden): persistentvolumeclaims is forbidden: User "system:serviceaccount:kubernetes-plugin-test:default" cannot list resource "persistentvolumeclaims" in API group "" in the namespace "kubernetes-plugin-test"
assumeNoException("was not permitted to list pvcs, so presumably cannot run test either", x);
}
r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
}
|
CI fails in runWithActiveDeadlineSeconds though I cannot reproduce this locally, so wait up to 10s for executors/queue to clear, then give up without failing.
|
src/test/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/KubernetesPipelineTest.java
|
CI fails in runWithActiveDeadlineSeconds though I cannot reproduce this locally, so wait up to 10s for executors/queue to clear, then give up without failing.
|
<ide><path>rc/test/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/KubernetesPipelineTest.java
<ide> LOGGER.warning(() -> "Had to interrupt " + b);
<ide> b.getExecutor().interrupt();
<ide> }
<del> r.waitUntilNoActivityUpTo(9999);
<add> for (int i = 0; i < 100 && r.isSomethingHappening(); i++) {
<add> Thread.sleep(100);
<add> }
<ide> }
<ide>
<ide> @Issue("JENKINS-57993")
|
|
JavaScript
|
apache-2.0
|
908290fcf860d35a3bc2737c6b4637732aaab7c7
| 0 |
PolicyStat/combokeys
|
/* eslint-env node, browser, mocha */
/* eslint no-unused-expressions:0 */
'use strict'
/* global
Event
*/
require('es5-shim/es5-shim')
require('es5-shim/es5-sham')
var assert = require('proclaim')
var sinon = require('sinon')
var Combokeys = require('..')
var KeyEvent = require('./lib/key-event')
var makeElement = require('./helpers/make-element')
describe('initialization', function () {
it('initializes on the document', function () {
var combokeys = new Combokeys(document.documentElement)
assert.instanceOf(combokeys, Combokeys)
assert.strictEqual(combokeys.element, document.documentElement)
})
it('can initialize multipe instances', function () {
var first = makeElement()
var second = makeElement()
var firstCombokeys = new Combokeys(first)
var secondCombokeys = new Combokeys(second)
assert.instanceOf(secondCombokeys, Combokeys)
assert.notEqual(firstCombokeys, secondCombokeys)
assert.strictEqual(firstCombokeys.element, first)
assert.strictEqual(secondCombokeys.element, second)
})
})
describe('combokeys.bind', function () {
it('should work', function () {
var combokeys = new Combokeys(document.documentElement)
var spy = sinon.spy()
combokeys.bind('z', spy)
KeyEvent.simulate('Z'.charCodeAt(0), 90, null, document.documentElement)
assert.strictEqual(spy.callCount, 1)
})
describe('basic', function () {
it('z key fires when pressing z', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('z', spy)
KeyEvent.simulate('Z'.charCodeAt(0), 90, null, element)
// really slow for some reason
// assert(spy).to.have.been.calledOnce
assert.strictEqual(spy.callCount, 1, 'callback should fire once')
assert.instanceOf(spy.args[0][0], Event, 'first argument should be Event')
assert.strictEqual(spy.args[0][1], 'z', 'second argument should be key combo')
})
it('z key fires from keydown', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('z', spy, 'keydown')
KeyEvent.simulate('Z'.charCodeAt(0), 90, null, element)
// really slow for some reason
// assert(spy).to.have.been.calledOnce
assert.strictEqual(spy.callCount, 1, 'callback should fire once')
assert.instanceOf(spy.args[0][0], Event, 'first argument should be Event')
assert.strictEqual(spy.args[0][1], 'z', 'second argument should be key combo')
})
it('z key does not fire when pressing b', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('z', spy)
KeyEvent.simulate('B'.charCodeAt(0), 66, null, element)
assert.strictEqual(spy.callCount, 0)
})
it('z key does not fire when holding a modifier key', function () {
var element = makeElement()
var spy = sinon.spy()
var modifiers = ['ctrl', 'alt', 'meta', 'shift']
var charCode
var modifier
var combokeys = new Combokeys(element)
combokeys.bind('z', spy)
for (var i = 0; i < 4; i++) {
modifier = modifiers[i]
charCode = 'Z'.charCodeAt(0)
// character code is different when alt is pressed
if (modifier === 'alt') {
charCode = 'Ω'.charCodeAt(0)
}
spy.reset()
KeyEvent.simulate(charCode, 90, [modifier], element)
assert.strictEqual(spy.callCount, 0)
}
})
it('keyup events should fire', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('z', spy, 'keyup')
KeyEvent.simulate('Z'.charCodeAt(0), 90, null, element)
assert.strictEqual(spy.callCount, 1, 'keyup event for `z` should fire')
// for key held down we should only get one key up
KeyEvent.simulate('Z'.charCodeAt(0), 90, [], element, 10)
assert.strictEqual(spy.callCount, 2, 'keyup event for `z` should fire once for held down key')
})
it('keyup event for 0 should fire', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('0', spy, 'keyup')
KeyEvent.simulate(0, 48, null, element)
assert.strictEqual(spy.callCount, 1, 'keyup event for `0` should fire')
})
it('rebinding a key overwrites the callback for that key', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('x', spy1)
combokeys.bind('x', spy2)
KeyEvent.simulate('X'.charCodeAt(0), 88, null, element)
assert.strictEqual(spy1.callCount, 0, 'original callback should not fire')
assert.strictEqual(spy2.callCount, 1, 'new callback should fire')
})
it('binding an array of keys', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind(['a', 'b', 'c'], spy)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy.callCount, 1, 'new callback was called')
assert.strictEqual(spy.args[0][1], 'a', 'callback should match `a`')
KeyEvent.simulate('B'.charCodeAt(0), 66, null, element)
assert.strictEqual(spy.callCount, 2, 'new callback was called twice')
assert.strictEqual(spy.args[1][1], 'b', 'callback should match `b`')
KeyEvent.simulate('C'.charCodeAt(0), 67, null, element)
assert.strictEqual(spy.callCount, 3, 'new callback was called three times')
assert.strictEqual(spy.args[2][1], 'c', 'callback should match `c`')
})
it('return false should prevent default and stop propagation', function () {
var element = makeElement()
var spy = sinon.spy(function () {
return false
})
var combokeys = new Combokeys(element)
combokeys.bind('command+s', spy)
var stopPropagationSpy = sinon.spy(Event.prototype, 'stopPropagation')
KeyEvent.simulate('S'.charCodeAt(0), 83, ['meta'], element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
assert.instanceOf(spy.args[0][0], Event, 'first argument should be Event')
var event = spy.args[0][0]
if (event.preventDefault) {
assert.isTrue(event.defaultPrevented, 'default is prevented')
} else {
assert.isFalse(event.returnValue, 'default is prevented')
}
if (event.stopPropagation) {
assert.isTrue(stopPropagationSpy.calledOnce, 'propagation was cancelled')
} else {
assert.isTrue(event.cancelBubble, 'propagation is cancelled')
}
// try without return false
spy = sinon.spy()
combokeys.bind('command+s', spy)
KeyEvent.simulate('S'.charCodeAt(0), 83, ['meta'], element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
assert.instanceOf(spy.args[0][0], Event, 'first argument should be Event')
event = spy.args[0][0]
if (event.preventDefault) {
assert.isFalse(event.defaultPrevented, 'default is not prevented')
} else {
assert.isNotFalse(event.returnValue, 'default is not prevented')
}
if (event.stopPropagation) {
assert.isTrue(stopPropagationSpy.calledOnce, 'propagation was not cancelled')
} else {
assert.isFalse(event.cancelBubble, 'propagation is not cancelled')
}
})
it('capslock key is ignored', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a', spy)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire for lowercase a')
spy.reset()
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire for capslock A')
spy.reset()
KeyEvent.simulate('A'.charCodeAt(0), 65, ['shift'], element)
assert.strictEqual(spy.callCount, 0, 'callback should not fire fort shift+a')
})
})
describe('special characters', function () {
it('binding special characters', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('*', spy)
KeyEvent.simulate('*'.charCodeAt(0), 56, ['shift'], element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
assert.strictEqual(spy.args[0][1], '*', 'callback should match *')
})
it('binding special characters keyup', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('*', spy, 'keyup')
KeyEvent.simulate('*'.charCodeAt(0), 56, ['shift'], element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
assert.strictEqual(spy.args[0][1], '*', 'callback should match *')
})
it('binding keys with no associated charCode', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('left', spy)
KeyEvent.simulate(0, 37, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
assert.strictEqual(spy.args[0][1], 'left', 'callback should match `left`')
})
it('able to bind plus and minus', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('ctrl+minus', spy1)
combokeys.bind('ctrl+plus', spy2)
KeyEvent.simulate('-'.charCodeAt(0), 189, ['ctrl'], element)
assert.strictEqual(spy1.callCount, 1, '`ctrl+minus` should fire')
KeyEvent.simulate('+'.charCodeAt(0), 187, ['ctrl'], element)
assert.strictEqual(spy2.callCount, 1, '`ctrl+plus` should fire')
})
})
describe('combos with modifiers', function () {
it('binding key combinations', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('command+o', spy)
KeyEvent.simulate('O'.charCodeAt(0), 79, ['meta'], element)
assert.strictEqual(spy.callCount, 1, 'command+o callback should fire')
assert.strictEqual(spy.args[0][1], 'command+o', 'keyboard string returned is correct')
})
it('binding key combos with multiple modifiers', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('command+shift+o', spy)
KeyEvent.simulate('O'.charCodeAt(0), 79, ['meta'], element)
assert.strictEqual(spy.callCount, 0, 'command+o callback should not fire')
KeyEvent.simulate('O'.charCodeAt(0), 79, ['meta', 'shift'], element)
assert.strictEqual(spy.callCount, 1, 'command+o callback should fire')
})
})
describe('sequences', function () {
it('binding sequences', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('g i', spy)
KeyEvent.simulate('G'.charCodeAt(0), 71, null, element)
assert.strictEqual(spy.callCount, 0, 'callback should not fire')
KeyEvent.simulate('I'.charCodeAt(0), 73, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
})
it('binding sequences with mixed types', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('g o enter', spy)
KeyEvent.simulate('G'.charCodeAt(0), 71, null, element)
assert.strictEqual(spy.callCount, 0, 'callback should not fire')
KeyEvent.simulate('O'.charCodeAt(0), 79, null, element)
assert.strictEqual(spy.callCount, 0, 'callback should not fire')
KeyEvent.simulate(0, 13, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
})
it('binding sequences starting with modifier keys', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('option enter', spy)
KeyEvent.simulate(0, 18, ['alt'], element)
KeyEvent.simulate(0, 13, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
spy = sinon.spy()
combokeys.bind('command enter', spy)
KeyEvent.simulate(0, 91, ['meta'], element)
KeyEvent.simulate(0, 13, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
spy = sinon.spy()
combokeys.bind('escape enter', spy)
KeyEvent.simulate(0, 27, null, element)
KeyEvent.simulate(0, 13, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
})
it('key within sequence should not fire', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a', spy1)
combokeys.bind('c a t', spy2)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy1.callCount, 1, 'callback 1 should fire')
spy1.reset()
KeyEvent.simulate('C'.charCodeAt(0), 67, null, element)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('T'.charCodeAt(0), 84, null, element)
assert.strictEqual(spy1.callCount, 0, 'callback for `a` key should not fire')
assert.strictEqual(spy2.callCount, 1, 'callback for `c a t` sequence should fire')
})
it('keyup at end of sequence should not fire', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('t', spy1, 'keyup')
combokeys.bind('b a t', spy2)
KeyEvent.simulate('B'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('T'.charCodeAt(0), 84, null, element)
assert.strictEqual(spy1.callCount, 0, 'callback for `t` keyup should not fire')
assert.strictEqual(spy2.callCount, 1, 'callback for `b a t` sequence should fire')
})
it('keyup sequences should work', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('b a t', spy, 'keyup')
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
// hold the last key down for a while
KeyEvent.simulate('t'.charCodeAt(0), 84, [], element, 10)
assert.strictEqual(spy.callCount, 1, 'callback for `b a t` sequence should fire on keyup')
})
it('extra spaces in sequences should be ignored', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('b a t', spy)
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('t'.charCodeAt(0), 84, null, element)
assert.strictEqual(spy.callCount, 1, 'callback for `b a t` sequence should fire')
})
it('modifiers and sequences play nicely', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('ctrl a', spy1)
combokeys.bind('ctrl+b', spy2)
KeyEvent.simulate(0, 17, ['ctrl'], element)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy1.callCount, 1, '`ctrl a` should fire')
KeyEvent.simulate('B'.charCodeAt(0), 66, ['ctrl'], element)
assert.strictEqual(spy2.callCount, 1, '`ctrl+b` should fire')
})
it('sequences that start the same work', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('g g l', spy2)
combokeys.bind('g g o', spy1)
KeyEvent.simulate('g'.charCodeAt(0), 71, null, element)
KeyEvent.simulate('g'.charCodeAt(0), 71, null, element)
KeyEvent.simulate('o'.charCodeAt(0), 79, null, element)
assert.strictEqual(spy1.callCount, 1, '`g g o` should fire')
assert.strictEqual(spy2.callCount, 0, '`g g l` should not fire')
spy1.reset()
spy2.reset()
KeyEvent.simulate('g'.charCodeAt(0), 71, null, element)
KeyEvent.simulate('g'.charCodeAt(0), 71, null, element)
KeyEvent.simulate('l'.charCodeAt(0), 76, null, element)
assert.strictEqual(spy1.callCount, 0, '`g g o` should not fire')
assert.strictEqual(spy2.callCount, 1, '`g g l` should fire')
})
it('sequences should not fire subsequences', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a b c', spy1)
combokeys.bind('b c', spy2)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('B'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('C'.charCodeAt(0), 67, null, element)
assert.strictEqual(spy1.callCount, 1, '`a b c` should fire')
assert.strictEqual(spy2.callCount, 0, '`b c` should not fire')
spy1.reset()
spy2.reset()
combokeys.bind('option b', spy1)
combokeys.bind('a option b', spy2)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
KeyEvent.simulate(0, 18, ['alt'], element)
KeyEvent.simulate('B'.charCodeAt(0), 66, null, element)
assert.strictEqual(spy1.callCount, 0, '`option b` should not fire')
assert.strictEqual(spy2.callCount, 1, '`a option b` should fire')
})
it('rebinding same sequence should override previous', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a b c', spy1)
combokeys.bind('a b c', spy2)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('c'.charCodeAt(0), 67, null, element)
assert.strictEqual(spy1.callCount, 0, 'first callback should not fire')
assert.strictEqual(spy2.callCount, 1, 'second callback should fire')
})
it('broken sequences', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('h a t', spy)
KeyEvent.simulate('h'.charCodeAt(0), 72, null, element)
KeyEvent.simulate('e'.charCodeAt(0), 69, null, element)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('r'.charCodeAt(0), 82, null, element)
KeyEvent.simulate('t'.charCodeAt(0), 84, null, element)
assert.strictEqual(spy.callCount, 0, 'sequence for `h a t` should not fire for `h e a r t`')
})
it('sequences containing combos should work', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a ctrl+b', spy)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('B'.charCodeAt(0), 66, ['ctrl'], element)
assert.strictEqual(spy.callCount, 1, '`a ctrl+b` should fire')
combokeys.unbind('a ctrl+b')
spy = sinon.spy()
combokeys.bind('ctrl+b a', spy)
KeyEvent.simulate('b'.charCodeAt(0), 66, ['ctrl'], element)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy.callCount, 1, '`ctrl+b a` should fire')
})
it('sequences starting with spacebar should work', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a space b c', spy)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate(32, 32, null, element)
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('c'.charCodeAt(0), 67, null, element)
assert.strictEqual(spy.callCount, 1, '`a space b c` should fire')
})
it('konami code', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('up up down down left right left right b a enter', spy)
KeyEvent.simulate(0, 38, null, element)
KeyEvent.simulate(0, 38, null, element)
KeyEvent.simulate(0, 40, null, element)
KeyEvent.simulate(0, 40, null, element)
KeyEvent.simulate(0, 37, null, element)
KeyEvent.simulate(0, 39, null, element)
KeyEvent.simulate(0, 37, null, element)
KeyEvent.simulate(0, 39, null, element)
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate(0, 13, null, element)
assert.strictEqual(spy.callCount, 1, 'konami code should fire')
})
it('sequence timer resets', function () {
var element = makeElement()
var spy = sinon.spy()
var clock = sinon.useFakeTimers()
var combokeys = new Combokeys(element)
combokeys.bind('h a t', spy)
KeyEvent.simulate('h'.charCodeAt(0), 72, null, element)
clock.tick(600)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
clock.tick(900)
KeyEvent.simulate('t'.charCodeAt(0), 84, null, element)
assert.strictEqual(spy.callCount, 1, 'sequence should fire after waiting')
clock.restore()
})
it('sequences timeout', function () {
var element = makeElement()
var spy = sinon.spy()
var clock = sinon.useFakeTimers()
var combokeys = new Combokeys(element)
combokeys.bind('g t', spy)
KeyEvent.simulate('g'.charCodeAt(0), 71, null, element)
clock.tick(1000)
KeyEvent.simulate('t'.charCodeAt(0), 84, null, element)
assert.strictEqual(spy.callCount, 0, 'sequence callback should not fire')
clock.restore()
})
})
describe('default actions', function () {
var keys = {
keypress: [
['a', 65],
['A', 65, ['shift']],
['7', 55],
['?', 191],
['*', 56],
['+', 187],
['$', 52],
['[', 219],
['.', 190]
],
keydown: [
["shift+'", 222, ['shift']],
['shift+a', 65, ['shift']],
['shift+5', 53, ['shift']],
['command+shift+p', 80, ['meta', 'shift']],
['space', 32],
['left', 37]
]
}
function getCallback (key, keyCode, type, modifiers) {
return function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind(key, spy)
KeyEvent.simulate(key.charCodeAt(0), keyCode, modifiers, element)
assert.strictEqual(spy.callCount, 1)
assert.strictEqual(spy.args[0][0].type, type)
}
}
for (var type in keys) {
for (var i = 0; i < keys[type].length; i++) {
var key = keys[type][i][0]
var keyCode = keys[type][i][1]
var modifiers = keys[type][i][2] || []
it('"' + key + '" uses "' + type + '"', getCallback(key, keyCode, type, modifiers))
}
}
})
})
describe('combokeys.unbind', function () {
it('unbind works', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a', spy)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy.callCount, 1, 'callback for a should fire')
combokeys.unbind('a')
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy.callCount, 1, 'callback for a should not fire after unbind')
})
it('unbind accepts an array', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind(['a', 'b', 'c'], spy)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('c'.charCodeAt(0), 67, null, element)
assert.strictEqual(spy.callCount, 3, 'callback should have fired 3 times')
combokeys.unbind(['a', 'b', 'c'])
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('c'.charCodeAt(0), 67, null, element)
assert.strictEqual(spy.callCount, 3, 'callback should not fire after unbind')
})
})
|
test/test.combokeys.js
|
/* eslint-env node, browser, mocha */
/* eslint no-unused-expressions:0 */
'use strict'
/* global
Event
*/
require('es5-shim/es5-shim')
require('es5-shim/es5-sham')
var assert = require('proclaim')
var sinon = require('sinon')
var Combokeys = require('..')
var KeyEvent = require('./lib/key-event')
var makeElement = require('./helpers/make-element')
describe('initialization', function () {
it('initializes on the document', function () {
var combokeys = new Combokeys(document.documentElement)
assert.instanceOf(combokeys, Combokeys)
assert.strictEqual(combokeys.element, document.documentElement)
})
it('can initialize multipe instances', function () {
var first = makeElement()
var second = makeElement()
var firstCombokeys = new Combokeys(first)
var secondCombokeys = new Combokeys(second)
assert.instanceOf(secondCombokeys, Combokeys)
assert.notEqual(firstCombokeys, secondCombokeys)
assert.strictEqual(firstCombokeys.element, first)
assert.strictEqual(secondCombokeys.element, second)
})
})
describe('combokeys.bind', function () {
it('should work', function () {
var combokeys = new Combokeys(document.documentElement)
var spy = sinon.spy()
combokeys.bind('z', spy)
KeyEvent.simulate('Z'.charCodeAt(0), 90, null, document.documentElement)
assert.strictEqual(spy.callCount, 1)
})
describe('basic', function () {
it('z key fires when pressing z', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('z', spy)
KeyEvent.simulate('Z'.charCodeAt(0), 90, null, element)
// really slow for some reason
// assert(spy).to.have.been.calledOnce
assert.strictEqual(spy.callCount, 1, 'callback should fire once')
assert.instanceOf(spy.args[0][0], Event, 'first argument should be Event')
assert.strictEqual(spy.args[0][1], 'z', 'second argument should be key combo')
})
it('z key fires from keydown', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('z', spy, 'keydown')
KeyEvent.simulate('Z'.charCodeAt(0), 90, null, element)
// really slow for some reason
// assert(spy).to.have.been.calledOnce
assert.strictEqual(spy.callCount, 1, 'callback should fire once')
assert.instanceOf(spy.args[0][0], Event, 'first argument should be Event')
assert.strictEqual(spy.args[0][1], 'z', 'second argument should be key combo')
})
it('z key does not fire when pressing b', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('z', spy)
KeyEvent.simulate('B'.charCodeAt(0), 66, null, element)
assert.strictEqual(spy.callCount, 0)
})
it('z key does not fire when holding a modifier key', function () {
var element = makeElement()
var spy = sinon.spy()
var modifiers = ['ctrl', 'alt', 'meta', 'shift']
var charCode
var modifier
var combokeys = new Combokeys(element)
combokeys.bind('z', spy)
for (var i = 0; i < 4; i++) {
modifier = modifiers[i]
charCode = 'Z'.charCodeAt(0)
// character code is different when alt is pressed
if (modifier === 'alt') {
charCode = 'Ω'.charCodeAt(0)
}
spy.reset()
KeyEvent.simulate(charCode, 90, [modifier], element)
assert.strictEqual(spy.callCount, 0)
}
})
it('keyup events should fire', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('z', spy, 'keyup')
KeyEvent.simulate('Z'.charCodeAt(0), 90, null, element)
assert.strictEqual(spy.callCount, 1, 'keyup event for `z` should fire')
// for key held down we should only get one key up
KeyEvent.simulate('Z'.charCodeAt(0), 90, [], element, 10)
assert.strictEqual(spy.callCount, 2, 'keyup event for `z` should fire once for held down key')
})
it('keyup event for 0 should fire', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('0', spy, 'keyup')
KeyEvent.simulate(0, 48, null, element)
assert.strictEqual(spy.callCount, 1, 'keyup event for `0` should fire')
})
it('rebinding a key overwrites the callback for that key', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('x', spy1)
combokeys.bind('x', spy2)
KeyEvent.simulate('X'.charCodeAt(0), 88, null, element)
assert.strictEqual(spy1.callCount, 0, 'original callback should not fire')
assert.strictEqual(spy2.callCount, 1, 'new callback should fire')
})
it('binding an array of keys', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind(['a', 'b', 'c'], spy)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy.callCount, 1, 'new callback was called')
assert.strictEqual(spy.args[0][1], 'a', 'callback should match `a`')
KeyEvent.simulate('B'.charCodeAt(0), 66, null, element)
assert.strictEqual(spy.callCount, 2, 'new callback was called twice')
assert.strictEqual(spy.args[1][1], 'b', 'callback should match `b`')
KeyEvent.simulate('C'.charCodeAt(0), 67, null, element)
assert.strictEqual(spy.callCount, 3, 'new callback was called three times')
assert.strictEqual(spy.args[2][1], 'c', 'callback should match `c`')
})
it('return false should prevent default and stop propagation', function () {
var element = makeElement()
var spy = sinon.spy(function () {
return false
})
var combokeys = new Combokeys(element)
combokeys.bind('command+s', spy)
KeyEvent.simulate('S'.charCodeAt(0), 83, ['meta'], element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
assert.instanceOf(spy.args[0][0], Event, 'first argument should be Event')
var event = spy.args[0][0]
if (event.preventDefault) {
assert.isTrue(event.defaultPrevented)
} else {
assert.isTrue(event.cancelBubble)
}
// try without return false
spy = sinon.spy()
combokeys.bind('command+s', spy)
KeyEvent.simulate('S'.charCodeAt(0), 83, ['meta'], element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
assert.instanceOf(spy.args[0][0], Event, 'first argument should be Event')
event = spy.args[0][0]
if (event.preventDefault) {
assert.isFalse(event.defaultPrevented)
} else {
assert.isFalse(event.cancelBubble)
}
})
it('capslock key is ignored', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a', spy)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire for lowercase a')
spy.reset()
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire for capslock A')
spy.reset()
KeyEvent.simulate('A'.charCodeAt(0), 65, ['shift'], element)
assert.strictEqual(spy.callCount, 0, 'callback should not fire fort shift+a')
})
})
describe('special characters', function () {
it('binding special characters', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('*', spy)
KeyEvent.simulate('*'.charCodeAt(0), 56, ['shift'], element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
assert.strictEqual(spy.args[0][1], '*', 'callback should match *')
})
it('binding special characters keyup', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('*', spy, 'keyup')
KeyEvent.simulate('*'.charCodeAt(0), 56, ['shift'], element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
assert.strictEqual(spy.args[0][1], '*', 'callback should match *')
})
it('binding keys with no associated charCode', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('left', spy)
KeyEvent.simulate(0, 37, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
assert.strictEqual(spy.args[0][1], 'left', 'callback should match `left`')
})
it('able to bind plus and minus', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('ctrl+minus', spy1)
combokeys.bind('ctrl+plus', spy2)
KeyEvent.simulate('-'.charCodeAt(0), 189, ['ctrl'], element)
assert.strictEqual(spy1.callCount, 1, '`ctrl+minus` should fire')
KeyEvent.simulate('+'.charCodeAt(0), 187, ['ctrl'], element)
assert.strictEqual(spy2.callCount, 1, '`ctrl+plus` should fire')
})
})
describe('combos with modifiers', function () {
it('binding key combinations', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('command+o', spy)
KeyEvent.simulate('O'.charCodeAt(0), 79, ['meta'], element)
assert.strictEqual(spy.callCount, 1, 'command+o callback should fire')
assert.strictEqual(spy.args[0][1], 'command+o', 'keyboard string returned is correct')
})
it('binding key combos with multiple modifiers', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('command+shift+o', spy)
KeyEvent.simulate('O'.charCodeAt(0), 79, ['meta'], element)
assert.strictEqual(spy.callCount, 0, 'command+o callback should not fire')
KeyEvent.simulate('O'.charCodeAt(0), 79, ['meta', 'shift'], element)
assert.strictEqual(spy.callCount, 1, 'command+o callback should fire')
})
})
describe('sequences', function () {
it('binding sequences', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('g i', spy)
KeyEvent.simulate('G'.charCodeAt(0), 71, null, element)
assert.strictEqual(spy.callCount, 0, 'callback should not fire')
KeyEvent.simulate('I'.charCodeAt(0), 73, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
})
it('binding sequences with mixed types', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('g o enter', spy)
KeyEvent.simulate('G'.charCodeAt(0), 71, null, element)
assert.strictEqual(spy.callCount, 0, 'callback should not fire')
KeyEvent.simulate('O'.charCodeAt(0), 79, null, element)
assert.strictEqual(spy.callCount, 0, 'callback should not fire')
KeyEvent.simulate(0, 13, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
})
it('binding sequences starting with modifier keys', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('option enter', spy)
KeyEvent.simulate(0, 18, ['alt'], element)
KeyEvent.simulate(0, 13, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
spy = sinon.spy()
combokeys.bind('command enter', spy)
KeyEvent.simulate(0, 91, ['meta'], element)
KeyEvent.simulate(0, 13, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
spy = sinon.spy()
combokeys.bind('escape enter', spy)
KeyEvent.simulate(0, 27, null, element)
KeyEvent.simulate(0, 13, null, element)
assert.strictEqual(spy.callCount, 1, 'callback should fire')
})
it('key within sequence should not fire', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a', spy1)
combokeys.bind('c a t', spy2)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy1.callCount, 1, 'callback 1 should fire')
spy1.reset()
KeyEvent.simulate('C'.charCodeAt(0), 67, null, element)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('T'.charCodeAt(0), 84, null, element)
assert.strictEqual(spy1.callCount, 0, 'callback for `a` key should not fire')
assert.strictEqual(spy2.callCount, 1, 'callback for `c a t` sequence should fire')
})
it('keyup at end of sequence should not fire', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('t', spy1, 'keyup')
combokeys.bind('b a t', spy2)
KeyEvent.simulate('B'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('T'.charCodeAt(0), 84, null, element)
assert.strictEqual(spy1.callCount, 0, 'callback for `t` keyup should not fire')
assert.strictEqual(spy2.callCount, 1, 'callback for `b a t` sequence should fire')
})
it('keyup sequences should work', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('b a t', spy, 'keyup')
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
// hold the last key down for a while
KeyEvent.simulate('t'.charCodeAt(0), 84, [], element, 10)
assert.strictEqual(spy.callCount, 1, 'callback for `b a t` sequence should fire on keyup')
})
it('extra spaces in sequences should be ignored', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('b a t', spy)
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('t'.charCodeAt(0), 84, null, element)
assert.strictEqual(spy.callCount, 1, 'callback for `b a t` sequence should fire')
})
it('modifiers and sequences play nicely', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('ctrl a', spy1)
combokeys.bind('ctrl+b', spy2)
KeyEvent.simulate(0, 17, ['ctrl'], element)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy1.callCount, 1, '`ctrl a` should fire')
KeyEvent.simulate('B'.charCodeAt(0), 66, ['ctrl'], element)
assert.strictEqual(spy2.callCount, 1, '`ctrl+b` should fire')
})
it('sequences that start the same work', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('g g l', spy2)
combokeys.bind('g g o', spy1)
KeyEvent.simulate('g'.charCodeAt(0), 71, null, element)
KeyEvent.simulate('g'.charCodeAt(0), 71, null, element)
KeyEvent.simulate('o'.charCodeAt(0), 79, null, element)
assert.strictEqual(spy1.callCount, 1, '`g g o` should fire')
assert.strictEqual(spy2.callCount, 0, '`g g l` should not fire')
spy1.reset()
spy2.reset()
KeyEvent.simulate('g'.charCodeAt(0), 71, null, element)
KeyEvent.simulate('g'.charCodeAt(0), 71, null, element)
KeyEvent.simulate('l'.charCodeAt(0), 76, null, element)
assert.strictEqual(spy1.callCount, 0, '`g g o` should not fire')
assert.strictEqual(spy2.callCount, 1, '`g g l` should fire')
})
it('sequences should not fire subsequences', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a b c', spy1)
combokeys.bind('b c', spy2)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('B'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('C'.charCodeAt(0), 67, null, element)
assert.strictEqual(spy1.callCount, 1, '`a b c` should fire')
assert.strictEqual(spy2.callCount, 0, '`b c` should not fire')
spy1.reset()
spy2.reset()
combokeys.bind('option b', spy1)
combokeys.bind('a option b', spy2)
KeyEvent.simulate('A'.charCodeAt(0), 65, null, element)
KeyEvent.simulate(0, 18, ['alt'], element)
KeyEvent.simulate('B'.charCodeAt(0), 66, null, element)
assert.strictEqual(spy1.callCount, 0, '`option b` should not fire')
assert.strictEqual(spy2.callCount, 1, '`a option b` should fire')
})
it('rebinding same sequence should override previous', function () {
var element = makeElement()
var spy1 = sinon.spy()
var spy2 = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a b c', spy1)
combokeys.bind('a b c', spy2)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('c'.charCodeAt(0), 67, null, element)
assert.strictEqual(spy1.callCount, 0, 'first callback should not fire')
assert.strictEqual(spy2.callCount, 1, 'second callback should fire')
})
it('broken sequences', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('h a t', spy)
KeyEvent.simulate('h'.charCodeAt(0), 72, null, element)
KeyEvent.simulate('e'.charCodeAt(0), 69, null, element)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('r'.charCodeAt(0), 82, null, element)
KeyEvent.simulate('t'.charCodeAt(0), 84, null, element)
assert.strictEqual(spy.callCount, 0, 'sequence for `h a t` should not fire for `h e a r t`')
})
it('sequences containing combos should work', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a ctrl+b', spy)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('B'.charCodeAt(0), 66, ['ctrl'], element)
assert.strictEqual(spy.callCount, 1, '`a ctrl+b` should fire')
combokeys.unbind('a ctrl+b')
spy = sinon.spy()
combokeys.bind('ctrl+b a', spy)
KeyEvent.simulate('b'.charCodeAt(0), 66, ['ctrl'], element)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy.callCount, 1, '`ctrl+b a` should fire')
})
it('sequences starting with spacebar should work', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a space b c', spy)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate(32, 32, null, element)
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('c'.charCodeAt(0), 67, null, element)
assert.strictEqual(spy.callCount, 1, '`a space b c` should fire')
})
it('konami code', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('up up down down left right left right b a enter', spy)
KeyEvent.simulate(0, 38, null, element)
KeyEvent.simulate(0, 38, null, element)
KeyEvent.simulate(0, 40, null, element)
KeyEvent.simulate(0, 40, null, element)
KeyEvent.simulate(0, 37, null, element)
KeyEvent.simulate(0, 39, null, element)
KeyEvent.simulate(0, 37, null, element)
KeyEvent.simulate(0, 39, null, element)
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate(0, 13, null, element)
assert.strictEqual(spy.callCount, 1, 'konami code should fire')
})
it('sequence timer resets', function () {
var element = makeElement()
var spy = sinon.spy()
var clock = sinon.useFakeTimers()
var combokeys = new Combokeys(element)
combokeys.bind('h a t', spy)
KeyEvent.simulate('h'.charCodeAt(0), 72, null, element)
clock.tick(600)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
clock.tick(900)
KeyEvent.simulate('t'.charCodeAt(0), 84, null, element)
assert.strictEqual(spy.callCount, 1, 'sequence should fire after waiting')
clock.restore()
})
it('sequences timeout', function () {
var element = makeElement()
var spy = sinon.spy()
var clock = sinon.useFakeTimers()
var combokeys = new Combokeys(element)
combokeys.bind('g t', spy)
KeyEvent.simulate('g'.charCodeAt(0), 71, null, element)
clock.tick(1000)
KeyEvent.simulate('t'.charCodeAt(0), 84, null, element)
assert.strictEqual(spy.callCount, 0, 'sequence callback should not fire')
clock.restore()
})
})
describe('default actions', function () {
var keys = {
keypress: [
['a', 65],
['A', 65, ['shift']],
['7', 55],
['?', 191],
['*', 56],
['+', 187],
['$', 52],
['[', 219],
['.', 190]
],
keydown: [
["shift+'", 222, ['shift']],
['shift+a', 65, ['shift']],
['shift+5', 53, ['shift']],
['command+shift+p', 80, ['meta', 'shift']],
['space', 32],
['left', 37]
]
}
function getCallback (key, keyCode, type, modifiers) {
return function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind(key, spy)
KeyEvent.simulate(key.charCodeAt(0), keyCode, modifiers, element)
assert.strictEqual(spy.callCount, 1)
assert.strictEqual(spy.args[0][0].type, type)
}
}
for (var type in keys) {
for (var i = 0; i < keys[type].length; i++) {
var key = keys[type][i][0]
var keyCode = keys[type][i][1]
var modifiers = keys[type][i][2] || []
it('"' + key + '" uses "' + type + '"', getCallback(key, keyCode, type, modifiers))
}
}
})
})
describe('combokeys.unbind', function () {
it('unbind works', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind('a', spy)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy.callCount, 1, 'callback for a should fire')
combokeys.unbind('a')
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
assert.strictEqual(spy.callCount, 1, 'callback for a should not fire after unbind')
})
it('unbind accepts an array', function () {
var element = makeElement()
var spy = sinon.spy()
var combokeys = new Combokeys(element)
combokeys.bind(['a', 'b', 'c'], spy)
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('c'.charCodeAt(0), 67, null, element)
assert.strictEqual(spy.callCount, 3, 'callback should have fired 3 times')
combokeys.unbind(['a', 'b', 'c'])
KeyEvent.simulate('a'.charCodeAt(0), 65, null, element)
KeyEvent.simulate('b'.charCodeAt(0), 66, null, element)
KeyEvent.simulate('c'.charCodeAt(0), 67, null, element)
assert.strictEqual(spy.callCount, 3, 'callback should not fire after unbind')
})
})
|
Properly test 'return false' in sane browsers
|
test/test.combokeys.js
|
Properly test 'return false' in sane browsers
|
<ide><path>est/test.combokeys.js
<ide> var combokeys = new Combokeys(element)
<ide> combokeys.bind('command+s', spy)
<ide>
<add> var stopPropagationSpy = sinon.spy(Event.prototype, 'stopPropagation')
<ide> KeyEvent.simulate('S'.charCodeAt(0), 83, ['meta'], element)
<ide>
<ide> assert.strictEqual(spy.callCount, 1, 'callback should fire')
<ide> assert.instanceOf(spy.args[0][0], Event, 'first argument should be Event')
<ide> var event = spy.args[0][0]
<ide> if (event.preventDefault) {
<del> assert.isTrue(event.defaultPrevented)
<add> assert.isTrue(event.defaultPrevented, 'default is prevented')
<ide> } else {
<del> assert.isTrue(event.cancelBubble)
<add> assert.isFalse(event.returnValue, 'default is prevented')
<add> }
<add> if (event.stopPropagation) {
<add> assert.isTrue(stopPropagationSpy.calledOnce, 'propagation was cancelled')
<add> } else {
<add> assert.isTrue(event.cancelBubble, 'propagation is cancelled')
<ide> }
<ide>
<ide> // try without return false
<ide> assert.instanceOf(spy.args[0][0], Event, 'first argument should be Event')
<ide> event = spy.args[0][0]
<ide> if (event.preventDefault) {
<del> assert.isFalse(event.defaultPrevented)
<add> assert.isFalse(event.defaultPrevented, 'default is not prevented')
<ide> } else {
<del> assert.isFalse(event.cancelBubble)
<add> assert.isNotFalse(event.returnValue, 'default is not prevented')
<add> }
<add> if (event.stopPropagation) {
<add> assert.isTrue(stopPropagationSpy.calledOnce, 'propagation was not cancelled')
<add> } else {
<add> assert.isFalse(event.cancelBubble, 'propagation is not cancelled')
<ide> }
<ide> })
<ide>
|
|
JavaScript
|
mit
|
6f729e62da570d92e34836d402e97c43b0b083b1
| 0 |
anitagraham/refinerycms,simi/refinerycms,bryanmtl/g-refinerycms,aguzubiaga/refinerycms,trevornez/refinerycms,donabrams/refinerycms,LytayTOUCH/refinerycms,hoopla-software/refinerycms,refinery/refinerycms,trevornez/refinerycms,pcantrell/refinerycms,aguzubiaga/refinerycms,LytayTOUCH/refinerycms,johanb/refinerycms,refinery/refinerycms,mabras/refinerycms,kappiah/refinerycms,simi/refinerycms,simi/refinerycms,louim/refinerycms,bricesanchez/refinerycms,chrise86/refinerycms,KingLemuel/refinerycms,mobilityhouse/refinerycms,gwagener/refinerycms,mkaplan9/refinerycms,pcantrell/refinerycms,kelkoo-services/refinerycms,refinery/refinerycms,mabras/refinerycms,kelkoo-services/refinerycms,chrise86/refinerycms,KingLemuel/refinerycms,hoopla-software/refinerycms,mojarra/myrefinerycms,mlinfoot/refinerycms,chrise86/refinerycms,SmartMedia/refinerycms-with-custom-icons,KingLemuel/refinerycms,Eric-Guo/refinerycms,Eric-Guo/refinerycms,bryanmtl/g-refinerycms,anitagraham/refinerycms,aguzubiaga/refinerycms,johanb/refinerycms,bricesanchez/refinerycms,mkaplan9/refinerycms,stefanspicer/refinerycms,donabrams/refinerycms,sideci-sample/sideci-sample-refinerycms,mabras/refinerycms,Retimont/refinerycms,SmartMedia/refinerycms-with-custom-icons,Retimont/refinerycms,johanb/refinerycms,hoopla-software/refinerycms,mkaplan9/refinerycms,mlinfoot/refinerycms,simi/refinerycms,sideci-sample/sideci-sample-refinerycms,Eric-Guo/refinerycms,Retimont/refinerycms,mobilityhouse/refinerycms,louim/refinerycms,anitagraham/refinerycms,koa/refinerycms,gwagener/refinerycms,LytayTOUCH/refinerycms,kappiah/refinerycms,kappiah/refinerycms,mojarra/myrefinerycms,koa/refinerycms,stefanspicer/refinerycms,gwagener/refinerycms,stefanspicer/refinerycms,trevornez/refinerycms,mlinfoot/refinerycms
|
$(document).ready(function(){
// focus first field in an admin form.
$('form input[type=text]:first').focus();
init_flash_messages();
});
init_flash_messages = function(){
$('#flash').css({
'opacity': 0
, 'visibility':'visible'
}).animate({'opacity': '1'}, 550);
$('#flash_close').click(function(e) {
try {
$('#flash').animate({
'opacity': 0,
'visibility': 'hidden'
}, 330, function() {
$('#flash').hide();
});
} catch(ex) {
$('#flash').hide();
}
e.preventDefault();
});
$('#flash.flash_message').prependTo('#records');
};
|
core/public/javascripts/refinery/core.js
|
$(document).ready(function(){
// focus first field in an admin form.
$('form input[type=text]:first').focus();
init_flash_messages();
});
init_flash_messages = function(){
$('#flash').css({
'opacity': 0
, 'visibility':'visible'
}).animate({'opacity': '1'}, 550);
$('#flash_close').click(function(e) {
try {
$('#flash').animate({
'opacity': 0,
'visibility': 'hidden'
}, 330);
} catch(ex) {
$('#flash').hide();
}
e.preventDefault();
});
$('#flash.flash_message').prependTo('#records');
};
|
Hide the flash completely when the animation is completed. Closes GH-539
|
core/public/javascripts/refinery/core.js
|
Hide the flash completely when the animation is completed. Closes GH-539
|
<ide><path>ore/public/javascripts/refinery/core.js
<ide> $('#flash').animate({
<ide> 'opacity': 0,
<ide> 'visibility': 'hidden'
<del> }, 330);
<add> }, 330, function() {
<add> $('#flash').hide();
<add> });
<ide> } catch(ex) {
<ide> $('#flash').hide();
<ide> }
|
|
JavaScript
|
mit
|
63a4f4fd53f7b24a6c0f791deaf80b94af93aa7d
| 0 |
jinroh/kadoh,jinroh/kadoh
|
describe('In Value Management', function() {
beforeEach(function() {
VM = KadOH.ValueManagement;
globals = KadOH.globals;
//mimic a node
node = {
getID: function() {
return '8ba5c4acf388e17a1a8a5364b14ee48c2cb29b01';
},
getAddress: function() {
return '[email protected]';
},
republish: function(key, value, exp) {
//do nothing for the moment
}
};
});
it('should be a function', function() {
expect(VM).toBeFunction();
});
it('should be instanciable', function() {
var v = new VM(node, {recover : false});
expect(typeof v).toEqual('object');
v.stop();
});
describe('when i instanciate one (no recover)', function() {
beforeEach(function(){
v = new VM(node, {recover : false});
});
afterEach(function(){
v.stop();
});
it('should be possible to store a value', function(){
v.save('9Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', {foo : 'bar'});
expect(true).toBeTruthy();
});
describe(' and when I\' ve stored a value', function() {
beforeEach(function(){
v.save('9Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', {foo : 'bar'});
});
it('should be possible to retrieve later (with callback)', function(){
res = undefined;
runs(function(){
v.retrieve('9Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', function(obj) {
res = obj.foo;
});
});
waits(10);
runs(function(){
expect(res).toEqual('bar');
});
});
it('should be possible to retrieve later (with deferred)', function(){
res = undefined;
runs(function(){
v.retrieve('9Va5c4acf388e17a1a8a5364b14ee48c2cb29b01').then(
function(obj) {
res = obj.foo;
});
});
waits(10);
runs(function(){
expect(res).toEqual('bar');
});
});
});
describe('and when I\' ve stored a value with an expiration time', function() {
beforeEach(function(){
TTL = 1000;
var exp = +(new Date()) + TTL;
v.save('1Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', {foo : 'babar'}, exp);
});
it('should be there now..', function(){
runs(function(){
v.retrieve('1Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', function(obj) {
res = obj.foo;
});
});
waits(10);
runs(function(){
expect(res).toEqual('babar');
});
});
it('should have exprired after a while', function(){
res = 12345;
waits(TTL+TTL/3);
runs(function(){
v.retrieve('1Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', function(obj) {
res = obj;
});
});
waits(10);
runs(function(){
expect(res).toEqual(null);
});
});
});
describe('when I\' ve stored a value (and manuelly dropped down the republish time to test it)', function(){
beforeEach(function(){
v._repTime = 500;
v.save('3Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', {foo : 'bar'});
});
afterEach(function() {
v._repTime = globals.TIMEOUT_REPUBLISH;
});
it('should be republished at least twice', function(){
spyOn(node,'republish');
waits(v._repTime+100);
runs(function(){
expect(node.republish).toHaveBeenCalled();
expect(node.republish.callCount).toEqual(1);
expect(node.republish.mostRecentCall.args[0]).toEqual('3Va5c4acf388e17a1a8a5364b14ee48c2cb29b01');
});
waits(v._repTime+100);
runs(function(){
expect(node.republish).toHaveBeenCalled();
expect(node.republish.callCount).toEqual(2);
expect(node.republish.mostRecentCall.args[0]).toEqual('3Va5c4acf388e17a1a8a5364b14ee48c2cb29b01');
});
});
describe('and when I re-store it a while later', function() {
beforeEach(function(){
waits(v._repTime/2);
runs(function() {
v.save('3Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', {foo : 'bar'});
});
});
it('should not have been republished too early..', function() {
spyOn(node,'republish');
expect(node.republish).not.toHaveBeenCalled();
});
it('..but at the rigth time', function() {
spyOn(node,'republish');
waits(v._repTime/2+10);
runs(function(){
expect(node.republish).toHaveBeenCalled();
expect(node.republish.callCount).toEqual(1);
});
});
});
});
});
});
|
spec/valuemanagement.spec.js
|
describe('In Value Management', function() {
beforeEach(function() {
VM = KadOH.ValueManagement;
globals = KadOH.globals;
//mimic a node
node = {
getID: function() {
return '8ba5c4acf388e17a1a8a5364b14ee48c2cb29b01';
},
getAddress: function() {
return '[email protected]';
},
republish: function(key, value, exp) {
//do nothing for the moment
}
};
});
it('should be a function', function() {
expect(VM).toBeFunction();
});
it('should be instanciable', function() {
var v = new VM(node, {recover : false});
expect(typeof v).toEqual('object');
v.stop();
});
describe('when i instanciate one (no recover)', function() {
beforeEach(function(){
v = new VM(node, {recover : false});
});
afterEach(function(){
v.stop();
});
it('should be possible to store a value', function(){
v.save('9Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', {foo : 'bar'});
expect(true).toBeTruthy();
});
describe(' and when I\' ve stored a value', function() {
beforeEach(function(){
v.save('9Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', {foo : 'bar'});
});
it('should be possible to retrieve later (with callback)', function(){
res = undefined;
runs(function(){
v.retrieve('9Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', function(obj) {
res = obj.foo;
});
});
waits(10);
runs(function(){
expect(res).toEqual('bar');
});
});
it('should be possible to retrieve later (with deferred)', function(){
res = undefined;
runs(function(){
v.retrieve('9Va5c4acf388e17a1a8a5364b14ee48c2cb29b01').then(
function(obj) {
res = obj.foo;
});
});
waits(10);
runs(function(){
expect(res).toEqual('bar');
});
});
});
describe('and when I\' ve stored a value with an expiration time', function() {
beforeEach(function(){
TTL = 1000;
var exp = +(new Date()) + TTL;
v.save('1Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', {foo : 'babar'}, exp);
});
it('should be there now..', function(){
runs(function(){
v.retrieve('1Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', function(obj) {
res = obj.foo;
});
});
waits(10);
runs(function(){
expect(res).toEqual('babar');
});
});
it('should have exprired after a while', function(){
res = 12345;
waits(TTL+TTL/3);
runs(function(){
v.retrieve('1Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', function(obj) {
res = obj;
});
});
waits(10);
runs(function(){
expect(res).toEqual(null);
});
});
});
describe('when I\' ve stored a value (and manuelly dropped down the republish time to test it)', function(){
beforeEach(function(){
v._repTime = 500;
v.save('3Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', {foo : 'bar'});
});
afterEach(function() {
v._repTime = globals.TIMEOUT_REPUBLISH;
});
it('should be republished at least twice', function(){
spyOn(node,'republish');
waits(v._repTime+20);
runs(function(){
expect(node.republish).toHaveBeenCalled();
expect(node.republish.callCount).toEqual(1);
expect(node.republish.mostRecentCall.args[0]).toEqual('3Va5c4acf388e17a1a8a5364b14ee48c2cb29b01');
});
waits(v._repTime+20);
runs(function(){
expect(node.republish).toHaveBeenCalled();
expect(node.republish.callCount).toEqual(2);
expect(node.republish.mostRecentCall.args[0]).toEqual('3Va5c4acf388e17a1a8a5364b14ee48c2cb29b01');
});
});
describe('and when I re-store it a while later', function() {
beforeEach(function(){
waits(v._repTime/2);
runs(function() {
v.save('3Va5c4acf388e17a1a8a5364b14ee48c2cb29b01', {foo : 'bar'});
});
});
it('should not have been republished too early..', function() {
spyOn(node,'republish');
expect(node.republish).not.toHaveBeenCalled();
});
it('..but at the rigth time', function() {
spyOn(node,'republish');
waits(v._repTime/2+10);
runs(function(){
expect(node.republish).toHaveBeenCalled();
expect(node.republish.callCount).toEqual(1);
});
});
});
});
});
});
|
VM : enforce test once more as much I could
|
spec/valuemanagement.spec.js
|
VM : enforce test once more as much I could
|
<ide><path>pec/valuemanagement.spec.js
<ide>
<ide> it('should be republished at least twice', function(){
<ide> spyOn(node,'republish');
<del> waits(v._repTime+20);
<add> waits(v._repTime+100);
<ide> runs(function(){
<ide> expect(node.republish).toHaveBeenCalled();
<ide> expect(node.republish.callCount).toEqual(1);
<ide> expect(node.republish.mostRecentCall.args[0]).toEqual('3Va5c4acf388e17a1a8a5364b14ee48c2cb29b01');
<ide> });
<ide>
<del> waits(v._repTime+20);
<add> waits(v._repTime+100);
<ide> runs(function(){
<ide> expect(node.republish).toHaveBeenCalled();
<ide> expect(node.republish.callCount).toEqual(2);
|
|
JavaScript
|
mit
|
2eba0324f3112431d4995853df91d998496af3af
| 0 |
onechiporenko/eslint-plugin-mocha-cleanup
|
var suites = [
"describe", "context", // BDD
"Feature", "Scenario", // Mocha Cakes 2
"suite" // TDD
];
var suitesSkipped = [
"describe.skip", "xdescribe", "xcontext", // BDD
"Feature.skip", "Scenario.skip", // Mocha Cakes 2
"suite.skip" // TDD
];
var tests = [
"it", "specify", // BDD
"Given", "Then", "And", "But", // Mocha Cakes 2
"test" // TDD
];
var testsSkipped = [
"xit", "it.skip", "xspecify", // BDD
"Given.skip", "Then.skip", "And.skip", "But.skip", // Mocha Cakes 2
"test.skip" // TDD
];
var hooks = [
"before", "beforeEach", "after", "afterEach"
];
module.exports = {
hooks: hooks,
suites: suites,
suitesSkipped: suitesSkipped,
allSuites: suites.concat(suitesSkipped),
tests: tests,
testsSkipped: testsSkipped,
allTests: tests.concat(testsSkipped),
allBlocks: suites.concat(tests),
allSkipped: suitesSkipped.concat(testsSkipped),
all: suites.concat(suitesSkipped).concat(tests).concat(testsSkipped)
};
|
lib/utils/mocha-specs.js
|
var suites = [
"describe", "context", // BDD
"suite" // TDD
];
var suitesSkipped = [
"describe.skip", "xdescribe", "xcontext", // BDD
"suite.skip" // TDD
];
var tests = [
"it", "specify", // BDD
"test" // TDD
];
var testsSkipped = [
"xit", "it.skip", "xspecify", // BDD
"test.skip" // TDD
];
var hooks = [
"before", "beforeEach", "after", "afterEach"
];
module.exports = {
hooks: hooks,
suites: suites,
suitesSkipped: suitesSkipped,
allSuites: suites.concat(suitesSkipped),
tests: tests,
testsSkipped: testsSkipped,
allTests: tests.concat(testsSkipped),
allBlocks: suites.concat(tests),
allSkipped: suitesSkipped.concat(testsSkipped),
all: suites.concat(suitesSkipped).concat(tests).concat(testsSkipped)
};
|
add mocha-cakes-2 it and describe specifiers
|
lib/utils/mocha-specs.js
|
add mocha-cakes-2 it and describe specifiers
|
<ide><path>ib/utils/mocha-specs.js
<ide> var suites = [
<ide> "describe", "context", // BDD
<add> "Feature", "Scenario", // Mocha Cakes 2
<ide> "suite" // TDD
<ide> ];
<ide>
<ide> var suitesSkipped = [
<ide> "describe.skip", "xdescribe", "xcontext", // BDD
<add> "Feature.skip", "Scenario.skip", // Mocha Cakes 2
<ide> "suite.skip" // TDD
<ide> ];
<ide>
<ide> var tests = [
<ide> "it", "specify", // BDD
<add> "Given", "Then", "And", "But", // Mocha Cakes 2
<ide> "test" // TDD
<ide> ];
<ide>
<ide> var testsSkipped = [
<ide> "xit", "it.skip", "xspecify", // BDD
<add> "Given.skip", "Then.skip", "And.skip", "But.skip", // Mocha Cakes 2
<ide> "test.skip" // TDD
<ide> ];
<ide>
|
|
JavaScript
|
agpl-3.0
|
f26ca65ef57221f7eb577fd2f5f44b196e7aa4bb
| 0 |
mmilaprat/policycompass-frontend,cbotsikas/policycompass-frontend,policycompass/policycompass-frontend,almey/policycompass-frontend,cbotsikas/policycompass-frontend,almey/policycompass-frontend,bullz/policycompass-frontend,almey/policycompass-frontend,mmilaprat/policycompass-frontend,mmilaprat/policycompass-frontend,cbotsikas/policycompass-frontend,bullz/policycompass-frontend,bullz/policycompass-frontend,policycompass/policycompass-frontend,policycompass/policycompass-frontend
|
angular.module('pcApp.metrics.directives.formula', [
])
.directive('formula', ['$http', 'API_CONF', '$q', function ($http, API_CONF, $q) {
return {
restrict: 'E',
replace: true,
scope: {
formula: '=formula',
variables: '=variables',
},
template: function(scope) {
return '<div style="min-height: 77px;" class="calculation-formula calculation-formula-2"></div>';
},
link: function(scope, element, attrs) {
var parseFormula = function() {
var parsedFormula = scope.formula;
if(angular.isObject(scope.variables)){
var variables = scope.variables;
}
else{
var variables = JSON.parse(scope.variables.replace(/'/g, '"'));
}
var urlCalls = [];
angular.forEach(variables, function(value, key, obj) {
var index = scope.formula.indexOf(key.replace(' ', ''));
if(index > -1) {
var url = API_CONF.INDICATOR_SERVICE_URL + "/indicators/" + value.id;
urlCalls.push($http({
url: url,
method: "GET",
params: {key: key}
}));
parsedFormula = parsedFormula.replace(key.replace(' ', ''), " __" + value.id + "__ ");
}
});
var deferred = $q.defer();
$q.all(urlCalls)
.then(
function(results) {
angular.forEach(results, function(value, key, obj){
var variable = value.config.params.key;
parsedFormula = parsedFormula.replace("__" + value.data.id + "__", '<span id="variable' + variable.trim() + '" class="indicator-formula indicator-formula-selected">' + value.data.name + '</span>');
});
element.empty();
element.append(parsedFormula);
},
function(errors) {
deferred.reject(errors);
},
function(updates) {
deferred.update(updates);
});
};
scope.$watch('formula', function() {
parseFormula();
});
}
};
}]);
|
app/modules/metrics/directives/formula.js
|
angular.module('pcApp.metrics.directives.formula', [
])
.directive('formula', ['$http', 'API_CONF', '$q', function ($http, API_CONF, $q) {
return {
restrict: 'E',
replace: true,
scope: {
formula: '=formula',
variables: '=variables',
},
template: function(scope) {
return '<div style="min-height: 77px;" class="calculation-formula calculation-formula-2"></div>';
},
link: function(scope, element, attrs) {
var parseFormula = function() {
var parsedFormula = scope.formula;
if(angular.isObject(scope.variables)){
var variables = scope.variables;
}
else{
var variables = JSON.parse(scope.variables.replace(/'/g, '"'));
}
var urlCalls = [];
angular.forEach(variables, function(value, key, obj) {
var index = scope.formula.indexOf(key.replace(' ', ''));
if(index > -1) {
var url = API_CONF.INDICATOR_SERVICE_URL + "/indicators/" + value.id;
urlCalls.push($http.get(url));
parsedFormula = parsedFormula.replace(key.replace(' ', ''), " __" + value.id + "__ ");
}
});
var deferred = $q.defer();
$q.all(urlCalls)
.then(
function(results) {
angular.forEach(results, function(value, key, obj){
parsedFormula = parsedFormula.replace("__" + value.data.id + "__", '<span class="indicator-formula indicator-formula-selected">' + value.data.name + '</span>');
});
element.empty();
element.append(parsedFormula);
},
function(errors) {
deferred.reject(errors);
},
function(updates) {
deferred.update(updates);
});
};
scope.$watch('formula', function() {
parseFormula();
});
}
};
}]);
|
make variable availbale in formula (hack)
|
app/modules/metrics/directives/formula.js
|
make variable availbale in formula (hack)
|
<ide><path>pp/modules/metrics/directives/formula.js
<ide> var index = scope.formula.indexOf(key.replace(' ', ''));
<ide> if(index > -1) {
<ide> var url = API_CONF.INDICATOR_SERVICE_URL + "/indicators/" + value.id;
<del> urlCalls.push($http.get(url));
<add> urlCalls.push($http({
<add> url: url,
<add> method: "GET",
<add> params: {key: key}
<add> }));
<ide> parsedFormula = parsedFormula.replace(key.replace(' ', ''), " __" + value.id + "__ ");
<ide> }
<ide> });
<ide> .then(
<ide> function(results) {
<ide> angular.forEach(results, function(value, key, obj){
<del> parsedFormula = parsedFormula.replace("__" + value.data.id + "__", '<span class="indicator-formula indicator-formula-selected">' + value.data.name + '</span>');
<add> var variable = value.config.params.key;
<add> parsedFormula = parsedFormula.replace("__" + value.data.id + "__", '<span id="variable' + variable.trim() + '" class="indicator-formula indicator-formula-selected">' + value.data.name + '</span>');
<ide> });
<ide> element.empty();
<ide> element.append(parsedFormula);
|
|
Java
|
bsd-3-clause
|
6744112cface93237b532853562f07cc61025361
| 0 |
vontrapp/hubroid,EddieRingle/hubroid,EddieRingle/hubroid
|
/**
* Hubroid - A GitHub app for Android
*
* Copyright (c) 2010 Eddie Ringle.
*
* Licensed under the New BSD License.
*/
package org.idlesoft.android.hubroid;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Search extends Activity {
private RepositoriesListAdapter m_repositories_adapter;
private SearchUsersListAdapter m_users_adapter;
public ProgressDialog m_progressDialog;
private SharedPreferences m_prefs;
private SharedPreferences.Editor m_editor;
public String m_username;
public String m_type;
public JSONArray m_repositoriesData;
public JSONArray m_usersData;
public Intent m_intent;
public int m_position;
public void initializeList() {
try {
if (m_type == "repositories") {
URL query = new URL(
"http://github.com/api/v2/json/repos/search/"
+ URLEncoder
.encode(((EditText) findViewById(R.id.et_search_search_box))
.getText().toString()));
m_repositoriesData = Hubroid.make_api_request(query)
.getJSONArray("repositories");
if (m_repositoriesData == null) {
runOnUiThread(new Runnable() {
public void run() {
Toast
.makeText(
Search.this,
"Error gathering repository data, please try again.",
Toast.LENGTH_SHORT).show();
}
});
} else {
m_repositories_adapter = new RepositoriesListAdapter(
getApplicationContext(), m_repositoriesData);
}
} else if (m_type == "users") {
URL query = new URL(
"http://github.com/api/v2/json/user/search/"
+ URLEncoder
.encode(((EditText) findViewById(R.id.et_search_search_box))
.getText().toString()));
m_usersData = Hubroid.make_api_request(query).getJSONArray(
"users");
if (m_usersData == null) {
runOnUiThread(new Runnable() {
public void run() {
Toast
.makeText(
Search.this,
"Error gathering user data, please try again.",
Toast.LENGTH_SHORT).show();
}
});
} else {
m_users_adapter = new SearchUsersListAdapter(
getApplicationContext(), m_usersData);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
private Runnable threadProc_itemClick = new Runnable() {
public void run() {
try {
if (m_type == "repositories") {
m_intent = new Intent(Search.this, RepositoryInfo.class);
m_intent.putExtra("repo_name", m_repositoriesData
.getJSONObject(m_position).getString("name"));
m_intent.putExtra("username", m_repositoriesData
.getJSONObject(m_position).getString("username"));
} else if (m_type == "users") {
m_intent = new Intent(Search.this, UserInfo.class);
m_intent.putExtra("username", m_usersData.getJSONObject(
m_position).getString("username"));
}
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
Search.this.startActivityForResult(m_intent, 5005);
}
});
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == 5005) {
Toast.makeText(Search.this, "That user has recently been deleted.", Toast.LENGTH_SHORT).show();
}
}
public void toggleList(String type) {
ListView repositoriesList = (ListView) findViewById(R.id.lv_search_repositories_list);
ListView usersList = (ListView) findViewById(R.id.lv_search_users_list);
TextView title = (TextView) findViewById(R.id.tv_top_bar_title);
if (type == "" || type == null) {
type = (m_type == "repositories") ? "users" : "repositories";
}
m_type = type;
if (m_type == "repositories") {
repositoriesList.setVisibility(View.VISIBLE);
usersList.setVisibility(View.GONE);
title.setText("Search Repositories");
} else if (m_type == "users") {
usersList.setVisibility(View.VISIBLE);
repositoriesList.setVisibility(View.GONE);
title.setText("Search Users");
}
}
private OnClickListener m_btnSearchListener = new OnClickListener() {
public void onClick(View v) {
EditText search_box = (EditText) findViewById(R.id.et_search_search_box);
if (search_box.getText().toString() != "") {
if (m_type == "repositories") {
m_progressDialog = ProgressDialog
.show(Search.this, "Please wait...",
"Searching Repositories...", true);
Thread thread = new Thread(new Runnable() {
public void run() {
initializeList();
runOnUiThread(new Runnable() {
public void run() {
((ListView)findViewById(R.id.lv_search_repositories_list)).setAdapter(m_repositories_adapter);
m_progressDialog.dismiss();
}
});
}
});
thread.start();
} else if (m_type == "users") {
m_progressDialog = ProgressDialog.show(Search.this,
"Please wait...", "Searching Users...", true);
Thread thread = new Thread(new Runnable() {
public void run() {
initializeList();
runOnUiThread(new Runnable() {
public void run() {
((ListView)findViewById(R.id.lv_search_users_list)).setAdapter(m_users_adapter);
m_progressDialog.dismiss();
}
});
}
});
thread.start();
}
}
}
};
private OnClickListener onButtonToggleClickListener = new OnClickListener() {
public void onClick(View v) {
if (v.getId() == R.id.btn_search_repositories) {
toggleList("repositories");
m_type = "repositories";
} else if (v.getId() == R.id.btn_search_users) {
toggleList("users");
m_type = "users";
}
}
};
private OnItemClickListener m_MessageClickedHandler = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
m_position = position;
Thread thread = new Thread(null, threadProc_itemClick);
thread.start();
}
};
public boolean onPrepareOptionsMenu(Menu menu) {
if (!menu.hasVisibleItems()) {
menu.add(0, 0, 0, "Back to Main").setIcon(android.R.drawable.ic_menu_revert);
menu.add(0, 1, 0, "Clear Preferences");
menu.add(0, 2, 0, "Clear Cache");
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
Intent i1 = new Intent(this, Hubroid.class);
startActivity(i1);
return true;
case 1:
m_editor.clear().commit();
Intent intent = new Intent(this, Hubroid.class);
startActivity(intent);
return true;
case 2:
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
File hubroid = new File(root, "hubroid");
if (!hubroid.exists() && !hubroid.isDirectory()) {
return true;
} else {
hubroid.delete();
return true;
}
}
}
return false;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.search);
m_prefs = getSharedPreferences(Hubroid.PREFS_NAME, 0);
m_editor = m_prefs.edit();
m_type = "repositories";
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.containsKey("username")) {
m_username = icicle.getString("username");
} else {
m_username = m_prefs.getString("login", "");
}
} else {
m_username = m_prefs.getString("login", "");
}
}
@Override
public void onStart() {
super.onStart();
((Button) findViewById(R.id.btn_search_repositories))
.setOnClickListener(onButtonToggleClickListener);
((Button) findViewById(R.id.btn_search_users))
.setOnClickListener(onButtonToggleClickListener);
((Button) findViewById(R.id.btn_search_go))
.setOnClickListener(m_btnSearchListener);
((ListView) findViewById(R.id.lv_search_repositories_list))
.setOnItemClickListener(m_MessageClickedHandler);
((ListView) findViewById(R.id.lv_search_users_list))
.setOnItemClickListener(m_MessageClickedHandler);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("type", m_type);
if (m_repositoriesData != null) {
savedInstanceState.putString("repositories_json",
m_repositoriesData.toString());
}
if (m_usersData != null) {
savedInstanceState.putString("users_json", m_usersData.toString());
}
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
m_type = savedInstanceState.getString("type");
try {
if (savedInstanceState.containsKey("repositories_json")) {
m_repositoriesData = new JSONArray(savedInstanceState
.getString("repositories_json"));
} else {
m_repositoriesData = new JSONArray();
}
} catch (JSONException e) {
m_repositoriesData = new JSONArray();
}
try {
if (savedInstanceState.containsKey("users_json")) {
m_usersData = new JSONArray(savedInstanceState
.getString("users_json"));
} else {
m_usersData = new JSONArray();
}
} catch (JSONException e) {
m_usersData = new JSONArray();
}
if (m_repositoriesData.length() > 0) {
m_repositories_adapter = new RepositoriesListAdapter(
Search.this, m_repositoriesData);
} else {
m_repositories_adapter = null;
}
if (m_usersData.length() > 0) {
m_users_adapter = new SearchUsersListAdapter(Search.this, m_usersData);
} else {
m_users_adapter = null;
}
}
@Override
public void onResume() {
super.onResume();
ListView repositories = (ListView) findViewById(R.id.lv_search_repositories_list);
ListView users = (ListView) findViewById(R.id.lv_search_users_list);
repositories.setAdapter(m_repositories_adapter);
users.setAdapter(m_users_adapter);
toggleList(m_type);
}
}
|
src/org/idlesoft/android/hubroid/Search.java
|
/**
* Hubroid - A GitHub app for Android
*
* Copyright (c) 2010 Eddie Ringle.
*
* Licensed under the New BSD License.
*/
package org.idlesoft.android.hubroid;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Search extends Activity {
private RepositoriesListAdapter m_repositories_adapter;
private SearchUsersListAdapter m_users_adapter;
public ProgressDialog m_progressDialog;
private SharedPreferences m_prefs;
private SharedPreferences.Editor m_editor;
public String m_username;
public String m_type;
public JSONArray m_repositoriesData;
public JSONArray m_usersData;
public Intent m_intent;
public int m_position;
public void initializeList() {
try {
if (m_type == "repositories") {
URL query = new URL(
"http://github.com/api/v2/json/repos/search/"
+ URLEncoder
.encode(((EditText) findViewById(R.id.et_search_search_box))
.getText().toString()));
m_repositoriesData = Hubroid.make_api_request(query)
.getJSONArray("repositories");
if (m_repositoriesData == null) {
runOnUiThread(new Runnable() {
public void run() {
Toast
.makeText(
Search.this,
"Error gathering repository data, please try again.",
Toast.LENGTH_SHORT).show();
}
});
} else {
m_repositories_adapter = new RepositoriesListAdapter(
getApplicationContext(), m_repositoriesData);
}
} else if (m_type == "users") {
URL query = new URL(
"http://github.com/api/v2/json/user/search/"
+ URLEncoder
.encode(((EditText) findViewById(R.id.et_search_search_box))
.getText().toString()));
m_usersData = Hubroid.make_api_request(query).getJSONArray(
"users");
if (m_usersData == null) {
runOnUiThread(new Runnable() {
public void run() {
Toast
.makeText(
Search.this,
"Error gathering user data, please try again.",
Toast.LENGTH_SHORT).show();
}
});
} else {
m_users_adapter = new SearchUsersListAdapter(
getApplicationContext(), m_usersData);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
private Runnable threadProc_itemClick = new Runnable() {
public void run() {
try {
if (m_type == "repositories") {
m_intent = new Intent(Search.this, RepositoryInfo.class);
m_intent.putExtra("repo_name", m_repositoriesData
.getJSONObject(m_position).getString("name"));
m_intent.putExtra("username", m_repositoriesData
.getJSONObject(m_position).getString("username"));
} else if (m_type == "users") {
m_intent = new Intent(Search.this, UserInfo.class);
m_intent.putExtra("username", m_usersData.getJSONObject(
m_position).getString("username"));
}
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
Search.this.startActivityForResult(m_intent, 5005);
}
});
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == 5005) {
Toast.makeText(Search.this, "That user has recently been deleted.", Toast.LENGTH_SHORT);
}
}
public void toggleList(String type) {
ListView repositoriesList = (ListView) findViewById(R.id.lv_search_repositories_list);
ListView usersList = (ListView) findViewById(R.id.lv_search_users_list);
TextView title = (TextView) findViewById(R.id.tv_top_bar_title);
if (type == "" || type == null) {
type = (m_type == "repositories") ? "users" : "repositories";
}
m_type = type;
if (m_type == "repositories") {
repositoriesList.setVisibility(View.VISIBLE);
usersList.setVisibility(View.GONE);
title.setText("Search Repositories");
} else if (m_type == "users") {
usersList.setVisibility(View.VISIBLE);
repositoriesList.setVisibility(View.GONE);
title.setText("Search Users");
}
}
private OnClickListener m_btnSearchListener = new OnClickListener() {
public void onClick(View v) {
EditText search_box = (EditText) findViewById(R.id.et_search_search_box);
if (search_box.getText().toString() != "") {
if (m_type == "repositories") {
m_progressDialog = ProgressDialog
.show(Search.this, "Please wait...",
"Searching Repositories...", true);
Thread thread = new Thread(new Runnable() {
public void run() {
initializeList();
runOnUiThread(new Runnable() {
public void run() {
((ListView)findViewById(R.id.lv_search_repositories_list)).setAdapter(m_repositories_adapter);
m_progressDialog.dismiss();
}
});
}
});
thread.start();
} else if (m_type == "users") {
m_progressDialog = ProgressDialog.show(Search.this,
"Please wait...", "Searching Users...", true);
Thread thread = new Thread(new Runnable() {
public void run() {
initializeList();
runOnUiThread(new Runnable() {
public void run() {
((ListView)findViewById(R.id.lv_search_users_list)).setAdapter(m_users_adapter);
m_progressDialog.dismiss();
}
});
}
});
thread.start();
}
}
}
};
private OnClickListener onButtonToggleClickListener = new OnClickListener() {
public void onClick(View v) {
if (v.getId() == R.id.btn_search_repositories) {
toggleList("repositories");
m_type = "repositories";
} else if (v.getId() == R.id.btn_search_users) {
toggleList("users");
m_type = "users";
}
}
};
private OnItemClickListener m_MessageClickedHandler = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
m_position = position;
Thread thread = new Thread(null, threadProc_itemClick);
thread.start();
}
};
public boolean onPrepareOptionsMenu(Menu menu) {
if (!menu.hasVisibleItems()) {
menu.add(0, 0, 0, "Back to Main").setIcon(android.R.drawable.ic_menu_revert);
menu.add(0, 1, 0, "Clear Preferences");
menu.add(0, 2, 0, "Clear Cache");
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
Intent i1 = new Intent(this, Hubroid.class);
startActivity(i1);
return true;
case 1:
m_editor.clear().commit();
Intent intent = new Intent(this, Hubroid.class);
startActivity(intent);
return true;
case 2:
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
File hubroid = new File(root, "hubroid");
if (!hubroid.exists() && !hubroid.isDirectory()) {
return true;
} else {
hubroid.delete();
return true;
}
}
}
return false;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.search);
m_prefs = getSharedPreferences(Hubroid.PREFS_NAME, 0);
m_editor = m_prefs.edit();
m_type = "repositories";
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.containsKey("username")) {
m_username = icicle.getString("username");
} else {
m_username = m_prefs.getString("login", "");
}
} else {
m_username = m_prefs.getString("login", "");
}
}
@Override
public void onStart() {
super.onStart();
((Button) findViewById(R.id.btn_search_repositories))
.setOnClickListener(onButtonToggleClickListener);
((Button) findViewById(R.id.btn_search_users))
.setOnClickListener(onButtonToggleClickListener);
((Button) findViewById(R.id.btn_search_go))
.setOnClickListener(m_btnSearchListener);
((ListView) findViewById(R.id.lv_search_repositories_list))
.setOnItemClickListener(m_MessageClickedHandler);
((ListView) findViewById(R.id.lv_search_users_list))
.setOnItemClickListener(m_MessageClickedHandler);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("type", m_type);
if (m_repositoriesData != null) {
savedInstanceState.putString("repositories_json",
m_repositoriesData.toString());
}
if (m_usersData != null) {
savedInstanceState.putString("users_json", m_usersData.toString());
}
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
m_type = savedInstanceState.getString("type");
try {
if (savedInstanceState.containsKey("repositories_json")) {
m_repositoriesData = new JSONArray(savedInstanceState
.getString("repositories_json"));
} else {
m_repositoriesData = new JSONArray();
}
} catch (JSONException e) {
m_repositoriesData = new JSONArray();
}
try {
if (savedInstanceState.containsKey("users_json")) {
m_usersData = new JSONArray(savedInstanceState
.getString("users_json"));
} else {
m_usersData = new JSONArray();
}
} catch (JSONException e) {
m_usersData = new JSONArray();
}
if (m_repositoriesData.length() > 0) {
m_repositories_adapter = new RepositoriesListAdapter(
Search.this, m_repositoriesData);
} else {
m_repositories_adapter = null;
}
if (m_usersData.length() > 0) {
m_users_adapter = new SearchUsersListAdapter(Search.this, m_usersData);
} else {
m_users_adapter = null;
}
}
@Override
public void onResume() {
super.onResume();
ListView repositories = (ListView) findViewById(R.id.lv_search_repositories_list);
ListView users = (ListView) findViewById(R.id.lv_search_users_list);
repositories.setAdapter(m_repositories_adapter);
users.setAdapter(m_users_adapter);
toggleList(m_type);
}
}
|
Actually show this toast notification.
Signed-off-by: Eddie Ringle <[email protected]>
|
src/org/idlesoft/android/hubroid/Search.java
|
Actually show this toast notification.
|
<ide><path>rc/org/idlesoft/android/hubroid/Search.java
<ide> protected void onActivityResult(int requestCode, int resultCode, Intent data)
<ide> {
<ide> if (resultCode == 5005) {
<del> Toast.makeText(Search.this, "That user has recently been deleted.", Toast.LENGTH_SHORT);
<add> Toast.makeText(Search.this, "That user has recently been deleted.", Toast.LENGTH_SHORT).show();
<ide> }
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
69fe94c17e841252b92fe8d8efbf6a6b2c741e9e
| 0 |
datastax/java-driver,datastax/java-driver
|
/*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.oss.driver.api.testinfra.ccm;
import com.datastax.oss.driver.api.core.Version;
public class DefaultCcmBridgeBuilderCustomizer {
public static CcmBridge.Builder configureBuilder(CcmBridge.Builder builder) {
if (!CcmBridge.DSE_ENABLEMENT
&& CcmBridge.VERSION.nextStable().compareTo(Version.V4_0_0) >= 0) {
builder.withCassandraConfiguration("enable_materialized_views", true);
builder.withCassandraConfiguration("enable_sasi_indexes", true);
}
return builder;
}
}
|
test-infra/src/main/java/com/datastax/oss/driver/api/testinfra/ccm/DefaultCcmBridgeBuilderCustomizer.java
|
/*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.oss.driver.api.testinfra.ccm;
import com.datastax.oss.driver.api.core.Version;
public class DefaultCcmBridgeBuilderCustomizer {
public static CcmBridge.Builder configureBuilder(CcmBridge.Builder builder) {
if (!CcmBridge.DSE_ENABLEMENT && CcmBridge.VERSION.compareTo(Version.V4_0_0) >= 0) {
builder.withCassandraConfiguration("enable_materialized_views", true);
}
return builder;
}
}
|
Enable SASI indexes when running mapper tests against C* 4
|
test-infra/src/main/java/com/datastax/oss/driver/api/testinfra/ccm/DefaultCcmBridgeBuilderCustomizer.java
|
Enable SASI indexes when running mapper tests against C* 4
|
<ide><path>est-infra/src/main/java/com/datastax/oss/driver/api/testinfra/ccm/DefaultCcmBridgeBuilderCustomizer.java
<ide> public class DefaultCcmBridgeBuilderCustomizer {
<ide>
<ide> public static CcmBridge.Builder configureBuilder(CcmBridge.Builder builder) {
<del> if (!CcmBridge.DSE_ENABLEMENT && CcmBridge.VERSION.compareTo(Version.V4_0_0) >= 0) {
<add> if (!CcmBridge.DSE_ENABLEMENT
<add> && CcmBridge.VERSION.nextStable().compareTo(Version.V4_0_0) >= 0) {
<ide> builder.withCassandraConfiguration("enable_materialized_views", true);
<add> builder.withCassandraConfiguration("enable_sasi_indexes", true);
<ide> }
<ide> return builder;
<ide> }
|
|
Java
|
apache-2.0
|
4fd25aabd0b054f5ef1765b4cb41349ab2ecbaf1
| 0 |
Valkryst/VTerminal
|
package com.valkryst.VTerminal.printer;
import com.valkryst.VTerminal.Tile;
import com.valkryst.VTerminal.TileGrid;
import com.valkryst.VTerminal.misc.ShapeAlgorithms;
import lombok.*;
import java.awt.Dimension;
import java.awt.Point;
@EqualsAndHashCode
@ToString
public class EllipsePrinter {
/** The width/height of the ellipse to print. */
@Getter private final Dimension dimensions = new Dimension(2, 2);
/** The character to print the ellipse with. */
@Getter @Setter private char printChar = '█';
/**
* Prints an ellipse on a tile grid.
*
* @param grid
* The grid.
*
* @param position
* The x/y-axis (column/row) coordinates of the top-left character.
*
* @throws NullPointerException
* If the component or position is null.
*/
public void print(final @NonNull TileGrid grid, final @NonNull Point position) {
for (final Point point : ShapeAlgorithms.getEllipse(position, dimensions)) {
final Tile tile = grid.getTileAt(point);
if (tile != null) {
tile.setCharacter(printChar);
}
}
}
/**
* Prints a filled ellipse on a tile grid.
*
* @param grid
* The grid.
*
* @param position
* The x/y-axis (column/row) coordinates of the top-left character.
*
* @throws NullPointerException
* If the grid or position is null.
*/
public void printFilled(final @NonNull TileGrid grid, final @NonNull Point position) {
for (final Point point : ShapeAlgorithms.getFilledEllipse(position, dimensions)) {
final Tile tile = grid.getTileAt(point);
if (tile != null) {
tile.setCharacter(printChar);
}
}
}
/**
* Sets the width.
*
* @param width
* The new width.
*
* @return
* This.
*/
public EllipsePrinter setWidth(final int width) {
if (width > 0) {
dimensions.setSize(width, dimensions.height);
}
return this;
}
/**
* Sets the height.
*
* @param height
* The new height.
*
* @return
* This.
*/
public EllipsePrinter setHeight(final int height) {
if (height > 0) {
dimensions.setSize(dimensions.width, height);
}
return this;
}
}
|
src/com/valkryst/VTerminal/printer/EllipsePrinter.java
|
package com.valkryst.VTerminal.printer;
import com.valkryst.VTerminal.Tile;
import com.valkryst.VTerminal.component.Component;
import com.valkryst.VTerminal.misc.ShapeAlgorithms;
import lombok.*;
import java.awt.Dimension;
import java.awt.Point;
@EqualsAndHashCode
@ToString
public class EllipsePrinter {
/** The width/height of the ellipse to print. */
@Getter private final Dimension dimensions = new Dimension(2, 2);
/** The character to print the ellipse with. */
@Getter @Setter private char printChar = '█';
/**
* Prints an ellipse on a component.
*
* @param component
* The component.
*
* @param position
* The x/y-axis (column/row) coordinates of the top-left character.
*
* @throws NullPointerException
* If the component or position is null.
*/
public void print(final @NonNull Component component, final @NonNull Point position) {
for (final Point point : ShapeAlgorithms.getEllipse(position, dimensions)) {
final Tile tile = component.getTiles().getTileAt(position);
if (tile != null) {
tile.setCharacter(printChar);
}
}
}
/**
* Prints a filled ellipse on a component.
*
* @param component
* The component.
*
* @param position
* The x/y-axis (column/row) coordinates of the top-left character.
*
* @throws NullPointerException
* If the component or position is null.
*/
public void printFilled(final @NonNull Component component, final @NonNull Point position) {
for (final Point point : ShapeAlgorithms.getFilledEllipse(position, dimensions)) {
final Tile tile = component.getTiles().getTileAt(position);
if (tile != null) {
tile.setCharacter(printChar);
}
}
}
/**
* Sets the width.
*
* @param width
* The new width.
*
* @return
* This.
*/
public EllipsePrinter setWidth(final int width) {
if (width > 0) {
dimensions.setSize(width, dimensions.height);
}
return this;
}
/**
* Sets the height.
*
* @param height
* The new height.
*
* @return
* This.
*/
public EllipsePrinter setHeight(final int height) {
if (height > 0) {
dimensions.setSize(dimensions.width, height);
}
return this;
}
}
|
Updates EllipsePrinter to print onto a TileGrid.
Also fixes a draw bug.
|
src/com/valkryst/VTerminal/printer/EllipsePrinter.java
|
Updates EllipsePrinter to print onto a TileGrid. Also fixes a draw bug.
|
<ide><path>rc/com/valkryst/VTerminal/printer/EllipsePrinter.java
<ide> package com.valkryst.VTerminal.printer;
<ide>
<ide> import com.valkryst.VTerminal.Tile;
<del>import com.valkryst.VTerminal.component.Component;
<add>import com.valkryst.VTerminal.TileGrid;
<ide> import com.valkryst.VTerminal.misc.ShapeAlgorithms;
<ide> import lombok.*;
<ide>
<ide> @Getter @Setter private char printChar = '█';
<ide>
<ide> /**
<del> * Prints an ellipse on a component.
<add> * Prints an ellipse on a tile grid.
<ide> *
<del> * @param component
<del> * The component.
<add> * @param grid
<add> * The grid.
<ide> *
<ide> * @param position
<ide> * The x/y-axis (column/row) coordinates of the top-left character.
<ide> * @throws NullPointerException
<ide> * If the component or position is null.
<ide> */
<del> public void print(final @NonNull Component component, final @NonNull Point position) {
<add> public void print(final @NonNull TileGrid grid, final @NonNull Point position) {
<ide> for (final Point point : ShapeAlgorithms.getEllipse(position, dimensions)) {
<del> final Tile tile = component.getTiles().getTileAt(position);
<add> final Tile tile = grid.getTileAt(point);
<ide>
<ide> if (tile != null) {
<ide> tile.setCharacter(printChar);
<ide> }
<ide>
<ide> /**
<del> * Prints a filled ellipse on a component.
<add> * Prints a filled ellipse on a tile grid.
<ide> *
<del> * @param component
<del> * The component.
<add> * @param grid
<add> * The grid.
<ide> *
<ide> * @param position
<ide> * The x/y-axis (column/row) coordinates of the top-left character.
<ide> *
<ide> * @throws NullPointerException
<del> * If the component or position is null.
<add> * If the grid or position is null.
<ide> */
<del> public void printFilled(final @NonNull Component component, final @NonNull Point position) {
<add> public void printFilled(final @NonNull TileGrid grid, final @NonNull Point position) {
<ide> for (final Point point : ShapeAlgorithms.getFilledEllipse(position, dimensions)) {
<del> final Tile tile = component.getTiles().getTileAt(position);
<add> final Tile tile = grid.getTileAt(point);
<ide>
<ide> if (tile != null) {
<ide> tile.setCharacter(printChar);
|
|
JavaScript
|
agpl-3.0
|
b4c6c7f2232aa0e986d6664bf0b397439630ce5d
| 0 |
renalreg/radar-client,renalreg/radar-client,renalreg/radar-client
|
(function() {
'use strict';
var app = angular.module('radar.patients.addresses');
app.factory('PatientAddressModel', ['Model', function(Model) {
function PatientAddressModel(modelName, data) {
Model.call(this, modelName, data);
}
PatientAddressModel.prototype = Object.create(Model.prototype);
PatientAddressModel.prototype.getAddress = function(demographics) {
if (demographics === undefined) {
demographics = true;
}
var lines = [];
if (demographics) {
if (this.address1) {
lines.push(this.address1);
}
if (this.address2) {
lines.push(this.address2);
}
if (this.address3) {
lines.push(this.address3);
}
if (this.address4) {
lines.push(this.address4);
}
if (this.postcode) {
lines.push(this.postcode);
}
} else {
if (this.postcode) {
// Postcode parts should be separated by a space but limit to first 4 charcters just in case
var area = this.postcode.split(' ')[0].substring(0, 4);
lines.push(area);
}
}
return lines.join(',\n');
};
return PatientAddressModel;
}]);
app.config(['storeProvider', function(storeProvider) {
storeProvider.registerModel('patient-addresses', 'PatientAddressModel');
storeProvider.registerMixin('patient-addresses', 'SourceModelMixin');
}]);
})();
|
src/app/patients/addresses/address-model.js
|
(function() {
'use strict';
var app = angular.module('radar.patients.addresses');
app.factory('PatientAddressModel', ['Model', function(Model) {
function PatientAddressModel(modelName, data) {
Model.call(this, modelName, data);
}
PatientAddressModel.prototype = Object.create(Model.prototype);
PatientAddressModel.prototype.getAddress = function(demographics) {
if (demographics === undefined) {
demographics = true;
}
var lines = [];
if (demographics) {
if (this.address1) {
lines.push(this.address1);
}
if (this.address2) {
lines.push(this.address2);
}
if (this.address3) {
lines.push(this.address3);
}
if (this.address4) {
lines.push(this.address4);
}
if (this.postcode) {
lines.push(this.postcode);
}
} else {
if (this.postcode) {
// Postcode parts should be separated by a space but limit to first 4 charcters just in case
var area = this.postcode.split(' ')[0].substring(0, 4)
lines.push(area);
}
}
return lines.join(',\n');
};
return PatientAddressModel;
}]);
app.config(['storeProvider', function(storeProvider) {
storeProvider.registerModel('patient-addresses', 'PatientAddressModel');
storeProvider.registerMixin('patient-addresses', 'SourceModelMixin');
}]);
})();
|
Add missing semicolon
|
src/app/patients/addresses/address-model.js
|
Add missing semicolon
|
<ide><path>rc/app/patients/addresses/address-model.js
<ide> } else {
<ide> if (this.postcode) {
<ide> // Postcode parts should be separated by a space but limit to first 4 charcters just in case
<del> var area = this.postcode.split(' ')[0].substring(0, 4)
<add> var area = this.postcode.split(' ')[0].substring(0, 4);
<ide> lines.push(area);
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
395fddafcedf30850c2bd380a8b25499f7ea0a72
| 0 |
codeaudit/OG-Platform,codeaudit/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,jeorme/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform
|
/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.riskfactors;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang.NotImplementedException;
import com.google.common.collect.ImmutableSet;
import com.opengamma.core.position.Portfolio;
import com.opengamma.core.position.PortfolioNode;
import com.opengamma.core.position.Position;
import com.opengamma.core.position.impl.AbstractPortfolioNodeTraversalCallback;
import com.opengamma.core.position.impl.PortfolioNodeTraverser;
import com.opengamma.core.security.SecuritySource;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.view.ViewCalculationConfiguration;
import com.opengamma.financial.analytics.FilteringSummingFunction;
import com.opengamma.financial.analytics.conversion.SwapSecurityUtils;
import com.opengamma.financial.analytics.fixedincome.InterestRateInstrumentType;
import com.opengamma.financial.analytics.ircurve.YieldCurveFunction;
import com.opengamma.financial.analytics.model.InstrumentTypeProperties;
import com.opengamma.financial.analytics.model.forex.option.black.deprecated.FXOptionBlackFunctionDeprecated;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.FinancialSecurityVisitorAdapter;
import com.opengamma.financial.security.bond.CorporateBondSecurity;
import com.opengamma.financial.security.bond.GovernmentBondSecurity;
import com.opengamma.financial.security.bond.MunicipalBondSecurity;
import com.opengamma.financial.security.capfloor.CapFloorCMSSpreadSecurity;
import com.opengamma.financial.security.capfloor.CapFloorSecurity;
import com.opengamma.financial.security.cash.CashSecurity;
import com.opengamma.financial.security.deposit.ContinuousZeroDepositSecurity;
import com.opengamma.financial.security.deposit.PeriodicZeroDepositSecurity;
import com.opengamma.financial.security.deposit.SimpleZeroDepositSecurity;
import com.opengamma.financial.security.equity.EquitySecurity;
import com.opengamma.financial.security.equity.EquityVarianceSwapSecurity;
import com.opengamma.financial.security.fra.FRASecurity;
import com.opengamma.financial.security.future.AgricultureFutureSecurity;
import com.opengamma.financial.security.future.BondFutureSecurity;
import com.opengamma.financial.security.future.EnergyFutureSecurity;
import com.opengamma.financial.security.future.EquityFutureSecurity;
import com.opengamma.financial.security.future.EquityIndexDividendFutureSecurity;
import com.opengamma.financial.security.future.FXFutureSecurity;
import com.opengamma.financial.security.future.IndexFutureSecurity;
import com.opengamma.financial.security.future.InterestRateFutureSecurity;
import com.opengamma.financial.security.future.MetalFutureSecurity;
import com.opengamma.financial.security.future.StockFutureSecurity;
import com.opengamma.financial.security.fx.FXForwardSecurity;
import com.opengamma.financial.security.fx.NonDeliverableFXForwardSecurity;
import com.opengamma.financial.security.option.CommodityFutureOptionSecurity;
import com.opengamma.financial.security.option.EquityBarrierOptionSecurity;
import com.opengamma.financial.security.option.EquityIndexDividendFutureOptionSecurity;
import com.opengamma.financial.security.option.EquityIndexOptionSecurity;
import com.opengamma.financial.security.option.EquityOptionSecurity;
import com.opengamma.financial.security.option.FXBarrierOptionSecurity;
import com.opengamma.financial.security.option.FXDigitalOptionSecurity;
import com.opengamma.financial.security.option.FXOptionSecurity;
import com.opengamma.financial.security.option.IRFutureOptionSecurity;
import com.opengamma.financial.security.option.NonDeliverableFXDigitalOptionSecurity;
import com.opengamma.financial.security.option.NonDeliverableFXOptionSecurity;
import com.opengamma.financial.security.option.SwaptionSecurity;
import com.opengamma.financial.security.swap.InterestRateNotional;
import com.opengamma.financial.security.swap.Notional;
import com.opengamma.financial.security.swap.SwapSecurity;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
import com.opengamma.util.tuple.Pair;
/**
* Default implementation of {@link RiskFactorsGatherer}.
*/
public class DefaultRiskFactorsGatherer extends FinancialSecurityVisitorAdapter<Set<Pair<String, ValueProperties>>> implements RiskFactorsGatherer {
private final SecuritySource _securities;
private final RiskFactorsConfigurationProvider _configProvider;
public DefaultRiskFactorsGatherer(final SecuritySource securities, final RiskFactorsConfigurationProvider configProvider) {
ArgumentChecker.notNull(securities, "securities");
ArgumentChecker.notNull(configProvider, "configProvider");
_securities = securities;
_configProvider = configProvider;
}
@Override
public Set<ValueRequirement> getPositionRiskFactors(final Position position) {
ArgumentChecker.notNull(position, "position");
final Set<Pair<String, ValueProperties>> securityRiskFactors = ((FinancialSecurity) position.getSecurity()).accept(this);
if (securityRiskFactors.isEmpty()) {
return ImmutableSet.of();
}
final Set<ValueRequirement> results = new HashSet<ValueRequirement>(securityRiskFactors.size());
for (final Pair<String, ValueProperties> securityRiskFactor : securityRiskFactors) {
results.add(getValueRequirement(position, securityRiskFactor.getFirst(), securityRiskFactor.getSecond()));
}
return results;
}
@Override
public Set<ValueRequirement> getPositionRiskFactors(final Portfolio portfolio) {
ArgumentChecker.notNull(portfolio, "portfolio");
final RiskFactorPortfolioTraverser callback = new RiskFactorPortfolioTraverser();
callback.traverse(portfolio.getRootNode());
return callback.getRiskFactors();
}
@Override
public void addPortfolioRiskFactors(final Portfolio portfolio, final ViewCalculationConfiguration calcConfig) {
ArgumentChecker.notNull(portfolio, "portfolio");
ArgumentChecker.notNull(calcConfig, "calcConfig");
final RiskFactorPortfolioTraverser callback = new RiskFactorPortfolioTraverser(calcConfig);
callback.traverse(portfolio.getRootNode());
}
//-------------------------------------------------------------------------
private class RiskFactorPortfolioTraverser extends AbstractPortfolioNodeTraversalCallback {
private final ViewCalculationConfiguration _calcConfig;
private final Set<ValueRequirement> _valueRequirements = new HashSet<ValueRequirement>();
public RiskFactorPortfolioTraverser() {
this(null);
}
public RiskFactorPortfolioTraverser(final ViewCalculationConfiguration calcConfig) {
_calcConfig = calcConfig;
}
public void traverse(final PortfolioNode rootNode) {
PortfolioNodeTraverser.depthFirst(this).traverse(rootNode);
}
public Set<ValueRequirement> getRiskFactors() {
return new HashSet<ValueRequirement>(_valueRequirements);
}
@Override
public void preOrderOperation(final PortfolioNode portfolioNode) {
}
@Override
public void preOrderOperation(final Position position) {
final Set<ValueRequirement> riskFactorRequirements = DefaultRiskFactorsGatherer.this.getPositionRiskFactors(position);
_valueRequirements.addAll(riskFactorRequirements);
if (_calcConfig != null) {
for (final ValueRequirement riskFactorRequirement : riskFactorRequirements) {
_calcConfig.addPortfolioRequirement(position.getSecurity().getSecurityType(),
riskFactorRequirement.getValueName(), riskFactorRequirement.getConstraints());
}
}
}
@Override
public void postOrderOperation(final Position position) {
}
@Override
public void postOrderOperation(final PortfolioNode portfolioNode) {
}
}
//-------------------------------------------------------------------------
// Securities
@Override
public Set<Pair<String, ValueProperties>> visitCorporateBondSecurity(CorporateBondSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getPresentValue(ValueProperties.builder()),
getPV01(getFundingCurve()),
getPV01(getForwardCurve(security.getCurrency())));
}
@Override
public Set<Pair<String, ValueProperties>> visitGovernmentBondSecurity(GovernmentBondSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getPresentValue(ValueProperties.builder()),
getPV01(getFundingCurve()),
getPV01(getForwardCurve(security.getCurrency())));
}
@Override
public Set<Pair<String, ValueProperties>> visitMunicipalBondSecurity(MunicipalBondSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getPresentValue(ValueProperties.builder()),
getPV01(getFundingCurve()),
getPV01(getForwardCurve(security.getCurrency())));
}
@Override
public Set<Pair<String, ValueProperties>> visitCashSecurity(final CashSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()),
getPresentValue(ValueProperties.builder()),
getPV01(getFundingCurve()),
getPV01(getForwardCurve(security.getCurrency())));
}
@Override
public Set<Pair<String, ValueProperties>> visitEquitySecurity(final EquitySecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitFRASecurity(final FRASecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()),
getPresentValue(ValueProperties.builder()),
getPV01(getFundingCurve()),
getPV01(getForwardCurve(security.getCurrency())));
}
@Override
public Set<Pair<String, ValueProperties>> visitSwapSecurity(final SwapSecurity security) {
final ImmutableSet.Builder<Pair<String, ValueProperties>> builder = ImmutableSet.<Pair<String, ValueProperties>>builder();
// At the moment pay and receive must be the same currency, so any one of them is sufficient
final Notional payNotional = security.getPayLeg().getNotional();
final Notional receiveNotional = security.getReceiveLeg().getNotional();
if (payNotional instanceof InterestRateNotional && receiveNotional instanceof InterestRateNotional) {
final Currency ccy = ((InterestRateNotional) payNotional).getCurrency();
builder.add(getYieldCurveNodeSensitivities(getFundingCurve(), ccy));
builder.add(getYieldCurveNodeSensitivities(getForwardCurve(ccy), ccy));
final InterestRateInstrumentType type = SwapSecurityUtils.getSwapType(security);
if (type == InterestRateInstrumentType.SWAP_CMS_CMS ||
type == InterestRateInstrumentType.SWAP_FIXED_CMS ||
type == InterestRateInstrumentType.SWAP_IBOR_CMS) {
builder.add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG")));
} else if (type == InterestRateInstrumentType.SWAP_FIXED_IBOR ||
type == InterestRateInstrumentType.SWAP_FIXED_IBOR_WITH_SPREAD ||
type == InterestRateInstrumentType.SWAP_IBOR_IBOR) {
builder.add(getPV01(getFundingCurve()));
builder.add(getPV01(getForwardCurve(ccy)));
}
}
builder.add(getPresentValue(ValueProperties.builder()));
return builder.build();
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityIndexOptionSecurity(final EquityIndexOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.addAll(getSabrSensitivities())
.add(getPresentValue(ValueProperties.builder())).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityOptionSecurity(final EquityOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getValueDelta()).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityBarrierOptionSecurity(final EquityBarrierOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.addAll(getSabrSensitivities())
.add(getPresentValue(ValueProperties.builder()))
.add(getVegaMatrix(ValueProperties.builder())).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitFXOptionSecurity(final FXOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getFXPresentValue(ValueProperties
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_FORWARD_CURVE, getForwardCurve(security.getPutCurrency()))
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_FORWARD_CURVE, getForwardCurve(security.getCallCurrency()))))
.add(getFXCurrencyExposure(ValueProperties
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_FORWARD_CURVE, getForwardCurve(security.getPutCurrency()))
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_FORWARD_CURVE, getForwardCurve(security.getCallCurrency()))))
.add(getVegaMatrix(ValueProperties
.with(ValuePropertyNames.SURFACE, "DEFAULT") //TODO this should not be hard-coded
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_CURVE, getFundingCurve())
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.FOREX)))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build();
}
// REVIEW: jim 23-Jan-2012 -- bit of a leap to assume it's the same as FX Options...
@Override
public Set<Pair<String, ValueProperties>> visitNonDeliverableFXDigitalOptionSecurity(final NonDeliverableFXDigitalOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getFXPresentValue())
.add(getFXCurrencyExposure())
.add(getVegaMatrix(ValueProperties
.with(ValuePropertyNames.SURFACE, "DEFAULT") //TODO this should not be hard-coded
.with(ValuePropertyNames.PAY_CURVE, getFundingCurve())
.with(ValuePropertyNames.RECEIVE_CURVE, getFundingCurve())
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.FOREX)))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build();
}
// REVIEW: jim 23-Jan-2012 -- bit of a leap to assume it's the same as FX Options...
@Override
public Set<Pair<String, ValueProperties>> visitNonDeliverableFXOptionSecurity(final NonDeliverableFXOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getFXPresentValue())
.add(getFXCurrencyExposure())
.add(getVegaMatrix(ValueProperties
.with(ValuePropertyNames.SURFACE, "DEFAULT") //TODO this should not be hard-coded
.with(ValuePropertyNames.PAY_CURVE, getFundingCurve())
.with(ValuePropertyNames.RECEIVE_CURVE, getFundingCurve())
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.FOREX)))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitSwaptionSecurity(final SwaptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()))
.addAll(getSabrSensitivities())
.add(getPresentValue(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG")))
.add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitIRFutureOptionSecurity(final IRFutureOptionSecurity security) {
final Currency ccy = security.getCurrency();
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.addAll(getSabrSensitivities())
.add(getYieldCurveNodeSensitivities(getFundingCurve(), ccy))
.add(getYieldCurveNodeSensitivities(getForwardCurve(ccy), ccy))
.add(getPresentValue(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT")))
.add(getVegaMatrix(ValueProperties
.with(ValuePropertyNames.SURFACE, "DEFAULT")
.with(YieldCurveFunction.PROPERTY_FUNDING_CURVE, getFundingCurve())
.with(YieldCurveFunction.PROPERTY_FORWARD_CURVE, getForwardCurve(ccy))
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.IR_FUTURE_OPTION))).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitCommodityFutureOptionSecurity(CommodityFutureOptionSecurity commodityFutureOptionSecurity) {
throw new NotImplementedException();
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityIndexDividendFutureOptionSecurity(
final EquityIndexDividendFutureOptionSecurity equityIndexDividendFutureOptionSecurity) {
throw new NotImplementedException();
}
@Override
public Set<Pair<String, ValueProperties>> visitFXBarrierOptionSecurity(final FXBarrierOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getFXPresentValue(ValueProperties
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_FORWARD_CURVE, getForwardCurve(security.getPutCurrency()))
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_FORWARD_CURVE, getForwardCurve(security.getCallCurrency()))))
.add(getFXCurrencyExposure(ValueProperties
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_FORWARD_CURVE, getForwardCurve(security.getPutCurrency()))
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_FORWARD_CURVE, getForwardCurve(security.getCallCurrency()))))
.add(getVegaMatrix(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT")))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitFXDigitalOptionSecurity(final FXDigitalOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getFXPresentValue())
.add(getFXCurrencyExposure())
.add(getVegaMatrix(ValueProperties
.with(ValuePropertyNames.SURFACE, "DEFAULT") //TODO this should not be hard-coded
.with(ValuePropertyNames.PAY_CURVE, getFundingCurve())
.with(ValuePropertyNames.RECEIVE_CURVE, getFundingCurve())
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.FOREX)))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build();
}
@SuppressWarnings("unchecked")
@Override
public Set<Pair<String, ValueProperties>> visitFXForwardSecurity(final FXForwardSecurity security) {
return ImmutableSet.of(
getFXPresentValue(),
getFXCurrencyExposure(),
getYieldCurveNodeSensitivities(getFundingCurve(), security.getPayCurrency()),
getYieldCurveNodeSensitivities(getFundingCurve(), security.getReceiveCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getPayCurrency()), security.getPayCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getReceiveCurrency()), security.getReceiveCurrency()));
}
// REVIEW jim 23-Jan-2012 -- bit of a leap to copy fx forwards, but there you go.
@SuppressWarnings("unchecked")
@Override
public Set<Pair<String, ValueProperties>> visitNonDeliverableFXForwardSecurity(
final NonDeliverableFXForwardSecurity security) {
return ImmutableSet.of(
getFXPresentValue(),
getFXCurrencyExposure(),
getYieldCurveNodeSensitivities(getFundingCurve(), security.getPayCurrency()),
getYieldCurveNodeSensitivities(getFundingCurve(), security.getReceiveCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getPayCurrency()), security.getPayCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getReceiveCurrency()), security.getReceiveCurrency()));
}
@Override
public Set<Pair<String, ValueProperties>> visitCapFloorSecurity(final CapFloorSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()))
.addAll(getSabrSensitivities())
.add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG")))
.add(getPresentValue(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitCapFloorCMSSpreadSecurity(final CapFloorCMSSpreadSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()))
.addAll(getSabrSensitivities())
.add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG")))
.add(getPresentValue(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityVarianceSwapSecurity(final EquityVarianceSwapSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getPresentValue(ValueProperties.builder()))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()))
.add(getVegaMatrix(ValueProperties
.with(ValuePropertyNames.SURFACE, "DEFAULT")
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, "EQUITY_OPTION"))).build();
}
//-------------------------------------------------------------------------
// Futures
@Override
public Set<Pair<String, ValueProperties>> visitAgricultureFutureSecurity(final AgricultureFutureSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitBondFutureSecurity(final BondFutureSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()));
}
@Override
public Set<Pair<String, ValueProperties>> visitEnergyFutureSecurity(final EnergyFutureSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitFXFutureSecurity(final FXFutureSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitIndexFutureSecurity(final IndexFutureSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitInterestRateFutureSecurity(final InterestRateFutureSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()),
getPresentValue(ValueProperties.builder()),
getPV01(getFundingCurve()),
getPV01(getForwardCurve(security.getCurrency())));
}
@Override
public Set<Pair<String, ValueProperties>> visitMetalFutureSecurity(final MetalFutureSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitStockFutureSecurity(final StockFutureSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityFutureSecurity(final EquityFutureSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getPresentValue(ValueProperties.builder()));
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityIndexDividendFutureSecurity(final EquityIndexDividendFutureSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getPresentValue(ValueProperties.builder()));
}
@Override
public Set<Pair<String, ValueProperties>> visitSimpleZeroDepositSecurity(final SimpleZeroDepositSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitPeriodicZeroDepositSecurity(final PeriodicZeroDepositSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitContinuousZeroDepositSecurity(final ContinuousZeroDepositSecurity security) {
return ImmutableSet.of();
}
//-------------------------------------------------------------------------
private Pair<String, ValueProperties> getYieldCurveNodeSensitivities(final String curve, final Currency currency) {
final ValueProperties.Builder constraints = ValueProperties
.with(ValuePropertyNames.CURVE_CURRENCY, currency.getCode())
.with(ValuePropertyNames.CURVE, curve)
.with(ValuePropertyNames.AGGREGATION, FilteringSummingFunction.AGGREGATION_STYLE_FILTERED)
.withOptional(ValuePropertyNames.AGGREGATION);
return getRiskFactor(ValueRequirementNames.YIELD_CURVE_NODE_SENSITIVITIES, constraints);
}
private Pair<String, ValueProperties> getPresentValue(final ValueProperties.Builder constraints) {
return getRiskFactor(ValueRequirementNames.PRESENT_VALUE, constraints);
}
private Pair<String, ValueProperties> getFXPresentValue() {
return getFXPresentValue(ValueProperties.builder());
}
private Pair<String, ValueProperties> getFXPresentValue(final ValueProperties.Builder constraints) {
return getRiskFactor(ValueRequirementNames.FX_PRESENT_VALUE, constraints);
}
private Pair<String, ValueProperties> getFXCurrencyExposure() {
return getFXCurrencyExposure(ValueProperties.builder());
}
private Pair<String, ValueProperties> getFXCurrencyExposure(final ValueProperties.Builder constraints) {
return getRiskFactor(ValueRequirementNames.FX_CURRENCY_EXPOSURE, constraints, false);
}
private Pair<String, ValueProperties> getVegaMatrix(final ValueProperties.Builder constraints) {
return getRiskFactor(ValueRequirementNames.VEGA_QUOTE_MATRIX, constraints, false);
}
private Pair<String, ValueProperties> getVegaCubeMatrix(final ValueProperties.Builder constraints) {
return getRiskFactor(ValueRequirementNames.VEGA_QUOTE_CUBE, constraints, false);
}
private Pair<String, ValueProperties> getValueDelta() {
return getRiskFactor(ValueRequirementNames.VALUE_DELTA, ValueProperties.builder());
}
private Pair<String, ValueProperties> getPV01(final String curveName) {
final ValueProperties.Builder constraints = ValueProperties
.with(ValuePropertyNames.CURVE, curveName);
return getRiskFactor(ValueRequirementNames.PV01, constraints, true);
}
private Set<Pair<String, ValueProperties>> getSabrSensitivities() {
return ImmutableSet.of(
getPresentValueSabrAlphaSensitivity(),
getPresentValueSabrRhoSensitivity(),
getPresentValueSabrNuSensitivity());
}
private Pair<String, ValueProperties> getPresentValueSabrAlphaSensitivity() {
return getRiskFactor(ValueRequirementNames.PRESENT_VALUE_SABR_ALPHA_SENSITIVITY);
}
private Pair<String, ValueProperties> getPresentValueSabrRhoSensitivity() {
return getRiskFactor(ValueRequirementNames.PRESENT_VALUE_SABR_RHO_SENSITIVITY);
}
private Pair<String, ValueProperties> getPresentValueSabrNuSensitivity() {
return getRiskFactor(ValueRequirementNames.PRESENT_VALUE_SABR_NU_SENSITIVITY);
}
//-------------------------------------------------------------------------
private Pair<String, ValueProperties> getRiskFactor(final String valueName) {
return getRiskFactor(valueName, ValueProperties.builder(), true);
}
private Pair<String, ValueProperties> getRiskFactor(final String valueName, final ValueProperties.Builder constraints) {
return getRiskFactor(valueName, constraints, true);
}
private Pair<String, ValueProperties> getRiskFactor(final String valueName, final ValueProperties.Builder constraints, final boolean allowCurrencyOverride) {
ArgumentChecker.notNull(valueName, "valueName");
ArgumentChecker.notNull(constraints, "constraints");
if (allowCurrencyOverride && getConfigProvider().getCurrencyOverride() != null) {
constraints.with(ValuePropertyNames.CURRENCY, getConfigProvider().getCurrencyOverride().getCode());
}
return Pair.of(valueName, constraints.get());
}
private ValueRequirement getValueRequirement(final Position position, final String valueName, final ValueProperties constraints) {
return new ValueRequirement(valueName, new ComputationTargetSpecification(position), constraints);
}
//-------------------------------------------------------------------------
private String getFundingCurve() {
return getConfigProvider().getFundingCurve();
}
private String getForwardCurve(final Currency currency) {
return getConfigProvider().getForwardCurve(currency);
}
//-------------------------------------------------------------------------
@SuppressWarnings("unused")
private SecuritySource getSecuritySource() {
return _securities;
}
private RiskFactorsConfigurationProvider getConfigProvider() {
return _configProvider;
}
}
|
projects/OG-Financial/src/com/opengamma/financial/analytics/riskfactors/DefaultRiskFactorsGatherer.java
|
/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.riskfactors;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang.NotImplementedException;
import com.google.common.collect.ImmutableSet;
import com.opengamma.core.position.Portfolio;
import com.opengamma.core.position.PortfolioNode;
import com.opengamma.core.position.Position;
import com.opengamma.core.position.impl.AbstractPortfolioNodeTraversalCallback;
import com.opengamma.core.position.impl.PortfolioNodeTraverser;
import com.opengamma.core.security.SecuritySource;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.view.ViewCalculationConfiguration;
import com.opengamma.financial.analytics.FilteringSummingFunction;
import com.opengamma.financial.analytics.conversion.SwapSecurityUtils;
import com.opengamma.financial.analytics.fixedincome.InterestRateInstrumentType;
import com.opengamma.financial.analytics.ircurve.YieldCurveFunction;
import com.opengamma.financial.analytics.model.InstrumentTypeProperties;
import com.opengamma.financial.analytics.model.forex.option.black.deprecated.FXOptionBlackFunctionDeprecated;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.FinancialSecurityVisitorAdapter;
import com.opengamma.financial.security.bond.CorporateBondSecurity;
import com.opengamma.financial.security.bond.GovernmentBondSecurity;
import com.opengamma.financial.security.bond.MunicipalBondSecurity;
import com.opengamma.financial.security.capfloor.CapFloorCMSSpreadSecurity;
import com.opengamma.financial.security.capfloor.CapFloorSecurity;
import com.opengamma.financial.security.cash.CashSecurity;
import com.opengamma.financial.security.deposit.ContinuousZeroDepositSecurity;
import com.opengamma.financial.security.deposit.PeriodicZeroDepositSecurity;
import com.opengamma.financial.security.deposit.SimpleZeroDepositSecurity;
import com.opengamma.financial.security.equity.EquitySecurity;
import com.opengamma.financial.security.equity.EquityVarianceSwapSecurity;
import com.opengamma.financial.security.fra.FRASecurity;
import com.opengamma.financial.security.future.AgricultureFutureSecurity;
import com.opengamma.financial.security.future.BondFutureSecurity;
import com.opengamma.financial.security.future.EnergyFutureSecurity;
import com.opengamma.financial.security.future.EquityFutureSecurity;
import com.opengamma.financial.security.future.EquityIndexDividendFutureSecurity;
import com.opengamma.financial.security.future.FXFutureSecurity;
import com.opengamma.financial.security.future.IndexFutureSecurity;
import com.opengamma.financial.security.future.InterestRateFutureSecurity;
import com.opengamma.financial.security.future.MetalFutureSecurity;
import com.opengamma.financial.security.future.StockFutureSecurity;
import com.opengamma.financial.security.fx.FXForwardSecurity;
import com.opengamma.financial.security.fx.NonDeliverableFXForwardSecurity;
import com.opengamma.financial.security.option.CommodityFutureOptionSecurity;
import com.opengamma.financial.security.option.EquityBarrierOptionSecurity;
import com.opengamma.financial.security.option.EquityIndexDividendFutureOptionSecurity;
import com.opengamma.financial.security.option.EquityIndexOptionSecurity;
import com.opengamma.financial.security.option.EquityOptionSecurity;
import com.opengamma.financial.security.option.FXBarrierOptionSecurity;
import com.opengamma.financial.security.option.FXDigitalOptionSecurity;
import com.opengamma.financial.security.option.FXOptionSecurity;
import com.opengamma.financial.security.option.IRFutureOptionSecurity;
import com.opengamma.financial.security.option.NonDeliverableFXDigitalOptionSecurity;
import com.opengamma.financial.security.option.NonDeliverableFXOptionSecurity;
import com.opengamma.financial.security.option.SwaptionSecurity;
import com.opengamma.financial.security.swap.InterestRateNotional;
import com.opengamma.financial.security.swap.Notional;
import com.opengamma.financial.security.swap.SwapSecurity;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
import com.opengamma.util.tuple.Pair;
/**
* Default implementation of {@link RiskFactorsGatherer}.
*/
public class DefaultRiskFactorsGatherer extends FinancialSecurityVisitorAdapter<Set<Pair<String, ValueProperties>>> implements RiskFactorsGatherer {
private final SecuritySource _securities;
private final RiskFactorsConfigurationProvider _configProvider;
public DefaultRiskFactorsGatherer(final SecuritySource securities, final RiskFactorsConfigurationProvider configProvider) {
ArgumentChecker.notNull(securities, "securities");
ArgumentChecker.notNull(configProvider, "configProvider");
_securities = securities;
_configProvider = configProvider;
}
@Override
public Set<ValueRequirement> getPositionRiskFactors(final Position position) {
ArgumentChecker.notNull(position, "position");
final Set<Pair<String, ValueProperties>> securityRiskFactors = ((FinancialSecurity) position.getSecurity()).accept(this);
if (securityRiskFactors.isEmpty()) {
return ImmutableSet.of();
}
final Set<ValueRequirement> results = new HashSet<ValueRequirement>(securityRiskFactors.size());
for (final Pair<String, ValueProperties> securityRiskFactor : securityRiskFactors) {
results.add(getValueRequirement(position, securityRiskFactor.getFirst(), securityRiskFactor.getSecond()));
}
return results;
}
@Override
public Set<ValueRequirement> getPositionRiskFactors(final Portfolio portfolio) {
ArgumentChecker.notNull(portfolio, "portfolio");
final RiskFactorPortfolioTraverser callback = new RiskFactorPortfolioTraverser();
callback.traverse(portfolio.getRootNode());
return callback.getRiskFactors();
}
@Override
public void addPortfolioRiskFactors(final Portfolio portfolio, final ViewCalculationConfiguration calcConfig) {
ArgumentChecker.notNull(portfolio, "portfolio");
ArgumentChecker.notNull(calcConfig, "calcConfig");
final RiskFactorPortfolioTraverser callback = new RiskFactorPortfolioTraverser(calcConfig);
callback.traverse(portfolio.getRootNode());
}
//-------------------------------------------------------------------------
private class RiskFactorPortfolioTraverser extends AbstractPortfolioNodeTraversalCallback {
private final ViewCalculationConfiguration _calcConfig;
private final Set<ValueRequirement> _valueRequirements = new HashSet<ValueRequirement>();
public RiskFactorPortfolioTraverser() {
this(null);
}
public RiskFactorPortfolioTraverser(final ViewCalculationConfiguration calcConfig) {
_calcConfig = calcConfig;
}
public void traverse(final PortfolioNode rootNode) {
PortfolioNodeTraverser.depthFirst(this).traverse(rootNode);
}
public Set<ValueRequirement> getRiskFactors() {
return new HashSet<ValueRequirement>(_valueRequirements);
}
@Override
public void preOrderOperation(final PortfolioNode portfolioNode) {
}
@Override
public void preOrderOperation(final Position position) {
final Set<ValueRequirement> riskFactorRequirements = DefaultRiskFactorsGatherer.this.getPositionRiskFactors(position);
_valueRequirements.addAll(riskFactorRequirements);
if (_calcConfig != null) {
for (final ValueRequirement riskFactorRequirement : riskFactorRequirements) {
_calcConfig.addPortfolioRequirement(position.getSecurity().getSecurityType(),
riskFactorRequirement.getValueName(), riskFactorRequirement.getConstraints());
}
}
}
@Override
public void postOrderOperation(final Position position) {
}
@Override
public void postOrderOperation(final PortfolioNode portfolioNode) {
}
}
//-------------------------------------------------------------------------
// Securities
@Override
public Set<Pair<String, ValueProperties>> visitCorporateBondSecurity(CorporateBondSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getPresentValue(ValueProperties.builder()),
getPV01(getFundingCurve()),
getPV01(getForwardCurve(security.getCurrency())));
}
@Override
public Set<Pair<String, ValueProperties>> visitGovernmentBondSecurity(GovernmentBondSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getPresentValue(ValueProperties.builder()),
getPV01(getFundingCurve()),
getPV01(getForwardCurve(security.getCurrency())));
}
@Override
public Set<Pair<String, ValueProperties>> visitMunicipalBondSecurity(MunicipalBondSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getPresentValue(ValueProperties.builder()),
getPV01(getFundingCurve()),
getPV01(getForwardCurve(security.getCurrency())));
}
@Override
public Set<Pair<String, ValueProperties>> visitCashSecurity(final CashSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()),
getPresentValue(ValueProperties.builder()),
getPV01(getFundingCurve()),
getPV01(getForwardCurve(security.getCurrency())));
}
@Override
public Set<Pair<String, ValueProperties>> visitEquitySecurity(final EquitySecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitFRASecurity(final FRASecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()),
getPresentValue(ValueProperties.builder()),
getPV01(getFundingCurve()),
getPV01(getForwardCurve(security.getCurrency())));
}
@Override
public Set<Pair<String, ValueProperties>> visitSwapSecurity(final SwapSecurity security) {
final ImmutableSet.Builder<Pair<String, ValueProperties>> builder = ImmutableSet.<Pair<String, ValueProperties>>builder();
// At the moment pay and receive must be the same currency, so any one of them is sufficient
final Notional payNotional = security.getPayLeg().getNotional();
final Notional receiveNotional = security.getReceiveLeg().getNotional();
if (payNotional instanceof InterestRateNotional && receiveNotional instanceof InterestRateNotional) {
final Currency ccy = ((InterestRateNotional) payNotional).getCurrency();
builder.add(getYieldCurveNodeSensitivities(getFundingCurve(), ccy));
builder.add(getYieldCurveNodeSensitivities(getForwardCurve(ccy), ccy));
final InterestRateInstrumentType type = SwapSecurityUtils.getSwapType(security);
if (type == InterestRateInstrumentType.SWAP_CMS_CMS ||
type == InterestRateInstrumentType.SWAP_FIXED_CMS ||
type == InterestRateInstrumentType.SWAP_IBOR_CMS) {
builder.add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG")));
} else if (type == InterestRateInstrumentType.SWAP_FIXED_IBOR ||
type == InterestRateInstrumentType.SWAP_FIXED_IBOR_WITH_SPREAD ||
type == InterestRateInstrumentType.SWAP_IBOR_IBOR) {
builder.add(getPV01(getFundingCurve()));
builder.add(getPV01(getForwardCurve(ccy)));
}
}
builder.add(getPresentValue(ValueProperties.builder()));
return builder.build();
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityIndexOptionSecurity(final EquityIndexOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.addAll(getSabrSensitivities())
.add(getPresentValue(ValueProperties.builder())).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityOptionSecurity(final EquityOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.addAll(getSabrSensitivities())
.add(getPresentValue(ValueProperties.builder()))
.add(getVegaMatrix(ValueProperties.builder())).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityBarrierOptionSecurity(final EquityBarrierOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.addAll(getSabrSensitivities())
.add(getPresentValue(ValueProperties.builder()))
.add(getVegaMatrix(ValueProperties.builder())).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitFXOptionSecurity(final FXOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getFXPresentValue(ValueProperties
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_FORWARD_CURVE, getForwardCurve(security.getPutCurrency()))
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_FORWARD_CURVE, getForwardCurve(security.getCallCurrency()))))
.add(getFXCurrencyExposure(ValueProperties
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_FORWARD_CURVE, getForwardCurve(security.getPutCurrency()))
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_FORWARD_CURVE, getForwardCurve(security.getCallCurrency()))))
.add(getVegaMatrix(ValueProperties
.with(ValuePropertyNames.SURFACE, "DEFAULT") //TODO this should not be hard-coded
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_CURVE, getFundingCurve())
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.FOREX)))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build();
}
// REVIEW: jim 23-Jan-2012 -- bit of a leap to assume it's the same as FX Options...
@Override
public Set<Pair<String, ValueProperties>> visitNonDeliverableFXDigitalOptionSecurity(final NonDeliverableFXDigitalOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getFXPresentValue())
.add(getFXCurrencyExposure())
.add(getVegaMatrix(ValueProperties
.with(ValuePropertyNames.SURFACE, "DEFAULT") //TODO this should not be hard-coded
.with(ValuePropertyNames.PAY_CURVE, getFundingCurve())
.with(ValuePropertyNames.RECEIVE_CURVE, getFundingCurve())
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.FOREX)))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build();
}
// REVIEW: jim 23-Jan-2012 -- bit of a leap to assume it's the same as FX Options...
@Override
public Set<Pair<String, ValueProperties>> visitNonDeliverableFXOptionSecurity(final NonDeliverableFXOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getFXPresentValue())
.add(getFXCurrencyExposure())
.add(getVegaMatrix(ValueProperties
.with(ValuePropertyNames.SURFACE, "DEFAULT") //TODO this should not be hard-coded
.with(ValuePropertyNames.PAY_CURVE, getFundingCurve())
.with(ValuePropertyNames.RECEIVE_CURVE, getFundingCurve())
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.FOREX)))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitSwaptionSecurity(final SwaptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()))
.addAll(getSabrSensitivities())
.add(getPresentValue(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG")))
.add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitIRFutureOptionSecurity(final IRFutureOptionSecurity security) {
final Currency ccy = security.getCurrency();
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.addAll(getSabrSensitivities())
.add(getYieldCurveNodeSensitivities(getFundingCurve(), ccy))
.add(getYieldCurveNodeSensitivities(getForwardCurve(ccy), ccy))
.add(getPresentValue(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT")))
.add(getVegaMatrix(ValueProperties
.with(ValuePropertyNames.SURFACE, "DEFAULT")
.with(YieldCurveFunction.PROPERTY_FUNDING_CURVE, getFundingCurve())
.with(YieldCurveFunction.PROPERTY_FORWARD_CURVE, getForwardCurve(ccy))
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.IR_FUTURE_OPTION))).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitCommodityFutureOptionSecurity(CommodityFutureOptionSecurity commodityFutureOptionSecurity) {
throw new NotImplementedException();
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityIndexDividendFutureOptionSecurity(
final EquityIndexDividendFutureOptionSecurity equityIndexDividendFutureOptionSecurity) {
throw new NotImplementedException();
}
@Override
public Set<Pair<String, ValueProperties>> visitFXBarrierOptionSecurity(final FXBarrierOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getFXPresentValue(ValueProperties
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_FORWARD_CURVE, getForwardCurve(security.getPutCurrency()))
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_FORWARD_CURVE, getForwardCurve(security.getCallCurrency()))))
.add(getFXCurrencyExposure(ValueProperties
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_PUT_FORWARD_CURVE, getForwardCurve(security.getPutCurrency()))
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_CURVE, getFundingCurve())
.with(FXOptionBlackFunctionDeprecated.PROPERTY_CALL_FORWARD_CURVE, getForwardCurve(security.getCallCurrency()))))
.add(getVegaMatrix(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT")))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitFXDigitalOptionSecurity(final FXDigitalOptionSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getFXPresentValue())
.add(getFXCurrencyExposure())
.add(getVegaMatrix(ValueProperties
.with(ValuePropertyNames.SURFACE, "DEFAULT") //TODO this should not be hard-coded
.with(ValuePropertyNames.PAY_CURVE, getFundingCurve())
.with(ValuePropertyNames.RECEIVE_CURVE, getFundingCurve())
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.FOREX)))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build();
}
@SuppressWarnings("unchecked")
@Override
public Set<Pair<String, ValueProperties>> visitFXForwardSecurity(final FXForwardSecurity security) {
return ImmutableSet.of(
getFXPresentValue(),
getFXCurrencyExposure(),
getYieldCurveNodeSensitivities(getFundingCurve(), security.getPayCurrency()),
getYieldCurveNodeSensitivities(getFundingCurve(), security.getReceiveCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getPayCurrency()), security.getPayCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getReceiveCurrency()), security.getReceiveCurrency()));
}
// REVIEW jim 23-Jan-2012 -- bit of a leap to copy fx forwards, but there you go.
@SuppressWarnings("unchecked")
@Override
public Set<Pair<String, ValueProperties>> visitNonDeliverableFXForwardSecurity(
final NonDeliverableFXForwardSecurity security) {
return ImmutableSet.of(
getFXPresentValue(),
getFXCurrencyExposure(),
getYieldCurveNodeSensitivities(getFundingCurve(), security.getPayCurrency()),
getYieldCurveNodeSensitivities(getFundingCurve(), security.getReceiveCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getPayCurrency()), security.getPayCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getReceiveCurrency()), security.getReceiveCurrency()));
}
@Override
public Set<Pair<String, ValueProperties>> visitCapFloorSecurity(final CapFloorSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()))
.addAll(getSabrSensitivities())
.add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG")))
.add(getPresentValue(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitCapFloorCMSSpreadSecurity(final CapFloorCMSSpreadSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()))
.add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()))
.addAll(getSabrSensitivities())
.add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG")))
.add(getPresentValue(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))).build();
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityVarianceSwapSecurity(final EquityVarianceSwapSecurity security) {
return ImmutableSet.<Pair<String, ValueProperties>>builder()
.add(getPresentValue(ValueProperties.builder()))
.add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()))
.add(getVegaMatrix(ValueProperties
.with(ValuePropertyNames.SURFACE, "DEFAULT")
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, "EQUITY_OPTION"))).build();
}
//-------------------------------------------------------------------------
// Futures
@Override
public Set<Pair<String, ValueProperties>> visitAgricultureFutureSecurity(final AgricultureFutureSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitBondFutureSecurity(final BondFutureSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()));
}
@Override
public Set<Pair<String, ValueProperties>> visitEnergyFutureSecurity(final EnergyFutureSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitFXFutureSecurity(final FXFutureSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitIndexFutureSecurity(final IndexFutureSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitInterestRateFutureSecurity(final InterestRateFutureSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()),
getPresentValue(ValueProperties.builder()),
getPV01(getFundingCurve()),
getPV01(getForwardCurve(security.getCurrency())));
}
@Override
public Set<Pair<String, ValueProperties>> visitMetalFutureSecurity(final MetalFutureSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitStockFutureSecurity(final StockFutureSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityFutureSecurity(final EquityFutureSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getPresentValue(ValueProperties.builder()));
}
@Override
public Set<Pair<String, ValueProperties>> visitEquityIndexDividendFutureSecurity(final EquityIndexDividendFutureSecurity security) {
return ImmutableSet.of(
getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()),
getPresentValue(ValueProperties.builder()));
}
@Override
public Set<Pair<String, ValueProperties>> visitSimpleZeroDepositSecurity(final SimpleZeroDepositSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitPeriodicZeroDepositSecurity(final PeriodicZeroDepositSecurity security) {
return ImmutableSet.of();
}
@Override
public Set<Pair<String, ValueProperties>> visitContinuousZeroDepositSecurity(final ContinuousZeroDepositSecurity security) {
return ImmutableSet.of();
}
//-------------------------------------------------------------------------
private Pair<String, ValueProperties> getYieldCurveNodeSensitivities(final String curve, final Currency currency) {
final ValueProperties.Builder constraints = ValueProperties
.with(ValuePropertyNames.CURVE_CURRENCY, currency.getCode())
.with(ValuePropertyNames.CURVE, curve)
.with(ValuePropertyNames.AGGREGATION, FilteringSummingFunction.AGGREGATION_STYLE_FILTERED)
.withOptional(ValuePropertyNames.AGGREGATION);
return getRiskFactor(ValueRequirementNames.YIELD_CURVE_NODE_SENSITIVITIES, constraints);
}
private Pair<String, ValueProperties> getPresentValue(final ValueProperties.Builder constraints) {
return getRiskFactor(ValueRequirementNames.PRESENT_VALUE, constraints);
}
private Pair<String, ValueProperties> getFXPresentValue() {
return getFXPresentValue(ValueProperties.builder());
}
private Pair<String, ValueProperties> getFXPresentValue(final ValueProperties.Builder constraints) {
return getRiskFactor(ValueRequirementNames.FX_PRESENT_VALUE, constraints);
}
private Pair<String, ValueProperties> getFXCurrencyExposure() {
return getFXCurrencyExposure(ValueProperties.builder());
}
private Pair<String, ValueProperties> getFXCurrencyExposure(final ValueProperties.Builder constraints) {
return getRiskFactor(ValueRequirementNames.FX_CURRENCY_EXPOSURE, constraints, false);
}
private Pair<String, ValueProperties> getVegaMatrix(final ValueProperties.Builder constraints) {
return getRiskFactor(ValueRequirementNames.VEGA_QUOTE_MATRIX, constraints, false);
}
private Pair<String, ValueProperties> getVegaCubeMatrix(final ValueProperties.Builder constraints) {
return getRiskFactor(ValueRequirementNames.VEGA_QUOTE_CUBE, constraints, false);
}
private Pair<String, ValueProperties> getPV01(final String curveName) {
final ValueProperties.Builder constraints = ValueProperties
.with(ValuePropertyNames.CURVE, curveName);
return getRiskFactor(ValueRequirementNames.PV01, constraints, true);
}
private Set<Pair<String, ValueProperties>> getSabrSensitivities() {
return ImmutableSet.of(
getPresentValueSabrAlphaSensitivity(),
getPresentValueSabrRhoSensitivity(),
getPresentValueSabrNuSensitivity());
}
private Pair<String, ValueProperties> getPresentValueSabrAlphaSensitivity() {
return getRiskFactor(ValueRequirementNames.PRESENT_VALUE_SABR_ALPHA_SENSITIVITY);
}
private Pair<String, ValueProperties> getPresentValueSabrRhoSensitivity() {
return getRiskFactor(ValueRequirementNames.PRESENT_VALUE_SABR_RHO_SENSITIVITY);
}
private Pair<String, ValueProperties> getPresentValueSabrNuSensitivity() {
return getRiskFactor(ValueRequirementNames.PRESENT_VALUE_SABR_NU_SENSITIVITY);
}
//-------------------------------------------------------------------------
private Pair<String, ValueProperties> getRiskFactor(final String valueName) {
return getRiskFactor(valueName, ValueProperties.builder(), true);
}
private Pair<String, ValueProperties> getRiskFactor(final String valueName, final ValueProperties.Builder constraints) {
return getRiskFactor(valueName, constraints, true);
}
private Pair<String, ValueProperties> getRiskFactor(final String valueName, final ValueProperties.Builder constraints, final boolean allowCurrencyOverride) {
ArgumentChecker.notNull(valueName, "valueName");
ArgumentChecker.notNull(constraints, "constraints");
if (allowCurrencyOverride && getConfigProvider().getCurrencyOverride() != null) {
constraints.with(ValuePropertyNames.CURRENCY, getConfigProvider().getCurrencyOverride().getCode());
}
return Pair.of(valueName, constraints.get());
}
private ValueRequirement getValueRequirement(final Position position, final String valueName, final ValueProperties constraints) {
return new ValueRequirement(valueName, new ComputationTargetSpecification(position), constraints);
}
//-------------------------------------------------------------------------
private String getFundingCurve() {
return getConfigProvider().getFundingCurve();
}
private String getForwardCurve(final Currency currency) {
return getConfigProvider().getForwardCurve(currency);
}
//-------------------------------------------------------------------------
@SuppressWarnings("unused")
private SecuritySource getSecuritySource() {
return _securities;
}
private RiskFactorsConfigurationProvider getConfigProvider() {
return _configProvider;
}
}
|
Fixing copy/paste code
|
projects/OG-Financial/src/com/opengamma/financial/analytics/riskfactors/DefaultRiskFactorsGatherer.java
|
Fixing copy/paste code
|
<ide><path>rojects/OG-Financial/src/com/opengamma/financial/analytics/riskfactors/DefaultRiskFactorsGatherer.java
<ide> @Override
<ide> public Set<Pair<String, ValueProperties>> visitEquityOptionSecurity(final EquityOptionSecurity security) {
<ide> return ImmutableSet.<Pair<String, ValueProperties>>builder()
<del> .addAll(getSabrSensitivities())
<del> .add(getPresentValue(ValueProperties.builder()))
<del> .add(getVegaMatrix(ValueProperties.builder())).build();
<add> .add(getValueDelta()).build();
<ide> }
<ide>
<ide> @Override
<ide> private Pair<String, ValueProperties> getVegaCubeMatrix(final ValueProperties.Builder constraints) {
<ide> return getRiskFactor(ValueRequirementNames.VEGA_QUOTE_CUBE, constraints, false);
<ide> }
<add>
<add> private Pair<String, ValueProperties> getValueDelta() {
<add> return getRiskFactor(ValueRequirementNames.VALUE_DELTA, ValueProperties.builder());
<add> }
<ide>
<ide> private Pair<String, ValueProperties> getPV01(final String curveName) {
<ide> final ValueProperties.Builder constraints = ValueProperties
|
|
Java
|
lgpl-2.1
|
683aecaf2243de00848160a44ad8206e992104d9
| 0 |
simoc/mapyrus,simoc/mapyrus,simoc/mapyrus
|
/*
* This file is part of Mapyrus, software for plotting maps.
* Copyright (C) 2003, 2004, 2005 Simon Chenery.
*
* Mapyrus is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Mapyrus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Mapyrus; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* @(#) $Id$
*/
package org.mapyrus.image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import org.mapyrus.MapyrusException;
import org.mapyrus.MapyrusMessages;
/*
* Holds an image read from a Netpbm PPM and PGM format image files.
*/
public class PNMImage
{
private BufferedImage mImage;
/**
* Read Netpbm PNM image from URL.
* @param url URL.
*/
public PNMImage(URL url) throws MapyrusException, IOException
{
DataInputStream stream = new DataInputStream(new BufferedInputStream(url.openStream()));
init(stream, url.toString());
}
/**
* Read Netpbm PNM image from file.
* @param filename name of file.
*/
public PNMImage(String filename) throws MapyrusException, IOException
{
DataInputStream stream = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
init(stream, filename);
}
/**
* Read Netpbm PNM image from open stream.
* @param stream open stream to read from.
* @param filename name of file.
*/
public PNMImage(InputStream stream, String filename) throws MapyrusException, IOException
{
DataInputStream stream2 = new DataInputStream(new BufferedInputStream(stream));
init(stream2, filename);
}
private void init(DataInputStream stream, String filename) throws MapyrusException, IOException
{
try
{
/*
* Check for 'P5' or 'P6' magic number in file.
*/
int magic1 = stream.read();
int magic2 = stream.read();
boolean isGreyscale;
boolean isBitmap;
if (magic1 == 'P' && magic2 == '6')
{
isGreyscale = isBitmap = false;
}
else if (magic1 == 'P' && magic2 == '5')
{
isGreyscale = true;
isBitmap = false;
}
else if (magic1 == 'P' && magic2 == '4')
{
isBitmap = true;
isGreyscale = false;
}
else
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NOT_A_PPM_FILE) +
": " + filename);
}
/*
* Read image header.
*/
int width = readNumber(stream);
int height = readNumber(stream);
int maxValue = 1;
if (!isBitmap)
maxValue = readNumber(stream);
int nBytes = (maxValue < 256) ? 1 : 2;
/*
* Read pixel values into image.
*/
mImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int nextByte = 0;
for (int y = 0; y < height; y++)
{
int bitMask = 0;
for (int x = 0; x < width; x++)
{
int r, g, b, pixel;
if (nBytes == 1)
{
if (isBitmap)
{
/*
* Extract pixel from next bit.
*/
if (bitMask == 0)
{
nextByte = stream.read();
bitMask = 128;
}
r = g = b = (((nextByte & bitMask) != 0) ? 0 : 255);
bitMask >>= 1;
}
else if (isGreyscale)
{
r = g = b = stream.read();
}
else
{
r = stream.read();
g = stream.read();
b = stream.read();
}
}
else
{
if (isGreyscale)
{
r = g = b = stream.readShort();
}
else
{
r = stream.readShort();
g = stream.readShort();
b = stream.readShort();
}
}
pixel = (r << 16) | (g << 8) | b;
mImage.setRGB(x, y, pixel);
}
}
}
finally
{
try
{
stream.close();
}
catch (IOException e)
{
}
}
}
/**
* Read decimal number from stream.
* @param stream stream to read from.
* @return number read from stream.
*/
private int readNumber(InputStream stream) throws IOException
{
int retval = 0;
int c = stream.read();
boolean inComment = (c == '#');
while (c != -1 && (inComment || Character.isWhitespace((char)c)))
{
c = stream.read();
if (c == '#')
inComment = true;
else if (inComment && (c == '\r' || c == '\n'))
inComment = false;
}
while (c >= '0' && c <= '9')
{
retval = retval * 10 + (c - '0');
c = stream.read();
}
return(retval);
}
/**
* Get Netpbm PNM image as buffered image.
* @return image.
*/
public BufferedImage getBufferedImage()
{
return(mImage);
}
/**
* Write an image to a Netpbm PPM format file.
* @param image image to write
* @param stream output stream to write image to.
*/
public static void write(BufferedImage image, OutputStream stream) throws IOException
{
/*
* Write file header.
*/
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
stream.write('P');
stream.write('6');
stream.write('\n');
stream.write(Integer.toString(imageWidth).getBytes());
stream.write(' ');
stream.write(Integer.toString(imageHeight).getBytes());
stream.write('\n');
stream.write(Integer.toString(255).getBytes());
stream.write('\n');
/*
* Write each row of pixels.
*/
for (int y = 0; y < imageHeight; y++)
{
for (int x = 0; x < imageWidth; x++)
{
int pixel = image.getRGB(x, y);
int b = (pixel & 0xff);
int g = ((pixel >> 8) & 0xff);
int r = ((pixel >> 16) & 0xff);
stream.write(r);
stream.write(g);
stream.write(b);
}
}
stream.flush();
}
}
|
src/org/mapyrus/image/PNMImage.java
|
/*
* This file is part of Mapyrus, software for plotting maps.
* Copyright (C) 2003, 2004, 2005 Simon Chenery.
*
* Mapyrus is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Mapyrus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Mapyrus; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* @(#) $Id$
*/
package org.mapyrus.image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import org.mapyrus.MapyrusException;
import org.mapyrus.MapyrusMessages;
/*
* Holds an image read from a Netpbm PPM and PGM format image files.
*/
public class PNMImage
{
private BufferedImage mImage;
/**
* Read Netpbm PNM image from URL.
* @param url URL.
*/
public PNMImage(URL url) throws MapyrusException, IOException
{
DataInputStream stream = new DataInputStream(new BufferedInputStream(url.openStream()));
init(stream, url.toString());
}
/**
* Read Netpbm PNM image from file.
* @param filename name of file.
*/
public PNMImage(String filename) throws MapyrusException, IOException
{
DataInputStream stream = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
init(stream, filename);
}
private void init(DataInputStream stream, String filename) throws MapyrusException, IOException
{
try
{
/*
* Check for 'P5' or 'P6' magic number in file.
*/
int magic1 = stream.read();
int magic2 = stream.read();
boolean isGreyscale;
boolean isBitmap;
if (magic1 == 'P' && magic2 == '6')
{
isGreyscale = isBitmap = false;
}
else if (magic1 == 'P' && magic2 == '5')
{
isGreyscale = true;
isBitmap = false;
}
else if (magic1 == 'P' && magic2 == '4')
{
isBitmap = true;
isGreyscale = false;
}
else
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NOT_A_PPM_FILE) +
": " + filename);
}
/*
* Read image header.
*/
int width = readNumber(stream);
int height = readNumber(stream);
int maxValue = 1;
if (!isBitmap)
maxValue = readNumber(stream);
int nBytes = (maxValue < 256) ? 1 : 2;
/*
* Read pixel values into image.
*/
mImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int nextByte = 0;
for (int y = 0; y < height; y++)
{
int bitMask = 0;
for (int x = 0; x < width; x++)
{
int r, g, b, pixel;
if (nBytes == 1)
{
if (isBitmap)
{
/*
* Extract pixel from next bit.
*/
if (bitMask == 0)
{
nextByte = stream.read();
bitMask = 128;
}
r = g = b = (((nextByte & bitMask) != 0) ? 0 : 255);
bitMask >>= 1;
}
else if (isGreyscale)
{
r = g = b = stream.read();
}
else
{
r = stream.read();
g = stream.read();
b = stream.read();
}
}
else
{
if (isGreyscale)
{
r = g = b = stream.readShort();
}
else
{
r = stream.readShort();
g = stream.readShort();
b = stream.readShort();
}
}
pixel = (r << 16) | (g << 8) | b;
mImage.setRGB(x, y, pixel);
}
}
}
finally
{
try
{
stream.close();
}
catch (IOException e)
{
}
}
}
/**
* Read decimal number from stream.
* @param stream stream to read from.
* @return number read from stream.
*/
private int readNumber(InputStream stream) throws IOException
{
int retval = 0;
int c = stream.read();
boolean inComment = (c == '#');
while (c != -1 && (inComment || Character.isWhitespace((char)c)))
{
c = stream.read();
if (c == '#')
inComment = true;
else if (inComment && (c == '\r' || c == '\n'))
inComment = false;
}
while (c >= '0' && c <= '9')
{
retval = retval * 10 + (c - '0');
c = stream.read();
}
return(retval);
}
/**
* Get Netpbm PNM image as buffered image.
* @return image.
*/
public BufferedImage getBufferedImage()
{
return(mImage);
}
/**
* Write an image to a Netpbm PPM format file.
* @param image image to write
* @param stream output stream to write image to.
*/
public static void write(BufferedImage image, OutputStream stream) throws IOException
{
/*
* Write file header.
*/
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
stream.write('P');
stream.write('6');
stream.write('\n');
stream.write(Integer.toString(imageWidth).getBytes());
stream.write(' ');
stream.write(Integer.toString(imageHeight).getBytes());
stream.write('\n');
stream.write(Integer.toString(255).getBytes());
stream.write('\n');
/*
* Write each row of pixels.
*/
for (int y = 0; y < imageHeight; y++)
{
for (int x = 0; x < imageWidth; x++)
{
int pixel = image.getRGB(x, y);
int b = (pixel & 0xff);
int g = ((pixel >> 8) & 0xff);
int r = ((pixel >> 16) & 0xff);
stream.write(r);
stream.write(g);
stream.write(b);
}
}
stream.flush();
}
}
|
Add new constructor, reading image from a InputStream.
|
src/org/mapyrus/image/PNMImage.java
|
Add new constructor, reading image from a InputStream.
|
<ide><path>rc/org/mapyrus/image/PNMImage.java
<ide> init(stream, filename);
<ide> }
<ide>
<add> /**
<add> * Read Netpbm PNM image from open stream.
<add> * @param stream open stream to read from.
<add> * @param filename name of file.
<add> */
<add> public PNMImage(InputStream stream, String filename) throws MapyrusException, IOException
<add> {
<add> DataInputStream stream2 = new DataInputStream(new BufferedInputStream(stream));
<add> init(stream2, filename);
<add> }
<add>
<ide> private void init(DataInputStream stream, String filename) throws MapyrusException, IOException
<ide> {
<ide> try
|
|
Java
|
apache-2.0
|
9d67cc1a84348c862a9776283db8db9aef152eb7
| 0 |
supersven/intellij-community,orekyuu/intellij-community,signed/intellij-community,holmes/intellij-community,clumsy/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,caot/intellij-community,vladmm/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,ryano144/intellij-community,robovm/robovm-studio,diorcety/intellij-community,clumsy/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,signed/intellij-community,samthor/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,supersven/intellij-community,kool79/intellij-community,fitermay/intellij-community,hurricup/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,samthor/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,blademainer/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,Lekanich/intellij-community,ernestp/consulo,akosyakov/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,robovm/robovm-studio,xfournet/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,da1z/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,kool79/intellij-community,dslomov/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,holmes/intellij-community,dslomov/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,ernestp/consulo,orekyuu/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,caot/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,samthor/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,SerCeMan/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,da1z/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,holmes/intellij-community,fitermay/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,supersven/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,kdwink/intellij-community,asedunov/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,da1z/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,allotria/intellij-community,blademainer/intellij-community,allotria/intellij-community,supersven/intellij-community,blademainer/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,vladmm/intellij-community,ryano144/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,semonte/intellij-community,jagguli/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,holmes/intellij-community,suncycheng/intellij-community,izonder/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,gnuhub/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,apixandru/intellij-community,ibinti/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,signed/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,consulo/consulo,petteyg/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,signed/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,slisson/intellij-community,fnouama/intellij-community,adedayo/intellij-community,allotria/intellij-community,petteyg/intellij-community,dslomov/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,allotria/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,supersven/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,FHannes/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,wreckJ/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,semonte/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,caot/intellij-community,hurricup/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,retomerz/intellij-community,clumsy/intellij-community,fitermay/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,slisson/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,holmes/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,consulo/consulo,ahb0327/intellij-community,wreckJ/intellij-community,slisson/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,izonder/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,signed/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,da1z/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,holmes/intellij-community,wreckJ/intellij-community,semonte/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,caot/intellij-community,allotria/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,izonder/intellij-community,hurricup/intellij-community,diorcety/intellij-community,allotria/intellij-community,semonte/intellij-community,adedayo/intellij-community,signed/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,amith01994/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,slisson/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,fnouama/intellij-community,izonder/intellij-community,izonder/intellij-community,ryano144/intellij-community,samthor/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,caot/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,consulo/consulo,akosyakov/intellij-community,kool79/intellij-community,FHannes/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,vladmm/intellij-community,fnouama/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,allotria/intellij-community,ibinti/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,signed/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,consulo/consulo,orekyuu/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,kool79/intellij-community,caot/intellij-community,signed/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,signed/intellij-community,apixandru/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,xfournet/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,signed/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,blademainer/intellij-community,asedunov/intellij-community,diorcety/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,apixandru/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,blademainer/intellij-community,robovm/robovm-studio,FHannes/intellij-community,ahb0327/intellij-community,slisson/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,petteyg/intellij-community,kdwink/intellij-community,asedunov/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,adedayo/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,da1z/intellij-community,ibinti/intellij-community,ibinti/intellij-community,adedayo/intellij-community,samthor/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,caot/intellij-community,petteyg/intellij-community,kdwink/intellij-community,diorcety/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,xfournet/intellij-community,izonder/intellij-community,allotria/intellij-community,da1z/intellij-community,retomerz/intellij-community,ernestp/consulo,FHannes/intellij-community,ernestp/consulo,michaelgallacher/intellij-community,akosyakov/intellij-community,caot/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,fitermay/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,FHannes/intellij-community,slisson/intellij-community,ernestp/consulo,FHannes/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,dslomov/intellij-community,hurricup/intellij-community,dslomov/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,da1z/intellij-community,xfournet/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ibinti/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,caot/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,consulo/consulo,FHannes/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,kool79/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,samthor/intellij-community,slisson/intellij-community,consulo/consulo,samthor/intellij-community,ryano144/intellij-community,xfournet/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,samthor/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,slisson/intellij-community
|
/*
* Copyright 2003-2009 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ipp.constant;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiBinaryExpression;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiJavaToken;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.IntentionPowerPackBundle;
import com.siyeh.ipp.base.MutablyNamedIntention;
import com.siyeh.ipp.base.PsiElementPredicate;
import com.siyeh.ipp.psiutils.ConcatenationUtils;
import com.siyeh.ipp.psiutils.ExpressionUtils;
import org.jetbrains.annotations.NotNull;
public class ConstantSubexpressionIntention extends MutablyNamedIntention {
@Override
@NotNull
protected PsiElementPredicate getElementPredicate() {
return new ConstantSubexpressionPredicate();
}
@Override
protected String getTextForElement(PsiElement element) {
final PsiBinaryExpression binaryExpression =
(PsiBinaryExpression)element.getParent();
assert binaryExpression != null;
final PsiExpression lhs = binaryExpression.getLOperand();
final PsiExpression leftSide;
if (lhs instanceof PsiBinaryExpression) {
final PsiBinaryExpression lhsBinaryExpression =
(PsiBinaryExpression)lhs;
leftSide = lhsBinaryExpression.getROperand();
} else {
leftSide = lhs;
}
final PsiJavaToken operationSign = binaryExpression.getOperationSign();
final PsiExpression rhs = binaryExpression.getROperand();
assert rhs != null;
assert leftSide != null;
return IntentionPowerPackBundle.message(
"constant.subexpression.intention.name", leftSide.getText() +
' ' + operationSign.getText() + ' ' + rhs.getText());
}
@Override
public void processIntention(@NotNull PsiElement element)
throws IncorrectOperationException {
final PsiExpression expression = (PsiExpression)element.getParent();
assert expression != null;
String newExpression = "";
final Object constantValue;
if (expression instanceof PsiBinaryExpression) {
final PsiBinaryExpression copy =
(PsiBinaryExpression)expression.copy();
final PsiExpression lhs = copy.getLOperand();
if (lhs instanceof PsiBinaryExpression) {
final PsiBinaryExpression lhsBinaryExpression =
(PsiBinaryExpression)lhs;
newExpression += getLeftSideText(lhsBinaryExpression);
final PsiExpression rightSide =
lhsBinaryExpression.getROperand();
assert rightSide != null;
lhs.replace(rightSide);
}
if (ConcatenationUtils.isConcatenation(expression)) {
constantValue = computeConstantStringExpression(copy);
} else {
constantValue =
ExpressionUtils.computeConstantExpression(copy);
}
} else {
constantValue =
ExpressionUtils.computeConstantExpression(expression);
}
if (constantValue instanceof String) {
newExpression += '"' + StringUtil.escapeStringCharacters(
constantValue.toString()) + '"';
} else if (constantValue != null) {
if (constantValue instanceof Number) {
final Number number = (Number) constantValue;
if (0 > number.doubleValue()) {
newExpression += " ";
}
}
newExpression += constantValue.toString();
}
replaceExpression(newExpression, expression);
}
/**
* handles the specified expression as if it was part of a string expression
* (even if it's of another type) and computes a constant string expression
* from it.
*/
private static String computeConstantStringExpression(
PsiBinaryExpression expression) {
final PsiExpression lhs = expression.getLOperand();
final String lhsText = lhs.getText();
String result;
if (lhsText.charAt(0) == '\'' || lhsText.charAt(0) == '"') {
result = lhsText.substring(1, lhsText.length() - 1);
} else {
result = lhsText;
}
final PsiExpression rhs = expression.getROperand();
assert rhs != null;
final String rhsText = rhs.getText();
if (rhsText.charAt(0) == '\'' || rhsText.charAt(0) == '"') {
result += rhsText.substring(1, rhsText.length() - 1);
} else {
result += rhsText;
}
return result;
}
private static String getLeftSideText(
PsiBinaryExpression binaryExpression) {
final PsiExpression lhs = binaryExpression.getLOperand();
final PsiJavaToken sign = binaryExpression.getOperationSign();
return lhs.getText() + sign.getText();
}
}
|
plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantSubexpressionIntention.java
|
/*
* Copyright 2003-2009 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ipp.constant;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiBinaryExpression;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiJavaToken;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.IntentionPowerPackBundle;
import com.siyeh.ipp.base.MutablyNamedIntention;
import com.siyeh.ipp.base.PsiElementPredicate;
import com.siyeh.ipp.psiutils.ConcatenationUtils;
import com.siyeh.ipp.psiutils.ExpressionUtils;
import org.jetbrains.annotations.NotNull;
public class ConstantSubexpressionIntention extends MutablyNamedIntention {
@Override
@NotNull
protected PsiElementPredicate getElementPredicate() {
return new ConstantSubexpressionPredicate();
}
@Override
protected String getTextForElement(PsiElement element) {
final PsiBinaryExpression binaryExpression =
(PsiBinaryExpression)element.getParent();
assert binaryExpression != null;
final PsiExpression lhs = binaryExpression.getLOperand();
final PsiExpression leftSide;
if (lhs instanceof PsiBinaryExpression) {
final PsiBinaryExpression lhsBinaryExpression =
(PsiBinaryExpression)lhs;
leftSide = lhsBinaryExpression.getROperand();
} else {
leftSide = lhs;
}
final PsiJavaToken operationSign = binaryExpression.getOperationSign();
final PsiExpression rhs = binaryExpression.getROperand();
assert rhs != null;
assert leftSide != null;
return IntentionPowerPackBundle.message(
"constant.subexpression.intention.name", leftSide.getText() +
' ' + operationSign.getText() + ' ' + rhs.getText());
}
@Override
public void processIntention(@NotNull PsiElement element)
throws IncorrectOperationException {
final PsiExpression expression = (PsiExpression)element.getParent();
assert expression != null;
String newExpression = "";
final Object constantValue;
if (expression instanceof PsiBinaryExpression) {
final PsiBinaryExpression copy =
(PsiBinaryExpression)expression.copy();
final PsiExpression lhs = copy.getLOperand();
if (lhs instanceof PsiBinaryExpression) {
final PsiBinaryExpression lhsBinaryExpression =
(PsiBinaryExpression)lhs;
newExpression += getLeftSideText(lhsBinaryExpression);
final PsiExpression rightSide =
lhsBinaryExpression.getROperand();
assert rightSide != null;
lhs.replace(rightSide);
}
if (ConcatenationUtils.isConcatenation(expression)) {
constantValue = computeConstantStringExpression(copy);
} else {
constantValue =
ExpressionUtils.computeConstantExpression(copy);
}
} else {
constantValue =
ExpressionUtils.computeConstantExpression(expression);
}
if (constantValue instanceof String) {
newExpression += '"' + StringUtil.escapeStringCharacters(
constantValue.toString()) + '"';
} else if (constantValue != null) {
newExpression += constantValue.toString();
}
replaceExpression(newExpression, expression);
}
/**
* handles the specified expression as if it was part of a string expression
* (even if it's of another type) and computes a constant string expression
* from it.
*/
private static String computeConstantStringExpression(
PsiBinaryExpression expression) {
final PsiExpression lhs = expression.getLOperand();
final String lhsText = lhs.getText();
String result;
if (lhsText.charAt(0) == '\'' || lhsText.charAt(0) == '"') {
result = lhsText.substring(1, lhsText.length() - 1);
} else {
result = lhsText;
}
final PsiExpression rhs = expression.getROperand();
assert rhs != null;
final String rhsText = rhs.getText();
if (rhsText.charAt(0) == '\'' || rhsText.charAt(0) == '"') {
result += rhsText.substring(1, rhsText.length() - 1);
} else {
result += rhsText;
}
return result;
}
private static String getLeftSideText(
PsiBinaryExpression binaryExpression) {
final PsiExpression lhs = binaryExpression.getLOperand();
final PsiJavaToken sign = binaryExpression.getOperationSign();
return lhs.getText() + sign.getText();
}
}
|
http://ea.jetbrains.com/browser/ea_problems/17729 (IOE: PsiJavaParserFacadeImpl.createExpressionFromText)
|
plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantSubexpressionIntention.java
|
http://ea.jetbrains.com/browser/ea_problems/17729 (IOE: PsiJavaParserFacadeImpl.createExpressionFromText)
|
<ide><path>lugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantSubexpressionIntention.java
<ide> newExpression += '"' + StringUtil.escapeStringCharacters(
<ide> constantValue.toString()) + '"';
<ide> } else if (constantValue != null) {
<add> if (constantValue instanceof Number) {
<add> final Number number = (Number) constantValue;
<add> if (0 > number.doubleValue()) {
<add> newExpression += " ";
<add> }
<add> }
<ide> newExpression += constantValue.toString();
<ide> }
<ide> replaceExpression(newExpression, expression);
|
|
Java
|
apache-2.0
|
75f59120671c0ba13aab856a3431d29124c30c5f
| 0 |
enioka/jqm,enioka/jqm,enioka/jqm,enioka/jqm,enioka/jqm
|
/**
* Copyright © 2013 enioka. All rights reserved
* Authors: Marc-Antoine GOUILLART ([email protected])
* Pierre COPPEE ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.enioka.jqm.tools;
import java.lang.management.ManagementFactory;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceException;
import org.apache.log4j.Logger;
import org.hibernate.TransactionException;
import org.hibernate.exception.JDBCConnectionException;
import com.enioka.jqm.jpamodel.DeploymentParameter;
import com.enioka.jqm.jpamodel.JobInstance;
import com.enioka.jqm.jpamodel.Queue;
import com.enioka.jqm.jpamodel.State;
/**
* A thread that polls a queue according to the parameters defined inside a {@link DeploymentParameter}.
*/
class QueuePoller implements Runnable, QueuePollerMBean
{
private static Logger jqmlogger = Logger.getLogger(QueuePoller.class);
private DeploymentParameter dp = null;
private Queue queue = null;
private LibraryCache cache = null;
JqmEngine engine;
private boolean run = true;
private AtomicInteger actualNbThread = new AtomicInteger(0);
private boolean hasStopped = true;
private Calendar lastLoop = null;
private ObjectName name = null;
private Thread localThread = null;
private Semaphore loop;
@Override
public void stop()
{
run = false;
if (localThread != null)
{
localThread.interrupt();
}
}
/**
* Will make the thread ready to run once again after it has stopped.
*/
void reset()
{
if (!hasStopped)
{
throw new IllegalStateException("cannot reset a non stopped queue poller");
}
hasStopped = false;
run = true;
actualNbThread.set(0);
lastLoop = null;
loop = new Semaphore(0);
}
QueuePoller(DeploymentParameter dp, LibraryCache cache, JqmEngine engine)
{
jqmlogger.info("Engine " + engine.getNode().getName() + " will poll JobInstances on queue " + dp.getQueue().getName() + " every "
+ dp.getPollingInterval() / 1000 + "s with " + dp.getNbThread() + " threads for concurrent instances");
reset();
EntityManager em = Helpers.getNewEm();
this.dp = em
.createQuery("SELECT dp FROM DeploymentParameter dp LEFT JOIN FETCH dp.queue LEFT JOIN FETCH dp.node WHERE dp.id = :l",
DeploymentParameter.class).setParameter("l", dp.getId()).getSingleResult();
this.queue = dp.getQueue();
this.cache = cache;
this.engine = engine;
try
{
if (this.engine.loadJmxBeans)
{
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
name = new ObjectName("com.enioka.jqm:type=Node.Queue,Node=" + this.dp.getNode().getName() + ",name="
+ this.dp.getQueue().getName());
mbs.registerMBean(this, name);
}
}
catch (Exception e)
{
throw new JqmInitError("Could not create JMX beans", e);
}
finally
{
em.close();
}
}
protected JobInstance dequeue(EntityManager em)
{
// Free room?
if (actualNbThread.get() >= dp.getNbThread())
{
return null;
}
// Get the list of all jobInstance within the defined queue, ordered by position
List<JobInstance> availableJobs = em
.createQuery(
"SELECT j FROM JobInstance j LEFT JOIN FETCH j.jd WHERE j.queue = :q AND j.state = :s ORDER BY j.internalPosition ASC",
JobInstance.class).setParameter("q", queue).setParameter("s", State.SUBMITTED).setMaxResults(dp.getNbThread())
.getResultList();
em.getTransaction().begin();
for (JobInstance res : availableJobs)
{
// Lock is given when object is read, not during select... stupid.
// So we must check if the object is still SUBMITTED.
try
{
em.refresh(res, LockModeType.PESSIMISTIC_WRITE);
}
catch (EntityNotFoundException e)
{
// It has already been eaten and finished by another engine
continue;
}
if (!res.getState().equals(State.SUBMITTED))
{
// Already eaten by another engine, not yet done
continue;
}
// Highlander?
if (res.getJd().isHighlander() && !highlanderPollingMode(res, em))
{
continue;
}
// Reserve the JI for this engine. Use a query rather than setter to avoid updating all fields (and locks when verifying FKs)
em.createQuery(
"UPDATE JobInstance j SET j.state = 'ATTRIBUTED', j.node = :n, j.attributionDate = current_timestamp() WHERE id=:i")
.setParameter("i", res.getId()).setParameter("n", dp.getNode()).executeUpdate();
// Stop at the first suitable JI. Release the lock & update the JI which has been attributed to us.
em.getTransaction().commit();
return res;
}
// If here, no suitable JI is available
em.getTransaction().rollback();
return null;
}
/**
*
* @param jobToTest
* @param em
* @return true if job can be launched even if it is in highlander mode
*/
protected boolean highlanderPollingMode(JobInstance jobToTest, EntityManager em)
{
List<JobInstance> jobs = em
.createQuery(
"SELECT j FROM JobInstance j WHERE j IS NOT :refid AND j.jd = :jd AND (j.state = 'RUNNING' OR j.state = 'ATTRIBUTED')",
JobInstance.class).setParameter("refid", jobToTest).setParameter("jd", jobToTest.getJd()).getResultList();
return jobs.isEmpty();
}
@Override
public void run()
{
this.localThread = Thread.currentThread();
this.localThread.setName("QUEUE_POLLER;polling;" + this.dp.getQueue().getName());
EntityManager em = null;
while (true)
{
lastLoop = Calendar.getInstance();
try
{
// Get a JI to run
em = Helpers.getNewEm();
JobInstance ji = dequeue(em);
while (ji != null)
{
// We will run this JI!
jqmlogger.trace("JI number " + ji.getId() + " will be run by this poller this loop (already " + actualNbThread + "/"
+ dp.getNbThread() + " on " + this.queue.getName() + ")");
actualNbThread.incrementAndGet();
// Run it
if (!ji.getJd().isExternal())
{
(new Thread(new Loader(ji, cache, this))).start();
}
else
{
(new Thread(new LoaderExternal(em, ji, this))).start();
}
// Check if there is another job to run (does nothing - no db query - if queue is full so this is not expensive)
ji = dequeue(em);
}
}
catch (PersistenceException e)
{
if (e.getCause() instanceof JDBCConnectionException || e.getCause() instanceof TransactionException)
{
jqmlogger.error("connection to database lost - stopping poller");
jqmlogger.trace("connection error was:", e.getCause());
this.engine.pollerRestartNeeded(this);
break;
}
else
{
throw e;
}
}
finally
{
// Reset the em on each loop.
Helpers.closeQuietly(em);
}
// Wait according to the deploymentParameter
try
{
loop.tryAcquire(dp.getPollingInterval(), TimeUnit.MILLISECONDS);
}
catch (InterruptedException e)
{
run = false;
}
// Exit if asked to
if (!run)
{
break;
}
}
if (!run)
{
// Run is true only if the loop has exited abnormally, in which case the engine should try to restart the poller
// So only do the graceful shutdown procedure if normal shutdown.
jqmlogger.info("Poller loop on queue " + this.queue.getName() + " is stopping [engine " + this.dp.getNode().getName() + "]");
waitForAllThreads(60 * 1000);
jqmlogger.info("Poller on queue " + dp.getQueue().getName() + " has ended normally");
// Let the engine decide if it should stop completely
this.hasStopped = true; // BEFORE check
this.engine.checkEngineEnd();
}
else
{
this.run = false;
this.hasStopped = true;
}
// JMX
if (this.engine.loadJmxBeans)
{
try
{
ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);
}
catch (Exception e)
{
jqmlogger.error("Could not unregister JMX beans", e);
}
}
}
@Override
public Integer getCurrentActiveThreadCount()
{
return actualNbThread.get();
}
/**
* Called when a payload thread has ended. This notifies the poller to free a slot and poll once again.
*/
synchronized void decreaseNbThread()
{
this.actualNbThread.decrementAndGet();
loop.release(1);
}
public DeploymentParameter getDp()
{
return dp;
}
boolean isRunning()
{
return !this.hasStopped;
}
private void waitForAllThreads(long timeOutMs)
{
long timeWaitedMs = 0;
long stepMs = 1000;
while (timeWaitedMs <= timeOutMs)
{
jqmlogger.trace("Waiting the end of " + actualNbThread + " job(s)");
if (actualNbThread.get() == 0)
{
break;
}
if (timeWaitedMs == 0)
{
jqmlogger.info("Waiting for the end of " + actualNbThread + " jobs on queue " + this.dp.getQueue().getName()
+ " - timeout is " + timeOutMs + "ms");
}
try
{
Thread.sleep(stepMs);
}
catch (InterruptedException e)
{
// Interruption => stop right now
jqmlogger.warn("Some job instances did not finish in time - wait was interrupted");
return;
}
timeWaitedMs += stepMs;
}
if (timeWaitedMs > timeOutMs)
{
jqmlogger.warn("Some job instances did not finish in time - they will be killed for the poller to be able to stop");
}
}
// //////////////////////////////////////////////////////////
// JMX
// //////////////////////////////////////////////////////////
@Override
public long getCumulativeJobInstancesCount()
{
EntityManager em2 = Helpers.getNewEm();
Long nb = em2.createQuery("SELECT COUNT(i) From History i WHERE i.node = :n AND i.queue = :q", Long.class)
.setParameter("n", this.dp.getNode()).setParameter("q", this.dp.getQueue()).getSingleResult();
em2.close();
return nb;
}
@Override
public float getJobsFinishedPerSecondLastMinute()
{
EntityManager em2 = Helpers.getNewEm();
Calendar minusOneMinute = Calendar.getInstance();
minusOneMinute.add(Calendar.MINUTE, -1);
Float nb = em2.createQuery("SELECT COUNT(i) From History i WHERE i.endDate >= :d and i.node = :n AND i.queue = :q", Long.class)
.setParameter("d", minusOneMinute).setParameter("n", this.dp.getNode()).setParameter("q", this.dp.getQueue())
.getSingleResult() / 60f;
em2.close();
return nb;
}
@Override
public long getCurrentlyRunningJobCount()
{
EntityManager em2 = Helpers.getNewEm();
Long nb = em2.createQuery("SELECT COUNT(i) From JobInstance i WHERE i.node = :n AND i.queue = :q", Long.class)
.setParameter("n", this.dp.getNode()).setParameter("q", this.dp.getQueue()).getSingleResult();
em2.close();
return nb;
}
@Override
public Integer getPollingIntervalMilliseconds()
{
return this.dp.getPollingInterval();
}
@Override
public Integer getMaxConcurrentJobInstanceCount()
{
return this.dp.getNbThread();
}
@Override
public boolean isActuallyPolling()
{
// 100ms is a rough estimate of the time taken to do the actual poll. If it's more, there is a huge issue elsewhere.
return (Calendar.getInstance().getTimeInMillis() - this.lastLoop.getTimeInMillis()) <= dp.getPollingInterval() + 100;
}
@Override
public boolean isFull()
{
return this.actualNbThread.get() >= this.dp.getNbThread();
}
}
|
jqm-all/jqm-engine/src/main/java/com/enioka/jqm/tools/QueuePoller.java
|
/**
* Copyright © 2013 enioka. All rights reserved
* Authors: Marc-Antoine GOUILLART ([email protected])
* Pierre COPPEE ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.enioka.jqm.tools;
import java.lang.management.ManagementFactory;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceException;
import org.apache.log4j.Logger;
import org.hibernate.TransactionException;
import org.hibernate.exception.JDBCConnectionException;
import com.enioka.jqm.jpamodel.DeploymentParameter;
import com.enioka.jqm.jpamodel.JobInstance;
import com.enioka.jqm.jpamodel.Queue;
import com.enioka.jqm.jpamodel.State;
/**
* A thread that polls a queue according to the parameters defined inside a {@link DeploymentParameter}.
*/
class QueuePoller implements Runnable, QueuePollerMBean
{
private static Logger jqmlogger = Logger.getLogger(QueuePoller.class);
private DeploymentParameter dp = null;
private Queue queue = null;
private LibraryCache cache = null;
JqmEngine engine;
private boolean run = true;
private Integer actualNbThread;
private boolean hasStopped = true;
private Calendar lastLoop = null;
private ObjectName name = null;
private Thread localThread = null;
private Semaphore loop;
@Override
public void stop()
{
run = false;
if (localThread != null)
{
localThread.interrupt();
}
}
/**
* Will make the thread ready to run once again after it has stopped.
*/
void reset()
{
if (!hasStopped)
{
throw new IllegalStateException("cannot reset a non stopped queue poller");
}
hasStopped = false;
run = true;
actualNbThread = 0;
lastLoop = null;
loop = new Semaphore(0);
}
QueuePoller(DeploymentParameter dp, LibraryCache cache, JqmEngine engine)
{
jqmlogger.info("Engine " + engine.getNode().getName() + " will poll JobInstances on queue " + dp.getQueue().getName() + " every "
+ dp.getPollingInterval() / 1000 + "s with " + dp.getNbThread() + " threads for concurrent instances");
reset();
EntityManager em = Helpers.getNewEm();
this.dp = em
.createQuery("SELECT dp FROM DeploymentParameter dp LEFT JOIN FETCH dp.queue LEFT JOIN FETCH dp.node WHERE dp.id = :l",
DeploymentParameter.class).setParameter("l", dp.getId()).getSingleResult();
this.queue = dp.getQueue();
this.cache = cache;
this.engine = engine;
try
{
if (this.engine.loadJmxBeans)
{
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
name = new ObjectName("com.enioka.jqm:type=Node.Queue,Node=" + this.dp.getNode().getName() + ",name="
+ this.dp.getQueue().getName());
mbs.registerMBean(this, name);
}
}
catch (Exception e)
{
throw new JqmInitError("Could not create JMX beans", e);
}
finally
{
em.close();
}
}
protected JobInstance dequeue(EntityManager em)
{
// Free room?
if (actualNbThread >= dp.getNbThread())
{
return null;
}
// Get the list of all jobInstance within the defined queue, ordered by position
List<JobInstance> availableJobs = em
.createQuery(
"SELECT j FROM JobInstance j LEFT JOIN FETCH j.jd WHERE j.queue = :q AND j.state = :s ORDER BY j.internalPosition ASC",
JobInstance.class).setParameter("q", queue).setParameter("s", State.SUBMITTED).setMaxResults(dp.getNbThread())
.getResultList();
em.getTransaction().begin();
for (JobInstance res : availableJobs)
{
// Lock is given when object is read, not during select... stupid.
// So we must check if the object is still SUBMITTED.
try
{
em.refresh(res, LockModeType.PESSIMISTIC_WRITE);
}
catch (EntityNotFoundException e)
{
// It has already been eaten and finished by another engine
continue;
}
if (!res.getState().equals(State.SUBMITTED))
{
// Already eaten by another engine, not yet done
continue;
}
// Highlander?
if (res.getJd().isHighlander() && !highlanderPollingMode(res, em))
{
continue;
}
// Reserve the JI for this engine. Use a query rather than setter to avoid updating all fields (and locks when verifying FKs)
em.createQuery(
"UPDATE JobInstance j SET j.state = 'ATTRIBUTED', j.node = :n, j.attributionDate = current_timestamp() WHERE id=:i")
.setParameter("i", res.getId()).setParameter("n", dp.getNode()).executeUpdate();
// Stop at the first suitable JI. Release the lock & update the JI which has been attributed to us.
em.getTransaction().commit();
return res;
}
// If here, no suitable JI is available
em.getTransaction().rollback();
return null;
}
/**
*
* @param jobToTest
* @param em
* @return true if job can be launched even if it is in highlander mode
*/
protected boolean highlanderPollingMode(JobInstance jobToTest, EntityManager em)
{
List<JobInstance> jobs = em
.createQuery(
"SELECT j FROM JobInstance j WHERE j IS NOT :refid AND j.jd = :jd AND (j.state = 'RUNNING' OR j.state = 'ATTRIBUTED')",
JobInstance.class).setParameter("refid", jobToTest).setParameter("jd", jobToTest.getJd()).getResultList();
return jobs.isEmpty();
}
@Override
public void run()
{
this.localThread = Thread.currentThread();
this.localThread.setName("QUEUE_POLLER;polling;" + this.dp.getQueue().getName());
EntityManager em = null;
while (true)
{
lastLoop = Calendar.getInstance();
try
{
// Get a JI to run
em = Helpers.getNewEm();
JobInstance ji = dequeue(em);
while (ji != null)
{
// We will run this JI!
jqmlogger.trace("JI number " + ji.getId() + " will be run by this poller this loop (already " + actualNbThread + "/"
+ dp.getNbThread() + " on " + this.queue.getName() + ")");
actualNbThread++;
// Run it
if (!ji.getJd().isExternal())
{
(new Thread(new Loader(ji, cache, this))).start();
}
else
{
(new Thread(new LoaderExternal(em, ji, this))).start();
}
// Check if there is another job to run (does nothing - no db query - if queue is full so this is not expensive)
ji = dequeue(em);
}
}
catch (PersistenceException e)
{
if (e.getCause() instanceof JDBCConnectionException || e.getCause() instanceof TransactionException)
{
jqmlogger.error("connection to database lost - stopping poller");
jqmlogger.trace("connection error was:", e.getCause());
this.engine.pollerRestartNeeded(this);
break;
}
else
{
throw e;
}
}
finally
{
// Reset the em on each loop.
Helpers.closeQuietly(em);
}
// Wait according to the deploymentParameter
try
{
loop.tryAcquire(dp.getPollingInterval(), TimeUnit.MILLISECONDS);
}
catch (InterruptedException e)
{
run = false;
}
// Exit if asked to
if (!run)
{
break;
}
}
if (!run)
{
// Run is true only if the loop has exited abnormally, in which case the engine should try to restart the poller
// So only do the graceful shutdown procedure if normal shutdown.
jqmlogger.info("Poller loop on queue " + this.queue.getName() + " is stopping [engine " + this.dp.getNode().getName() + "]");
waitForAllThreads(60 * 1000);
jqmlogger.info("Poller on queue " + dp.getQueue().getName() + " has ended normally");
// Let the engine decide if it should stop completely
this.hasStopped = true; // BEFORE check
this.engine.checkEngineEnd();
}
else
{
this.run = false;
this.hasStopped = true;
}
// JMX
if (this.engine.loadJmxBeans)
{
try
{
ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);
}
catch (Exception e)
{
jqmlogger.error("Could not unregister JMX beans", e);
}
}
}
@Override
public Integer getCurrentActiveThreadCount()
{
return actualNbThread;
}
/**
* Called when a payload thread has ended. This notifies the poller to free a slot and poll once again.
*/
synchronized void decreaseNbThread()
{
this.actualNbThread--;
loop.release(1);
}
public DeploymentParameter getDp()
{
return dp;
}
boolean isRunning()
{
return !this.hasStopped;
}
private void waitForAllThreads(long timeOutMs)
{
long timeWaitedMs = 0;
long stepMs = 1000;
while (timeWaitedMs <= timeOutMs)
{
jqmlogger.trace("Waiting the end of " + actualNbThread + " job(s)");
if (actualNbThread == 0)
{
break;
}
if (timeWaitedMs == 0)
{
jqmlogger.info("Waiting for the end of " + actualNbThread + " jobs on queue " + this.dp.getQueue().getName()
+ " - timeout is " + timeOutMs + "ms");
}
try
{
Thread.sleep(stepMs);
}
catch (InterruptedException e)
{
// Interruption => stop right now
jqmlogger.warn("Some job instances did not finish in time - wait was interrupted");
return;
}
timeWaitedMs += stepMs;
}
if (timeWaitedMs > timeOutMs)
{
jqmlogger.warn("Some job instances did not finish in time - they will be killed for the poller to be able to stop");
}
}
// //////////////////////////////////////////////////////////
// JMX
// //////////////////////////////////////////////////////////
@Override
public long getCumulativeJobInstancesCount()
{
EntityManager em2 = Helpers.getNewEm();
Long nb = em2.createQuery("SELECT COUNT(i) From History i WHERE i.node = :n AND i.queue = :q", Long.class)
.setParameter("n", this.dp.getNode()).setParameter("q", this.dp.getQueue()).getSingleResult();
em2.close();
return nb;
}
@Override
public float getJobsFinishedPerSecondLastMinute()
{
EntityManager em2 = Helpers.getNewEm();
Calendar minusOneMinute = Calendar.getInstance();
minusOneMinute.add(Calendar.MINUTE, -1);
Float nb = em2.createQuery("SELECT COUNT(i) From History i WHERE i.endDate >= :d and i.node = :n AND i.queue = :q", Long.class)
.setParameter("d", minusOneMinute).setParameter("n", this.dp.getNode()).setParameter("q", this.dp.getQueue())
.getSingleResult() / 60f;
em2.close();
return nb;
}
@Override
public long getCurrentlyRunningJobCount()
{
EntityManager em2 = Helpers.getNewEm();
Long nb = em2.createQuery("SELECT COUNT(i) From JobInstance i WHERE i.node = :n AND i.queue = :q", Long.class)
.setParameter("n", this.dp.getNode()).setParameter("q", this.dp.getQueue()).getSingleResult();
em2.close();
return nb;
}
@Override
public Integer getPollingIntervalMilliseconds()
{
return this.dp.getPollingInterval();
}
@Override
public Integer getMaxConcurrentJobInstanceCount()
{
return this.dp.getNbThread();
}
@Override
public boolean isActuallyPolling()
{
// 100ms is a rough estimate of the time taken to do the actual poll. If it's more, there is a huge issue elsewhere.
return (Calendar.getInstance().getTimeInMillis() - this.lastLoop.getTimeInMillis()) <= dp.getPollingInterval() + 100;
}
@Override
public boolean isFull()
{
return this.actualNbThread >= this.dp.getNbThread();
}
}
|
Fix: number of running JI could very rarely become wrong
Because -- is not an atomic operator in Java...
|
jqm-all/jqm-engine/src/main/java/com/enioka/jqm/tools/QueuePoller.java
|
Fix: number of running JI could very rarely become wrong
|
<ide><path>qm-all/jqm-engine/src/main/java/com/enioka/jqm/tools/QueuePoller.java
<ide> import java.util.List;
<ide> import java.util.concurrent.Semaphore;
<ide> import java.util.concurrent.TimeUnit;
<add>import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> import javax.management.MBeanServer;
<ide> import javax.management.ObjectName;
<ide> JqmEngine engine;
<ide>
<ide> private boolean run = true;
<del> private Integer actualNbThread;
<add> private AtomicInteger actualNbThread = new AtomicInteger(0);
<ide> private boolean hasStopped = true;
<ide> private Calendar lastLoop = null;
<ide>
<ide> }
<ide> hasStopped = false;
<ide> run = true;
<del> actualNbThread = 0;
<add> actualNbThread.set(0);
<ide> lastLoop = null;
<ide> loop = new Semaphore(0);
<ide> }
<ide> protected JobInstance dequeue(EntityManager em)
<ide> {
<ide> // Free room?
<del> if (actualNbThread >= dp.getNbThread())
<add> if (actualNbThread.get() >= dp.getNbThread())
<ide> {
<ide> return null;
<ide> }
<ide> // We will run this JI!
<ide> jqmlogger.trace("JI number " + ji.getId() + " will be run by this poller this loop (already " + actualNbThread + "/"
<ide> + dp.getNbThread() + " on " + this.queue.getName() + ")");
<del> actualNbThread++;
<add> actualNbThread.incrementAndGet();
<ide>
<ide> // Run it
<ide> if (!ji.getJd().isExternal())
<ide> @Override
<ide> public Integer getCurrentActiveThreadCount()
<ide> {
<del> return actualNbThread;
<add> return actualNbThread.get();
<ide> }
<ide>
<ide> /**
<ide> */
<ide> synchronized void decreaseNbThread()
<ide> {
<del> this.actualNbThread--;
<add> this.actualNbThread.decrementAndGet();
<ide> loop.release(1);
<ide> }
<ide>
<ide> {
<ide> jqmlogger.trace("Waiting the end of " + actualNbThread + " job(s)");
<ide>
<del> if (actualNbThread == 0)
<add> if (actualNbThread.get() == 0)
<ide> {
<ide> break;
<ide> }
<ide> @Override
<ide> public boolean isFull()
<ide> {
<del> return this.actualNbThread >= this.dp.getNbThread();
<add> return this.actualNbThread.get() >= this.dp.getNbThread();
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
ea6fe829fc08deb164af1411cc19486f5793b82a
| 0 |
anomaly/closure-compiler,google/closure-compiler,nawawi/closure-compiler,vobruba-martin/closure-compiler,vobruba-martin/closure-compiler,mprobst/closure-compiler,anomaly/closure-compiler,tdelmas/closure-compiler,Pimm/closure-compiler,ChadKillingsworth/closure-compiler,Dominator008/closure-compiler,GerHobbelt/closure-compiler,Dominator008/closure-compiler,ChadKillingsworth/closure-compiler,mprobst/closure-compiler,MatrixFrog/closure-compiler,shantanusharma/closure-compiler,vobruba-martin/closure-compiler,Yannic/closure-compiler,Dominator008/closure-compiler,google/closure-compiler,GerHobbelt/closure-compiler,monetate/closure-compiler,tdelmas/closure-compiler,brad4d/closure-compiler,nawawi/closure-compiler,Yannic/closure-compiler,Pimm/closure-compiler,Yannic/closure-compiler,tdelmas/closure-compiler,google/closure-compiler,brad4d/closure-compiler,MatrixFrog/closure-compiler,Pimm/closure-compiler,shantanusharma/closure-compiler,nawawi/closure-compiler,tiobe/closure-compiler,tiobe/closure-compiler,ChadKillingsworth/closure-compiler,monetate/closure-compiler,mprobst/closure-compiler,Yannic/closure-compiler,vobruba-martin/closure-compiler,shantanusharma/closure-compiler,tdelmas/closure-compiler,MatrixFrog/closure-compiler,GerHobbelt/closure-compiler,MatrixFrog/closure-compiler,shantanusharma/closure-compiler,mprobst/closure-compiler,anomaly/closure-compiler,monetate/closure-compiler,GerHobbelt/closure-compiler,tiobe/closure-compiler,monetate/closure-compiler,nawawi/closure-compiler,ChadKillingsworth/closure-compiler,anomaly/closure-compiler,brad4d/closure-compiler,google/closure-compiler,tiobe/closure-compiler
|
/*
* Copyright 2010 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.jscomp.CodingConvention.Bind;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.regex.Pattern;
/**
* A peephole optimization that minimizes code by simplifying conditional
* expressions, replacing IFs with HOOKs, replacing object constructors
* with literals, and simplifying returns.
*
*/
class PeepholeSubstituteAlternateSyntax
extends AbstractPeepholeOptimization {
private static final CodeGenerator REGEXP_ESCAPER =
CodeGenerator.forCostEstimation(
null /* blow up if we try to produce code */);
private final boolean late;
private static final int STRING_SPLIT_OVERHEAD = ".split('.')".length();
static final DiagnosticType INVALID_REGULAR_EXPRESSION_FLAGS =
DiagnosticType.warning(
"JSC_INVALID_REGULAR_EXPRESSION_FLAGS",
"Invalid flags to RegExp constructor: {0}");
/**
* @param late When late is false, this mean we are currently running before
* most of the other optimizations. In this case we would avoid optimizations
* that would make the code harder to analyze (such as using string splitting,
* merging statements with commas, etc). When this is true, we would
* do anything to minimize for size.
*/
PeepholeSubstituteAlternateSyntax(boolean late) {
this.late = late;
}
/**
* Tries apply our various peephole minimizations on the passed in node.
*/
@Override
@SuppressWarnings("fallthrough")
public Node optimizeSubtree(Node node) {
switch (node.getToken()) {
case ASSIGN_SUB:
return reduceSubstractionAssignment(node);
case TRUE:
case FALSE:
return reduceTrueFalse(node);
case NEW:
node = tryFoldStandardConstructors(node);
if (!node.isCall()) {
return node;
}
// Fall through on purpose because tryFoldStandardConstructors() may
// convert a NEW node into a CALL node
case CALL:
Node result = tryFoldLiteralConstructor(node);
if (result == node) {
result = tryFoldSimpleFunctionCall(node);
if (result == node) {
result = tryFoldImmediateCallToBoundFunction(node);
}
}
return result;
case RETURN:
return tryReduceReturn(node);
case COMMA:
return trySplitComma(node);
case NAME:
return tryReplaceUndefined(node);
case ARRAYLIT:
return tryMinimizeArrayLiteral(node);
case GETPROP:
return tryMinimizeWindowRefs(node);
case MUL:
case AND:
case OR:
case BITOR:
case BITXOR:
case BITAND:
return tryRotateAssociativeOperator(node);
default:
return node; //Nothing changed
}
}
private static final ImmutableSet<String> BUILTIN_EXTERNS = ImmutableSet.of(
"Object",
"Array",
"Error",
"RegExp",
"Math");
private Node tryMinimizeWindowRefs(Node node) {
// Normalization needs to be done to ensure there's no shadowing. The window prefix is also
// required if the global externs are not on the window.
if (!isASTNormalized() || !areDeclaredGlobalExternsOnWindow()) {
return node;
}
Preconditions.checkArgument(node.isGetProp());
if (node.getFirstChild().isName()) {
Node nameNode = node.getFirstChild();
Node stringNode = node.getLastChild();
// Since normalization has run we know we're referring to the global window.
if ("window".equals(nameNode.getString())
&& BUILTIN_EXTERNS.contains(stringNode.getString())) {
Node newNameNode = IR.name(stringNode.getString());
Node parentNode = node.getParent();
newNameNode.useSourceInfoFrom(stringNode);
parentNode.replaceChild(node, newNameNode);
if (parentNode.isCall()) {
parentNode.putBooleanProp(Node.FREE_CALL, true);
}
reportCodeChange();
return newNameNode;
}
}
return node;
}
private Node tryRotateAssociativeOperator(Node n) {
if (!late) {
return n;
}
// All commutative operators are also associative
Preconditions.checkArgument(NodeUtil.isAssociative(n.getToken()));
Node rhs = n.getLastChild();
if (n.getToken() == rhs.getToken()) {
// Transform a * (b * c) to a * b * c
Node first = n.getFirstChild().detach();
Node second = rhs.getFirstChild().detach();
Node third = rhs.getLastChild().detach();
Node newLhs = new Node(n.getToken(), first, second).useSourceInfoIfMissingFrom(n);
Node newRoot = new Node(rhs.getToken(), newLhs, third).useSourceInfoIfMissingFrom(rhs);
n.getParent().replaceChild(n, newRoot);
reportCodeChange();
return newRoot;
} else if (NodeUtil.isCommutative(n.getToken()) && !NodeUtil.mayHaveSideEffects(n)) {
// Transform a * (b / c) to b / c * a
Node lhs = n.getFirstChild();
while (lhs.getToken() == n.getToken()) {
lhs = lhs.getFirstChild();
}
int precedence = NodeUtil.precedence(n.getToken());
int lhsPrecedence = NodeUtil.precedence(lhs.getToken());
int rhsPrecedence = NodeUtil.precedence(rhs.getToken());
if (rhsPrecedence == precedence && lhsPrecedence != precedence) {
n.removeChild(rhs);
lhs.getParent().replaceChild(lhs, rhs);
n.addChildToBack(lhs);
reportCodeChange();
return n;
}
}
return n;
}
private Node tryFoldSimpleFunctionCall(Node n) {
Preconditions.checkState(n.isCall(), n);
Node callTarget = n.getFirstChild();
if (callTarget == null || !callTarget.isName()) {
return n;
}
String targetName = callTarget.getString();
switch (targetName) {
case "Boolean": {
// Fold Boolean(a) to !!a
// http://www.ecma-international.org/ecma-262/6.0/index.html#sec-boolean-constructor-boolean-value
// and
// http://www.ecma-international.org/ecma-262/6.0/index.html#sec-logical-not-operator-runtime-semantics-evaluation
int paramCount = n.getChildCount() - 1;
// only handle the single known parameter case
if (paramCount == 1) {
Node value = n.getLastChild().detach();
Node replacement;
if (NodeUtil.isBooleanResult(value)) {
// If it is already a boolean do nothing.
replacement = value;
} else {
// Replace it with a "!!value"
replacement = IR.not(IR.not(value).srcref(n));
}
n.getParent().replaceChild(n, replacement);
reportCodeChange();
}
break;
}
case "String": {
// Fold String(a) to '' + (a) on immutable literals,
// which allows further optimizations
//
// We can't do this in the general case, because String(a) has
// slightly different semantics than '' + (a). See
// https://blickly.github.io/closure-compiler-issues/#759
Node value = callTarget.getNext();
if (value != null && value.getNext() == null &&
NodeUtil.isImmutableValue(value)) {
Node addition = IR.add(
IR.string("").srcref(callTarget),
value.detach());
n.getParent().replaceChild(n, addition);
reportCodeChange();
return addition;
}
break;
}
default:
// nothing.
break;
}
return n;
}
private Node tryFoldImmediateCallToBoundFunction(Node n) {
// Rewriting "(fn.bind(a,b))()" to "fn.call(a,b)" makes it inlinable
Preconditions.checkState(n.isCall());
Node callTarget = n.getFirstChild();
Bind bind = getCodingConvention()
.describeFunctionBind(callTarget, false, false);
if (bind != null) {
// replace the call target
bind.target.detach();
n.replaceChild(callTarget, bind.target);
callTarget = bind.target;
// push the parameters
addParameterAfter(bind.parameters, callTarget);
// add the this value before the parameters if necessary
if (bind.thisValue != null && !NodeUtil.isUndefined(bind.thisValue)) {
// rewrite from "fn(a, b)" to "fn.call(thisValue, a, b)"
Node newCallTarget = IR.getprop(
callTarget.cloneTree(),
IR.string("call").srcref(callTarget));
n.replaceChild(callTarget, newCallTarget);
n.addChildAfter(bind.thisValue.cloneTree(), newCallTarget);
n.putBooleanProp(Node.FREE_CALL, false);
} else {
n.putBooleanProp(Node.FREE_CALL, true);
}
reportCodeChange();
}
return n;
}
private static void addParameterAfter(Node parameterList, Node after) {
if (parameterList != null) {
// push the last parameter to the head of the list first.
addParameterAfter(parameterList.getNext(), after);
after.getParent().addChildAfter(parameterList.cloneTree(), after);
}
}
private Node trySplitComma(Node n) {
if (late) {
return n;
}
Node parent = n.getParent();
Node left = n.getFirstChild();
Node right = n.getLastChild();
if (parent.isExprResult()
&& !parent.getParent().isLabel()) {
// split comma
n.detachChildren();
// Replace the original expression with the left operand.
parent.replaceChild(n, left);
// Add the right expression afterward.
Node newStatement = IR.exprResult(right);
newStatement.useSourceInfoIfMissingFrom(n);
//This modifies outside the subtree, which is not
//desirable in a peephole optimization.
parent.getParent().addChildAfter(newStatement, parent);
reportCodeChange();
return left;
} else {
return n;
}
}
/**
* Use "void 0" in place of "undefined"
*/
private Node tryReplaceUndefined(Node n) {
// TODO(johnlenz): consider doing this as a normalization.
if (isASTNormalized()
&& NodeUtil.isUndefined(n)
&& !NodeUtil.isLValue(n)) {
Node replacement = NodeUtil.newUndefinedNode(n);
n.getParent().replaceChild(n, replacement);
reportCodeChange();
return replacement;
}
return n;
}
/**
* Reduce "return undefined" or "return void 0" to simply "return".
*
* @return The original node, maybe simplified.
*/
private Node tryReduceReturn(Node n) {
Node result = n.getFirstChild();
if (result != null) {
switch (result.getToken()) {
case VOID:
Node operand = result.getFirstChild();
if (!mayHaveSideEffects(operand)) {
n.removeFirstChild();
reportCodeChange();
}
break;
case NAME:
String name = result.getString();
if (name.equals("undefined")) {
n.removeFirstChild();
reportCodeChange();
}
break;
default:
break;
}
}
return n;
}
private static final ImmutableSet<String> STANDARD_OBJECT_CONSTRUCTORS =
// String, Number, and Boolean functions return non-object types, whereas
// new String, new Number, and new Boolean return object types, so don't
// include them here.
ImmutableSet.of(
"Object",
"Array",
"Error"
);
/**
* Fold "new Object()" to "Object()".
*/
private Node tryFoldStandardConstructors(Node n) {
Preconditions.checkState(n.isNew());
if (canFoldStandardConstructors(n)) {
n.setToken(Token.CALL);
n.putBooleanProp(Node.FREE_CALL, true);
reportCodeChange();
}
return n;
}
/**
* @return Whether "new Object()" can be folded to "Object()" on {@code n}.
*/
private boolean canFoldStandardConstructors(Node n) {
// If name normalization has been run then we know that
// new Object() does in fact refer to what we think it is
// and not some custom-defined Object().
if (isASTNormalized() && n.getFirstChild().isName()) {
String className = n.getFirstChild().getString();
if (STANDARD_OBJECT_CONSTRUCTORS.contains(className)) {
return true;
}
if ("RegExp".equals(className)) {
// Fold "new RegExp()" to "RegExp()", but only if the argument is a string.
// See issue 1260.
if (n.getSecondChild() == null || n.getSecondChild().isString()) {
return true;
}
}
}
return false;
}
/**
* Replaces a new Array, Object, or RegExp node with a literal, unless the
* call is to a local constructor function with the same name.
*/
private Node tryFoldLiteralConstructor(Node n) {
Preconditions.checkArgument(n.isCall()
|| n.isNew());
Node constructorNameNode = n.getFirstChild();
Node newLiteralNode = null;
// We require the AST to be normalized to ensure that, say,
// Object() really refers to the built-in Object constructor
// and not a user-defined constructor with the same name.
if (isASTNormalized() && Token.NAME == constructorNameNode.getToken()) {
String className = constructorNameNode.getString();
if ("RegExp".equals(className)) {
// "RegExp("boo", "g")" --> /boo/g
return tryFoldRegularExpressionConstructor(n);
} else {
boolean constructorHasArgs = constructorNameNode.getNext() != null;
if ("Object".equals(className) && !constructorHasArgs) {
// "Object()" --> "{}"
newLiteralNode = IR.objectlit();
} else if ("Array".equals(className)) {
// "Array(arg0, arg1, ...)" --> "[arg0, arg1, ...]"
Node arg0 = constructorNameNode.getNext();
FoldArrayAction action = isSafeToFoldArrayConstructor(arg0);
if (action == FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS ||
action == FoldArrayAction.SAFE_TO_FOLD_WITHOUT_ARGS) {
newLiteralNode = IR.arraylit();
n.removeFirstChild(); // discard the function name
Node elements = n.removeChildren();
if (action == FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS) {
newLiteralNode.addChildrenToFront(elements);
}
}
}
if (newLiteralNode != null) {
n.getParent().replaceChild(n, newLiteralNode);
reportCodeChange();
return newLiteralNode;
}
}
}
return n;
}
private static enum FoldArrayAction {
NOT_SAFE_TO_FOLD, SAFE_TO_FOLD_WITH_ARGS, SAFE_TO_FOLD_WITHOUT_ARGS}
/**
* Checks if it is safe to fold Array() constructor into []. It can be
* obviously done, if the initial constructor has either no arguments or
* at least two. The remaining case may be unsafe since Array(number)
* actually reserves memory for an empty array which contains number elements.
*/
private static FoldArrayAction isSafeToFoldArrayConstructor(Node arg) {
FoldArrayAction action = FoldArrayAction.NOT_SAFE_TO_FOLD;
if (arg == null) {
action = FoldArrayAction.SAFE_TO_FOLD_WITHOUT_ARGS;
} else if (arg.getNext() != null) {
action = FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS;
} else {
switch (arg.getToken()) {
case STRING:
// "Array('a')" --> "['a']"
action = FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS;
break;
case NUMBER:
// "Array(0)" --> "[]"
if (arg.getDouble() == 0) {
action = FoldArrayAction.SAFE_TO_FOLD_WITHOUT_ARGS;
}
break;
case ARRAYLIT:
// "Array([args])" --> "[[args]]"
action = FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS;
break;
default:
}
}
return action;
}
private Node tryFoldRegularExpressionConstructor(Node n) {
Node parent = n.getParent();
Node constructor = n.getFirstChild();
Node pattern = constructor.getNext(); // e.g. ^foobar$
Node flags = null != pattern ? pattern.getNext() : null; // e.g. gi
if (null == pattern || (null != flags && null != flags.getNext())) {
// too few or too many arguments
return n;
}
if (// is pattern folded
pattern.isString()
// make sure empty pattern doesn't fold to //
&& !"".equals(pattern.getString())
&& (null == flags || flags.isString())
// don't escape patterns with Unicode escapes since Safari behaves badly
// (read can't parse or crashes) on regex literals with Unicode escapes
&& (isEcmaScript5OrGreater()
|| !containsUnicodeEscape(pattern.getString()))) {
// Make sure that / is escaped, so that it will fit safely in /brackets/
// and make sure that no LineTerminatorCharacters appear literally inside
// the pattern.
// pattern is a string value with \\ and similar already escaped
pattern = makeForwardSlashBracketSafe(pattern);
Node regexLiteral;
if (null == flags || "".equals(flags.getString())) {
// fold to /foobar/
regexLiteral = IR.regexp(pattern);
} else {
// fold to /foobar/gi
if (!areValidRegexpFlags(flags.getString())) {
report(INVALID_REGULAR_EXPRESSION_FLAGS, flags);
return n;
}
if (!areSafeFlagsToFold(flags.getString())) {
return n;
}
n.removeChild(flags);
regexLiteral = IR.regexp(pattern, flags);
}
parent.replaceChild(n, regexLiteral);
reportCodeChange();
return regexLiteral;
}
return n;
}
private Node reduceSubstractionAssignment(Node n) {
Node right = n.getLastChild();
if (right.isNumber()) {
if (right.getDouble() == 1) {
Node newNode = IR.dec(n.removeFirstChild(), false);
n.getParent().replaceChild(n, newNode);
reportCodeChange();
return newNode;
} else if (right.getDouble() == -1) {
Node newNode = IR.inc(n.removeFirstChild(), false);
n.getParent().replaceChild(n, newNode);
reportCodeChange();
return newNode;
}
}
return n;
}
private Node reduceTrueFalse(Node n) {
if (late) {
switch (n.getParent().getToken()) {
case EQ:
case GT:
case GE:
case LE:
case LT:
case NE:
Node number = IR.number(n.isTrue() ? 1 : 0);
n.getParent().replaceChild(n, number);
reportCodeChange();
return number;
default:
break;
}
Node not = IR.not(IR.number(n.isTrue() ? 0 : 1));
not.useSourceInfoIfMissingFromForTree(n);
n.getParent().replaceChild(n, not);
reportCodeChange();
return not;
}
return n;
}
private Node tryMinimizeArrayLiteral(Node n) {
boolean allStrings = true;
for (Node cur = n.getFirstChild(); cur != null; cur = cur.getNext()) {
if (!cur.isString()) {
allStrings = false;
}
}
if (allStrings) {
return tryMinimizeStringArrayLiteral(n);
} else {
return n;
}
}
private Node tryMinimizeStringArrayLiteral(Node n) {
if (!late) {
return n;
}
int numElements = n.getChildCount();
// We save two bytes per element.
int saving = numElements * 2 - STRING_SPLIT_OVERHEAD;
if (saving <= 0) {
return n;
}
String[] strings = new String[n.getChildCount()];
int idx = 0;
for (Node cur = n.getFirstChild(); cur != null; cur = cur.getNext()) {
strings[idx++] = cur.getString();
}
// These delimiters are chars that appears a lot in the program therefore
// probably have a small Huffman encoding.
String delimiter = pickDelimiter(strings);
if (delimiter != null) {
String template = Joiner.on(delimiter).join(strings);
Node call = IR.call(
IR.getprop(
IR.string(template),
IR.string("split")),
IR.string("" + delimiter));
call.useSourceInfoIfMissingFromForTree(n);
n.getParent().replaceChild(n, call);
reportCodeChange();
return call;
}
return n;
}
/**
* Find a delimiter that does not occur in the given strings
* @param strings The strings that must be separated.
* @return a delimiter string or null
*/
private static String pickDelimiter(String[] strings) {
boolean allLength1 = true;
for (String s : strings) {
if (s.length() != 1) {
allLength1 = false;
break;
}
}
if (allLength1) {
return "";
}
String[] delimiters = new String[]{" ", ";", ",", "{", "}", null};
int i = 0;
NEXT_DELIMITER: for (; delimiters[i] != null; i++) {
for (String cur : strings) {
if (cur.contains(delimiters[i])) {
continue NEXT_DELIMITER;
}
}
break;
}
return delimiters[i];
}
private static final Pattern REGEXP_FLAGS_RE = Pattern.compile("^[gmi]*$");
/**
* are the given flags valid regular expression flags?
* JavaScript recognizes several suffix flags for regular expressions,
* 'g' - global replace, 'i' - case insensitive, 'm' - multi-line.
* They are case insensitive, and JavaScript does not recognize the extended
* syntax mode, single-line mode, or expression replacement mode from Perl 5.
*/
private static boolean areValidRegexpFlags(String flags) {
return REGEXP_FLAGS_RE.matcher(flags).matches();
}
/**
* are the given flags safe to fold?
* We don't fold the regular expression if global ('g') flag is on,
* because in this case it isn't really a constant: its 'lastIndex'
* property contains the state of last execution, so replacing
* 'new RegExp('foobar','g')' with '/foobar/g' may change the behavior of
* the program if the RegExp is used inside a loop, for example.
* <p>
* ECMAScript 5 explicitly disallows pooling of regular expression literals so
* in ECMAScript 5, {@code /foo/g} and {@code new RegExp('foo', 'g')} are
* equivalent.
* From section 7.8.5:
* "Then each time the literal is evaluated, a new object is created as if by
* the expression new RegExp(Pattern, Flags) where RegExp is the standard
* built-in constructor with that name."
*/
private boolean areSafeFlagsToFold(String flags) {
return isEcmaScript5OrGreater() || flags.indexOf('g') < 0;
}
/**
* returns a string node that can safely be rendered inside /brackets/.
*/
private static Node makeForwardSlashBracketSafe(Node n) {
String s = n.getString();
// sb contains everything in s[0:pos]
StringBuilder sb = null;
int pos = 0;
boolean isEscaped = false;
boolean inCharset = false;
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
switch (ch) {
case '\\':
isEscaped = !isEscaped;
continue;
case '/':
// Escape a literal forward slash if it is not already escaped and is
// not inside a character set.
// new RegExp('/') -> /\//
// but the following do not need extra escaping
// new RegExp('\\/') -> /\//
// new RegExp('[/]') -> /[/]/
if (!isEscaped && !inCharset) {
if (null == sb) { sb = new StringBuilder(s.length() + 16); }
sb.append(s, pos, i).append('\\');
pos = i;
}
break;
case '[':
if (!isEscaped) {
inCharset = true;
}
break;
case ']':
if (!isEscaped) {
inCharset = false;
}
break;
case '\r': case '\n': case '\u2028': case '\u2029':
// LineTerminators cannot appear raw inside a regular
// expression literal.
// They can't appear legally in a quoted string, but when
// the quoted string from
// new RegExp('\n')
// reaches here, the quoting has been removed.
// Requote just these code-points.
if (null == sb) { sb = new StringBuilder(s.length() + 16); }
if (isEscaped) {
sb.append(s, pos, i - 1);
} else {
sb.append(s, pos, i);
}
switch (ch) {
case '\r': sb.append("\\r"); break;
case '\n': sb.append("\\n"); break;
case '\u2028': sb.append("\\u2028"); break;
case '\u2029': sb.append("\\u2029"); break;
}
pos = i + 1;
break;
}
isEscaped = false;
}
if (null == sb) { return n.cloneTree(); }
sb.append(s, pos, s.length());
return IR.string(sb.toString()).srcref(n);
}
/**
* true if the JavaScript string would contain a Unicode escape when written
* out as the body of a regular expression literal.
*/
static boolean containsUnicodeEscape(String s) {
String esc = REGEXP_ESCAPER.regexpEscape(s);
for (int i = -1; (i = esc.indexOf("\\u", i + 1)) >= 0;) {
int nSlashes = 0;
while (i - nSlashes > 0 && '\\' == esc.charAt(i - nSlashes - 1)) {
++nSlashes;
}
// if there are an even number of slashes before the \ u then it is a
// Unicode literal.
if (0 == (nSlashes & 1)) { return true; }
}
return false;
}
}
|
src/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java
|
/*
* Copyright 2010 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.jscomp.CodingConvention.Bind;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.regex.Pattern;
/**
* A peephole optimization that minimizes code by simplifying conditional
* expressions, replacing IFs with HOOKs, replacing object constructors
* with literals, and simplifying returns.
*
*/
class PeepholeSubstituteAlternateSyntax
extends AbstractPeepholeOptimization {
private static final CodeGenerator REGEXP_ESCAPER =
CodeGenerator.forCostEstimation(
null /* blow up if we try to produce code */);
private final boolean late;
private static final int STRING_SPLIT_OVERHEAD = ".split('.')".length();
static final DiagnosticType INVALID_REGULAR_EXPRESSION_FLAGS =
DiagnosticType.warning(
"JSC_INVALID_REGULAR_EXPRESSION_FLAGS",
"Invalid flags to RegExp constructor: {0}");
/**
* @param late When late is false, this mean we are currently running before
* most of the other optimizations. In this case we would avoid optimizations
* that would make the code harder to analyze (such as using string splitting,
* merging statements with commas, etc). When this is true, we would
* do anything to minimize for size.
*/
PeepholeSubstituteAlternateSyntax(boolean late) {
this.late = late;
}
/**
* Tries apply our various peephole minimizations on the passed in node.
*/
@Override
@SuppressWarnings("fallthrough")
public Node optimizeSubtree(Node node) {
switch (node.getToken()) {
case ASSIGN_SUB:
return reduceSubstractionAssignment(node);
case TRUE:
case FALSE:
return reduceTrueFalse(node);
case NEW:
node = tryFoldStandardConstructors(node);
if (!node.isCall()) {
return node;
}
// Fall through on purpose because tryFoldStandardConstructors() may
// convert a NEW node into a CALL node
case CALL:
Node result = tryFoldLiteralConstructor(node);
if (result == node) {
result = tryFoldSimpleFunctionCall(node);
if (result == node) {
result = tryFoldImmediateCallToBoundFunction(node);
}
}
return result;
case RETURN:
return tryReduceReturn(node);
case COMMA:
return trySplitComma(node);
case NAME:
return tryReplaceUndefined(node);
case ARRAYLIT:
return tryMinimizeArrayLiteral(node);
case GETPROP:
return tryMinimizeWindowRefs(node);
case MUL:
case AND:
case OR:
case BITOR:
case BITXOR:
case BITAND:
return tryRotateAssociativeOperator(node);
default:
return node; //Nothing changed
}
}
private static final ImmutableSet<String> BUILTIN_EXTERNS = ImmutableSet.of(
"Object",
"Array",
"Error",
"RegExp",
"Math");
private Node tryMinimizeWindowRefs(Node node) {
// Normalization needs to be done to ensure there's no shadowing. The window prefix is also
// required if the global externs are not on the window.
if (!isASTNormalized() || !areDeclaredGlobalExternsOnWindow()) {
return node;
}
Preconditions.checkArgument(node.isGetProp());
if (node.getFirstChild().isName()) {
Node nameNode = node.getFirstChild();
Node stringNode = node.getLastChild();
// Since normalization has run we know we're referring to the global window.
if ("window".equals(nameNode.getString())
&& BUILTIN_EXTERNS.contains(stringNode.getString())) {
Node newNameNode = IR.name(stringNode.getString());
Node parentNode = node.getParent();
newNameNode.useSourceInfoFrom(stringNode);
parentNode.replaceChild(node, newNameNode);
if (parentNode.isCall()) {
parentNode.putBooleanProp(Node.FREE_CALL, true);
}
reportCodeChange();
return newNameNode;
}
}
return node;
}
private Node tryRotateAssociativeOperator(Node n) {
if (!late) {
return n;
}
// All commutative operators are also associative
Preconditions.checkArgument(NodeUtil.isAssociative(n.getToken()));
Node rhs = n.getLastChild();
if (n.getToken() == rhs.getToken()) {
// Transform a * (b * c) to a * b * c
Node first = n.getFirstChild().detach();
Node second = rhs.getFirstChild().detach();
Node third = rhs.getLastChild().detach();
Node newLhs = new Node(n.getToken(), first, second).useSourceInfoIfMissingFrom(n);
Node newRoot = new Node(rhs.getToken(), newLhs, third).useSourceInfoIfMissingFrom(rhs);
n.getParent().replaceChild(n, newRoot);
reportCodeChange();
return newRoot;
} else if (NodeUtil.isCommutative(n.getToken()) && !NodeUtil.mayHaveSideEffects(n)) {
// Transform a * (b / c) to b / c * a
Node lhs = n.getFirstChild();
while (lhs.getToken() == n.getToken()) {
lhs = lhs.getFirstChild();
}
int precedence = NodeUtil.precedence(n.getToken());
int lhsPrecedence = NodeUtil.precedence(lhs.getToken());
int rhsPrecedence = NodeUtil.precedence(rhs.getToken());
if (rhsPrecedence == precedence && lhsPrecedence != precedence) {
n.removeChild(rhs);
lhs.getParent().replaceChild(lhs, rhs);
n.addChildToBack(lhs);
reportCodeChange();
return n;
}
}
return n;
}
private Node tryFoldSimpleFunctionCall(Node n) {
Preconditions.checkState(n.isCall(), n);
Node callTarget = n.getFirstChild();
if (callTarget == null || !callTarget.isName()) {
return n;
}
String targetName = callTarget.getString();
switch (targetName) {
case "Boolean": {
// Fold Boolean(a) to !!a
// http://www.ecma-international.org/ecma-262/6.0/index.html#sec-boolean-constructor-boolean-value
// and
// http://www.ecma-international.org/ecma-262/6.0/index.html#sec-logical-not-operator-runtime-semantics-evaluation
int paramCount = n.getChildCount() - 1;
// only handle the single known parameter case
if (paramCount == 1) {
Node value = n.getLastChild().detach();
Node replacement;
if (NodeUtil.isBooleanResult(value)) {
// If it is already a boolean do nothing.
replacement = value;
} else {
// Replace it with a "!!value"
replacement = IR.not(IR.not(value).srcref(n));
}
n.getParent().replaceChild(n, replacement);
reportCodeChange();
}
break;
}
case "String": {
// Fold String(a) to '' + (a) on immutable literals,
// which allows further optimizations
//
// We can't do this in the general case, because String(a) has
// slightly different semantics than '' + (a). See
// http://code.google.com/p/closure-compiler/issues/detail?id=759
Node value = callTarget.getNext();
if (value != null && value.getNext() == null &&
NodeUtil.isImmutableValue(value)) {
Node addition = IR.add(
IR.string("").srcref(callTarget),
value.detach());
n.getParent().replaceChild(n, addition);
reportCodeChange();
return addition;
}
break;
}
default:
// nothing.
break;
}
return n;
}
private Node tryFoldImmediateCallToBoundFunction(Node n) {
// Rewriting "(fn.bind(a,b))()" to "fn.call(a,b)" makes it inlinable
Preconditions.checkState(n.isCall());
Node callTarget = n.getFirstChild();
Bind bind = getCodingConvention()
.describeFunctionBind(callTarget, false, false);
if (bind != null) {
// replace the call target
bind.target.detach();
n.replaceChild(callTarget, bind.target);
callTarget = bind.target;
// push the parameters
addParameterAfter(bind.parameters, callTarget);
// add the this value before the parameters if necessary
if (bind.thisValue != null && !NodeUtil.isUndefined(bind.thisValue)) {
// rewrite from "fn(a, b)" to "fn.call(thisValue, a, b)"
Node newCallTarget = IR.getprop(
callTarget.cloneTree(),
IR.string("call").srcref(callTarget));
n.replaceChild(callTarget, newCallTarget);
n.addChildAfter(bind.thisValue.cloneTree(), newCallTarget);
n.putBooleanProp(Node.FREE_CALL, false);
} else {
n.putBooleanProp(Node.FREE_CALL, true);
}
reportCodeChange();
}
return n;
}
private static void addParameterAfter(Node parameterList, Node after) {
if (parameterList != null) {
// push the last parameter to the head of the list first.
addParameterAfter(parameterList.getNext(), after);
after.getParent().addChildAfter(parameterList.cloneTree(), after);
}
}
private Node trySplitComma(Node n) {
if (late) {
return n;
}
Node parent = n.getParent();
Node left = n.getFirstChild();
Node right = n.getLastChild();
if (parent.isExprResult()
&& !parent.getParent().isLabel()) {
// split comma
n.detachChildren();
// Replace the original expression with the left operand.
parent.replaceChild(n, left);
// Add the right expression afterward.
Node newStatement = IR.exprResult(right);
newStatement.useSourceInfoIfMissingFrom(n);
//This modifies outside the subtree, which is not
//desirable in a peephole optimization.
parent.getParent().addChildAfter(newStatement, parent);
reportCodeChange();
return left;
} else {
return n;
}
}
/**
* Use "void 0" in place of "undefined"
*/
private Node tryReplaceUndefined(Node n) {
// TODO(johnlenz): consider doing this as a normalization.
if (isASTNormalized()
&& NodeUtil.isUndefined(n)
&& !NodeUtil.isLValue(n)) {
Node replacement = NodeUtil.newUndefinedNode(n);
n.getParent().replaceChild(n, replacement);
reportCodeChange();
return replacement;
}
return n;
}
/**
* Reduce "return undefined" or "return void 0" to simply "return".
*
* @return The original node, maybe simplified.
*/
private Node tryReduceReturn(Node n) {
Node result = n.getFirstChild();
if (result != null) {
switch (result.getToken()) {
case VOID:
Node operand = result.getFirstChild();
if (!mayHaveSideEffects(operand)) {
n.removeFirstChild();
reportCodeChange();
}
break;
case NAME:
String name = result.getString();
if (name.equals("undefined")) {
n.removeFirstChild();
reportCodeChange();
}
break;
default:
break;
}
}
return n;
}
private static final ImmutableSet<String> STANDARD_OBJECT_CONSTRUCTORS =
// String, Number, and Boolean functions return non-object types, whereas
// new String, new Number, and new Boolean return object types, so don't
// include them here.
ImmutableSet.of(
"Object",
"Array",
"Error"
);
/**
* Fold "new Object()" to "Object()".
*/
private Node tryFoldStandardConstructors(Node n) {
Preconditions.checkState(n.isNew());
if (canFoldStandardConstructors(n)) {
n.setToken(Token.CALL);
n.putBooleanProp(Node.FREE_CALL, true);
reportCodeChange();
}
return n;
}
/**
* @return Whether "new Object()" can be folded to "Object()" on {@code n}.
*/
private boolean canFoldStandardConstructors(Node n) {
// If name normalization has been run then we know that
// new Object() does in fact refer to what we think it is
// and not some custom-defined Object().
if (isASTNormalized() && n.getFirstChild().isName()) {
String className = n.getFirstChild().getString();
if (STANDARD_OBJECT_CONSTRUCTORS.contains(className)) {
return true;
}
if ("RegExp".equals(className)) {
// Fold "new RegExp()" to "RegExp()", but only if the argument is a string.
// See issue 1260.
if (n.getSecondChild() == null || n.getSecondChild().isString()) {
return true;
}
}
}
return false;
}
/**
* Replaces a new Array, Object, or RegExp node with a literal, unless the
* call is to a local constructor function with the same name.
*/
private Node tryFoldLiteralConstructor(Node n) {
Preconditions.checkArgument(n.isCall()
|| n.isNew());
Node constructorNameNode = n.getFirstChild();
Node newLiteralNode = null;
// We require the AST to be normalized to ensure that, say,
// Object() really refers to the built-in Object constructor
// and not a user-defined constructor with the same name.
if (isASTNormalized() && Token.NAME == constructorNameNode.getToken()) {
String className = constructorNameNode.getString();
if ("RegExp".equals(className)) {
// "RegExp("boo", "g")" --> /boo/g
return tryFoldRegularExpressionConstructor(n);
} else {
boolean constructorHasArgs = constructorNameNode.getNext() != null;
if ("Object".equals(className) && !constructorHasArgs) {
// "Object()" --> "{}"
newLiteralNode = IR.objectlit();
} else if ("Array".equals(className)) {
// "Array(arg0, arg1, ...)" --> "[arg0, arg1, ...]"
Node arg0 = constructorNameNode.getNext();
FoldArrayAction action = isSafeToFoldArrayConstructor(arg0);
if (action == FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS ||
action == FoldArrayAction.SAFE_TO_FOLD_WITHOUT_ARGS) {
newLiteralNode = IR.arraylit();
n.removeFirstChild(); // discard the function name
Node elements = n.removeChildren();
if (action == FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS) {
newLiteralNode.addChildrenToFront(elements);
}
}
}
if (newLiteralNode != null) {
n.getParent().replaceChild(n, newLiteralNode);
reportCodeChange();
return newLiteralNode;
}
}
}
return n;
}
private static enum FoldArrayAction {
NOT_SAFE_TO_FOLD, SAFE_TO_FOLD_WITH_ARGS, SAFE_TO_FOLD_WITHOUT_ARGS}
/**
* Checks if it is safe to fold Array() constructor into []. It can be
* obviously done, if the initial constructor has either no arguments or
* at least two. The remaining case may be unsafe since Array(number)
* actually reserves memory for an empty array which contains number elements.
*/
private static FoldArrayAction isSafeToFoldArrayConstructor(Node arg) {
FoldArrayAction action = FoldArrayAction.NOT_SAFE_TO_FOLD;
if (arg == null) {
action = FoldArrayAction.SAFE_TO_FOLD_WITHOUT_ARGS;
} else if (arg.getNext() != null) {
action = FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS;
} else {
switch (arg.getToken()) {
case STRING:
// "Array('a')" --> "['a']"
action = FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS;
break;
case NUMBER:
// "Array(0)" --> "[]"
if (arg.getDouble() == 0) {
action = FoldArrayAction.SAFE_TO_FOLD_WITHOUT_ARGS;
}
break;
case ARRAYLIT:
// "Array([args])" --> "[[args]]"
action = FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS;
break;
default:
}
}
return action;
}
private Node tryFoldRegularExpressionConstructor(Node n) {
Node parent = n.getParent();
Node constructor = n.getFirstChild();
Node pattern = constructor.getNext(); // e.g. ^foobar$
Node flags = null != pattern ? pattern.getNext() : null; // e.g. gi
if (null == pattern || (null != flags && null != flags.getNext())) {
// too few or too many arguments
return n;
}
if (// is pattern folded
pattern.isString()
// make sure empty pattern doesn't fold to //
&& !"".equals(pattern.getString())
&& (null == flags || flags.isString())
// don't escape patterns with Unicode escapes since Safari behaves badly
// (read can't parse or crashes) on regex literals with Unicode escapes
&& (isEcmaScript5OrGreater()
|| !containsUnicodeEscape(pattern.getString()))) {
// Make sure that / is escaped, so that it will fit safely in /brackets/
// and make sure that no LineTerminatorCharacters appear literally inside
// the pattern.
// pattern is a string value with \\ and similar already escaped
pattern = makeForwardSlashBracketSafe(pattern);
Node regexLiteral;
if (null == flags || "".equals(flags.getString())) {
// fold to /foobar/
regexLiteral = IR.regexp(pattern);
} else {
// fold to /foobar/gi
if (!areValidRegexpFlags(flags.getString())) {
report(INVALID_REGULAR_EXPRESSION_FLAGS, flags);
return n;
}
if (!areSafeFlagsToFold(flags.getString())) {
return n;
}
n.removeChild(flags);
regexLiteral = IR.regexp(pattern, flags);
}
parent.replaceChild(n, regexLiteral);
reportCodeChange();
return regexLiteral;
}
return n;
}
private Node reduceSubstractionAssignment(Node n) {
Node right = n.getLastChild();
if (right.isNumber()) {
if (right.getDouble() == 1) {
Node newNode = IR.dec(n.removeFirstChild(), false);
n.getParent().replaceChild(n, newNode);
reportCodeChange();
return newNode;
} else if (right.getDouble() == -1) {
Node newNode = IR.inc(n.removeFirstChild(), false);
n.getParent().replaceChild(n, newNode);
reportCodeChange();
return newNode;
}
}
return n;
}
private Node reduceTrueFalse(Node n) {
if (late) {
switch (n.getParent().getToken()) {
case EQ:
case GT:
case GE:
case LE:
case LT:
case NE:
Node number = IR.number(n.isTrue() ? 1 : 0);
n.getParent().replaceChild(n, number);
reportCodeChange();
return number;
default:
break;
}
Node not = IR.not(IR.number(n.isTrue() ? 0 : 1));
not.useSourceInfoIfMissingFromForTree(n);
n.getParent().replaceChild(n, not);
reportCodeChange();
return not;
}
return n;
}
private Node tryMinimizeArrayLiteral(Node n) {
boolean allStrings = true;
for (Node cur = n.getFirstChild(); cur != null; cur = cur.getNext()) {
if (!cur.isString()) {
allStrings = false;
}
}
if (allStrings) {
return tryMinimizeStringArrayLiteral(n);
} else {
return n;
}
}
private Node tryMinimizeStringArrayLiteral(Node n) {
if (!late) {
return n;
}
int numElements = n.getChildCount();
// We save two bytes per element.
int saving = numElements * 2 - STRING_SPLIT_OVERHEAD;
if (saving <= 0) {
return n;
}
String[] strings = new String[n.getChildCount()];
int idx = 0;
for (Node cur = n.getFirstChild(); cur != null; cur = cur.getNext()) {
strings[idx++] = cur.getString();
}
// These delimiters are chars that appears a lot in the program therefore
// probably have a small Huffman encoding.
String delimiter = pickDelimiter(strings);
if (delimiter != null) {
String template = Joiner.on(delimiter).join(strings);
Node call = IR.call(
IR.getprop(
IR.string(template),
IR.string("split")),
IR.string("" + delimiter));
call.useSourceInfoIfMissingFromForTree(n);
n.getParent().replaceChild(n, call);
reportCodeChange();
return call;
}
return n;
}
/**
* Find a delimiter that does not occur in the given strings
* @param strings The strings that must be separated.
* @return a delimiter string or null
*/
private static String pickDelimiter(String[] strings) {
boolean allLength1 = true;
for (String s : strings) {
if (s.length() != 1) {
allLength1 = false;
break;
}
}
if (allLength1) {
return "";
}
String[] delimiters = new String[]{" ", ";", ",", "{", "}", null};
int i = 0;
NEXT_DELIMITER: for (; delimiters[i] != null; i++) {
for (String cur : strings) {
if (cur.contains(delimiters[i])) {
continue NEXT_DELIMITER;
}
}
break;
}
return delimiters[i];
}
private static final Pattern REGEXP_FLAGS_RE = Pattern.compile("^[gmi]*$");
/**
* are the given flags valid regular expression flags?
* JavaScript recognizes several suffix flags for regular expressions,
* 'g' - global replace, 'i' - case insensitive, 'm' - multi-line.
* They are case insensitive, and JavaScript does not recognize the extended
* syntax mode, single-line mode, or expression replacement mode from Perl 5.
*/
private static boolean areValidRegexpFlags(String flags) {
return REGEXP_FLAGS_RE.matcher(flags).matches();
}
/**
* are the given flags safe to fold?
* We don't fold the regular expression if global ('g') flag is on,
* because in this case it isn't really a constant: its 'lastIndex'
* property contains the state of last execution, so replacing
* 'new RegExp('foobar','g')' with '/foobar/g' may change the behavior of
* the program if the RegExp is used inside a loop, for example.
* <p>
* ECMAScript 5 explicitly disallows pooling of regular expression literals so
* in ECMAScript 5, {@code /foo/g} and {@code new RegExp('foo', 'g')} are
* equivalent.
* From section 7.8.5:
* "Then each time the literal is evaluated, a new object is created as if by
* the expression new RegExp(Pattern, Flags) where RegExp is the standard
* built-in constructor with that name."
*/
private boolean areSafeFlagsToFold(String flags) {
return isEcmaScript5OrGreater() || flags.indexOf('g') < 0;
}
/**
* returns a string node that can safely be rendered inside /brackets/.
*/
private static Node makeForwardSlashBracketSafe(Node n) {
String s = n.getString();
// sb contains everything in s[0:pos]
StringBuilder sb = null;
int pos = 0;
boolean isEscaped = false, inCharset = false;
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
switch (ch) {
case '\\':
isEscaped = !isEscaped;
continue;
case '/':
// Escape a literal forward slash if it is not already escaped and is
// not inside a character set.
// new RegExp('/') -> /\//
// but the following do not need extra escaping
// new RegExp('\\/') -> /\//
// new RegExp('[/]') -> /[/]/
if (!isEscaped && !inCharset) {
if (null == sb) { sb = new StringBuilder(s.length() + 16); }
sb.append(s, pos, i).append('\\');
pos = i;
}
break;
case '[':
if (!isEscaped) {
inCharset = true;
}
break;
case ']':
if (!isEscaped) {
inCharset = false;
}
break;
case '\r': case '\n': case '\u2028': case '\u2029':
// LineTerminators cannot appear raw inside a regular
// expression literal.
// They can't appear legally in a quoted string, but when
// the quoted string from
// new RegExp('\n')
// reaches here, the quoting has been removed.
// Requote just these code-points.
if (null == sb) { sb = new StringBuilder(s.length() + 16); }
if (isEscaped) {
sb.append(s, pos, i - 1);
} else {
sb.append(s, pos, i);
}
switch (ch) {
case '\r': sb.append("\\r"); break;
case '\n': sb.append("\\n"); break;
case '\u2028': sb.append("\\u2028"); break;
case '\u2029': sb.append("\\u2029"); break;
}
pos = i + 1;
break;
}
isEscaped = false;
}
if (null == sb) { return n.cloneTree(); }
sb.append(s, pos, s.length());
return IR.string(sb.toString()).srcref(n);
}
/**
* true if the JavaScript string would contain a Unicode escape when written
* out as the body of a regular expression literal.
*/
static boolean containsUnicodeEscape(String s) {
String esc = REGEXP_ESCAPER.regexpEscape(s);
for (int i = -1; (i = esc.indexOf("\\u", i + 1)) >= 0;) {
int nSlashes = 0;
while (i - nSlashes > 0 && '\\' == esc.charAt(i - nSlashes - 1)) {
++nSlashes;
}
// if there are an even number of slashes before the \ u then it is a
// Unicode literal.
if (0 == (nSlashes & 1)) { return true; }
}
return false;
}
}
|
Fix a link in PeepholeSubstituteAlternateSyntax
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=138127324
|
src/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java
|
Fix a link in PeepholeSubstituteAlternateSyntax
|
<ide><path>rc/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java
<ide> //
<ide> // We can't do this in the general case, because String(a) has
<ide> // slightly different semantics than '' + (a). See
<del> // http://code.google.com/p/closure-compiler/issues/detail?id=759
<add> // https://blickly.github.io/closure-compiler-issues/#759
<ide> Node value = callTarget.getNext();
<ide> if (value != null && value.getNext() == null &&
<ide> NodeUtil.isImmutableValue(value)) {
<ide> // sb contains everything in s[0:pos]
<ide> StringBuilder sb = null;
<ide> int pos = 0;
<del> boolean isEscaped = false, inCharset = false;
<add> boolean isEscaped = false;
<add> boolean inCharset = false;
<ide> for (int i = 0; i < s.length(); ++i) {
<ide> char ch = s.charAt(i);
<ide> switch (ch) {
|
|
Java
|
agpl-3.0
|
ba7cfa6596e7f0d5641b54bff68b213dc98c0fc7
| 0 |
thunderbit/thunderbit,thunderbit/thunderbit,thunderbit/thunderbit
|
package modules.storage;
import akka.dispatch.Futures;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.event.ProgressEventType;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.*;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
import com.google.inject.Inject;
import play.Configuration;
import play.Logger;
import play.libs.F;
import play.mvc.Result;
import scala.concurrent.Promise;
import java.net.URL;
import java.nio.file.Path;
import static play.mvc.Results.internalServerError;
import static play.mvc.Results.redirect;
public class AmazonS3Storage implements Storage {
private final AWSCredentials credentials;
private final String bucketName;
@Inject
public AmazonS3Storage (Configuration configuration) {
bucketName = configuration.getString("storage.s3.bucket");
String accessKey = configuration.getString("storage.s3.accesskey");
String secretKey = configuration.getString("storage.s3.secretkey");
credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3 amazonS3 = new AmazonS3Client(credentials);
try {
if(!(amazonS3.doesBucketExist(bucketName))) {
amazonS3.createBucket(new CreateBucketRequest(bucketName));
}
String bucketLocation = amazonS3.getBucketLocation(new GetBucketLocationRequest(bucketName));
Logger.info("Amazon S3 bucket created at " + bucketLocation);
} catch (AmazonServiceException ase) {
Logger.error("Caught an AmazonServiceException, which " +
"means your request made it " +
"to Amazon S3, but was rejected with an error response " +
"for some reason." +
" Error Message: " + ase.getMessage() +
" HTTP Status Code: " + ase.getStatusCode() +
" AWS Error Code: " + ase.getErrorCode() +
" Error Type: " + ase.getErrorType() +
" Request ID: " + ase.getRequestId()
);
} catch (AmazonClientException ace) {
Logger.error("Caught an AmazonClientException, which " +
"means the client encountered " +
"an internal error while trying to " +
"communicate with S3, " +
"such as not being able to access the network." +
" Error Message: " + ace.getMessage()
);
}
}
@Override
public F.Promise<Void> store(Path path, String key) {
Promise<Void> promise = Futures.promise();
TransferManager transferManager = new TransferManager(credentials);
Upload upload = transferManager.upload(bucketName, key, path.toFile());
upload.addProgressListener((ProgressListener) progressEvent -> {
if (progressEvent.getEventType().isTransferEvent()) {
if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_COMPLETED_EVENT)) {
transferManager.shutdownNow();
promise.success(null);
} else if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_FAILED_EVENT)) {
transferManager.shutdownNow();
promise.failure(new Exception("Upload failed"));
}
}
});
return F.Promise.wrap(promise.future());
}
@Override
public F.Promise<Result> getDownload(String key, String name) {
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key);
ResponseHeaderOverrides responseHeaders = new ResponseHeaderOverrides();
responseHeaders.setContentDisposition("attachment; filename="+name);
generatePresignedUrlRequest.setResponseHeaders(responseHeaders);
AmazonS3 amazonS3 = new AmazonS3Client(credentials);
try {
URL url = amazonS3.generatePresignedUrl(generatePresignedUrlRequest);
return F.Promise.pure(redirect(url.toString()));
} catch (AmazonClientException ace) {
Logger.error("Caught an AmazonClientException, which " +
"means the client encountered " +
"an internal error while trying to " +
"communicate with S3, " +
"such as not being able to access the network." +
" Error Message: " + ace.getMessage()
);
return F.Promise.pure(internalServerError("Download failed"));
}
}
@Override
public F.Promise<Void> delete(String key) {
Promise<Void> promise = Futures.promise();
AmazonS3 amazonS3 = new AmazonS3Client(credentials);
DeleteObjectRequest request = new DeleteObjectRequest(bucketName, key);
request.withGeneralProgressListener(progressEvent -> {
if (progressEvent.getEventType().isTransferEvent()) {
if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_COMPLETED_EVENT)) {
promise.success(null);
} else if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_FAILED_EVENT)) {
promise.failure(new Exception("Delete failed"));
}
}
});
amazonS3.deleteObject(request);
return F.Promise.wrap(promise.future());
}
}
|
app/modules/storage/AmazonS3Storage.java
|
package modules.storage;
import akka.dispatch.Futures;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.event.ProgressEventType;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CreateBucketRequest;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.GetBucketLocationRequest;
import com.amazonaws.services.s3.transfer.Download;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
import com.google.inject.Inject;
import play.Configuration;
import play.Logger;
import play.libs.F;
import play.mvc.Result;
import scala.concurrent.Promise;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static play.mvc.Results.ok;
public class AmazonS3Storage implements Storage {
private final AWSCredentials credentials;
private final String bucketName;
@Inject
public AmazonS3Storage (Configuration configuration) {
bucketName = configuration.getString("storage.s3.bucket");
String accessKey = configuration.getString("storage.s3.accesskey");
String secretKey = configuration.getString("storage.s3.secretkey");
credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3 amazonS3 = new AmazonS3Client(credentials);
try {
if(!(amazonS3.doesBucketExist(bucketName))) {
amazonS3.createBucket(new CreateBucketRequest(bucketName));
}
String bucketLocation = amazonS3.getBucketLocation(new GetBucketLocationRequest(bucketName));
Logger.info("Amazon S3 bucket created at " + bucketLocation);
} catch (AmazonServiceException ase) {
Logger.error("Caught an AmazonServiceException, which " +
"means your request made it " +
"to Amazon S3, but was rejected with an error response " +
"for some reason." +
" Error Message: " + ase.getMessage() +
" HTTP Status Code: " + ase.getStatusCode() +
" AWS Error Code: " + ase.getErrorCode() +
" Error Type: " + ase.getErrorType() +
" Request ID: " + ase.getRequestId()
);
} catch (AmazonClientException ace) {
Logger.error("Caught an AmazonClientException, which " +
"means the client encountered " +
"an internal error while trying to " +
"communicate with S3, " +
"such as not being able to access the network." +
" Error Message: " + ace.getMessage()
);
}
}
@Override
public F.Promise<Void> store(Path path, String key) {
Promise<Void> promise = Futures.promise();
TransferManager transferManager = new TransferManager(credentials);
Upload upload = transferManager.upload(bucketName, key, path.toFile());
upload.addProgressListener((ProgressListener) progressEvent -> {
if (progressEvent.getEventType().isTransferEvent()) {
if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_COMPLETED_EVENT)) {
transferManager.shutdownNow();
promise.success(null);
} else if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_FAILED_EVENT)) {
transferManager.shutdownNow();
promise.failure(new Exception("Upload failed"));
}
}
});
return F.Promise.wrap(promise.future());
}
@Override
public F.Promise<Result> getDownload(String key, String name) {
Promise<Result> promise = Futures.promise();
TransferManager transferManager = new TransferManager(credentials);
try {
Path path = Files.createTempFile(key, "");
Download download = transferManager.download(bucketName, key, path.toFile());
download.addProgressListener((ProgressListener) progressEvent -> {
if (progressEvent.getEventType().isTransferEvent()) {
if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_COMPLETED_EVENT)) {
transferManager.shutdownNow();
promise.success(ok (path.toFile()));
} else if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_FAILED_EVENT)) {
transferManager.shutdownNow();
promise.failure(new Exception("Download failed"));
}
}
});
} catch (IOException e) {
promise.failure(e);
}
return F.Promise.wrap(promise.future());
}
@Override
public F.Promise<Void> delete(String key) {
Promise<Void> promise = Futures.promise();
AmazonS3 amazonS3 = new AmazonS3Client(credentials);
DeleteObjectRequest request = new DeleteObjectRequest(bucketName, key);
request.withGeneralProgressListener(progressEvent -> {
if (progressEvent.getEventType().isTransferEvent()) {
if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_COMPLETED_EVENT)) {
promise.success(null);
} else if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_FAILED_EVENT)) {
promise.failure(new Exception("Delete failed"));
}
}
});
amazonS3.deleteObject(request);
return F.Promise.wrap(promise.future());
}
}
|
Added direct file download from S3
Now, for S3 stored files, the app serves a Redirect to a pre-signed
download link from Amazon S3.
|
app/modules/storage/AmazonS3Storage.java
|
Added direct file download from S3
|
<ide><path>pp/modules/storage/AmazonS3Storage.java
<ide> import com.amazonaws.event.ProgressListener;
<ide> import com.amazonaws.services.s3.AmazonS3;
<ide> import com.amazonaws.services.s3.AmazonS3Client;
<del>import com.amazonaws.services.s3.model.CreateBucketRequest;
<del>import com.amazonaws.services.s3.model.DeleteObjectRequest;
<del>import com.amazonaws.services.s3.model.GetBucketLocationRequest;
<del>import com.amazonaws.services.s3.transfer.Download;
<add>import com.amazonaws.services.s3.model.*;
<ide> import com.amazonaws.services.s3.transfer.TransferManager;
<ide> import com.amazonaws.services.s3.transfer.Upload;
<ide> import com.google.inject.Inject;
<ide> import play.mvc.Result;
<ide> import scala.concurrent.Promise;
<ide>
<del>import java.io.IOException;
<del>import java.nio.file.Files;
<add>import java.net.URL;
<ide> import java.nio.file.Path;
<ide>
<del>import static play.mvc.Results.ok;
<add>import static play.mvc.Results.internalServerError;
<add>import static play.mvc.Results.redirect;
<ide>
<ide> public class AmazonS3Storage implements Storage {
<ide> private final AWSCredentials credentials;
<ide>
<ide> @Override
<ide> public F.Promise<Result> getDownload(String key, String name) {
<del> Promise<Result> promise = Futures.promise();
<add> GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key);
<add> ResponseHeaderOverrides responseHeaders = new ResponseHeaderOverrides();
<add> responseHeaders.setContentDisposition("attachment; filename="+name);
<add> generatePresignedUrlRequest.setResponseHeaders(responseHeaders);
<ide>
<del> TransferManager transferManager = new TransferManager(credentials);
<add> AmazonS3 amazonS3 = new AmazonS3Client(credentials);
<ide>
<ide> try {
<del> Path path = Files.createTempFile(key, "");
<add> URL url = amazonS3.generatePresignedUrl(generatePresignedUrlRequest);
<ide>
<del> Download download = transferManager.download(bucketName, key, path.toFile());
<del>
<del> download.addProgressListener((ProgressListener) progressEvent -> {
<del> if (progressEvent.getEventType().isTransferEvent()) {
<del> if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_COMPLETED_EVENT)) {
<del> transferManager.shutdownNow();
<del> promise.success(ok (path.toFile()));
<del> } else if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_FAILED_EVENT)) {
<del> transferManager.shutdownNow();
<del> promise.failure(new Exception("Download failed"));
<del> }
<del> }
<del> });
<del> } catch (IOException e) {
<del> promise.failure(e);
<add> return F.Promise.pure(redirect(url.toString()));
<add> } catch (AmazonClientException ace) {
<add> Logger.error("Caught an AmazonClientException, which " +
<add> "means the client encountered " +
<add> "an internal error while trying to " +
<add> "communicate with S3, " +
<add> "such as not being able to access the network." +
<add> " Error Message: " + ace.getMessage()
<add> );
<add> return F.Promise.pure(internalServerError("Download failed"));
<ide> }
<del>
<del> return F.Promise.wrap(promise.future());
<ide> }
<ide>
<ide> @Override
|
|
JavaScript
|
mit
|
4f52afbdd7ac9eb824d7e506dcc4704b08b2f1f7
| 0 |
DustinH/CodeMirror,xeronith/CodeMirror,CartoDB/CodeMirror,dbarnett/CodeMirror,davidpham87/CodeMirror,kerabromsmu/CodeMirror,Icenium/CodeMirror,dudb/CodeMirror,jessegrosjean/CodeMirror,notepadqq/CodeMirror,pjkui/CodeMirror,d0liver/CodeMirror,jayaprabhakar/CodeMirror,alur/CodeMirror,dbarnett/CodeMirror,sourcelair/CodeMirror,bocharsky-bw/CodeMirror,karevn/CodeMirror,Ermlab/CodeMirror,buchslava/CodeMirror,kuangyeheng/CodeMirror,supriyantomaftuh/CodeMirror,Allenice/CodeMirror,vincentwoo/CodeMirror,webida/CodeMirror,anthonygego/CodeMirror,namin/CodeMirror,antimatter15/CodeMirror,amshali/CodeMirror,philuchansky/CodeMirror,kolya-ay/CodeMirror,ssxxue/CodeMirror,joshterrell805-historic/CodeMirror,pjkui/CodeMirror,sekcheong/CodeMirror,Navaneethsen/CodeMirror,Icenium/CodeMirror,rrandom/CodeMirror,schanzer/CodeMirror,hackmdio/CodeMirror,wingify/CodeMirror,MarcelGerber/CodeMirror,fmoliveira/CodeMirror,kerabromsmu/CodeMirror,NeZaMy/CodeMirror2,EasonYi/CodeMirror,ficristo/CodeMirror,hackmdio/CodeMirror,flyskyko/CodeMirror,SidPresse/CodeMirror,supriyantomaftuh/CodeMirror,GerHobbelt/CodeMirror2,d0liver/CodeMirror,AlanWasTaken/codemirror,djadmin/CodeMirror,GerHobbelt/CodeMirror2,kangkot/CodeMirror,davidpham87/CodeMirror,qweasd1/CodeMirror,shiren/CodeMirror,kevinushey/CodeMirror,Ermlab/CodeMirror,notepadqq/CodeMirror,jayaprabhakar/CodeMirror,kangkot/CodeMirror,cben/CodeMirror,happibum/CodeMirror-main,amsul/CodeMirror,agendor/CodeMirror,ksanaforge/CodeMirror,ashmind/CodeMirror,ejgallego/CodeMirror,grzegorzmazur/CodeMirror,fmoliveira/CodeMirror,Carreau/CodeMirror,cben/CodeMirror,antimatter15/CodeMirror,nawroth/CodeMirror,sanyaade-iot/CodeMirror,sekcheong/CodeMirror,elisee/CodeMirror,shiren/CodeMirror,agendor/CodeMirror,mtaran-google/CodeMirror,schanzer/CodeMirror,TDaglis/CodeMirror,gkoberger/CodeMirror,isdampe/CodeMirror,KamranMackey/CodeMirror,codio/CodeMirror,kk9599/CodeMirror,webida/CodeMirror,jkaplon/CodeMirror,rasata/CodeMirror,qiankun007/CodeMirror,jessegrosjean/CodeMirror,cintiamh/CodeMirror,fivetran/CodeMirror,nawroth/CodeMirror,dbarnett/CodeMirror,joshterrell805-historic/CodeMirror,sekcheong/CodeMirror,hackmdio/CodeMirror,r7kamura/CodeMirror,sanyaade-iot/CodeMirror,supriyantomaftuh/CodeMirror,nawroth/CodeMirror,kangkot/CodeMirror,increpare/CodeMirror,r7kamura/CodeMirror,melpon/CodeMirror,MarcelGerber/CodeMirror,Allenice/CodeMirror,TDaglis/CodeMirror,antimatter15/CodeMirror,skylarkcob/CodeMirror,buchslava/CodeMirror,cintiamh/CodeMirror,matthewbauer/CodeMirror,loopspace/CodeMirror,skylarkcob/CodeMirror,Carreau/CodeMirror,grzegorzmazur/CodeMirror,crazy4chrissi/CodeMirror,djadmin/CodeMirror,Aliccer/CodeMirror,trumanliu/CodeMirror,apatawari/CodeMirror,pabloferz/CodeMirror,elisee/CodeMirror,karthikeyansam/CodeMirror,qiankun007/CodeMirror,thomasjm/CodeMirror,karevn/CodeMirror,sgoo/CodeMirror,jhnesk/CodeMirror,namin/CodeMirror,rustemferreira/CodeMirror,codio/CodeMirror,kevinushey/CodeMirror,dudb/CodeMirror,symbla/CodeMirror,bgrins/CodeMirror,buchslava/CodeMirror,melpon/CodeMirror,ashmind/CodeMirror,Allenice/CodeMirror,pinbe/CodeMirror,notepadqq/CodeMirror,trumanliu/CodeMirror,gkoberger/CodeMirror,dperetti/CodeMirror,bgrins/CodeMirror,matthewbauer/CodeMirror,EasonYi/CodeMirror,nightwing/CodeMirror,alur/CodeMirror,philuchansky/CodeMirror,jhnesk/CodeMirror,rasata/CodeMirror,fpco/codemirror,sanyaade-iot/CodeMirror,karevn/CodeMirror,schanzer/CodeMirror,isdampe/CodeMirror,loopspace/CodeMirror,adobe/CodeMirror2,qweasd1/CodeMirror,thomasjm/CodeMirror,NumbersInternational/CodeMirror,vincentwoo/CodeMirror,rustemferreira/CodeMirror,isdampe/CodeMirror,jpolitz/CodeMirror,kolya-ay/CodeMirror,camellhf/CodeMirror,rrandom/CodeMirror,ksanaforge/CodeMirror,ThebingServices/CodeMirror,melpon/CodeMirror,tpphu/CodeMirror,bocharsky-bw/CodeMirror,symbla/CodeMirror,xeronith/CodeMirror,philuchansky/CodeMirror,ssxxue/CodeMirror,mtaran-google/CodeMirror,NeZaMy/CodeMirror2,INTELOGIE/CodeMirror,ssxxue/CodeMirror,NumbersInternational/CodeMirror,ZombieHippie/CodeMirror,wingify/CodeMirror,belph/CodeMirror,camellhf/CodeMirror,apatawari/CodeMirror,webida/CodeMirror,karthikeyansam/CodeMirror,wingify/CodeMirror,jochenberger/CodeMirror,hccampos/CodeMirror,nightwing/CodeMirror,abdelouahabb/CodeMirror,mightyguava/CodeMirror,hccampos/CodeMirror,qweasd1/CodeMirror,jessegrosjean/CodeMirror,bgrins/CodeMirror,gkoberger/CodeMirror,amshali/CodeMirror,agendor/CodeMirror,sourcelair/CodeMirror,michaelerobertsjr/CodeMirror,Aliccer/CodeMirror,pabloferz/CodeMirror,Dominator008/CodeMirror,namin/CodeMirror,axter/CodeMirror,KamranMackey/CodeMirror,rrandom/CodeMirror,Icenium/CodeMirror,camellhf/CodeMirror,SidPresse/CodeMirror,ejgallego/CodeMirror,tpphu/CodeMirror,ThebingServices/CodeMirror,davidpham87/CodeMirror,angelozerr/CodeMirror,ZombieHippie/CodeMirror,INTELOGIE/CodeMirror,kk9599/CodeMirror,AlanWasTaken/codemirror,NeZaMy/CodeMirror2,mizchi/CodeMirror,djadmin/CodeMirror,dperetti/CodeMirror,ZombieHippie/CodeMirror,ejgallego/CodeMirror,ThebingServices/CodeMirror,d0liver/CodeMirror,trumanliu/CodeMirror,increpare/CodeMirror,jpolitz/CodeMirror,crazy4chrissi/CodeMirror,vanloswang/CodeMirror,wbinnssmith/CodeMirror,systay/CodeMirror,CartoDB/CodeMirror,DustinH/CodeMirror,jpolitz/CodeMirror,rasata/CodeMirror,pjkui/CodeMirror,sourcelair/CodeMirror,kk9599/CodeMirror,cintiamh/CodeMirror,manderson23/CodeMirror,jochenberger/CodeMirror,loopspace/CodeMirror,systay/CodeMirror,Navaneethsen/CodeMirror,sgoo/CodeMirror,fmoliveira/CodeMirror,jkaplon/CodeMirror,fpco/codemirror,flyskyko/CodeMirror,dperetti/CodeMirror,rustemferreira/CodeMirror,bluesh55/CodeMirror,InternetGuru/CodeMirror,Aliccer/CodeMirror,vanloswang/CodeMirror,happibum/CodeMirror-main,ficristo/CodeMirror,alur/CodeMirror,mihailik/CodeMirror,mightyguava/CodeMirror,michaelerobertsjr/CodeMirror,adobe/CodeMirror2,ashmind/CodeMirror,SidPresse/CodeMirror,shiren/CodeMirror,bocharsky-bw/CodeMirror,mizchi/CodeMirror,mightyguava/CodeMirror,morrisonwudi/CodeMirror,manderson23/CodeMirror,bfrohs/CodeMirror,thomasjm/CodeMirror,systay/CodeMirror,happibum/CodeMirror-main,matthewbauer/CodeMirror,TechnicalPursuit/CodeMirror,NumbersInternational/CodeMirror,amsul/CodeMirror,pinbe/CodeMirror,hccampos/CodeMirror,anthonygego/CodeMirror,r7kamura/CodeMirror,crazy4chrissi/CodeMirror,bluesh55/CodeMirror,tpphu/CodeMirror,belph/CodeMirror,morrisonwudi/CodeMirror,KamranMackey/CodeMirror,webida/CodeMirror,manderson23/CodeMirror,kerabromsmu/CodeMirror,nightwing/CodeMirror,mtaran-google/CodeMirror,Dominator008/CodeMirror,EasonYi/CodeMirror,Jisuanke/CodeMirror,bfrohs/CodeMirror,bfrohs/CodeMirror,mizchi/CodeMirror,fivetran/CodeMirror,wbinnssmith/CodeMirror,bluesh55/CodeMirror,mihailik/CodeMirror,axter/CodeMirror,jkaplon/CodeMirror,morrisonwudi/CodeMirror,codio/CodeMirror,abdelouahabb/CodeMirror,vincentwoo/CodeMirror,axter/CodeMirror,pabloferz/CodeMirror,TDaglis/CodeMirror,Jisuanke/CodeMirror,karthikeyansam/CodeMirror,DustinH/CodeMirror,qiankun007/CodeMirror,grzegorzmazur/CodeMirror,Dominator008/CodeMirror,belph/CodeMirror,jayaprabhakar/CodeMirror,dudb/CodeMirror,anthonygego/CodeMirror,InternetGuru/CodeMirror,michaelerobertsjr/CodeMirror,kuangyeheng/CodeMirror,pinbe/CodeMirror,TechnicalPursuit/CodeMirror,mihailik/CodeMirror,ficristo/CodeMirror,skylarkcob/CodeMirror,elisee/CodeMirror,adobe/CodeMirror2,apatawari/CodeMirror,angelozerr/CodeMirror,AlanWasTaken/codemirror,ksanaforge/CodeMirror,kuangyeheng/CodeMirror,flyskyko/CodeMirror,Jisuanke/CodeMirror,xeronith/CodeMirror,TechnicalPursuit/CodeMirror,amshali/CodeMirror,InternetGuru/CodeMirror,INTELOGIE/CodeMirror,MarcelGerber/CodeMirror,vanloswang/CodeMirror,abdelouahabb/CodeMirror,Navaneethsen/CodeMirror,increpare/CodeMirror,symbla/CodeMirror
|
CodeMirror.defineMode('rst-base', function (config) {
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function format(string) {
var args = Array.prototype.slice.call(arguments, 1);
return string.replace(/{(\d+)}/g, function (match, n) {
return typeof args[n] != 'undefined' ? args[n] : match;
});
}
function AssertException(message) {
this.message = message;
}
AssertException.prototype.toString = function () {
return 'AssertException: ' + this.message;
};
function assert(expression, message) {
if (!expression) throw new AssertException(message);
return expression;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
var mode_python = CodeMirror.getMode(config, 'python');
var mode_stex = CodeMirror.getMode(config, 'stex');
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
var SEPA = "\\s+";
var TAIL = "(?:\\s*|\\W|$)",
rx_TAIL = new RegExp(format('^{0}', TAIL));
var NAME =
"(?:[^\\W\\d_](?:[\\w!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)",
rx_NAME = new RegExp(format('^{0}', NAME));
var NAME_WWS =
"(?:[^\\W\\d_](?:[\\w\\s!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)";
var REF_NAME = format('(?:{0}|`{1}`)', NAME, NAME_WWS);
var TEXT1 = "(?:[^\\s\\|](?:[^\\|]*[^\\s\\|])?)";
var TEXT2 = "(?:[^\\`]+)",
rx_TEXT2 = new RegExp(format('^{0}', TEXT2));
var rx_section = new RegExp(
"^([!'#$%&\"()*+,-./:;<=>?@\\[\\\\\\]^_`{|}~])\\1{3,}\\s*$");
var rx_explicit = new RegExp(
format('^\\.\\.{0}', SEPA));
var rx_link = new RegExp(
format('^_{0}:{1}|^__:{1}', REF_NAME, TAIL));
var rx_directive = new RegExp(
format('^{0}::{1}', REF_NAME, TAIL));
var rx_substitution = new RegExp(
format('^\\|{0}\\|{1}{2}::{3}', TEXT1, SEPA, REF_NAME, TAIL));
var rx_footnote = new RegExp(
format('^\\[(?:\\d+|#{0}?|\\*)]{1}', REF_NAME, TAIL));
var rx_citation = new RegExp(
format('^\\[{0}\\]{1}', REF_NAME, TAIL));
var rx_substitution_ref = new RegExp(
format('^\\|{0}\\|', TEXT1));
var rx_footnote_ref = new RegExp(
format('^\\[(?:\\d+|#{0}?|\\*)]_', REF_NAME));
var rx_citation_ref = new RegExp(
format('^\\[{0}\\]_', REF_NAME));
var rx_link_ref1 = new RegExp(
format('^{0}__?', REF_NAME));
var rx_link_ref2 = new RegExp(
format('^`{0}`_', TEXT2));
var rx_role_pre = new RegExp(
format('^:{0}:`{1}`{2}', NAME, TEXT2, TAIL));
var rx_role_suf = new RegExp(
format('^`{1}`:{0}:{2}', NAME, TEXT2, TAIL));
var rx_role = new RegExp(
format('^:{0}:{1}', NAME, TAIL));
var rx_directive_name = new RegExp(format('^{0}', REF_NAME));
var rx_directive_tail = new RegExp(format('^::{0}', TAIL));
var rx_substitution_text = new RegExp(format('^\\|{0}\\|', TEXT1));
var rx_substitution_sepa = new RegExp(format('^{0}', SEPA));
var rx_substitution_name = new RegExp(format('^{0}', REF_NAME));
var rx_substitution_tail = new RegExp(format('^::{0}', TAIL));
var rx_link_head = new RegExp("^_");
var rx_link_name = new RegExp(format('^{0}|_', REF_NAME));
var rx_link_tail = new RegExp(format('^:{0}', TAIL));
var rx_verbatim = new RegExp('^::\\s*$');
var rx_examples = new RegExp('^\\s+(?:>>>|In \\[\\d+\\]:)\\s');
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function to_normal(stream, state) {
var token = null;
if (stream.sol() && stream.match(rx_examples, false)) {
change(state, to_mode, {
mode: mode_python, local: mode_python.startState()
});
} else if (stream.sol() && stream.match(rx_explicit)) {
change(state, to_explicit);
token = 'meta';
} else if (stream.sol() && stream.match(rx_section)) {
change(state, to_normal);
token = 'header';
} else if (phase(state) == rx_role_pre ||
stream.match(rx_role_pre, false)) {
switch (stage(state)) {
case 0:
change(state, to_normal, context(rx_role_pre, 1));
assert(stream.match(/^:/));
token = 'meta';
break;
case 1:
change(state, to_normal, context(rx_role_pre, 2));
assert(stream.match(rx_NAME));
token = 'keyword';
if (stream.current().match(/^(?:math|latex)/)) {
state.tmp = {
mode: mode_stex, local: mode_stex.startState()
};
}
break;
case 2:
change(state, to_normal, context(rx_role_pre, 3));
assert(stream.match(/^:`/));
token = 'meta';
break;
case 3:
if (state.tmp) {
if (stream.peek() == '`') {
change(state, to_normal, context(rx_role_pre, 4));
state.tmp = undefined;
break;
}
token = state.tmp.mode.token(stream, state.tmp.local);
break;
}
change(state, to_normal, context(rx_role_pre, 4));
assert(stream.match(rx_TEXT2));
token = 'string';
break;
case 4:
change(state, to_normal, context(rx_role_pre, 5));
assert(stream.match(/^`/));
token = 'meta';
break;
case 5:
change(state, to_normal, context(rx_role_pre, 6));
assert(stream.match(rx_TAIL));
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (phase(state) == rx_role_suf ||
stream.match(rx_role_suf, false)) {
switch (stage(state)) {
case 0:
change(state, to_normal, context(rx_role_suf, 1));
assert(stream.match(/^`/));
token = 'meta';
break;
case 1:
change(state, to_normal, context(rx_role_suf, 2));
assert(stream.match(rx_TEXT2));
token = 'string';
break;
case 2:
change(state, to_normal, context(rx_role_suf, 3));
assert(stream.match(/^`:/));
token = 'meta';
break;
case 3:
change(state, to_normal, context(rx_role_suf, 4));
assert(stream.match(rx_NAME));
token = 'keyword';
break;
case 4:
change(state, to_normal, context(rx_role_suf, 5));
assert(stream.match(/^:/));
token = 'meta';
break;
case 5:
change(state, to_normal, context(rx_role_suf, 6));
assert(stream.match(rx_TAIL));
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (phase(state) == rx_role || stream.match(rx_role, false)) {
switch (stage(state)) {
case 0:
change(state, to_normal, context(rx_role, 1));
assert(stream.match(/^:/));
token = 'meta';
break;
case 1:
change(state, to_normal, context(rx_role, 2));
assert(stream.match(rx_NAME));
token = 'keyword';
break;
case 2:
change(state, to_normal, context(rx_role, 3));
assert(stream.match(/^:/));
token = 'meta';
break;
case 3:
change(state, to_normal, context(rx_role, 4));
assert(stream.match(rx_TAIL));
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (phase(state) == rx_substitution_ref ||
stream.match(rx_substitution_ref, false)) {
switch (stage(state)) {
case 0:
change(state, to_normal, context(rx_substitution_ref, 1));
assert(stream.match(rx_substitution_text));
token = 'variable-2';
break;
case 1:
change(state, to_normal, context(rx_substitution_ref, 2));
if (stream.match(/^_?_?/)) token = 'link';
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (stream.match(rx_footnote_ref)) {
change(state, to_normal);
token = 'quote';
} else if (stream.match(rx_citation_ref)) {
change(state, to_normal);
token = 'quote';
} else if (stream.match(rx_link_ref1)) {
change(state, to_normal);
if (!stream.peek() || stream.peek().match(/^\W$/)) {
token = 'link';
}
} else if (phase(state) == rx_link_ref2 ||
stream.match(rx_link_ref2, false)) {
switch (stage(state)) {
case 0:
if (!stream.peek() || stream.peek().match(/^\W$/)) {
change(state, to_normal, context(rx_link_ref2, 1));
} else {
stream.match(rx_link_ref2);
}
break;
case 1:
change(state, to_normal, context(rx_link_ref2, 2));
assert(stream.match(/^`/));
token = 'link';
break;
case 2:
change(state, to_normal, context(rx_link_ref2, 3));
assert(stream.match(rx_TEXT2));
break;
case 3:
change(state, to_normal, context(rx_link_ref2, 4));
assert(stream.match(/^`_/));
token = 'link';
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (stream.match(rx_verbatim)) {
change(state, to_verbatim);
}
else {
if (stream.next()) change(state, to_normal);
}
return token;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function to_explicit(stream, state) {
var token = null;
if (phase(state) == rx_substitution ||
stream.match(rx_substitution, false)) {
switch (stage(state)) {
case 0:
change(state, to_explicit, context(rx_substitution, 1));
assert(stream.match(rx_substitution_text));
token = 'variable-2';
break;
case 1:
change(state, to_explicit, context(rx_substitution, 2));
assert(stream.match(rx_substitution_sepa));
break;
case 2:
change(state, to_explicit, context(rx_substitution, 3));
assert(stream.match(rx_substitution_name));
token = 'keyword';
break;
case 3:
change(state, to_explicit, context(rx_substitution, 4));
assert(stream.match(rx_substitution_tail));
token = 'meta';
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (phase(state) == rx_directive ||
stream.match(rx_directive, false)) {
switch (stage(state)) {
case 0:
change(state, to_explicit, context(rx_directive, 1));
assert(stream.match(rx_directive_name));
token = 'keyword';
if (stream.current().match(/^(?:math|latex)/))
state.tmp_stex = true;
else if (stream.current().match(/^python/))
state.tmp_py = true;
break;
case 1:
change(state, to_explicit, context(rx_directive, 2));
assert(stream.match(rx_directive_tail));
token = 'meta';
break;
default:
if (stream.match(/^latex\s*$/) || state.tmp_stex) {
state.tmp_stex = undefined;
change(state, to_mode, {
mode: mode_stex, local: mode_stex.startState()
});
} else if (stream.match(/^python\s*$/) || state.tmp_py) {
state.tmp_py = undefined;
change(state, to_mode, {
mode: mode_python, local: mode_python.startState()
});
}
else {
change(state, to_normal);
assert(stream.current() == '');
}
}
} else if (phase(state) == rx_link || stream.match(rx_link, false)) {
switch (stage(state)) {
case 0:
change(state, to_explicit, context(rx_link, 1));
assert(stream.match(rx_link_head));
assert(stream.match(rx_link_name));
token = 'link';
break;
case 1:
change(state, to_explicit, context(rx_link, 2));
assert(stream.match(rx_link_tail));
token = 'meta';
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (stream.match(rx_footnote)) {
change(state, to_normal);
token = 'quote';
} else if (stream.match(rx_citation)) {
change(state, to_normal);
token = 'quote';
}
else {
stream.eatSpace();
if (stream.eol()) {
change(state, to_normal);
} else {
stream.skipToEnd();
change(state, to_comment);
token = 'comment';
}
}
return token;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function to_comment(stream, state) {
return as_block(stream, state, 'comment');
}
function to_verbatim(stream, state) {
return as_block(stream, state, 'meta');
}
function as_block(stream, state, token) {
if (stream.eol() || stream.eatSpace()) {
stream.skipToEnd();
return token;
} else {
change(state, to_normal);
return null;
}
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function to_mode(stream, state) {
if (state.ctx.mode && state.ctx.local) {
if (stream.sol()) {
if (!stream.eatSpace()) change(state, to_normal);
return null;
}
try {
return state.ctx.mode.token(stream, state.ctx.local);
} catch (ex) {
change(state, to_normal);
return null;
}
}
change(state, to_normal);
return null;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function context(phase, stage, mode, local) {
return {phase: phase, stage: stage, mode: mode, local: local};
}
function change(state, tok, ctx) {
state.tok = tok;
state.ctx = ctx || {};
}
function stage(state) {
return state.ctx.stage || 0;
}
function phase(state) {
return state.ctx.phase;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
return {
startState: function () {
return {tok: to_normal, ctx: context(undefined, 0)};
},
copyState: function (state) {
return {tok: state.tok, ctx: state.ctx};
},
innerMode: function (state) {
return {state: state.ctx.local, mode: state.ctx.mode};
},
token: function (stream, state) {
return state.tok(stream, state);
}
};
}, 'python', 'stex');
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
CodeMirror.defineMode('rst', function (config, options) {
var rx_strong = /^\*\*[^\*\s](?:[^\*]*[^\*\s])?\*\*/;
var rx_emphasis = /^\*[^\*\s](?:[^\*]*[^\*\s])?\*/;
var rx_literal = /^``[^`\s](?:[^`]*[^`\s])``/;
var rx_number = /^(?:[\d]+(?:[\.,]\d+)*)/;
var rx_positive = /^(?:\s\+[\d]+(?:[\.,]\d+)*)/;
var rx_negative = /^(?:\s\-[\d]+(?:[\.,]\d+)*)/;
var rx_uri_protocol = "[Hh][Tt][Tt][Pp][Ss]?://";
var rx_uri_domain = "(?:[\\d\\w.-]+)\\.(?:\\w{2,6})";
var rx_uri_path = "(?:/[\\d\\w\\#\\%\\&\\-\\.\\,\\/\\:\\=\\?\\~]+)*";
var rx_uri = new RegExp("^" +
rx_uri_protocol + rx_uri_domain + rx_uri_path
);
var overlay = {
token: function (stream) {
if (stream.match(rx_strong) && stream.match (/\W+|$/, false))
return 'strong';
if (stream.match(rx_emphasis) && stream.match (/\W+|$/, false))
return 'em';
if (stream.match(rx_literal) && stream.match (/\W+|$/, false))
return 'string-2';
if (stream.match(rx_number))
return 'number';
if (stream.match(rx_positive))
return 'positive';
if (stream.match(rx_negative))
return 'negative';
if (stream.match(rx_uri))
return 'link';
while (stream.next() != null) {
if (stream.match(rx_strong, false)) break;
if (stream.match(rx_emphasis, false)) break;
if (stream.match(rx_literal, false)) break;
if (stream.match(rx_number, false)) break;
if (stream.match(rx_positive, false)) break;
if (stream.match(rx_negative, false)) break;
if (stream.match(rx_uri, false)) break;
}
return null;
}
};
var mode = CodeMirror.getMode(
config, options.backdrop || 'rst-base'
);
return CodeMirror.overlayMode(mode, overlay, true); // combine
}, 'python', 'stex');
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
CodeMirror.defineMIME('text/x-rst', 'rst');
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
|
mode/rst/rst.js
|
CodeMirror.defineMode('rst-base', function (config) {
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function format(string) {
var args = Array.prototype.slice.call(arguments, 1);
return string.replace(/{(\d+)}/g, function (match, n) {
return typeof args[n] != 'undefined' ? args[n] : match;
});
}
function AssertException(message) {
this.message = message;
}
AssertException.prototype.toString = function () {
return 'AssertException: ' + this.message;
};
function assert(expression, message) {
if (!expression) throw new AssertException(message);
return expression;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
var mode_python = CodeMirror.getMode(config, 'python');
var mode_stex = CodeMirror.getMode(config, 'stex');
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
var SEPA = "\\s+";
var TAIL = "(?:\\s*|\\W|$)",
rx_TAIL = new RegExp(format('^{0}', TAIL));
var NAME = "(?:[^\\W\\d_](?:[\\w\\+\\.\\-:]*[^\\W_])?)",
rx_NAME = new RegExp(format('^{0}', NAME));
var NAME_WWS = "(?:[^\\W\\d_](?:[\\w\\s\\+\\.\\-:]*[^\\W_])?)";
var REF_NAME = format('(?:{0}|`{1}`)', NAME, NAME_WWS);
var TEXT1 = "(?:[^\\s\\|](?:[^\\|]*[^\\s\\|])?)";
var TEXT2 = "(?:[^\\`]+)",
rx_TEXT2 = new RegExp(format('^{0}', TEXT2));
var rx_section = new RegExp(
"^([!'#$%&\"()*+,-./:;<=>?@\\[\\\\\\]^_`{|}~])\\1{3,}\\s*$");
var rx_explicit = new RegExp(
format('^\\.\\.{0}', SEPA));
var rx_link = new RegExp(
format('^_{0}:{1}|^__:{1}', REF_NAME, TAIL));
var rx_directive = new RegExp(
format('^{0}::{1}', REF_NAME, TAIL));
var rx_substitution = new RegExp(
format('^\\|{0}\\|{1}{2}::{3}', TEXT1, SEPA, REF_NAME, TAIL));
var rx_footnote = new RegExp(
format('^\\[(?:\\d+|#{0}?|\\*)]{1}', REF_NAME, TAIL));
var rx_citation = new RegExp(
format('^\\[{0}\\]{1}', REF_NAME, TAIL));
var rx_substitution_ref = new RegExp(
format('^\\|{0}\\|', TEXT1));
var rx_footnote_ref = new RegExp(
format('^\\[(?:\\d+|#{0}?|\\*)]_', REF_NAME));
var rx_citation_ref = new RegExp(
format('^\\[{0}\\]_', REF_NAME));
var rx_link_ref1 = new RegExp(
format('^{0}__?', REF_NAME));
var rx_link_ref2 = new RegExp(
format('^`{0}`_', TEXT2));
var rx_role_pre = new RegExp(
format('^:{0}:`{1}`{2}', NAME, TEXT2, TAIL));
var rx_role_suf = new RegExp(
format('^`{1}`:{0}:{2}', NAME, TEXT2, TAIL));
var rx_role = new RegExp(
format('^:{0}:{1}', NAME, TAIL));
var rx_directive_name = new RegExp(format('^{0}', REF_NAME));
var rx_directive_tail = new RegExp(format('^::{0}', TAIL));
var rx_substitution_text = new RegExp(format('^\\|{0}\\|', TEXT1));
var rx_substitution_sepa = new RegExp(format('^{0}', SEPA));
var rx_substitution_name = new RegExp(format('^{0}', REF_NAME));
var rx_substitution_tail = new RegExp(format('^::{0}', TAIL));
var rx_link_head = new RegExp("^_");
var rx_link_name = new RegExp(format('^{0}|_', REF_NAME));
var rx_link_tail = new RegExp(format('^:{0}', TAIL));
var rx_verbatim = new RegExp('^::\\s*$');
var rx_examples = new RegExp('^\\s+(?:>>>|In \\[\\d+\\]:)\\s');
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function to_normal(stream, state) {
var token = null;
if (stream.sol() && stream.match(rx_examples, false)) {
change(state, to_mode, {
mode: mode_python, local: mode_python.startState()
});
} else if (stream.sol() && stream.match(rx_explicit)) {
change(state, to_explicit);
token = 'meta';
} else if (stream.sol() && stream.match(rx_section)) {
change(state, to_normal);
token = 'header';
} else if (phase(state) == rx_role_pre ||
stream.match(rx_role_pre, false)) {
switch (stage(state)) {
case 0:
change(state, to_normal, context(rx_role_pre, 1));
assert(stream.match(/^:/));
token = 'meta';
break;
case 1:
change(state, to_normal, context(rx_role_pre, 2));
assert(stream.match(rx_NAME));
token = 'keyword';
if (stream.current().match(/^(?:math|latex)/)) {
state.tmp = {
mode: mode_stex, local: mode_stex.startState()
};
}
break;
case 2:
change(state, to_normal, context(rx_role_pre, 3));
assert(stream.match(/^:`/));
token = 'meta';
break;
case 3:
if (state.tmp) {
if (stream.peek() == '`') {
change(state, to_normal, context(rx_role_pre, 4));
state.tmp = undefined;
break;
}
token = state.tmp.mode.token(stream, state.tmp.local);
break;
}
change(state, to_normal, context(rx_role_pre, 4));
assert(stream.match(rx_TEXT2));
token = 'string';
break;
case 4:
change(state, to_normal, context(rx_role_pre, 5));
assert(stream.match(/^`/));
token = 'meta';
break;
case 5:
change(state, to_normal, context(rx_role_pre, 6));
assert(stream.match(rx_TAIL));
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (phase(state) == rx_role_suf ||
stream.match(rx_role_suf, false)) {
switch (stage(state)) {
case 0:
change(state, to_normal, context(rx_role_suf, 1));
assert(stream.match(/^`/));
token = 'meta';
break;
case 1:
change(state, to_normal, context(rx_role_suf, 2));
assert(stream.match(rx_TEXT2));
token = 'string';
break;
case 2:
change(state, to_normal, context(rx_role_suf, 3));
assert(stream.match(/^`:/));
token = 'meta';
break;
case 3:
change(state, to_normal, context(rx_role_suf, 4));
assert(stream.match(rx_NAME));
token = 'keyword';
break;
case 4:
change(state, to_normal, context(rx_role_suf, 5));
assert(stream.match(/^:/));
token = 'meta';
break;
case 5:
change(state, to_normal, context(rx_role_suf, 6));
assert(stream.match(rx_TAIL));
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (phase(state) == rx_role || stream.match(rx_role, false)) {
switch (stage(state)) {
case 0:
change(state, to_normal, context(rx_role, 1));
assert(stream.match(/^:/));
token = 'meta';
break;
case 1:
change(state, to_normal, context(rx_role, 2));
assert(stream.match(rx_NAME));
token = 'keyword';
break;
case 2:
change(state, to_normal, context(rx_role, 3));
assert(stream.match(/^:/));
token = 'meta';
break;
case 3:
change(state, to_normal, context(rx_role, 4));
assert(stream.match(rx_TAIL));
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (phase(state) == rx_substitution_ref ||
stream.match(rx_substitution_ref, false)) {
switch (stage(state)) {
case 0:
change(state, to_normal, context(rx_substitution_ref, 1));
assert(stream.match(rx_substitution_text));
token = 'variable-2';
break;
case 1:
change(state, to_normal, context(rx_substitution_ref, 2));
if (stream.match(/^_?_?/)) token = 'link';
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (stream.match(rx_footnote_ref)) {
change(state, to_normal);
token = 'quote';
} else if (stream.match(rx_citation_ref)) {
change(state, to_normal);
token = 'quote';
} else if (stream.match(rx_link_ref1)) {
change(state, to_normal);
if (!stream.peek() || stream.peek().match(/^\W$/)) {
token = 'link';
}
} else if (phase(state) == rx_link_ref2 ||
stream.match(rx_link_ref2, false)) {
switch (stage(state)) {
case 0:
if (!stream.peek() || stream.peek().match(/^\W$/)) {
change(state, to_normal, context(rx_link_ref2, 1));
} else {
stream.match(rx_link_ref2);
}
break;
case 1:
change(state, to_normal, context(rx_link_ref2, 2));
assert(stream.match(/^`/));
token = 'link';
break;
case 2:
change(state, to_normal, context(rx_link_ref2, 3));
assert(stream.match(rx_TEXT2));
break;
case 3:
change(state, to_normal, context(rx_link_ref2, 4));
assert(stream.match(/^`_/));
token = 'link';
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (stream.match(rx_verbatim)) {
change(state, to_verbatim);
}
else {
if (stream.next()) change(state, to_normal);
}
return token;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function to_explicit(stream, state) {
var token = null;
if (phase(state) == rx_substitution ||
stream.match(rx_substitution, false)) {
switch (stage(state)) {
case 0:
change(state, to_explicit, context(rx_substitution, 1));
assert(stream.match(rx_substitution_text));
token = 'variable-2';
break;
case 1:
change(state, to_explicit, context(rx_substitution, 2));
assert(stream.match(rx_substitution_sepa));
break;
case 2:
change(state, to_explicit, context(rx_substitution, 3));
assert(stream.match(rx_substitution_name));
token = 'keyword';
break;
case 3:
change(state, to_explicit, context(rx_substitution, 4));
assert(stream.match(rx_substitution_tail));
token = 'meta';
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (phase(state) == rx_directive ||
stream.match(rx_directive, false)) {
switch (stage(state)) {
case 0:
change(state, to_explicit, context(rx_directive, 1));
assert(stream.match(rx_directive_name));
token = 'keyword';
if (stream.current().match(/^(?:math|latex)/))
state.tmp_stex = true;
else if (stream.current().match(/^python/))
state.tmp_py = true;
break;
case 1:
change(state, to_explicit, context(rx_directive, 2));
assert(stream.match(rx_directive_tail));
token = 'meta';
break;
default:
if (stream.match(/^latex\s*$/) || state.tmp_stex) {
state.tmp_stex = undefined;
change(state, to_mode, {
mode: mode_stex, local: mode_stex.startState()
});
} else if (stream.match(/^python\s*$/) || state.tmp_py) {
state.tmp_py = undefined;
change(state, to_mode, {
mode: mode_python, local: mode_python.startState()
});
}
else {
change(state, to_normal);
assert(stream.current() == '');
}
}
} else if (phase(state) == rx_link || stream.match(rx_link, false)) {
switch (stage(state)) {
case 0:
change(state, to_explicit, context(rx_link, 1));
assert(stream.match(rx_link_head));
assert(stream.match(rx_link_name));
token = 'link';
break;
case 1:
change(state, to_explicit, context(rx_link, 2));
assert(stream.match(rx_link_tail));
token = 'meta';
break;
default:
change(state, to_normal);
assert(stream.current() == '');
}
} else if (stream.match(rx_footnote)) {
change(state, to_normal);
token = 'quote';
} else if (stream.match(rx_citation)) {
change(state, to_normal);
token = 'quote';
}
else {
stream.eatSpace();
if (stream.eol()) {
change(state, to_normal);
} else {
stream.skipToEnd();
change(state, to_comment);
token = 'comment';
}
}
return token;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function to_comment(stream, state) {
return as_block(stream, state, 'comment');
}
function to_verbatim(stream, state) {
return as_block(stream, state, 'meta');
}
function as_block(stream, state, token) {
if (stream.eol() || stream.eatSpace()) {
stream.skipToEnd();
return token;
} else {
change(state, to_normal);
return null;
}
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function to_mode(stream, state) {
if (state.ctx.mode && state.ctx.local) {
if (stream.sol()) {
if (!stream.eatSpace()) change(state, to_normal);
return null;
}
try {
return state.ctx.mode.token(stream, state.ctx.local);
} catch (ex) {
change(state, to_normal);
return null;
}
}
change(state, to_normal);
return null;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function context(phase, stage, mode, local) {
return {phase: phase, stage: stage, mode: mode, local: local};
}
function change(state, tok, ctx) {
state.tok = tok;
state.ctx = ctx || {};
}
function stage(state) {
return state.ctx.stage || 0;
}
function phase(state) {
return state.ctx.phase;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
return {
startState: function () {
return {tok: to_normal, ctx: context(undefined, 0)};
},
copyState: function (state) {
return {tok: state.tok, ctx: state.ctx};
},
innerMode: function (state) {
return {state: state.ctx.local, mode: state.ctx.mode};
},
token: function (stream, state) {
return state.tok(stream, state);
}
};
}, 'python', 'stex');
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
CodeMirror.defineMode('rst', function (config, options) {
var rx_strong = /^\*\*[^\*\s](?:[^\*]*[^\*\s])?\*\*/;
var rx_emphasis = /^\*[^\*\s](?:[^\*]*[^\*\s])?\*/;
var rx_literal = /^``[^`\s](?:[^`]*[^`\s])``/;
var rx_number = /^(?:[\d]+(?:[\.,]\d+)*)/;
var rx_positive = /^(?:\s\+[\d]+(?:[\.,]\d+)*)/;
var rx_negative = /^(?:\s\-[\d]+(?:[\.,]\d+)*)/;
var rx_uri_protocol = "[Hh][Tt][Tt][Pp][Ss]?://";
var rx_uri_domain = "(?:[\\d\\w.-]+)\\.(?:\\w{2,6})";
var rx_uri_path = "(?:/[\\d\\w\\#\\%\\&\\-\\.\\,\\/\\:\\=\\?\\~]+)*";
var rx_uri = new RegExp("^" +
rx_uri_protocol + rx_uri_domain + rx_uri_path
);
var overlay = {
token: function (stream) {
if (stream.match(rx_strong) && stream.match (/\W+|$/, false))
return 'strong';
if (stream.match(rx_emphasis) && stream.match (/\W+|$/, false))
return 'em';
if (stream.match(rx_literal) && stream.match (/\W+|$/, false))
return 'string-2';
if (stream.match(rx_number))
return 'number';
if (stream.match(rx_positive))
return 'positive';
if (stream.match(rx_negative))
return 'negative';
if (stream.match(rx_uri))
return 'link';
while (stream.next() != null) {
if (stream.match(rx_strong, false)) break;
if (stream.match(rx_emphasis, false)) break;
if (stream.match(rx_literal, false)) break;
if (stream.match(rx_number, false)) break;
if (stream.match(rx_positive, false)) break;
if (stream.match(rx_negative, false)) break;
if (stream.match(rx_uri, false)) break;
}
return null;
}
};
var mode = CodeMirror.getMode(
config, options.backdrop || 'rst-base'
);
return CodeMirror.overlayMode(mode, overlay, true); // combine
}, 'python', 'stex');
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
CodeMirror.defineMIME('text/x-rst', 'rst');
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
|
[rst] Reference name fix w.r.t. "phrase-references"
Phrase-references should be able to contain interpunction characters; fixed.
|
mode/rst/rst.js
|
[rst] Reference name fix w.r.t. "phrase-references"
|
<ide><path>ode/rst/rst.js
<ide> var TAIL = "(?:\\s*|\\W|$)",
<ide> rx_TAIL = new RegExp(format('^{0}', TAIL));
<ide>
<del> var NAME = "(?:[^\\W\\d_](?:[\\w\\+\\.\\-:]*[^\\W_])?)",
<add> var NAME =
<add> "(?:[^\\W\\d_](?:[\\w!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)",
<ide> rx_NAME = new RegExp(format('^{0}', NAME));
<del> var NAME_WWS = "(?:[^\\W\\d_](?:[\\w\\s\\+\\.\\-:]*[^\\W_])?)";
<add> var NAME_WWS =
<add> "(?:[^\\W\\d_](?:[\\w\\s!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)";
<ide> var REF_NAME = format('(?:{0}|`{1}`)', NAME, NAME_WWS);
<ide>
<ide> var TEXT1 = "(?:[^\\s\\|](?:[^\\|]*[^\\s\\|])?)";
|
|
Java
|
mit
|
93444bbf988c45a245ac85c5ae0df7b9359bfd53
| 0 |
GreenfieldTech/irked
|
package tech.greenfield.vertx.irked.auth;
import java.util.Objects;
import java.util.ServiceLoader;
public class AuthorizationToken {
private String token;
private String type;
protected AuthorizationToken() {
}
public static AuthorizationToken parse(String authorizationHeader) {
if (Objects.isNull(authorizationHeader))
return new NullAuthorizationToken();
String[] parts = authorizationHeader.split("\\s+",2);
if (parts.length == 1)
return new SimpleAuthrizationToken(parts[0]);
for (AuthorizationToken a : ServiceLoader.load(AuthorizationToken.class)) {
if (a.supports(parts[0]))
return a.update(parts[0], parts[1]);
}
return new AuthorizationToken().update(parts[0], parts[1]);
}
protected AuthorizationToken update(String type, String token) {
this.type = type;
this.token = token;
return this;
}
protected boolean supports(String type) {
return false;
}
public boolean is(String type) {
return Objects.isNull(type) ? Objects.isNull(this.type) : type.equalsIgnoreCase(this.type);
}
public String getToken() {
return token;
}
public String getType() {
return type;
}
public String toString() {
return type + " " + token;
}
}
|
src/main/java/tech/greenfield/vertx/irked/auth/AuthorizationToken.java
|
package tech.greenfield.vertx.irked.auth;
import java.util.Objects;
import java.util.ServiceLoader;
public class AuthorizationToken {
private String token;
private String type;
protected AuthorizationToken() {
}
public static AuthorizationToken parse(String authorizationHeader) {
if (Objects.isNull(authorizationHeader))
return new NullAuthorizationToken();
String[] parts = authorizationHeader.split("\\s+",2);
if (parts.length == 1)
return new SimpleAuthrizationToken(parts[0]);
for (AuthorizationToken a : ServiceLoader.load(AuthorizationToken.class)) {
if (a.supports(parts[0]))
return a.update(parts[0], parts[1]);
}
return new AuthorizationToken().update(parts[0], parts[1]);
}
protected AuthorizationToken update(String type, String token) {
this.type = type;
this.token = token;
return this;
}
protected boolean supports(String type) {
return false;
}
public boolean is(String type) {
return Objects.isNull(type) ? Objects.isNull(this.type) : type.equalsIgnoreCase(this.type);
}
public String getToken() {
return token;
}
public String getType() {
return type;
}
}
|
add toString to authorization token so users can debug dump it
|
src/main/java/tech/greenfield/vertx/irked/auth/AuthorizationToken.java
|
add toString to authorization token so users can debug dump it
|
<ide><path>rc/main/java/tech/greenfield/vertx/irked/auth/AuthorizationToken.java
<ide> public String getType() {
<ide> return type;
<ide> }
<add>
<add> public String toString() {
<add> return type + " " + token;
<add> }
<ide> }
|
|
JavaScript
|
mit
|
23dc32975e44e07742460fe202a343b0921447e0
| 0 |
fistlabs/fist,golyshevd/fist,golyshevd/fist,golyshevd/fist,fistlabs/fist
|
'use strict';
var Connect = require('../../track/Connect');
var Server = require('../../Server');
var Fs = require('fs');
var Http = require('http');
var STATUS_CODES = Http.STATUS_CODES;
var http = require('../util/http');
var sock = require('../stuff/conf/sock');
var asker = require('asker');
var server = new Server();
server.decl('index', function () {
this.send(200, 'INDEX');
});
server.decl('page', function (bundle, done) {
done(null, this.match.pageName);
});
server.decl('error', function () {
this.send(500, new Error('O_O'));
});
server.route('GET', '/', 'index');
server.route('GET', '/index/', 'index-2', 'index');
server.route('GET', '/error/', 'error');
server.route('GET', '/<pageName>/', 'page');
server.route('POST', '/upload/', 'upload');
module.exports = {
'Server.prototype.resolve': function (test) {
var s = new Server();
s.decl('a', function (bundle, done) {
done(null, 'a');
});
s.decl('b', function () {
this.send(201, 'b');
test.strictEqual(this.send, Connect.noop);
});
s.decl('c', function (bundle, done) {
setTimeout(function () {
done(null, 'c');
}, 0);
});
s.decl('x', ['a', 'b', 'c'], function () {});
http({method: 'GET'}, function (req, res) {
var connect = new Connect(s, req, res);
s.resolve(connect, 'x', function () {
test.ok(false);
});
}, function (err, data) {
test.strictEqual(data.statusCode, 201);
test.strictEqual(data.data, 'b');
test.done();
});
},
'Server-0': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'GET',
path: '/fist.io.server/',
socketPath: sock
}, function (err, res) {
test.deepEqual(res.data, new Buffer('fist.io.server'));
test.done();
});
},
'Server-1': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'HEAD',
path: '/',
socketPath: sock
}, function (err, res) {
test.deepEqual(res.data, null);
test.done();
});
},
'Server-2': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'GET',
path: '/asd/asd/',
socketPath: sock,
statusFilter: function () {
return {
accept: true,
isRetryAllowed: false
};
}
}, function (err, res) {
test.strictEqual(res.statusCode, 404);
test.deepEqual(res.data, new Buffer(STATUS_CODES[res.statusCode]));
test.done();
});
},
'Server-3': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'POST',
path: '/',
socketPath: sock,
statusFilter: function () {
return {
accept: true,
isRetryAllowed: false
};
}
}, function (err, res) {
test.strictEqual(res.statusCode, 405);
test.strictEqual(res.headers.allow, 'GET');
test.deepEqual(res.data, new Buffer(STATUS_CODES[res.statusCode]));
test.done();
});
},
'Server-4': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'PUT',
path: '/',
socketPath: sock,
statusFilter: function () {
return {
accept: true,
isRetryAllowed: false
};
}
}, function (err, res) {
test.strictEqual(res.statusCode, 501);
test.deepEqual(res.data, new Buffer(STATUS_CODES[res.statusCode]));
test.done();
});
},
'Server-5': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'GET',
path: '/error/',
socketPath: sock,
statusFilter: function () {
return {
accept: true,
isRetryAllowed: false
};
}
}, function (err, res) {
test.strictEqual(res.statusCode, 500);
test.ok(res.data + '' !== STATUS_CODES[res.statusCode]);
test.done();
});
},
'Server-7': function (test) {
var spy = [];
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
server.on('response', function (event) {
event.status(500);
test.strictEqual(typeof event.time, 'number');
test.ok(isFinite(event.time));
spy.push(event.status());
});
asker({
method: 'GET',
path: '/index/',
socketPath: sock
}, function (err, res) {
test.deepEqual(res.data + '', 'INDEX');
test.deepEqual(spy, [500]);
test.done();
});
},
'Server-8': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'GET',
path: '/',
socketPath: sock
}, function (err, res) {
test.deepEqual(res.data + '', 'INDEX');
test.done();
});
},
'Server-9': function (test) {
var serv = new Server();
try {
Fs.unlinkSync(sock);
} catch (ex) {}
serv.on('request', function (track) {
track.send(201);
});
Http.createServer(serv.getHandler()).listen(sock);
asker({
method: 'GET',
path: '/',
socketPath: sock
}, function (err, res) {
test.deepEqual(res.statusCode, 201);
test.done();
});
}
};
|
test/common/Server.js
|
'use strict';
var Connect = require('../../track/Connect');
var Server = require('../../Server');
var Fs = require('fs');
var Http = require('http');
var STATUS_CODES = Http.STATUS_CODES;
var http = require('../util/http');
var sock = require('../stuff/conf/sock');
var asker = require('asker');
var server = new Server();
server.decl('index', function () {
this.send(200, 'INDEX');
});
server.decl('page', function (bundle, done) {
done(null, this.match.pageName);
});
server.decl('error', function () {
this.send(500, new Error('O_O'));
});
server.route('GET', '/', 'index');
server.route('GET', '/index/', 'index-2', 'index');
server.route('GET', '/error/', 'error');
server.route('GET', '/<pageName>/', 'page');
server.route('POST', '/upload/', 'upload');
module.exports = {
'Server.prototype.resolve': function (test) {
var s = new Server();
s.decl('a', function (bundle, done) {
done(null, 'a');
});
s.decl('b', function () {
this.send(201, 'b');
test.strictEqual(this.send, Connect.noop);
});
s.decl('c', function (bundle, done) {
setTimeout(function () {
done(null, 'c');
}, 0);
});
s.decl('x', ['a', 'b', 'c'], function () {});
http({method: 'GET'}, function (req, res) {
var connect = new Connect(s, req, res);
s.resolve(connect, 'x', function () {
test.ok(false);
});
}, function (err, data) {
test.strictEqual(data.statusCode, 201);
test.strictEqual(data.data, 'b');
test.done();
});
},
'Server-0': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'GET',
path: '/fist.io.server/',
socketPath: sock
}, function (err, res) {
test.deepEqual(res.data, new Buffer('fist.io.server'));
test.done();
});
},
'Server-1': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'HEAD',
path: '/',
socketPath: sock
}, function (err, res) {
test.deepEqual(res.data, null);
test.done();
});
},
'Server-2': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'GET',
path: '/asd/asd/',
socketPath: sock,
statusFilter: function () {
return {
accept: true,
isRetryAllowed: false
};
}
}, function (err, res) {
test.strictEqual(res.statusCode, 404);
test.deepEqual(res.data, new Buffer(STATUS_CODES[res.statusCode]));
test.done();
});
},
'Server-3': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'POST',
path: '/',
socketPath: sock,
statusFilter: function () {
return {
accept: true,
isRetryAllowed: false
};
}
}, function (err, res) {
test.strictEqual(res.statusCode, 405);
test.strictEqual(res.headers.allow, 'GET');
test.deepEqual(res.data, new Buffer(STATUS_CODES[res.statusCode]));
test.done();
});
},
'Server-4': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'PUT',
path: '/',
socketPath: sock,
statusFilter: function () {
return {
accept: true,
isRetryAllowed: false
};
}
}, function (err, res) {
test.strictEqual(res.statusCode, 501);
test.deepEqual(res.data, new Buffer(STATUS_CODES[res.statusCode]));
test.done();
});
},
'Server-5': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'GET',
path: '/error/',
socketPath: sock,
statusFilter: function () {
return {
accept: true,
isRetryAllowed: false
};
}
}, function (err, res) {
test.strictEqual(res.statusCode, 500);
test.ok(res.data + '' !== STATUS_CODES[res.statusCode]);
test.done();
});
},
'Server-7': function (test) {
var spy = [];
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
server.on('response', function (event) {
event.status(500);
test.strictEqual(typeof event.time, 'number');
test.ok(isFinite(event.time));
spy.push(event.status());
});
asker({
method: 'GET',
path: '/index/',
socketPath: sock
}, function (err, res) {
test.deepEqual(res.data + '', 'INDEX');
test.deepEqual(spy, [500]);
test.done();
});
},
'Server-8': function (test) {
try {
Fs.unlinkSync(sock);
} catch (ex) {}
Http.createServer(server.getHandler()).listen(sock);
asker({
method: 'GET',
path: '/',
socketPath: sock
}, function (err, res) {
test.deepEqual(res.data + '', 'INDEX');
test.done();
});
},
'Server-9': function (test) {
var serv = new Server();
try {
Fs.unlinkSync(sock);
} catch (ex) {}
serv.on('request', function (track) {
track.send(201);
});
Http.createServer(serv.getHandler()).listen(sock);
asker({
method: 'GET',
path: '/',
socketPath: sock
}, function (err, res) {
test.deepEqual(res.statusCode, 201);
test.done();
});
}
};
|
v2.0.x: fix code style issues
|
test/common/Server.js
|
v2.0.x: fix code style issues
|
<ide><path>est/common/Server.js
<ide> });
<ide> }
<ide>
<del>
<ide> };
|
|
Java
|
unlicense
|
3a74133d20859e22a6c98293a406d71680034ef2
| 0 |
mac-reid/MapTool,mac-reid/MapTool
|
package Backend;
import Backend.*;
import java.util.ArrayList;
import org.newdawn.slick.Image;
public class Control {
private Map map;
Storage store;
public Control() {
}
public void sendTextToGUI(String user, String message) {
}
public void addText(String user, String text) {
if (!gameLoaded()) {
System.out.println("Some error here");
return;
}
// search for user in current chat buffer
for (Pair p : store.getUsers())
if (p.getUser().equals(user))
p.addText(text);
store.writeUserChat(user, text);
}
public void addToken(Image pic, int x, int y, String name) {
if (!gameLoaded()) {
System.out.println("Some error here");
return;
}
map.addToken(pic, x, y, name);
}
public void addToken(String s, int x, int y, String name) {
}
public Token getToken(int x, int y) {
if (!gameLoaded()) {
System.out.println("Some error here");
return null;
}
return map.getToken(x,y);
}
public ArrayList<Token> getTokenList() {
if (!gameLoaded()) {
System.out.println("Some error here");
return null;
}
return map.getTokens();
}
public void hideMapArea(int startX, int startY, int endX, int endY) {
if (!gameLoaded()) {
System.out.println("Some error here");
return;
}
map.hideArea(startX, startY, endX, endY);
}
public void loadGame(String s) {
}
private Storage loadSave(String saveFilePath) {
map = new Map(480, 480, 48, null);
return store = new Storage(saveFilePath);
}
public boolean moveToken(String s, int tileX, int tileY) {
}
public boolean moveToken(Token t, int tileX, int tileY) {
if (!gameLoaded()) {
System.out.println("Some error here");
return false;
}
return map.move(t, tileX, tileY);
}
public boolean removeToken(String name) {
if (!gameLoaded()) {
System.out.println("Some error here");
return false;
}
for (Token t : map.getTokens())
if (t.getName().equals(name))
return removeToken(t);
return false;
}
public boolean removeToken(Token t) {
if (!gameLoaded()) {
System.out.println("Some error here");
return false;
}
return map.removeToken(t);
}
public void saveMap(String saveFilePath) {
if (!gameLoaded()) {
System.out.println("Some error here");
return;
}
}
public void showMapArea(int startX, int startY, int endX, int endY) {
if (!gameLoaded()) {
System.out.println("Some error here");
return;
}
map.unHideArea(startX, startY, endX, endY);
}
private boolean gameLoaded() {
if (map == null)
return false;
if (store == null)
return false;
return true;
}
public static void main(String[] args) {
Control c = new Control();
String mydir = System.getProperty("user.dir") + "\\MapTool\\";
Storage s = c.loadSave(mydir + "saves/default.sav");
s.closeFile();
}
}
|
MapTool/Backend/Control.java
|
package Backend;
import Backend.*;
import java.util.ArrayList;
import org.newdawn.slick.Image;
public class Control {
private Map map;
Storage store;
public Control() {
}
public void addText(String user, String text) {
if (!gameLoaded()) {
System.out.println("Some error here");
return;
}
// search for user in current chat buffer
for (Pair p : store.getUsers())
if (p.getUser().equals(user))
p.addText(text);
store.writeUserChat(user, text);
}
public void addToken(Image pic, int x, int y, String name) {
if (!gameLoaded()) {
System.out.println("Some error here");
return;
}
map.addToken(pic, x, y, name);
}
public Token getToken(int x, int y) {
if (!gameLoaded()) {
System.out.println("Some error here");
return null;
}
return map.getToken(x,y);
}
public ArrayList<Token> getTokenList() {
if (!gameLoaded()) {
System.out.println("Some error here");
return null;
}
return map.getTokens();
}
public void hideMapArea(int startX, int startY, int endX, int endY) {
if (!gameLoaded()) {
System.out.println("Some error here");
return;
}
map.hideArea(startX, startY, endX, endY);
}
public Storage loadSave(String saveFilePath) {
map = new Map(480, 480, 48, null);
return store = new Storage(saveFilePath);
}
public boolean moveToken(Token t, int tileX, int tileY) {
if (!gameLoaded()) {
System.out.println("Some error here");
return false;
}
return map.move(t, tileX, tileY);
}
public boolean removeToken(String name) {
if (!gameLoaded()) {
System.out.println("Some error here");
return false;
}
for (Token t : map.getTokens())
if (t.getName().equals(name))
return removeToken(t);
return false;
}
public boolean removeToken(Token t) {
if (!gameLoaded()) {
System.out.println("Some error here");
return false;
}
return map.removeToken(t);
}
public void saveMap(String saveFilePath) {
if (!gameLoaded()) {
System.out.println("Some error here");
return;
}
}
public void showMapArea(int startX, int startY, int endX, int endY) {
if (!gameLoaded()) {
System.out.println("Some error here");
return;
}
map.unHideArea(startX, startY, endX, endY);
}
private boolean gameLoaded() {
if (map == null)
return false;
if (store == null)
return false;
return true;
}
public static void main(String[] args) {
Control c = new Control();
String mydir = System.getProperty("user.dir") + "\\MapTool\\";
Storage s = c.loadSave(mydir + "saves/default.sav");
s.closeFile();
}
}
|
Signed-off-by: mareid <[email protected]>
|
MapTool/Backend/Control.java
|
Signed-off-by: mareid <[email protected]>
|
<ide><path>apTool/Backend/Control.java
<ide> Storage store;
<ide>
<ide> public Control() {
<add>
<add> }
<add>
<add> public void sendTextToGUI(String user, String message) {
<ide>
<ide> }
<ide>
<ide> return;
<ide> }
<ide> map.addToken(pic, x, y, name);
<add> }
<add>
<add> public void addToken(String s, int x, int y, String name) {
<add>
<ide> }
<ide>
<ide> public Token getToken(int x, int y) {
<ide> map.hideArea(startX, startY, endX, endY);
<ide> }
<ide>
<del> public Storage loadSave(String saveFilePath) {
<add> public void loadGame(String s) {
<add>
<add> }
<add>
<add> private Storage loadSave(String saveFilePath) {
<ide>
<ide> map = new Map(480, 480, 48, null);
<ide> return store = new Storage(saveFilePath);
<add> }
<add>
<add> public boolean moveToken(String s, int tileX, int tileY) {
<add>
<ide> }
<ide>
<ide> public boolean moveToken(Token t, int tileX, int tileY) {
|
|
JavaScript
|
mit
|
1402313dde36b95739683caf515b5d856a96afc7
| 0 |
Lazyuki/Discord-Stats-Bot,Lazyuki/Discord-Stats-Bot
|
const Discord = require('discord.js');
const init = require('./init.json');
const Server = require('./classes/Server.js');
const midnightTask = require('./classes/MidnightTask.js');
const savingTask = require('./classes/SavingTask.js');
let cmds = require('./cmds.js');
const commands = cmds.commands;
const inits = cmds.inits;
const prcs = require('./prcs.js');
// Set up Discord client settings.
// Note: Disabling other events such as user update tends to break everything.
const bot = new Discord.Client({
disableEveryone: true,
disabledEvents: [
'TYPING_START'
]
});
// Load initial configurations.
const token = init.token;
bot.owner_ID = init.owner_ID;
// Initialize the bot and servers.
bot.on('ready', () => {
setTimeout(() => { // Set up hourly backup state task
savingTask(bot);
}, 60*60*1000);
let time = new Date();
let h = time.getUTCHours();
let m = time.getUTCMinutes();
let s = time.getUTCSeconds();
let timeLeft = (24*60*60) - (h*60*60) - (m*60) - s;
setTimeout(() => { // Set up the day changing task
midnightTask(bot);
}, timeLeft * 1000); // Time left until the next day
console.log('Logged in as ' + bot.user.username);
console.log(`${time.toLocaleDateString()} ${time.toLocaleTimeString()}`);
console.log('--------------------------');
bot.servers = {};
bot.usableEmotes = [];
for (let guild of bot.guilds.values()) {
if (guild.id == '293787390710120449') continue;
bot.servers[guild.id] = new Server(guild, inits, prcs);
}
let helps = [',help',',h',',halp',',tasukete'];
bot.user.setActivity(helps[Math.floor(Math.random() * helps.length)], {type:'LISTENING'});
});
bot.on('message', async message => {
if (message.author.bot || message.system) return; // Ignore messages by bots and system
if (message.channel.type != 'text') { // Direct message.
respondDM(message);
return;
}
let server = bot.servers[message.guild.id];
let serverOverride = false;
if (/^!!\d+,/.test(message.content) && message.author.id == bot.owner_ID) {
server = bot.servers[message.content.match(/^!!(\d+),/)[1]];
message.content = message.content.replace(/^!!\d+/, '');
serverOverride = true;
}
// Changes my server to EJLX
let mine = false;
if (server == undefined) {
server = bot.servers['189571157446492161'];
mine = true;
}
// Cache member => prevents weird errors
if (!message.member) {
message.member = await server.guild.fetchMember(message.author);
}
// Is it not a command?
if (!message.content.startsWith(server.prefix)) {
if (!mine && !serverOverride) server.processNewMessage(message, bot);
return;
}
// Separate the command and the content
let command = message.content.split(' ')[0].slice(1).toLowerCase();
let content = message.content.substr(command.length + 2).trim();
if (commands[command]) { // if Ciri's command
if (commands[command].isAllowed(message, server, bot)) { // Check permission
commands[command].command(message, content, bot, server, cmds);
return;
}
}
if (!mine && !serverOverride) server.processNewMessage(message, bot); // Wasn't a valid command, so process it
});
bot.on('messageUpdate', (oldMessage, newMessage) => {
if (oldMessage.author.bot || oldMessage.system) return;
if (oldMessage.content == newMessage.content) return; // Discord's auto embed for links sends this event too
if (oldMessage.channel.type != 'text') return;
if (oldMessage.guild.id == '293787390710120449') return; // Ignore my server
bot.servers[oldMessage.guild.id].addEdits(oldMessage, newMessage, bot);
});
bot.on('messageDelete', message => {
if (message.author.bot || message.system) return;
if (message.channel.type != 'text') return;
if (message.guild.id == '293787390710120449') return; // Ignore my server
bot.servers[message.guild.id].addDeletedMessage(message);
});
bot.on('messageDeleteBulk', messages => {
let m = messages.first();
if (m.author.bot || m.system) return;
if (m.channel.type != 'text') return;
if (m.guild.id == '293787390710120449') return; // Ignore my server
for (let [, message] of messages) {
bot.servers[message.guild.id].addDeletedMessage(message);
}
});
bot.on('messageReactionAdd', async (reaction, user) => {
let m = reaction.message;
if (user.bot) return;
if (m.channel.type != 'text') return;
if (m.guild.id == '293787390710120449') {
if (reaction.emoji.toString() == '▶️') {
prcs.processors['REACTION'][0].process(reaction, user, true, bot.servers['189571157446492161'], bot);
}
return; // Ignore my server
}
bot.servers[m.guild.id].processReaction(reaction, user, true, bot);
});
bot.on('messageReactionRemove', async (reaction, user) => {
let m = reaction.message;
if (user.bot) return;
if (m.channel.type != 'text') return;
if (m.guild.id == '293787390710120449') {
if (reaction.emoji.toString() == '▶️') {
prcs.processors['REACTION'][0].process(reaction, user, false, bot.servers['189571157446492161'], bot);
}
return; // Ignore my server
} bot.servers[m.guild.id].processReaction(reaction, user, false, bot);
});
bot.on('voiceStateUpdate', async (oldMember, newMember) => {
if (oldMember.user.bot) return;
if (oldMember.guild.id == '293787390710120449') return; // Ignore my server
bot.servers[oldMember.guild.id].processVoice(oldMember, newMember);
});
bot.on('userUpdate', (oldUser, newUser) => {
for (let serverID in bot.servers) {
bot.servers[serverID].userUpdate(oldUser, newUser);
}
});
bot.on('guildMemberUpdate', (oldMember, newMember) => {
if (oldMember.guild.id == '293787390710120449') return; // Ignore my server
bot.servers[oldMember.guild.id].memberUpdate(oldMember, newMember);
});
bot.on('guildMemberAdd', member => {
if (member.guild.id == '293787390710120449') return; // Ignore my server
bot.servers[member.guild.id].addNewUser(member);
});
bot.on('guildBanAdd', (guild, user) => {
if (guild.id == '293787390710120449') return;// Ignore my server
// Clean up watchedUsers
let index = bot.servers[guild.id].watchedUsers.indexOf(user.id);
if (index == -1) return;
bot.servers[guild.id].watchedUsers.splice(index, 1);
});
bot.on('guildMemberRemove', (member) => {
if (member.guild.id == '293787390710120449') return;// Ignore my server
bot.servers[member.guild.id].removeUser(member);
});
bot.on('guildCreate', guild => {
bot.servers[guild.id] = new Server(guild, inits, prcs);
console.log(`Server added: ${guild.name}`);
});
bot.on('guildDelete', guild => {
let index = bot.servers.indexOf(guild.id);
if (index == -1) return;
bot.servers.splice(index, 1);
console.log(`Server removed: ${guild.name}`);
});
// Respond to DMs since it's not supported there
function respondDM(message) {
let msgs = [
'Come on... I\'m not available here... \n https://media3.giphy.com/media/mfGYunx8bcWJy/giphy.gif',
'*sigh* Why did you PM me https://68.media.tumblr.com/d0238a0224ac18b47d1ac2fbbb6dd168/tumblr_nselfnnY3l1rpd9dfo1_250.gif',
'I don\'t work here ¯\\\_(ツ)_/¯ http://cloud-3.steamusercontent.com/ugc/576816221180356023/FF4FF60F13F2A773123B3B26A19935944480F510/'];
let msg = msgs[Math.floor(Math.random() * msgs.length)];
message.channel.send(msg);
}
process.on('unhandledRejection', console.dir); // Show stack trace on unhandled rejection.
// Log in. This should be the last call
bot.login(token);
|
bot.js
|
const Discord = require('discord.js');
const init = require('./init.json');
const Server = require('./classes/Server.js');
const midnightTask = require('./classes/MidnightTask.js');
const savingTask = require('./classes/SavingTask.js');
let cmds = require('./cmds.js');
const commands = cmds.commands;
const inits = cmds.inits;
const prcs = require('./prcs.js');
// Set up Discord client settings.
// Note: Disabling other events such as user update tends to break everything.
const bot = new Discord.Client({
disableEveryone: true,
disabledEvents: [
'TYPING_START'
]
});
// Load initial configurations.
const token = init.token;
bot.owner_ID = init.owner_ID;
// Initialize the bot and servers.
bot.on('ready', () => {
setTimeout(() => { // Set up hourly backup state task
savingTask(bot);
}, 60*60*1000);
let time = new Date();
let h = time.getUTCHours();
let m = time.getUTCMinutes();
let s = time.getUTCSeconds();
let timeLeft = (24*60*60) - (h*60*60) - (m*60) - s;
setTimeout(() => { // Set up the day changing task
midnightTask(bot);
}, timeLeft * 1000); // Time left until the next day
console.log('Logged in as ' + bot.user.username);
console.log(`${time.toLocaleDateString()} ${time.toLocaleTimeString()}`);
console.log('--------------------------');
bot.servers = {};
bot.usableEmotes = [];
for (let guild of bot.guilds.values()) {
if (guild.id == '293787390710120449') continue;
bot.servers[guild.id] = new Server(guild, inits, prcs);
}
let helps = [',help',',h',',halp',',tasukete'];
bot.user.setActivity(helps[Math.floor(Math.random() * helps.length)], {type:'LISTENING'});
});
bot.on('message', async message => {
if (message.author.bot || message.system) return; // Ignore messages by bots and system
if (message.channel.type != 'text') { // Direct message.
respondDM(message);
return;
}
let server = bot.servers[message.guild.id];
let serverOverride = false;
if (/^!!\d+,/.test(message.content) && message.author.id == bot.owner_ID) {
server = bot.servers[message.content.match(/^!!(\d+),/)[1]];
message.content = message.content.replace(/^!!\d+/, '');
serverOverride = true;
}
// Changes my server to EJLX
let mine = false;
if (server == undefined) {
server = bot.servers['189571157446492161'];
mine = true;
}
// Cache member => prevents weird errors
if (!message.member) {
message.member = await server.guild.fetchMember(message.author);
}
// Is it not a command?
if (!message.content.startsWith(server.prefix)) {
if (!mine && !serverOverride) server.processNewMessage(message, bot);
return;
}
// Separate the command and the content
let command = message.content.split(' ')[0].slice(1).toLowerCase();
let content = message.content.substr(command.length + 2).trim();
if (commands[command]) { // if Ciri's command
if (commands[command].isAllowed(message, server, bot)) { // Check permission
commands[command].command(message, content, bot, server, cmds);
return;
}
}
if (!mine && !serverOverride) server.processNewMessage(message, bot); // Wasn't a valid command, so process it
});
bot.on('messageUpdate', (oldMessage, newMessage) => {
if (oldMessage.author.bot || oldMessage.system) return;
if (oldMessage.content == newMessage.content) return; // Discord's auto embed for links sends this event too
if (oldMessage.channel.type != 'text') return;
if (oldMessage.guild.id == '293787390710120449') return; // Ignore my server
bot.servers[oldMessage.guild.id].addEdits(oldMessage, newMessage, bot);
});
bot.on('messageDelete', message => {
if (message.author.bot || message.system) return;
if (message.channel.type != 'text') return;
if (message.guild.id == '293787390710120449') return; // Ignore my server
bot.servers[message.guild.id].addDeletedMessage(message);
});
bot.on('messageDeleteBulk', messages => {
let m = messages.first();
if (m.author.bot || m.system) return;
if (m.channel.type != 'text') return;
if (m.guild.id == '293787390710120449') return; // Ignore my server
for (let [, message] of messages) {
bot.servers[message.guild.id].addDeletedMessage(message);
}
});
bot.on('messageReactionAdd', async (reaction, user) => {
let m = reaction.message;
if (user.bot) return;
if (m.channel.type != 'text') return;
if (m.guild.id == '293787390710120449') return; // Ignore my server
bot.servers[m.guild.id].processReaction(reaction, user, true, bot);
});
bot.on('messageReactionRemove', async (reaction, user) => {
let m = reaction.message;
if (user.bot) return;
if (m.channel.type != 'text') return;
if (m.guild.id == '293787390710120449') return; // Ignore my server
bot.servers[m.guild.id].processReaction(reaction, user, false, bot);
});
bot.on('voiceStateUpdate', async (oldMember, newMember) => {
if (oldMember.user.bot) return;
if (oldMember.guild.id == '293787390710120449') return; // Ignore my server
bot.servers[oldMember.guild.id].processVoice(oldMember, newMember);
});
bot.on('userUpdate', (oldUser, newUser) => {
for (let serverID in bot.servers) {
bot.servers[serverID].userUpdate(oldUser, newUser);
}
});
bot.on('guildMemberUpdate', (oldMember, newMember) => {
if (oldMember.guild.id == '293787390710120449') return; // Ignore my server
bot.servers[oldMember.guild.id].memberUpdate(oldMember, newMember);
});
bot.on('guildMemberAdd', member => {
if (member.guild.id == '293787390710120449') return; // Ignore my server
bot.servers[member.guild.id].addNewUser(member);
});
bot.on('guildBanAdd', (guild, user) => {
if (guild.id == '293787390710120449') return;// Ignore my server
// Clean up watchedUsers
let index = bot.servers[guild.id].watchedUsers.indexOf(user.id);
if (index == -1) return;
bot.servers[guild.id].watchedUsers.splice(index, 1);
});
bot.on('guildMemberRemove', (member) => {
if (member.guild.id == '293787390710120449') return;// Ignore my server
bot.servers[member.guild.id].removeUser(member);
});
bot.on('guildCreate', guild => {
bot.servers[guild.id] = new Server(guild, inits, prcs);
console.log(`Server added: ${guild.name}`);
});
bot.on('guildDelete', guild => {
let index = bot.servers.indexOf(guild.id);
if (index == -1) return;
bot.servers.splice(index, 1);
console.log(`Server removed: ${guild.name}`);
});
// Respond to DMs since it's not supported there
function respondDM(message) {
let msgs = [
'Come on... I\'m not available here... \n https://media3.giphy.com/media/mfGYunx8bcWJy/giphy.gif',
'*sigh* Why did you PM me https://68.media.tumblr.com/d0238a0224ac18b47d1ac2fbbb6dd168/tumblr_nselfnnY3l1rpd9dfo1_250.gif',
'I don\'t work here ¯\\\_(ツ)_/¯ http://cloud-3.steamusercontent.com/ugc/576816221180356023/FF4FF60F13F2A773123B3B26A19935944480F510/'];
let msg = msgs[Math.floor(Math.random() * msgs.length)];
message.channel.send(msg);
}
process.on('unhandledRejection', console.dir); // Show stack trace on unhandled rejection.
// Log in. This should be the last call
bot.login(token);
|
let my server use reactionEval
|
bot.js
|
let my server use reactionEval
|
<ide><path>ot.js
<ide> let m = reaction.message;
<ide> if (user.bot) return;
<ide> if (m.channel.type != 'text') return;
<del> if (m.guild.id == '293787390710120449') return; // Ignore my server
<add> if (m.guild.id == '293787390710120449') {
<add> if (reaction.emoji.toString() == '▶️') {
<add> prcs.processors['REACTION'][0].process(reaction, user, true, bot.servers['189571157446492161'], bot);
<add> }
<add> return; // Ignore my server
<add> }
<ide> bot.servers[m.guild.id].processReaction(reaction, user, true, bot);
<ide> });
<ide>
<ide> let m = reaction.message;
<ide> if (user.bot) return;
<ide> if (m.channel.type != 'text') return;
<del> if (m.guild.id == '293787390710120449') return; // Ignore my server
<del> bot.servers[m.guild.id].processReaction(reaction, user, false, bot);
<add> if (m.guild.id == '293787390710120449') {
<add> if (reaction.emoji.toString() == '▶️') {
<add> prcs.processors['REACTION'][0].process(reaction, user, false, bot.servers['189571157446492161'], bot);
<add> }
<add> return; // Ignore my server
<add> } bot.servers[m.guild.id].processReaction(reaction, user, false, bot);
<ide> });
<ide>
<ide> bot.on('voiceStateUpdate', async (oldMember, newMember) => {
|
|
Java
|
mit
|
98753d2c994f41b8fc51cb34a56fb10d497bb5c3
| 0 |
davidfialho14/bgp-simulator
|
package network;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import policies.DummyAttribute;
import policies.DummyAttributeFactory;
import policies.DummyLabel;
import protocols.DummyProtocol;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class NodeTest {
@Mock
private Network mockNetwork;
@Mock
private DummyProtocol stubProtocol;
@Mock
private RouteTable stubRouteTable;
private DummyAttributeFactory attributeFactory = new DummyAttributeFactory();
private Node node;
private Node exportingNode;
private Node destination;
private Link outLink;
private Link inLink;
@Before
public void setUp() throws Exception {
when(mockNetwork.getAttrFactory()).thenReturn(new DummyAttributeFactory());
}
@After
public void tearDown() throws Exception {
reset(stubProtocol);
reset(stubRouteTable);
}
private void setNodeLinkedBothWaysWithANeighbourAndWithEmptyTable() {
node = new Node(mockNetwork, 0, this.stubProtocol);
node.startTable();
node.routeTable = stubRouteTable;
exportingNode = new Node(mockNetwork, 1, stubProtocol);
destination = new Node(mockNetwork, 2, stubProtocol);
outLink = new Link(node, exportingNode, new DummyLabel());
node.addOutLink(outLink);
inLink = new Link(exportingNode, node, new DummyLabel());
node.addInLink(inLink);
}
@Test
public void
learn_ValidRouteWhenNodeHasNoValidRouteForDestination_ExportsExtendedValidRoute()
throws Exception {
setNodeLinkedBothWaysWithANeighbourAndWithEmptyTable();
node.selectedAttributes.put(destination, attributeFactory.createInvalid());
node.selectedPaths.put(destination, PathAttribute.createInvalid());
Route learnedRoute = new Route(destination, new DummyAttribute(), new PathAttribute());
when(stubProtocol.extend(outLink, learnedRoute.getAttribute())).thenReturn(new DummyAttribute());
Route selectedRoute = Route.createInvalid(destination, attributeFactory);
when(stubRouteTable.getSelectedRoute(any(), any())).thenReturn(selectedRoute);
Route extendedRoute = new Route(destination, new DummyAttribute(), new PathAttribute(exportingNode));
node.learn(outLink, learnedRoute);
verify(mockNetwork).export(inLink, extendedRoute);
}
@Test
public void
learn_InvalidRouteWhenNodeHasNoValidRouteForDestination_ExportsIsNotCalled() throws Exception {
setNodeLinkedBothWaysWithANeighbourAndWithEmptyTable();
node.selectedAttributes.put(destination, attributeFactory.createInvalid());
node.selectedPaths.put(destination, PathAttribute.createInvalid());
Route learnedRoute = Route.createInvalid(destination, attributeFactory);
when(stubProtocol.extend(outLink, learnedRoute.getAttribute())).thenReturn(attributeFactory.createInvalid());
Route selectedRoute = Route.createInvalid(destination, attributeFactory);
when(stubRouteTable.getSelectedRoute(any(), any())).thenReturn(selectedRoute);
node.learn(outLink, learnedRoute);
verify(mockNetwork, never()).export(any(), any());
}
@Test
public void
learn_Route1FromNeighbour1ExtendsToRoutePreferredToCurrentSelectedRouteFromOtherNeighbour_ExportsExtendedRoute1()
throws Exception {
setNodeLinkedBothWaysWithANeighbourAndWithEmptyTable();
Route selectedRoute = new Route(destination, new DummyAttribute(0), new PathAttribute());
node.selectedAttributes.put(destination, selectedRoute.getAttribute());
node.selectedPaths.put(destination, selectedRoute.getPath());
Route learnedRoute = new Route(destination, new DummyAttribute(), new PathAttribute());
Attribute extendedAttribute = new DummyAttribute(1);
when(stubProtocol.extend(outLink, learnedRoute.getAttribute())).thenReturn(extendedAttribute);
when(stubRouteTable.getSelectedRoute(any(), any())).thenReturn(selectedRoute);
Route extendedRoute = new Route(destination, extendedAttribute, new PathAttribute(exportingNode));
node.learn(outLink, learnedRoute);
verify(mockNetwork).export(inLink, extendedRoute);
}
@Test
public void
learn_Route1FromNeighbour1ExtendsToRouteNotPreferredToCurrentSelectedRouteFromOtherNeighbour_ExportsNotCalled()
throws Exception {
setNodeLinkedBothWaysWithANeighbourAndWithEmptyTable();
Route selectedRoute = new Route(destination, new DummyAttribute(1), new PathAttribute());
node.selectedAttributes.put(destination, selectedRoute.getAttribute());
node.selectedPaths.put(destination, selectedRoute.getPath());
Route learnedRoute = new Route(destination, new DummyAttribute(), new PathAttribute());
Attribute extendedAttribute = new DummyAttribute(0);
when(stubProtocol.extend(outLink, learnedRoute.getAttribute())).thenReturn(extendedAttribute);
when(stubRouteTable.getSelectedRoute(any(), any())).thenReturn(selectedRoute);
node.learn(outLink, learnedRoute);
verify(mockNetwork, never()).export(any(), any());
}
// TODO last two test but for same neighbour
// TODO learns route that extends to invalid route -> not exported
}
|
test/network/NodeTest.java
|
package network;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import policies.DummyAttribute;
import policies.DummyAttributeFactory;
import policies.DummyLabel;
import protocols.DummyProtocol;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class NodeTest {
@Mock
private Network mockNetwork;
@Mock
private DummyProtocol stubProtocol;
@Mock
private RouteTable stubRouteTable;
private DummyAttributeFactory attributeFactory = new DummyAttributeFactory();
private Node node;
private Node exportingNode;
private Node destination;
private Link outLink;
private Link inLink;
@Before
public void setUp() throws Exception {
when(mockNetwork.getAttrFactory()).thenReturn(new DummyAttributeFactory());
}
@After
public void tearDown() throws Exception {
reset(stubProtocol);
reset(stubRouteTable);
}
private void setNodeLinkedBothWaysWithANeighbourAndWithEmptyTable() {
node = new Node(mockNetwork, 0, this.stubProtocol);
node.startTable();
node.routeTable = stubRouteTable;
exportingNode = new Node(mockNetwork, 1, stubProtocol);
destination = new Node(mockNetwork, 2, stubProtocol);
outLink = new Link(node, exportingNode, new DummyLabel());
node.addOutLink(outLink);
inLink = new Link(exportingNode, node, new DummyLabel());
node.addInLink(inLink);
}
@Test
public void
learn_ValidRouteWhenNodeHasNoValidRouteForDestination_ExportsExtendedValidRoute()
throws Exception {
setNodeLinkedBothWaysWithANeighbourAndWithEmptyTable();
node.selectedAttributes.put(destination, attributeFactory.createInvalid());
node.selectedPaths.put(destination, PathAttribute.createInvalid());
Route learnedRoute = new Route(destination, new DummyAttribute(), new PathAttribute());
when(stubProtocol.extend(outLink, learnedRoute.getAttribute())).thenReturn(new DummyAttribute());
Route selectedRoute = Route.createInvalid(destination, attributeFactory);
when(stubRouteTable.getSelectedRoute(destination, exportingNode)).thenReturn(selectedRoute);
Route extendedRoute = new Route(destination, new DummyAttribute(), new PathAttribute(exportingNode));
node.learn(outLink, learnedRoute);
verify(mockNetwork).export(inLink, extendedRoute);
}
@Test
public void
learn_InvalidRouteWhenNodeHasNoValidRouteForDestination_ExportsIsNotCalled() throws Exception {
setNodeLinkedBothWaysWithANeighbourAndWithEmptyTable();
node.selectedAttributes.put(destination, attributeFactory.createInvalid());
node.selectedPaths.put(destination, PathAttribute.createInvalid());
Route learnedRoute = Route.createInvalid(destination, attributeFactory);
when(stubProtocol.extend(outLink, learnedRoute.getAttribute())).thenReturn(attributeFactory.createInvalid());
Route selectedRoute = Route.createInvalid(destination, attributeFactory);
when(stubRouteTable.getSelectedRoute(any(), any())).thenReturn(selectedRoute);
node.learn(outLink, learnedRoute);
verify(mockNetwork, never()).export(any(), any());
}
// TODO learns route not preferred -> does not export
}
|
added two new tests for the learn method
|
test/network/NodeTest.java
|
added two new tests for the learn method
|
<ide><path>est/network/NodeTest.java
<ide> Route learnedRoute = new Route(destination, new DummyAttribute(), new PathAttribute());
<ide> when(stubProtocol.extend(outLink, learnedRoute.getAttribute())).thenReturn(new DummyAttribute());
<ide> Route selectedRoute = Route.createInvalid(destination, attributeFactory);
<del> when(stubRouteTable.getSelectedRoute(destination, exportingNode)).thenReturn(selectedRoute);
<add> when(stubRouteTable.getSelectedRoute(any(), any())).thenReturn(selectedRoute);
<ide>
<ide> Route extendedRoute = new Route(destination, new DummyAttribute(), new PathAttribute(exportingNode));
<ide> node.learn(outLink, learnedRoute);
<ide> verify(mockNetwork, never()).export(any(), any());
<ide> }
<ide>
<del> // TODO learns route not preferred -> does not export
<add> @Test
<add> public void
<add> learn_Route1FromNeighbour1ExtendsToRoutePreferredToCurrentSelectedRouteFromOtherNeighbour_ExportsExtendedRoute1()
<add> throws Exception {
<add> setNodeLinkedBothWaysWithANeighbourAndWithEmptyTable();
<add> Route selectedRoute = new Route(destination, new DummyAttribute(0), new PathAttribute());
<add> node.selectedAttributes.put(destination, selectedRoute.getAttribute());
<add> node.selectedPaths.put(destination, selectedRoute.getPath());
<add> Route learnedRoute = new Route(destination, new DummyAttribute(), new PathAttribute());
<add> Attribute extendedAttribute = new DummyAttribute(1);
<add> when(stubProtocol.extend(outLink, learnedRoute.getAttribute())).thenReturn(extendedAttribute);
<add> when(stubRouteTable.getSelectedRoute(any(), any())).thenReturn(selectedRoute);
<add>
<add> Route extendedRoute = new Route(destination, extendedAttribute, new PathAttribute(exportingNode));
<add> node.learn(outLink, learnedRoute);
<add>
<add> verify(mockNetwork).export(inLink, extendedRoute);
<add> }
<add>
<add> @Test
<add> public void
<add> learn_Route1FromNeighbour1ExtendsToRouteNotPreferredToCurrentSelectedRouteFromOtherNeighbour_ExportsNotCalled()
<add> throws Exception {
<add> setNodeLinkedBothWaysWithANeighbourAndWithEmptyTable();
<add> Route selectedRoute = new Route(destination, new DummyAttribute(1), new PathAttribute());
<add> node.selectedAttributes.put(destination, selectedRoute.getAttribute());
<add> node.selectedPaths.put(destination, selectedRoute.getPath());
<add> Route learnedRoute = new Route(destination, new DummyAttribute(), new PathAttribute());
<add> Attribute extendedAttribute = new DummyAttribute(0);
<add> when(stubProtocol.extend(outLink, learnedRoute.getAttribute())).thenReturn(extendedAttribute);
<add> when(stubRouteTable.getSelectedRoute(any(), any())).thenReturn(selectedRoute);
<add>
<add> node.learn(outLink, learnedRoute);
<add>
<add> verify(mockNetwork, never()).export(any(), any());
<add> }
<add>
<add> // TODO last two test but for same neighbour
<add> // TODO learns route that extends to invalid route -> not exported
<ide>
<ide> }
|
|
Java
|
apache-2.0
|
c64c2654bd2acfee6fdf3bebaab9faf0b43ace48
| 0 |
babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble
|
// PHPConvertor.java
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ed.lang.php;
import java.lang.reflect.*;
import java.util.*;
import javax.script.*;
import ed.util.*;
import ed.lang.*;
import ed.js.*;
import ed.js.engine.*;
import com.caucho.quercus.*;
import com.caucho.quercus.env.*;
import com.caucho.quercus.expr.*;
import com.caucho.quercus.script.*;
import com.caucho.quercus.module.*;
import com.caucho.quercus.function.*;
import com.caucho.quercus.program.*;
public class PHPConvertor extends Value implements ObjectConvertor {
PHPConvertor( Env env ){
_env = env;
_moduleContext = env.getModuleContext();
_marshalFactory = _moduleContext.getMarshalFactory();
}
public Object[] toJS( Value[] values ){
Object[] js = new Object[values.length];
for ( int i=0; i<values.length; i++ )
js[i] = toJS( values[i] );
return js;
}
public Object toJS( Object o ){
if ( o == null || o instanceof NullValue )
return null;
if ( o instanceof Value )
o = ((Value)o).toJavaObject();
if ( o instanceof Expr )
o = _getMarshal( o ).marshal( _env , (Expr)o , o.getClass() );
if ( o instanceof JSObject )
return o;
if ( o instanceof String || o instanceof StringValue || o instanceof StringBuilderValue )
return new JSString( o.toString() );
if ( o instanceof Number || o instanceof Boolean )
return o;
if ( o instanceof NumberValue || o instanceof BooleanValue )
return ((Value)o).toJavaObject();
if ( o instanceof ArrayValue )
return new PHPWrapper( this , (Value) o );
if ( o instanceof ed.db.ObjectId )
return o;
throw new RuntimeException( "don't know what to do with : " + o.getClass().getName() + " : " + o );
}
public Value toPHP( Object o ){
return (Value)toOther( o );
}
public Object toOther( Object o ){
if ( o == null )
return null; // TODO: should this be NullValue
if( o instanceof PHPWrapper)
return ((PHPWrapper) o)._value;
if ( o instanceof JSString )
o = o.toString();
checkConfigged( o );
if ( o instanceof JSObject )
return _getClassDef( o.getClass() ).wrap( _env , o );
return _getMarshal( o ).unmarshal( _env , o );
}
void checkConfigged( Object o ){
checkConfigged( o , true );
}
void checkConfigged( Object o , boolean tryAgain ){
if ( ! ( o instanceof JSObject ) )
return;
Class c = o.getClass();
if ( _configged.contains( c ) )
return;
JavaClassDef def = null;
try {
if ( PHP.DEBUG ) System.out.println( "Adding for : " + c.getName() );
def = _moduleContext.addClass( c.getName() , c , null , PHPJSObjectClassDef.class );
}
catch ( Exception e ){
throw new RuntimeException( "internal error : " + c.getClass() , e );
}
if ( def instanceof PHPJSObjectClassDef ){
_configged.add( c );
return;
}
if ( ! tryAgain )
throw new RuntimeException( "someone got in ahead of me and i can't recover" );
try {
Map m = (Map)(PHP.getField( _moduleContext , "_javaClassWrappers" ));
m.remove( c.getName() );
m.remove( c.getName().toLowerCase() );
checkConfigged( o , false );
}
catch( Exception e ){
throw new RuntimeException( "someone got in ahead of me and i can't recover" , e );
}
}
private Marshal _getMarshal( Object o ){
Class c = o.getClass();
Marshal m = _cache.get( c );
if ( m == null ){
m = _marshalFactory.create( c );
_cache.put( c , m );
}
return m;
}
PHPJSObjectClassDef _getClassDef( Class c ){
PHPJSObjectClassDef def = _defCache.get( c );
if ( def == null ){
def = new PHPJSObjectClassDef( _moduleContext , c.getName() , c );
_defCache.put( c , def );
}
return def;
}
final Env _env;
final ModuleContext _moduleContext;
final MarshalFactory _marshalFactory;
final Map<Class,Marshal> _cache = new HashMap<Class,Marshal>();
final IdentitySet<Class> _configged = new IdentitySet<Class>();
final Map<Class,PHPJSObjectClassDef> _defCache = new HashMap<Class,PHPJSObjectClassDef>();
}
|
src/main/ed/lang/php/PHPConvertor.java
|
// PHPConvertor.java
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ed.lang.php;
import java.lang.reflect.*;
import java.util.*;
import javax.script.*;
import ed.util.*;
import ed.lang.*;
import ed.js.*;
import ed.js.engine.*;
import com.caucho.quercus.*;
import com.caucho.quercus.env.*;
import com.caucho.quercus.expr.*;
import com.caucho.quercus.script.*;
import com.caucho.quercus.module.*;
import com.caucho.quercus.function.*;
import com.caucho.quercus.program.*;
public class PHPConvertor extends Value implements ObjectConvertor {
PHPConvertor( Env env ){
_env = env;
_moduleContext = env.getModuleContext();
_marshalFactory = _moduleContext.getMarshalFactory();
}
public Object[] toJS( Value[] values ){
Object[] js = new Object[values.length];
for ( int i=0; i<values.length; i++ )
js[i] = toJS( values[i] );
return js;
}
public Object toJS( Object o ){
if ( o == null || o instanceof NullValue )
return null;
if ( o instanceof Value )
o = ((Value)o).toJavaObject();
if ( o instanceof Expr )
o = _getMarshal( o ).marshal( _env , (Expr)o , o.getClass() );
if ( o instanceof JSObject )
return o;
if ( o instanceof String || o instanceof StringValue || o instanceof StringBuilderValue )
return new JSString( o.toString() );
if ( o instanceof Number || o instanceof Boolean )
return o;
if ( o instanceof NumberValue || o instanceof BooleanValue )
return ((Value)o).toJavaObject();
if ( o instanceof ArrayValue )
return new PHPWrapper( this , (Value) o );
if ( o instanceof ed.db.ObjectId )
return o;
throw new RuntimeException( "don't know what to do with : " + o.getClass().getName() + " : " + o );
}
public Value toPHP( Object o ){
return (Value)toOther( o );
}
public Object toOther( Object o ){
if ( o == null )
return null; // TODO: should this be NullValue
if ( o instanceof JSString )
o = o.toString();
checkConfigged( o );
if ( o instanceof JSObject )
return _getClassDef( o.getClass() ).wrap( _env , o );
return _getMarshal( o ).unmarshal( _env , o );
}
void checkConfigged( Object o ){
checkConfigged( o , true );
}
void checkConfigged( Object o , boolean tryAgain ){
if ( ! ( o instanceof JSObject ) )
return;
Class c = o.getClass();
if ( _configged.contains( c ) )
return;
JavaClassDef def = null;
try {
if ( PHP.DEBUG ) System.out.println( "Adding for : " + c.getName() );
def = _moduleContext.addClass( c.getName() , c , null , PHPJSObjectClassDef.class );
}
catch ( Exception e ){
throw new RuntimeException( "internal error : " + c.getClass() , e );
}
if ( def instanceof PHPJSObjectClassDef ){
_configged.add( c );
return;
}
if ( ! tryAgain )
throw new RuntimeException( "someone got in ahead of me and i can't recover" );
try {
Map m = (Map)(PHP.getField( _moduleContext , "_javaClassWrappers" ));
m.remove( c.getName() );
m.remove( c.getName().toLowerCase() );
checkConfigged( o , false );
}
catch( Exception e ){
throw new RuntimeException( "someone got in ahead of me and i can't recover" , e );
}
}
private Marshal _getMarshal( Object o ){
Class c = o.getClass();
Marshal m = _cache.get( c );
if ( m == null ){
m = _marshalFactory.create( c );
_cache.put( c , m );
}
return m;
}
PHPJSObjectClassDef _getClassDef( Class c ){
PHPJSObjectClassDef def = _defCache.get( c );
if ( def == null ){
def = new PHPJSObjectClassDef( _moduleContext , c.getName() , c );
_defCache.put( c , def );
}
return def;
}
final Env _env;
final ModuleContext _moduleContext;
final MarshalFactory _marshalFactory;
final Map<Class,Marshal> _cache = new HashMap<Class,Marshal>();
final IdentitySet<Class> _configged = new IdentitySet<Class>();
final Map<Class,PHPJSObjectClassDef> _defCache = new HashMap<Class,PHPJSObjectClassDef>();
}
|
prevent double wrapping
|
src/main/ed/lang/php/PHPConvertor.java
|
prevent double wrapping
|
<ide><path>rc/main/ed/lang/php/PHPConvertor.java
<ide> if ( o == null )
<ide> return null; // TODO: should this be NullValue
<ide>
<add> if( o instanceof PHPWrapper)
<add> return ((PHPWrapper) o)._value;
<add>
<ide> if ( o instanceof JSString )
<ide> o = o.toString();
<ide>
|
|
Java
|
apache-2.0
|
eb0604df9138ab39a6d73698c10c222de8388e39
| 0 |
EsupPortail/esup-publisher,GIP-RECIA/esup-publisher-ui,EsupPortail/esup-publisher,GIP-RECIA/esup-publisher-ui,GIP-RECIA/esup-publisher-ui,EsupPortail/esup-publisher,EsupPortail/esup-publisher
|
package org.esupportail.publisher.config;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.esupportail.publisher.domain.enums.OperatorType;
import org.esupportail.publisher.domain.enums.StringEvaluationMode;
import org.esupportail.publisher.security.AjaxAuthenticationFailureHandler;
import org.esupportail.publisher.security.AjaxAuthenticationSuccessHandler;
import org.esupportail.publisher.security.AjaxLogoutSuccessHandler;
import org.esupportail.publisher.security.AuthoritiesConstants;
import org.esupportail.publisher.security.CustomSessionFixationProtectionStrategy;
import org.esupportail.publisher.security.CustomSingleSignOutFilter;
import org.esupportail.publisher.security.RememberCasAuthenticationEntryPoint;
import org.esupportail.publisher.security.RememberCasAuthenticationProvider;
import org.esupportail.publisher.security.RememberWebAuthenticationDetailsSource;
import org.esupportail.publisher.service.bean.AuthoritiesDefinition;
import org.esupportail.publisher.service.bean.IAuthoritiesDefinition;
import org.esupportail.publisher.service.bean.IpVariableHolder;
import org.esupportail.publisher.service.bean.ServiceUrlHelper;
import org.esupportail.publisher.service.evaluators.IEvaluation;
import org.esupportail.publisher.service.evaluators.OperatorEvaluation;
import org.esupportail.publisher.service.evaluators.UserAttributesEvaluation;
import org.esupportail.publisher.service.evaluators.UserMultivaluedAttributesEvaluation;
import org.esupportail.publisher.web.filter.CsrfCookieGeneratorFilter;
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.util.Assert;
@Configuration
@EnableWebMvcSecurity
@EnableWebSecurity
@Slf4j
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String CAS_URL_LOGIN = "cas.url.login";
private static final String CAS_URL_LOGOUT = "cas.url.logout";
private static final String CAS_URL_PREFIX = "cas.url.prefix";
private static final String CAS_SERVICE_URI = "app.service.security";
private static final String CAS_SERVICE_KEY = "app.service.idKeyProvider";
private static final String CAS_SERVICE_SERVERNAMES = "app.service.authorizedDomainNames";
private static final String APP_SERVICE_REDIRECTPARAM = "app.service.redirectParamName";
private static final String APP_URI_LOGIN = "/app/login";
private static final String APP_ADMIN_USER_NAME = "app.admin.userName";
private static final String APP_ADMIN_GROUP_NAME = "app.admin.groupName";
private static final String APP_USERS_GROUP_NAME = "app.users.groupName";
private static final String APP_CONTEXT_PATH = "server.contextPath";
private static final String APP_PROTOCOL = "app.service.protocol";
private static final String DefaultTargetUrlParameter = "spring-security-redirect";
@Inject
private Environment env;
@Inject
private AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler;
@Inject
private AjaxAuthenticationFailureHandler ajaxAuthenticationFailureHandler;
@Inject
private AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;
// @Inject
// private Http401UnauthorizedEntryPoint authenticationEntryPoint;
@Inject
private AuthenticationUserDetailsService<CasAssertionAuthenticationToken> userDetailsService;
@Inject
private IpVariableHolder ipVariableHolder;
// @Inject
// private RememberMeServices rememberMeServices;
// @Bean
// public PasswordEncoder passwordEncoder() {
// return new BCryptPasswordEncoder();
// }
/*@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.enable(S)
jsonConverter.setObjectMapper(objectMapper);
return jsonConverter;
}*/
@Bean
public IAuthoritiesDefinition mainRolesDefs() {
Assert.notNull(env);
AuthoritiesDefinition defs = new AuthoritiesDefinition();
Set<IEvaluation> set = new HashSet<IEvaluation>();
final String userAdmin = env.getProperty(APP_ADMIN_USER_NAME);
if (userAdmin != null && !userAdmin.isEmpty()) {
final UserAttributesEvaluation uae1 = new UserAttributesEvaluation("uid", userAdmin, StringEvaluationMode.EQUALS);
set.add(uae1);
}
final String groupAdmin = env.getProperty(APP_ADMIN_GROUP_NAME);
if (groupAdmin != null && !groupAdmin.isEmpty()) {
final UserAttributesEvaluation uae2 = new UserMultivaluedAttributesEvaluation("isMemberOf", groupAdmin, StringEvaluationMode.EQUALS);
set.add(uae2);
}
Assert.isTrue(set.size() > 0, "Properties '" + APP_ADMIN_USER_NAME + "' or '" + APP_ADMIN_GROUP_NAME
+ "' aren't defined in properties, there are needed to define an Admin user");
OperatorEvaluation admins = new OperatorEvaluation(OperatorType.OR, set);
defs.setAdmins(admins);
final String groupUsers = env.getProperty(APP_USERS_GROUP_NAME);
UserMultivaluedAttributesEvaluation umae = new UserMultivaluedAttributesEvaluation("isMemberOf", groupUsers, StringEvaluationMode.MATCH);
defs.setUsers(umae);
return defs;
}
@Bean
public ServiceProperties serviceProperties() {
ServiceProperties sp = new ServiceProperties();
sp.setService(env.getRequiredProperty(CAS_SERVICE_URI));
sp.setSendRenew(false);
sp.setAuthenticateAllArtifacts(true);
return sp;
}
@Bean
public ServiceUrlHelper serviceUrlHelper() {
String ctxPath = env.getRequiredProperty(APP_CONTEXT_PATH);
if (!ctxPath.startsWith("/")) ctxPath = "/" + ctxPath;
final String protocol = env.getRequiredProperty(APP_PROTOCOL);
//final List<String> domainName = Lists.newArrayList(env.getRequiredProperty(CAS_SERVICE_SERVERNAMES).replaceAll(",//s", ",").split(","));
List<String> validCasServerHosts = new ArrayList<>();
for (String ending : StringUtils.split(env.getRequiredProperty(CAS_SERVICE_SERVERNAMES), ",")) {
if (StringUtils.isNotBlank(ending)){
validCasServerHosts.add(StringUtils.trim(ending));
}
}
ServiceUrlHelper serviceUrlHelper = new ServiceUrlHelper(ctxPath, validCasServerHosts, protocol, "/view/item/");
log.info("ServiceUrlHelper is configured with properties : {}", serviceUrlHelper.toString());
return serviceUrlHelper;
}
@Bean String getCasTargetUrlParameter() {
return env.getProperty(APP_SERVICE_REDIRECTPARAM, DefaultTargetUrlParameter);
}
@Bean
public SimpleUrlAuthenticationSuccessHandler authenticationSuccessHandler() {
SimpleUrlAuthenticationSuccessHandler authenticationSuccessHandler = new SimpleUrlAuthenticationSuccessHandler();
authenticationSuccessHandler.setDefaultTargetUrl("/");
authenticationSuccessHandler.setTargetUrlParameter(getCasTargetUrlParameter());
return authenticationSuccessHandler;
}
@Bean
public RememberCasAuthenticationProvider casAuthenticationProvider() {
RememberCasAuthenticationProvider casAuthenticationProvider = new RememberCasAuthenticationProvider();
casAuthenticationProvider.setAuthenticationUserDetailsService(userDetailsService);
casAuthenticationProvider.setServiceProperties(serviceProperties());
casAuthenticationProvider.setTicketValidator(cas20ServiceTicketValidator());
casAuthenticationProvider.setKey(env.getRequiredProperty(CAS_SERVICE_KEY));
return casAuthenticationProvider;
}
@Bean
public SessionAuthenticationStrategy sessionStrategy() {
SessionFixationProtectionStrategy sessionStrategy = new CustomSessionFixationProtectionStrategy(
serviceUrlHelper(), serviceProperties(), getCasTargetUrlParameter());
sessionStrategy.setMigrateSessionAttributes(false);
return sessionStrategy;
}
@Bean
public Cas20ServiceTicketValidator cas20ServiceTicketValidator() {
return new Cas20ServiceTicketValidator(env.getRequiredProperty(CAS_URL_PREFIX));
}
@Bean
public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter();
casAuthenticationFilter.setAuthenticationManager(authenticationManager());
casAuthenticationFilter.setAuthenticationDetailsSource(new RememberWebAuthenticationDetailsSource(
serviceUrlHelper(), serviceProperties(), getCasTargetUrlParameter()));
casAuthenticationFilter.setSessionAuthenticationStrategy(sessionStrategy());
casAuthenticationFilter.setAuthenticationFailureHandler(ajaxAuthenticationFailureHandler);
casAuthenticationFilter.setAuthenticationSuccessHandler(ajaxAuthenticationSuccessHandler);
// casAuthenticationFilter.setRequiresAuthenticationRequestMatcher(new
// AntPathRequestMatcher("/login", "GET"));
return casAuthenticationFilter;
}
@Bean
public RememberCasAuthenticationEntryPoint casAuthenticationEntryPoint() {
RememberCasAuthenticationEntryPoint casAuthenticationEntryPoint = new RememberCasAuthenticationEntryPoint();
casAuthenticationEntryPoint.setLoginUrl(env.getRequiredProperty(CAS_URL_LOGIN));
casAuthenticationEntryPoint.setServiceProperties(serviceProperties());
casAuthenticationEntryPoint.setUrlHelper(serviceUrlHelper());
//move to /app/login due to cachebuster instead of api/authenticate
casAuthenticationEntryPoint.setPathLogin(APP_URI_LOGIN);
return casAuthenticationEntryPoint;
}
@Bean
public CustomSingleSignOutFilter singleSignOutFilter() {
CustomSingleSignOutFilter singleSignOutFilter = new CustomSingleSignOutFilter();
singleSignOutFilter.setCasServerUrlPrefix(env.getRequiredProperty(CAS_URL_PREFIX));
return singleSignOutFilter;
}
@Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(casAuthenticationProvider());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/scripts/**/*.{js,html}").antMatchers("/bower_components/**")
.antMatchers("/i18n/**").antMatchers("/assets/**").antMatchers("/swagger-ui/**")
.antMatchers("/test/**").antMatchers("/console/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class).exceptionHandling()
.authenticationEntryPoint(casAuthenticationEntryPoint()).and()
.addFilterBefore(casAuthenticationFilter(), BasicAuthenticationFilter.class)
.addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class);
// .and()
// .rememberMe()
// .rememberMeServices(rememberMeServices)
// .key(env.getProperty("jhipster.security.rememberme.key"))
// .and()
// .formLogin()
// .loginProcessingUrl("/api/authentication")
// .successHandler(ajaxAuthenticationSuccessHandler)
// .failureHandler(ajaxAuthenticationFailureHandler)
// .usernameParameter("j_username")
// .passwordParameter("j_password")
// .permitAll()
http
.headers()
.frameOptions()
.disable()
.authorizeRequests()
.antMatchers("/app/**").authenticated()
.antMatchers("/published/**").access("hasRole('" + AuthoritiesConstants.ANONYMOUS + "') and (hasIpAddress('" + ipVariableHolder.getIpRange()
+ "') or hasIpAddress('127.0.0.1/32') or hasIpAddress('::1'))")
.antMatchers("/api/register").denyAll()
.antMatchers("/api/activate").denyAll()
.antMatchers("/api/authenticate").denyAll()
.antMatchers("/api/logs/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/api/enums/**").permitAll()
.antMatchers("/api/conf/**").permitAll()
.antMatchers("/api/**").hasAuthority(AuthoritiesConstants.USER)
.antMatchers("/metrics/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/health/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/dump/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/shutdown/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/beans/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/configprops/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/info/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/autoconfig/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/env/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/api-docs/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/protected/**").authenticated()
.antMatchers("/view/**").permitAll();
http
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler)
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll();
}
/**
* This allows SpEL support in Spring Data JPA @Query definitions.
*
* See https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions
*/
/*@Bean
EvaluationContextExtension securityExtension() {
return new EvaluationContextExtensionSupport() {
@Override
public String getExtensionId() {
return "security";
}
@Override
public SecurityExpressionRoot getRootObject() {
SecurityExpressionRoot ser = new SecurityExpressionRoot(SecurityContextHolder.getContext().getAuthentication()) {};
ser.setPermissionEvaluator(permissionEvaluator());
ser.setRoleHierarchy(roleHierarchy());
return ser;
}
};
}*/
}
|
src/main/java/org/esupportail/publisher/config/SecurityConfiguration.java
|
package org.esupportail.publisher.config;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.esupportail.publisher.domain.enums.OperatorType;
import org.esupportail.publisher.domain.enums.StringEvaluationMode;
import org.esupportail.publisher.security.AjaxAuthenticationFailureHandler;
import org.esupportail.publisher.security.AjaxAuthenticationSuccessHandler;
import org.esupportail.publisher.security.AjaxLogoutSuccessHandler;
import org.esupportail.publisher.security.AuthoritiesConstants;
import org.esupportail.publisher.security.CustomSessionFixationProtectionStrategy;
import org.esupportail.publisher.security.CustomSingleSignOutFilter;
import org.esupportail.publisher.security.RememberCasAuthenticationEntryPoint;
import org.esupportail.publisher.security.RememberCasAuthenticationProvider;
import org.esupportail.publisher.security.RememberWebAuthenticationDetailsSource;
import org.esupportail.publisher.service.bean.AuthoritiesDefinition;
import org.esupportail.publisher.service.bean.IAuthoritiesDefinition;
import org.esupportail.publisher.service.bean.IpVariableHolder;
import org.esupportail.publisher.service.bean.ServiceUrlHelper;
import org.esupportail.publisher.service.evaluators.IEvaluation;
import org.esupportail.publisher.service.evaluators.OperatorEvaluation;
import org.esupportail.publisher.service.evaluators.UserAttributesEvaluation;
import org.esupportail.publisher.service.evaluators.UserMultivaluedAttributesEvaluation;
import org.esupportail.publisher.web.filter.CsrfCookieGeneratorFilter;
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.util.Assert;
@Configuration
@EnableWebMvcSecurity
@EnableWebSecurity
@Slf4j
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String CAS_URL_LOGIN = "cas.url.login";
private static final String CAS_URL_LOGOUT = "cas.url.logout";
private static final String CAS_URL_PREFIX = "cas.url.prefix";
private static final String CAS_SERVICE_URI = "app.service.security";
private static final String CAS_SERVICE_KEY = "app.service.idKeyProvider";
private static final String CAS_SERVICE_SERVERNAMES = "app.service.authorizedDomainNames";
private static final String APP_SERVICE_REDIRECTPARAM = "app.service.redirectParamName";
private static final String APP_URI_LOGIN = "/app/login";
private static final String APP_ADMIN_USER_NAME = "app.admin.userName";
private static final String APP_ADMIN_GROUP_NAME = "app.admin.groupName";
private static final String APP_CONTEXT_PATH = "server.contextPath";
private static final String APP_PROTOCOL = "app.service.protocol";
private static final String DefaultTargetUrlParameter = "spring-security-redirect";
@Inject
private Environment env;
@Inject
private AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler;
@Inject
private AjaxAuthenticationFailureHandler ajaxAuthenticationFailureHandler;
@Inject
private AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;
// @Inject
// private Http401UnauthorizedEntryPoint authenticationEntryPoint;
@Inject
private AuthenticationUserDetailsService<CasAssertionAuthenticationToken> userDetailsService;
@Inject
private IpVariableHolder ipVariableHolder;
// @Inject
// private RememberMeServices rememberMeServices;
// @Bean
// public PasswordEncoder passwordEncoder() {
// return new BCryptPasswordEncoder();
// }
/*@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.enable(S)
jsonConverter.setObjectMapper(objectMapper);
return jsonConverter;
}*/
@Bean
public IAuthoritiesDefinition mainRolesDefs() {
Assert.notNull(env);
AuthoritiesDefinition defs = new AuthoritiesDefinition();
Set<IEvaluation> set = new HashSet<IEvaluation>();
final String userAdmin = env.getProperty(APP_ADMIN_USER_NAME);
if (userAdmin != null && !userAdmin.isEmpty()) {
final UserAttributesEvaluation uae1 = new UserAttributesEvaluation("uid", userAdmin, StringEvaluationMode.EQUALS);
set.add(uae1);
}
final String groupAdmin = env.getProperty(APP_ADMIN_GROUP_NAME);
if (groupAdmin != null && !groupAdmin.isEmpty()) {
final UserAttributesEvaluation uae2 = new UserMultivaluedAttributesEvaluation("isMemberOf", groupAdmin, StringEvaluationMode.EQUALS);
set.add(uae2);
}
Assert.isTrue(set.size() > 0, "Properties '" + APP_ADMIN_USER_NAME + "' or '" + APP_ADMIN_GROUP_NAME
+ "' aren't defined in properties, there are needed to define an Admin user");
OperatorEvaluation admins = new OperatorEvaluation(OperatorType.OR, set);
defs.setAdmins(admins);
UserMultivaluedAttributesEvaluation umae = new UserMultivaluedAttributesEvaluation("isMemberOf",
"((esco)|(cfa)|(clg37)|(agri)|(coll)):Applications:((Publisher)|(Publication_annonces)):.*",
StringEvaluationMode.MATCH);
defs.setUsers(umae);
return defs;
}
@Bean
public ServiceProperties serviceProperties() {
ServiceProperties sp = new ServiceProperties();
sp.setService(env.getRequiredProperty(CAS_SERVICE_URI));
sp.setSendRenew(false);
sp.setAuthenticateAllArtifacts(true);
return sp;
}
@Bean
public ServiceUrlHelper serviceUrlHelper() {
String ctxPath = env.getRequiredProperty(APP_CONTEXT_PATH);
if (!ctxPath.startsWith("/")) ctxPath = "/" + ctxPath;
final String protocol = env.getRequiredProperty(APP_PROTOCOL);
//final List<String> domainName = Lists.newArrayList(env.getRequiredProperty(CAS_SERVICE_SERVERNAMES).replaceAll(",//s", ",").split(","));
List<String> validCasServerHosts = new ArrayList<>();
for (String ending : StringUtils.split(env.getRequiredProperty(CAS_SERVICE_SERVERNAMES), ",")) {
if (StringUtils.isNotBlank(ending)){
validCasServerHosts.add(StringUtils.trim(ending));
}
}
ServiceUrlHelper serviceUrlHelper = new ServiceUrlHelper(ctxPath, validCasServerHosts, protocol, "/view/item/");
log.info("ServiceUrlHelper is configured with properties : {}", serviceUrlHelper.toString());
return serviceUrlHelper;
}
@Bean String getCasTargetUrlParameter() {
return env.getProperty(APP_SERVICE_REDIRECTPARAM, DefaultTargetUrlParameter);
}
@Bean
public SimpleUrlAuthenticationSuccessHandler authenticationSuccessHandler() {
SimpleUrlAuthenticationSuccessHandler authenticationSuccessHandler = new SimpleUrlAuthenticationSuccessHandler();
authenticationSuccessHandler.setDefaultTargetUrl("/");
authenticationSuccessHandler.setTargetUrlParameter(getCasTargetUrlParameter());
return authenticationSuccessHandler;
}
@Bean
public RememberCasAuthenticationProvider casAuthenticationProvider() {
RememberCasAuthenticationProvider casAuthenticationProvider = new RememberCasAuthenticationProvider();
casAuthenticationProvider.setAuthenticationUserDetailsService(userDetailsService);
casAuthenticationProvider.setServiceProperties(serviceProperties());
casAuthenticationProvider.setTicketValidator(cas20ServiceTicketValidator());
casAuthenticationProvider.setKey(env.getRequiredProperty(CAS_SERVICE_KEY));
return casAuthenticationProvider;
}
@Bean
public SessionAuthenticationStrategy sessionStrategy() {
SessionFixationProtectionStrategy sessionStrategy = new CustomSessionFixationProtectionStrategy(
serviceUrlHelper(), serviceProperties(), getCasTargetUrlParameter());
sessionStrategy.setMigrateSessionAttributes(false);
return sessionStrategy;
}
@Bean
public Cas20ServiceTicketValidator cas20ServiceTicketValidator() {
return new Cas20ServiceTicketValidator(env.getRequiredProperty(CAS_URL_PREFIX));
}
@Bean
public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter();
casAuthenticationFilter.setAuthenticationManager(authenticationManager());
casAuthenticationFilter.setAuthenticationDetailsSource(new RememberWebAuthenticationDetailsSource(
serviceUrlHelper(), serviceProperties(), getCasTargetUrlParameter()));
casAuthenticationFilter.setSessionAuthenticationStrategy(sessionStrategy());
casAuthenticationFilter.setAuthenticationFailureHandler(ajaxAuthenticationFailureHandler);
casAuthenticationFilter.setAuthenticationSuccessHandler(ajaxAuthenticationSuccessHandler);
// casAuthenticationFilter.setRequiresAuthenticationRequestMatcher(new
// AntPathRequestMatcher("/login", "GET"));
return casAuthenticationFilter;
}
@Bean
public RememberCasAuthenticationEntryPoint casAuthenticationEntryPoint() {
RememberCasAuthenticationEntryPoint casAuthenticationEntryPoint = new RememberCasAuthenticationEntryPoint();
casAuthenticationEntryPoint.setLoginUrl(env.getRequiredProperty(CAS_URL_LOGIN));
casAuthenticationEntryPoint.setServiceProperties(serviceProperties());
casAuthenticationEntryPoint.setUrlHelper(serviceUrlHelper());
//move to /app/login due to cachebuster instead of api/authenticate
casAuthenticationEntryPoint.setPathLogin(APP_URI_LOGIN);
return casAuthenticationEntryPoint;
}
@Bean
public CustomSingleSignOutFilter singleSignOutFilter() {
CustomSingleSignOutFilter singleSignOutFilter = new CustomSingleSignOutFilter();
singleSignOutFilter.setCasServerUrlPrefix(env.getRequiredProperty(CAS_URL_PREFIX));
return singleSignOutFilter;
}
@Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(casAuthenticationProvider());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/scripts/**/*.{js,html}").antMatchers("/bower_components/**")
.antMatchers("/i18n/**").antMatchers("/assets/**").antMatchers("/swagger-ui/**")
.antMatchers("/test/**").antMatchers("/console/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class).exceptionHandling()
.authenticationEntryPoint(casAuthenticationEntryPoint()).and()
.addFilterBefore(casAuthenticationFilter(), BasicAuthenticationFilter.class)
.addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class);
// .and()
// .rememberMe()
// .rememberMeServices(rememberMeServices)
// .key(env.getProperty("jhipster.security.rememberme.key"))
// .and()
// .formLogin()
// .loginProcessingUrl("/api/authentication")
// .successHandler(ajaxAuthenticationSuccessHandler)
// .failureHandler(ajaxAuthenticationFailureHandler)
// .usernameParameter("j_username")
// .passwordParameter("j_password")
// .permitAll()
http
.headers()
.frameOptions()
.disable()
.authorizeRequests()
.antMatchers("/app/**").authenticated()
.antMatchers("/published/**").access("hasRole('" + AuthoritiesConstants.ANONYMOUS + "') and (hasIpAddress('" + ipVariableHolder.getIpRange()
+ "') or hasIpAddress('127.0.0.1/32') or hasIpAddress('::1'))")
.antMatchers("/api/register").denyAll()
.antMatchers("/api/activate").denyAll()
.antMatchers("/api/authenticate").denyAll()
.antMatchers("/api/logs/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/api/enums/**").permitAll()
.antMatchers("/api/conf/**").permitAll()
.antMatchers("/api/**").hasAuthority(AuthoritiesConstants.USER)
.antMatchers("/metrics/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/health/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/dump/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/shutdown/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/beans/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/configprops/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/info/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/autoconfig/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/env/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/api-docs/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/protected/**").authenticated()
.antMatchers("/view/**").permitAll();
http
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler)
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll();
}
/**
* This allows SpEL support in Spring Data JPA @Query definitions.
*
* See https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions
*/
/*@Bean
EvaluationContextExtension securityExtension() {
return new EvaluationContextExtensionSupport() {
@Override
public String getExtensionId() {
return "security";
}
@Override
public SecurityExpressionRoot getRootObject() {
SecurityExpressionRoot ser = new SecurityExpressionRoot(SecurityContextHolder.getContext().getAuthentication()) {};
ser.setPermissionEvaluator(permissionEvaluator());
ser.setRoleHierarchy(roleHierarchy());
return ser;
}
};
}*/
}
|
Ajout configuration groupe des Utilisateurs de l'application
|
src/main/java/org/esupportail/publisher/config/SecurityConfiguration.java
|
Ajout configuration groupe des Utilisateurs de l'application
|
<ide><path>rc/main/java/org/esupportail/publisher/config/SecurityConfiguration.java
<ide> private static final String APP_URI_LOGIN = "/app/login";
<ide> private static final String APP_ADMIN_USER_NAME = "app.admin.userName";
<ide> private static final String APP_ADMIN_GROUP_NAME = "app.admin.groupName";
<add> private static final String APP_USERS_GROUP_NAME = "app.users.groupName";
<ide> private static final String APP_CONTEXT_PATH = "server.contextPath";
<ide> private static final String APP_PROTOCOL = "app.service.protocol";
<ide>
<ide> OperatorEvaluation admins = new OperatorEvaluation(OperatorType.OR, set);
<ide> defs.setAdmins(admins);
<ide>
<del> UserMultivaluedAttributesEvaluation umae = new UserMultivaluedAttributesEvaluation("isMemberOf",
<del> "((esco)|(cfa)|(clg37)|(agri)|(coll)):Applications:((Publisher)|(Publication_annonces)):.*",
<del> StringEvaluationMode.MATCH);
<add> final String groupUsers = env.getProperty(APP_USERS_GROUP_NAME);
<add> UserMultivaluedAttributesEvaluation umae = new UserMultivaluedAttributesEvaluation("isMemberOf", groupUsers, StringEvaluationMode.MATCH);
<ide> defs.setUsers(umae);
<ide>
<ide> return defs;
|
|
Java
|
epl-1.0
|
2e1fb5f506a200f88aa3e3fc29c94ead1cf09286
| 0 |
bigdataops/bgpcep,bigdataops/bgpcep,opendaylight/bgpcep,inocybe/odl-bgpcep,inocybe/odl-bgpcep
|
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.protocol.bgp.rib.impl;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.net.InetSocketAddress;
import org.opendaylight.protocol.bgp.parser.spi.MessageRegistry;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionValidator;
import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
import org.opendaylight.protocol.framework.AbstractDispatcher;
import org.opendaylight.protocol.framework.ReconnectStrategy;
import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
import org.opendaylight.tcpmd5.api.KeyMapping;
import org.opendaylight.tcpmd5.netty.MD5ChannelFactory;
import org.opendaylight.tcpmd5.netty.MD5ChannelOption;
import org.opendaylight.tcpmd5.netty.MD5ServerChannelFactory;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
/**
* Implementation of BGPDispatcher.
*/
public final class BGPDispatcherImpl extends AbstractDispatcher<BGPSessionImpl, BGPSessionListener> implements BGPDispatcher, AutoCloseable {
private final MD5ServerChannelFactory<?> scf;
private final MD5ChannelFactory<?> cf;
private final BGPHandlerFactory hf;
private KeyMapping keys;
private static final String NEGOTIATOR = "negotiator";
public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
this(messageRegistry, bossGroup, workerGroup, null, null);
}
public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final MD5ChannelFactory<?> cf, final MD5ServerChannelFactory<?> scf) {
super(bossGroup, workerGroup);
this.hf = new BGPHandlerFactory(messageRegistry);
this.cf = cf;
this.scf = scf;
}
@Override
public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress address,
final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategy strategy) {
final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(remoteAs, listener);
return super.createClient(address, strategy, new PipelineInitializer<BGPSessionImpl>() {
@Override
public void initializeChannel(final SocketChannel ch, final Promise<BGPSessionImpl> promise) {
ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getDecoders());
ch.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(null, ch, promise));
ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getEncoders());
}
});
}
@Override
public Future<Void> createReconnectingClient(final InetSocketAddress address,
final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategyFactory connectStrategyFactory,
final ReconnectStrategyFactory reestablishStrategyFactory) {
return this.createReconnectingClient(address, remoteAs, listener, connectStrategyFactory, reestablishStrategyFactory,
null);
}
@Override
public void close() {
}
@Override
public synchronized Future<Void> createReconnectingClient(final InetSocketAddress address,
final AsNumber remoteAs, final BGPPeerRegistry peerRegistry, final ReconnectStrategyFactory connectStrategyFactory,
final ReconnectStrategyFactory reestablishStrategyFactory, final KeyMapping keys) {
final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(remoteAs, peerRegistry);
this.keys = keys;
final Future<Void> ret = super.createReconnectingClient(address, connectStrategyFactory, reestablishStrategyFactory.createReconnectStrategy(), new PipelineInitializer<BGPSessionImpl>() {
@Override
public void initializeChannel(final SocketChannel ch, final Promise<BGPSessionImpl> promise) {
ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getDecoders());
ch.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(null, ch, promise));
ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getEncoders());
}
});
this.keys = null;
return ret;
}
@Override
public ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress address, final BGPSessionValidator sessionValidator) {
return this.createServer(registry, address, sessionValidator, null);
}
@Override
public ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress address, final BGPSessionValidator sessionValidator, final KeyMapping keys) {
final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(sessionValidator, registry);
this.keys = keys;
final ChannelFuture ret = super.createServer(address, new PipelineInitializer<BGPSessionImpl>() {
@Override
public void initializeChannel(final SocketChannel ch, final Promise<BGPSessionImpl> promise) {
ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getDecoders());
ch.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(null, ch, promise));
ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getEncoders());
}
});
this.keys = null;
return ret;
}
@Override
protected void customizeBootstrap(final Bootstrap b) {
if (this.keys != null && !this.keys.isEmpty()) {
if (this.cf == null) {
throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
}
b.channelFactory(this.cf);
b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
}
// Make sure we are doing round-robin processing
b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
}
@Override
protected void customizeBootstrap(final ServerBootstrap b) {
if (this.keys != null && !this.keys.isEmpty()) {
if (this.scf == null) {
throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
}
b.channelFactory(this.scf);
b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
}
// Make sure we are doing round-robin processing
b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, 1);
}
}
|
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPDispatcherImpl.java
|
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.protocol.bgp.rib.impl;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.net.InetSocketAddress;
import org.opendaylight.protocol.bgp.parser.spi.MessageRegistry;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionValidator;
import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
import org.opendaylight.protocol.framework.AbstractDispatcher;
import org.opendaylight.protocol.framework.ReconnectStrategy;
import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
import org.opendaylight.tcpmd5.api.KeyMapping;
import org.opendaylight.tcpmd5.netty.MD5ChannelFactory;
import org.opendaylight.tcpmd5.netty.MD5ChannelOption;
import org.opendaylight.tcpmd5.netty.MD5ServerChannelFactory;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
/**
* Implementation of BGPDispatcher.
*/
public final class BGPDispatcherImpl extends AbstractDispatcher<BGPSessionImpl, BGPSessionListener> implements BGPDispatcher, AutoCloseable {
private final MD5ServerChannelFactory<?> scf;
private final MD5ChannelFactory<?> cf;
private final BGPHandlerFactory hf;
private KeyMapping keys;
private static final String NEGOTIATOR = "negotiator";
public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
this(messageRegistry, bossGroup, workerGroup, null, null);
}
public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final MD5ChannelFactory<?> cf, final MD5ServerChannelFactory<?> scf) {
super(bossGroup, workerGroup);
this.hf = new BGPHandlerFactory(messageRegistry);
this.cf = cf;
this.scf = scf;
}
@Override
public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress address,
final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategy strategy) {
final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(remoteAs, listener);
return super.createClient(address, strategy, new PipelineInitializer<BGPSessionImpl>() {
@Override
public void initializeChannel(final SocketChannel ch, final Promise<BGPSessionImpl> promise) {
ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getDecoders());
ch.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(null, ch, promise));
ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getEncoders());
}
});
}
@Override
public Future<Void> createReconnectingClient(final InetSocketAddress address,
final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategyFactory connectStrategyFactory,
final ReconnectStrategyFactory reestablishStrategyFactory) {
return this.createReconnectingClient(address, remoteAs, listener, connectStrategyFactory, reestablishStrategyFactory,
null);
}
@Override
public void close() {
}
@Override
public synchronized Future<Void> createReconnectingClient(final InetSocketAddress address,
final AsNumber remoteAs, final BGPPeerRegistry peerRegistry, final ReconnectStrategyFactory connectStrategyFactory,
final ReconnectStrategyFactory reestablishStrategyFactory, final KeyMapping keys) {
final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(remoteAs, peerRegistry);
this.keys = keys;
final Future<Void> ret = super.createReconnectingClient(address, connectStrategyFactory, reestablishStrategyFactory.createReconnectStrategy(), new PipelineInitializer<BGPSessionImpl>() {
@Override
public void initializeChannel(final SocketChannel ch, final Promise<BGPSessionImpl> promise) {
ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getDecoders());
ch.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(null, ch, promise));
ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getEncoders());
}
});
this.keys = null;
return ret;
}
@Override
public ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress address, final BGPSessionValidator sessionValidator) {
return this.createServer(registry, address, sessionValidator, null);
}
@Override
public ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress address, final BGPSessionValidator sessionValidator, final KeyMapping keys) {
final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(sessionValidator, registry);
this.keys = keys;
final ChannelFuture ret = super.createServer(address, new PipelineInitializer<BGPSessionImpl>() {
@Override
public void initializeChannel(final SocketChannel ch, final Promise<BGPSessionImpl> promise) {
ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getDecoders());
ch.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(null, ch, promise));
ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getEncoders());
}
});
this.keys = null;
return ret;
}
@Override
protected void customizeBootstrap(final Bootstrap b) {
if (this.keys != null && !this.keys.isEmpty()) {
if (this.cf == null) {
throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
}
b.channelFactory(this.cf);
b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
// Make sure we are doing round-robin processing
b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
}
}
@Override
protected void customizeBootstrap(final ServerBootstrap b) {
if (this.keys != null && !this.keys.isEmpty()) {
if (this.scf == null) {
throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
}
b.channelFactory(this.scf);
b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
// Make sure we are doing round-robin processing
b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, 1);
}
}
}
|
BUG-2475: Fix keepalives not being sent
As it turns out, we failed to update channel configuration when MD5 keys
were not specified.
Change-Id: I5c2a5983c0797d032bb058974aac82254b554041
Signed-off-by: Robert Varga <[email protected]>
|
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPDispatcherImpl.java
|
BUG-2475: Fix keepalives not being sent
|
<ide><path>gp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPDispatcherImpl.java
<ide> }
<ide> b.channelFactory(this.cf);
<ide> b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
<del> // Make sure we are doing round-robin processing
<del> b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
<ide> }
<add>
<add> // Make sure we are doing round-robin processing
<add> b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
<ide> }
<ide>
<ide> @Override
<ide> }
<ide> b.channelFactory(this.scf);
<ide> b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
<del> // Make sure we are doing round-robin processing
<del> b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, 1);
<ide> }
<add>
<add> // Make sure we are doing round-robin processing
<add> b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, 1);
<ide> }
<ide>
<ide> }
|
|
Java
|
apache-2.0
|
5ca855dc500382e8324f80d8f4371cf7abb912a2
| 0 |
ljacomet/ehcache3,aurbroszniowski/ehcache3,kedar031/ehcache3,palmanojkumar/ehcache3,rkavanap/ehcache3,CapeSepias/ehcache3,henri-tremblay/ehcache3,ehcache/ehcache3,lorban/ehcache3,lorban/ehcache3,anthonydahanne/ehcache3,rishabhmonga/ehcache3,albinsuresh/ehcache3,GaryWKeim/ehcache3,ehcache/ehcache3,mingyaaaa/ehcache3,albinsuresh/ehcache3,sreekanth-r/ehcache3,chenrui2014/ehcache3,cljohnso/ehcache3,cschanck/ehcache3,AbfrmBlr/ehcache3,AbfrmBlr/ehcache3,aurbroszniowski/ehcache3,jhouserizer/ehcache3,jhouserizer/ehcache3,chrisdennis/ehcache3,rkavanap/ehcache3,cschanck/ehcache3,292388900/ehcache3,ljacomet/ehcache3,GaryWKeim/ehcache3,cljohnso/ehcache3,akomakom/ehcache3,alexsnaps/ehcache3,wantstudy/ehcache3,chrisdennis/ehcache3
|
/*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ehcache.internal.store;
import org.ehcache.exceptions.CacheAccessException;
import org.ehcache.function.Function;
import org.ehcache.spi.cache.Store;
import org.ehcache.spi.test.SPITest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
/**
* Test the {@link org.ehcache.spi.cache.Store#bulkCompute(Iterable, org.ehcache.function.Function)} contract of the
* {@link org.ehcache.spi.cache.Store Store} interface.
* <p/>
*
* @author Gaurav Mangalick
*/
public class StoreBulkComputeTest<K, V> extends SPIStoreTester<K, V> {
public StoreBulkComputeTest(final StoreFactory<K, V> factory) {
super(factory);
}
@SuppressWarnings({ "unchecked" })
@SPITest
public void remappingFunctionReturnsIterableOfEntriesForEachInputEntry() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
int nbElements = 10;
Set<K> inputKeys = new HashSet<K>();
for (long i = 0; i < nbElements; i++) {
final K k = factory.createKey(i);
final V v = factory.createValue(i);
inputKeys.add(k);
kvStore.put(k, v);
}
try {
Map<K, Store.ValueHolder<V>> mapFromRemappingFunction = kvStore.bulkCompute(inputKeys, new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
Map<K, V> map = new HashMap<K, V>();
for (final Map.Entry<? extends K, ? extends V> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return map.entrySet();
}
}
);
assertThat(mapFromRemappingFunction.keySet(), containsInAnyOrder((K[])inputKeys.toArray()));
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void testWrongKeyType() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
Set<K> set = new HashSet<K>();
if (factory.getKeyType() == String.class) {
set.add((K)new Object());
} else {
set.add((K)"WrongKeyType");
}
try {
kvStore.bulkCompute(Arrays.asList((K[])set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
throw new AssertionError("Expected ClassCastException because the key is of the wrong type");
}
});
throw new AssertionError("Expected ClassCastException because the key is of the wrong type");
} catch (ClassCastException e) {
// expected
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void mappingIsRemovedFromStoreForNullValueEntriesFromRemappingFunction() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
final K k1 = factory.createKey(1L);
final V v1 = factory.createValue(1L);
Set<K> set = new HashSet<K>();
set.add(k1);
kvStore.put(k1, v1);
try {
kvStore.bulkCompute(Arrays.asList((K[])set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
Map<K, V> map = new HashMap<K, V>();
map.put(k1, null);
return map.entrySet();
}
});
assertThat(kvStore.get(k1), is(nullValue()));
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void remappingFunctionGetsIterableWithMappedStoreEntryValueOrNull() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
final K k1 = factory.createKey(1L);
Set<K> set = new HashSet<K>();
set.add(k1);
try {
kvStore.bulkCompute(Arrays.asList((K[])set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
Map.Entry<? extends K, ? extends V> entry = entries.iterator().next();
assertThat(entry.getValue(), is(nullValue()));
Map<K, V> map = new HashMap<K, V>();
map.put(entry.getKey(), entry.getValue());
return map.entrySet();
}
}
);
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void computeValuesForEveryKeyUsingARemappingFunction() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
final K k1 = factory.createKey(1L);
final V v1 = factory.createValue(1L);
Set<K> set = new HashSet<K>();
set.add(k1);
try {
kvStore.bulkCompute(Arrays.asList((K[])set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
Map<K, V> map = new HashMap<K, V>();
map.put(k1, v1);
return map.entrySet();
}
});
assertThat(kvStore.get(k1).value(), is(v1));
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void testRemappingFunctionProducesWrongKeyType() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
final K k1 = factory.createKey(1L);
final V v1 = factory.createValue(1L);
Set<K> set = new HashSet<K>();
set.add(k1);
try {
kvStore.bulkCompute(Arrays.asList((K[])set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
Map<K, V> map = new HashMap<K, V>();
if (factory.getKeyType() == String.class) {
map.put((K)new Object(), v1);
} else {
map.put((K)"WrongKeyType", v1);
}
return map.entrySet();
}
});
throw new AssertionError("Expected ClassCastException because the key is of the wrong type");
} catch (ClassCastException cce) {
//expected
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void testRemappingFunctionProducesWrongValueType() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
final K k1 = factory.createKey(1L);
Set<K> set = new HashSet<K>();
set.add(k1);
try {
kvStore.bulkCompute(Arrays.asList((K[])set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
Map<K, V> map = new HashMap<K, V>();
if (factory.getValueType() == String.class) {
map.put(k1, (V)new Object());
} else {
map.put(k1, (V)"WrongValueType");
}
return map.entrySet();
}
});
throw new AssertionError("Expected ClassCastException because the value is of the wrong type");
} catch (ClassCastException cce) {
//expected
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
}
|
core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java
|
/*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ehcache.internal.store;
import org.ehcache.Cache;
import org.ehcache.config.StoreConfigurationImpl;
import org.ehcache.exceptions.CacheAccessException;
import org.ehcache.expiry.Expirations;
import org.ehcache.function.Function;
import org.ehcache.function.Predicate;
import org.ehcache.function.Predicates;
import org.ehcache.spi.cache.Store;
import org.ehcache.spi.test.Ignore;
import org.ehcache.spi.test.SPITest;
import org.hamcrest.Matchers;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import java.lang.Long;
import java.util.Set;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.HashSet;
/**
* Test the {@link org.ehcache.spi.cache.Store#bulkCompute(Iterable, org.ehcache.function.Function)} contract of the
* {@link org.ehcache.spi.cache.Store Store} interface.
* <p/>
*
* @author Gaurav Mangalick
*/
public class StoreBulkComputeTest<K, V> extends SPIStoreTester<K, V> {
public StoreBulkComputeTest(final StoreFactory<K, V> factory) {
super(factory);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void remappingFunctionReturnsIterableOfEntriesForEachInputEntry() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
final K k1 = factory.createKey(1L);
final V v1 = factory.createValue(1L);
Set<K> set = new HashSet<K>();
set.add(k1);
kvStore.put(k1, v1);
try {
kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
Map.Entry<? extends K, ? extends V> entry = entries.iterator().next();
assertThat(entry.getValue(), is(v1));
Map<K, V> map = new HashMap<K, V>();
map.put(entry.getKey(), entry.getValue());
return map.entrySet();
}
}
);
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void testWrongKeyType() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
Set<K> set = new HashSet<K>();
if (factory.getKeyType() == String.class) {
set.add((K) new Object());
} else {
set.add((K) "WrongKeyType");
}
try {
kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
throw new AssertionError("Expected ClassCastException because the key is of the wrong type");
}
});
throw new AssertionError("Expected ClassCastException because the key is of the wrong type");
} catch (ClassCastException e) {
// expected
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void mappingIsRemovedFromStoreForNullValueEntriesFromRemappingFunction() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
final K k1 = factory.createKey(1L);
final V v1 = factory.createValue(1L);
Set<K> set = new HashSet<K>();
set.add(k1);
kvStore.put(k1, v1);
try {
kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
Map<K, V> map = new HashMap<K, V>();
map.put(k1, null);
return map.entrySet();
}
});
assertThat(kvStore.get(k1), is(nullValue()));
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void remappingFunctionGetsIterableWithMappedStoreEntryValueOrNull() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
final K k1 = factory.createKey(1L);
Set<K> set = new HashSet<K>();
set.add(k1);
try {
kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
Map.Entry<? extends K, ? extends V> entry = entries.iterator().next();
assertThat(entry.getValue(), is(nullValue()));
Map<K, V> map = new HashMap<K, V>();
map.put(entry.getKey(), entry.getValue());
return map.entrySet();
}
}
);
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void computeValuesForEveryKeyUsingARemappingFunction() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
final K k1 = factory.createKey(1L);
final V v1 = factory.createValue(1L);
Set<K> set = new HashSet<K>();
set.add(k1);
try {
kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
Map<K, V> map = new HashMap<K, V>();
map.put(k1, v1);
return map.entrySet();
}
});
assertThat(kvStore.get(k1).value(), is(v1));
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void testRemappingFunctionProducesWrongKeyType() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
final K k1 = factory.createKey(1L);
final V v1 = factory.createValue(1L);
Set<K> set = new HashSet<K>();
set.add(k1);
try {
kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
Map<K, V> map = new HashMap<K, V>();
if (factory.getKeyType() == String.class) {
map.put((K)new Object(), v1);
} else {
map.put((K)"WrongKeyType", v1);
}
return map.entrySet();
}
});
throw new AssertionError("Expected ClassCastException because the key is of the wrong type");
} catch (ClassCastException cce) {
//expected
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SPITest
public void testRemappingFunctionProducesWrongValueType() throws Exception {
final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
final K k1 = factory.createKey(1L);
Set<K> set = new HashSet<K>();
set.add(k1);
try {
kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
@Override
public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
Map<K, V> map = new HashMap<K, V>();
if (factory.getValueType() == String.class) {
map.put(k1, (V) new Object());
} else {
map.put(k1, (V) "WrongValueType");
}
return map.entrySet();
}
});
throw new AssertionError("Expected ClassCastException because the value is of the wrong type");
} catch (ClassCastException cce) {
//expected
} catch (CacheAccessException e) {
System.err.println("Warning, an exception is thrown due to the SPI test");
e.printStackTrace();
}
}
}
|
issue #176 use multiple keys in remappingFunctionReturnsIterableOfEntriesForEachInputEntry
|
core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java
|
issue #176 use multiple keys in remappingFunctionReturnsIterableOfEntriesForEachInputEntry
|
<ide><path>ore-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java
<ide>
<ide> package org.ehcache.internal.store;
<ide>
<del>import org.ehcache.Cache;
<del>import org.ehcache.config.StoreConfigurationImpl;
<ide> import org.ehcache.exceptions.CacheAccessException;
<del>import org.ehcache.expiry.Expirations;
<ide> import org.ehcache.function.Function;
<del>import org.ehcache.function.Predicate;
<del>import org.ehcache.function.Predicates;
<ide> import org.ehcache.spi.cache.Store;
<del>import org.ehcache.spi.test.Ignore;
<ide> import org.ehcache.spi.test.SPITest;
<del>import org.hamcrest.Matchers;
<del>
<del>import static org.hamcrest.MatcherAssert.assertThat;
<del>import static org.hamcrest.Matchers.equalTo;
<del>import static org.hamcrest.Matchers.is;
<del>import static org.hamcrest.Matchers.not;
<del>import static org.hamcrest.Matchers.nullValue;
<del>
<del>import java.lang.Long;
<del>import java.util.Set;
<add>
<ide> import java.util.Arrays;
<del>import java.util.Map;
<ide> import java.util.HashMap;
<ide> import java.util.HashSet;
<add>import java.util.Map;
<add>import java.util.Set;
<add>
<add>import static org.hamcrest.MatcherAssert.assertThat;
<add>import static org.hamcrest.Matchers.containsInAnyOrder;
<add>import static org.hamcrest.Matchers.is;
<add>import static org.hamcrest.Matchers.nullValue;
<ide>
<ide> /**
<ide> * Test the {@link org.ehcache.spi.cache.Store#bulkCompute(Iterable, org.ehcache.function.Function)} contract of the
<ide> super(factory);
<ide> }
<ide>
<del> @SuppressWarnings({ "rawtypes", "unchecked" })
<add> @SuppressWarnings({ "unchecked" })
<ide> @SPITest
<ide> public void remappingFunctionReturnsIterableOfEntriesForEachInputEntry() throws Exception {
<ide> final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
<add>
<add> int nbElements = 10;
<add>
<add> Set<K> inputKeys = new HashSet<K>();
<add> for (long i = 0; i < nbElements; i++) {
<add> final K k = factory.createKey(i);
<add> final V v = factory.createValue(i);
<add>
<add> inputKeys.add(k);
<add> kvStore.put(k, v);
<add> }
<add>
<add> try {
<add> Map<K, Store.ValueHolder<V>> mapFromRemappingFunction = kvStore.bulkCompute(inputKeys, new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<add> @Override
<add> public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
<add> Map<K, V> map = new HashMap<K, V>();
<add> for (final Map.Entry<? extends K, ? extends V> entry : entries) {
<add> map.put(entry.getKey(), entry.getValue());
<add> }
<add> return map.entrySet();
<add> }
<add> }
<add> );
<add> assertThat(mapFromRemappingFunction.keySet(), containsInAnyOrder((K[])inputKeys.toArray()));
<add> } catch (CacheAccessException e) {
<add> System.err.println("Warning, an exception is thrown due to the SPI test");
<add> e.printStackTrace();
<add> }
<add> }
<add>
<add> @SuppressWarnings({ "rawtypes", "unchecked" })
<add> @SPITest
<add> public void testWrongKeyType() throws Exception {
<add> final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
<add> Set<K> set = new HashSet<K>();
<add> if (factory.getKeyType() == String.class) {
<add> set.add((K)new Object());
<add> } else {
<add> set.add((K)"WrongKeyType");
<add> }
<add> try {
<add> kvStore.bulkCompute(Arrays.asList((K[])set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<add> @Override
<add> public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
<add> throw new AssertionError("Expected ClassCastException because the key is of the wrong type");
<add> }
<add> });
<add> throw new AssertionError("Expected ClassCastException because the key is of the wrong type");
<add> } catch (ClassCastException e) {
<add> // expected
<add> } catch (CacheAccessException e) {
<add> System.err.println("Warning, an exception is thrown due to the SPI test");
<add> e.printStackTrace();
<add> }
<add> }
<add>
<add> @SuppressWarnings({ "rawtypes", "unchecked" })
<add> @SPITest
<add> public void mappingIsRemovedFromStoreForNullValueEntriesFromRemappingFunction() throws Exception {
<add> final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
<ide> final K k1 = factory.createKey(1L);
<ide> final V v1 = factory.createValue(1L);
<ide>
<ide> kvStore.put(k1, v1);
<ide>
<ide> try {
<del> kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<add> kvStore.bulkCompute(Arrays.asList((K[])set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<add> @Override
<add> public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
<add> Map<K, V> map = new HashMap<K, V>();
<add> map.put(k1, null);
<add> return map.entrySet();
<add> }
<add> });
<add> assertThat(kvStore.get(k1), is(nullValue()));
<add> } catch (CacheAccessException e) {
<add> System.err.println("Warning, an exception is thrown due to the SPI test");
<add> e.printStackTrace();
<add> }
<add> }
<add>
<add> @SuppressWarnings({ "rawtypes", "unchecked" })
<add> @SPITest
<add> public void remappingFunctionGetsIterableWithMappedStoreEntryValueOrNull() throws Exception {
<add> final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
<add> final K k1 = factory.createKey(1L);
<add>
<add> Set<K> set = new HashSet<K>();
<add> set.add(k1);
<add>
<add> try {
<add> kvStore.bulkCompute(Arrays.asList((K[])set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<ide> @Override
<ide> public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
<ide> Map.Entry<? extends K, ? extends V> entry = entries.iterator().next();
<del> assertThat(entry.getValue(), is(v1));
<add> assertThat(entry.getValue(), is(nullValue()));
<ide> Map<K, V> map = new HashMap<K, V>();
<ide> map.put(entry.getKey(), entry.getValue());
<ide> return map.entrySet();
<ide>
<ide> @SuppressWarnings({ "rawtypes", "unchecked" })
<ide> @SPITest
<del> public void testWrongKeyType() throws Exception {
<del> final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
<del> Set<K> set = new HashSet<K>();
<del> if (factory.getKeyType() == String.class) {
<del> set.add((K) new Object());
<del> } else {
<del> set.add((K) "WrongKeyType");
<del> }
<del> try {
<del> kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<del> @Override
<del> public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
<del> throw new AssertionError("Expected ClassCastException because the key is of the wrong type");
<del> }
<del> });
<del> throw new AssertionError("Expected ClassCastException because the key is of the wrong type");
<del> } catch (ClassCastException e) {
<del> // expected
<del> } catch (CacheAccessException e) {
<del> System.err.println("Warning, an exception is thrown due to the SPI test");
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del> @SuppressWarnings({ "rawtypes", "unchecked" })
<del> @SPITest
<del> public void mappingIsRemovedFromStoreForNullValueEntriesFromRemappingFunction() throws Exception {
<add> public void computeValuesForEveryKeyUsingARemappingFunction() throws Exception {
<ide> final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
<ide> final K k1 = factory.createKey(1L);
<ide> final V v1 = factory.createValue(1L);
<ide> Set<K> set = new HashSet<K>();
<ide> set.add(k1);
<ide>
<del> kvStore.put(k1, v1);
<del>
<del> try {
<del> kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<del> @Override
<del> public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
<del> Map<K, V> map = new HashMap<K, V>();
<del> map.put(k1, null);
<del> return map.entrySet();
<del> }
<del> });
<del> assertThat(kvStore.get(k1), is(nullValue()));
<del> } catch (CacheAccessException e) {
<del> System.err.println("Warning, an exception is thrown due to the SPI test");
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del> @SuppressWarnings({ "rawtypes", "unchecked" })
<del> @SPITest
<del> public void remappingFunctionGetsIterableWithMappedStoreEntryValueOrNull() throws Exception {
<del> final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
<del> final K k1 = factory.createKey(1L);
<del>
<del> Set<K> set = new HashSet<K>();
<del> set.add(k1);
<del>
<del> try {
<del> kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<del> @Override
<del> public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
<del> Map.Entry<? extends K, ? extends V> entry = entries.iterator().next();
<del> assertThat(entry.getValue(), is(nullValue()));
<del> Map<K, V> map = new HashMap<K, V>();
<del> map.put(entry.getKey(), entry.getValue());
<del> return map.entrySet();
<del> }
<del> }
<del> );
<del> } catch (CacheAccessException e) {
<del> System.err.println("Warning, an exception is thrown due to the SPI test");
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del> @SuppressWarnings({ "rawtypes", "unchecked" })
<del> @SPITest
<del> public void computeValuesForEveryKeyUsingARemappingFunction() throws Exception {
<add> try {
<add> kvStore.bulkCompute(Arrays.asList((K[])set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<add> @Override
<add> public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
<add> Map<K, V> map = new HashMap<K, V>();
<add> map.put(k1, v1);
<add> return map.entrySet();
<add> }
<add> });
<add> assertThat(kvStore.get(k1).value(), is(v1));
<add> } catch (CacheAccessException e) {
<add> System.err.println("Warning, an exception is thrown due to the SPI test");
<add> e.printStackTrace();
<add> }
<add> }
<add>
<add> @SuppressWarnings({ "rawtypes", "unchecked" })
<add> @SPITest
<add> public void testRemappingFunctionProducesWrongKeyType() throws Exception {
<ide> final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
<ide> final K k1 = factory.createKey(1L);
<ide> final V v1 = factory.createValue(1L);
<del>
<del> Set<K> set = new HashSet<K>();
<del> set.add(k1);
<del>
<del> try {
<del> kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<del> @Override
<del> public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
<del> Map<K, V> map = new HashMap<K, V>();
<del> map.put(k1, v1);
<del> return map.entrySet();
<del> }
<del> });
<del> assertThat(kvStore.get(k1).value(), is(v1));
<del> } catch (CacheAccessException e) {
<del> System.err.println("Warning, an exception is thrown due to the SPI test");
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del> @SuppressWarnings({ "rawtypes", "unchecked" })
<del> @SPITest
<del> public void testRemappingFunctionProducesWrongKeyType() throws Exception {
<del> final Store<K, V> kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null));
<del> final K k1 = factory.createKey(1L);
<del> final V v1 = factory.createValue(1L);
<del> Set<K> set = new HashSet<K>();
<del> set.add(k1);
<del> try {
<del> kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<add> Set<K> set = new HashSet<K>();
<add> set.add(k1);
<add> try {
<add> kvStore.bulkCompute(Arrays.asList((K[])set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<ide> @Override
<ide> public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
<ide> Map<K, V> map = new HashMap<K, V>();
<ide> Set<K> set = new HashSet<K>();
<ide> set.add(k1);
<ide> try {
<del> kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<add> kvStore.bulkCompute(Arrays.asList((K[])set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() {
<ide> @Override
<ide> public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
<ide> Map<K, V> map = new HashMap<K, V>();
<ide> if (factory.getValueType() == String.class) {
<del> map.put(k1, (V) new Object());
<add> map.put(k1, (V)new Object());
<ide> } else {
<del> map.put(k1, (V) "WrongValueType");
<add> map.put(k1, (V)"WrongValueType");
<ide> }
<ide> return map.entrySet();
<ide> }
|
|
Java
|
apache-2.0
|
42e8c381b15dd48c2f00c088c897ebdd25405aef
| 0 |
wangyum/spark,dongjoon-hyun/spark,ConeyLiu/spark,srowen/spark,icexelloss/spark,shaneknapp/spark,wzhfy/spark,rezasafi/spark,hhbyyh/spark,srowen/spark,mahak/spark,pgandhi999/spark,skonto/spark,WindCanDie/spark,ConeyLiu/spark,JoshRosen/spark,xuanyuanking/spark,spark-test/spark,apache/spark,skonto/spark,ptkool/spark,cloud-fan/spark,bdrillard/spark,kevinyu98/spark,ptkool/spark,hvanhovell/spark,hhbyyh/spark,zuotingbing/spark,jkbradley/spark,dongjoon-hyun/spark,jiangxb1987/spark,ueshin/apache-spark,LantaoJin/spark,taroplus/spark,actuaryzhang/spark,ptkool/spark,kiszk/spark,srowen/spark,cloud-fan/spark,WeichenXu123/spark,spark-test/spark,wangyum/spark,caneGuy/spark,yanboliang/spark,highfei2011/spark,milliman/spark,jiangxb1987/spark,BryanCutler/spark,darionyaphet/spark,Aegeaner/spark,hvanhovell/spark,milliman/spark,vinodkc/spark,Aegeaner/spark,darionyaphet/spark,facaiy/spark,guoxiaolongzte/spark,icexelloss/spark,gengliangwang/spark,milliman/spark,wzhfy/spark,hhbyyh/spark,skonto/spark,BryanCutler/spark,pgandhi999/spark,spark-test/spark,HyukjinKwon/spark,actuaryzhang/spark,vinodkc/spark,wangmiao1981/spark,zero323/spark,techaddict/spark,chuckchen/spark,Aegeaner/spark,jiangxb1987/spark,techaddict/spark,jiangxb1987/spark,witgo/spark,hvanhovell/spark,xuanyuanking/spark,maropu/spark,WindCanDie/spark,ptkool/spark,highfei2011/spark,Aegeaner/spark,HyukjinKwon/spark,hhbyyh/spark,shaneknapp/spark,dbtsai/spark,shuangshuangwang/spark,apache/spark,maropu/spark,caneGuy/spark,facaiy/spark,goldmedal/spark,bdrillard/spark,vinodkc/spark,wangmiao1981/spark,darionyaphet/spark,icexelloss/spark,chuckchen/spark,caneGuy/spark,mdespriee/spark,matthewfranglen/spark,skonto/spark,HyukjinKwon/spark,caneGuy/spark,JoshRosen/spark,guoxiaolongzte/spark,WindCanDie/spark,bdrillard/spark,caneGuy/spark,WeichenXu123/spark,caneGuy/spark,goldmedal/spark,shuangshuangwang/spark,Aegeaner/spark,srowen/spark,mdespriee/spark,BryanCutler/spark,wangyum/spark,facaiy/spark,pgandhi999/spark,rednaxelafx/apache-spark,vinodkc/spark,JoshRosen/spark,hvanhovell/spark,WeichenXu123/spark,wangyum/spark,vinodkc/spark,jkbradley/spark,techaddict/spark,wangyum/spark,guoxiaolongzte/spark,kiszk/spark,wangyum/spark,mahak/spark,maropu/spark,mahak/spark,ueshin/apache-spark,actuaryzhang/spark,ConeyLiu/spark,goldmedal/spark,guoxiaolongzte/spark,chuckchen/spark,highfei2011/spark,mahak/spark,rednaxelafx/apache-spark,zuotingbing/spark,rednaxelafx/apache-spark,pgandhi999/spark,BryanCutler/spark,yanboliang/spark,taroplus/spark,jkbradley/spark,actuaryzhang/spark,guoxiaolongzte/spark,ptkool/spark,xuanyuanking/spark,cloud-fan/spark,dongjoon-hyun/spark,highfei2011/spark,yanboliang/spark,mdespriee/spark,holdenk/spark,dongjoon-hyun/spark,yanboliang/spark,rednaxelafx/apache-spark,witgo/spark,kevinyu98/spark,LantaoJin/spark,hhbyyh/spark,taroplus/spark,WindCanDie/spark,wzhfy/spark,actuaryzhang/spark,milliman/spark,highfei2011/spark,yanboliang/spark,techaddict/spark,dbtsai/spark,guoxiaolongzte/spark,kiszk/spark,ConeyLiu/spark,mahak/spark,skonto/spark,goldmedal/spark,wangmiao1981/spark,maropu/spark,srowen/spark,ueshin/apache-spark,actuaryzhang/spark,hhbyyh/spark,aosagie/spark,bdrillard/spark,ptkool/spark,skonto/spark,wangmiao1981/spark,shuangshuangwang/spark,wzhfy/spark,JoshRosen/spark,wangmiao1981/spark,mahak/spark,nchammas/spark,zzcclp/spark,aosagie/spark,actuaryzhang/spark,LantaoJin/spark,zero323/spark,WeichenXu123/spark,facaiy/spark,jkbradley/spark,goldmedal/spark,icexelloss/spark,xuanyuanking/spark,mdespriee/spark,nchammas/spark,facaiy/spark,rednaxelafx/apache-spark,witgo/spark,HyukjinKwon/spark,aosagie/spark,apache/spark,rezasafi/spark,wzhfy/spark,WindCanDie/spark,WeichenXu123/spark,taroplus/spark,kiszk/spark,jiangxb1987/spark,hvanhovell/spark,wzhfy/spark,jkbradley/spark,JoshRosen/spark,JoshRosen/spark,chuckchen/spark,rednaxelafx/apache-spark,mahak/spark,aosagie/spark,xuanyuanking/spark,techaddict/spark,bdrillard/spark,maropu/spark,kevinyu98/spark,shaneknapp/spark,chuckchen/spark,holdenk/spark,spark-test/spark,ptkool/spark,highfei2011/spark,kevinyu98/spark,kevinyu98/spark,dbtsai/spark,BryanCutler/spark,ConeyLiu/spark,mdespriee/spark,kiszk/spark,kiszk/spark,taroplus/spark,skonto/spark,witgo/spark,srowen/spark,aosagie/spark,zero323/spark,WindCanDie/spark,witgo/spark,zzcclp/spark,shaneknapp/spark,witgo/spark,cloud-fan/spark,chuckchen/spark,zzcclp/spark,apache/spark,shaneknapp/spark,facaiy/spark,zuotingbing/spark,milliman/spark,cloud-fan/spark,zuotingbing/spark,chuckchen/spark,LantaoJin/spark,darionyaphet/spark,ueshin/apache-spark,bdrillard/spark,dbtsai/spark,LantaoJin/spark,wangmiao1981/spark,shuangshuangwang/spark,taroplus/spark,caneGuy/spark,LantaoJin/spark,rezasafi/spark,gengliangwang/spark,shuangshuangwang/spark,LantaoJin/spark,apache/spark,gengliangwang/spark,zzcclp/spark,hvanhovell/spark,bdrillard/spark,rezasafi/spark,jiangxb1987/spark,kevinyu98/spark,zero323/spark,cloud-fan/spark,wangyum/spark,apache/spark,zzcclp/spark,jkbradley/spark,dongjoon-hyun/spark,cloud-fan/spark,nchammas/spark,nchammas/spark,maropu/spark,zuotingbing/spark,wangmiao1981/spark,spark-test/spark,zero323/spark,holdenk/spark,nchammas/spark,Aegeaner/spark,WeichenXu123/spark,icexelloss/spark,pgandhi999/spark,xuanyuanking/spark,BryanCutler/spark,HyukjinKwon/spark,holdenk/spark,nchammas/spark,spark-test/spark,holdenk/spark,goldmedal/spark,maropu/spark,yanboliang/spark,kevinyu98/spark,witgo/spark,zzcclp/spark,darionyaphet/spark,guoxiaolongzte/spark,HyukjinKwon/spark,hvanhovell/spark,zuotingbing/spark,dongjoon-hyun/spark,ConeyLiu/spark,zzcclp/spark,holdenk/spark,srowen/spark,aosagie/spark,apache/spark,WindCanDie/spark,shaneknapp/spark,pgandhi999/spark,taroplus/spark,milliman/spark,icexelloss/spark,ueshin/apache-spark,shaneknapp/spark,ConeyLiu/spark,vinodkc/spark,dongjoon-hyun/spark,pgandhi999/spark,dbtsai/spark,gengliangwang/spark,goldmedal/spark,xuanyuanking/spark,ueshin/apache-spark,rezasafi/spark,darionyaphet/spark,shuangshuangwang/spark,wzhfy/spark,zero323/spark,dbtsai/spark,dbtsai/spark,gengliangwang/spark,techaddict/spark,holdenk/spark,jkbradley/spark,gengliangwang/spark,mdespriee/spark,hhbyyh/spark,vinodkc/spark,facaiy/spark,highfei2011/spark,icexelloss/spark,rednaxelafx/apache-spark,spark-test/spark,Aegeaner/spark,darionyaphet/spark,milliman/spark,ueshin/apache-spark,aosagie/spark,techaddict/spark,rezasafi/spark,HyukjinKwon/spark,kiszk/spark,jiangxb1987/spark,yanboliang/spark,nchammas/spark,BryanCutler/spark,shuangshuangwang/spark,mdespriee/spark,WeichenXu123/spark,JoshRosen/spark,zero323/spark,rezasafi/spark,zuotingbing/spark,gengliangwang/spark
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.unsafe.map;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import scala.Tuple2$;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.apache.spark.SparkConf;
import org.apache.spark.executor.ShuffleWriteMetrics;
import org.apache.spark.memory.TaskMemoryManager;
import org.apache.spark.memory.TestMemoryManager;
import org.apache.spark.network.util.JavaUtils;
import org.apache.spark.serializer.JavaSerializer;
import org.apache.spark.serializer.SerializerInstance;
import org.apache.spark.serializer.SerializerManager;
import org.apache.spark.storage.*;
import org.apache.spark.unsafe.Platform;
import org.apache.spark.unsafe.array.ByteArrayMethods;
import org.apache.spark.util.Utils;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Answers.RETURNS_SMART_NULLS;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.when;
public abstract class AbstractBytesToBytesMapSuite {
private final Random rand = new Random(42);
private TestMemoryManager memoryManager;
private TaskMemoryManager taskMemoryManager;
private SerializerManager serializerManager = new SerializerManager(
new JavaSerializer(new SparkConf()),
new SparkConf().set("spark.shuffle.spill.compress", "false"));
private static final long PAGE_SIZE_BYTES = 1L << 26; // 64 megabytes
final LinkedList<File> spillFilesCreated = new LinkedList<>();
File tempDir;
@Mock(answer = RETURNS_SMART_NULLS) BlockManager blockManager;
@Mock(answer = RETURNS_SMART_NULLS) DiskBlockManager diskBlockManager;
@Before
public void setup() {
memoryManager =
new TestMemoryManager(
new SparkConf()
.set("spark.memory.offHeap.enabled", "" + useOffHeapMemoryAllocator())
.set("spark.memory.offHeap.size", "256mb")
.set("spark.shuffle.spill.compress", "false")
.set("spark.shuffle.compress", "false"));
taskMemoryManager = new TaskMemoryManager(memoryManager, 0);
tempDir = Utils.createTempDir(System.getProperty("java.io.tmpdir"), "unsafe-test");
spillFilesCreated.clear();
MockitoAnnotations.initMocks(this);
when(blockManager.diskBlockManager()).thenReturn(diskBlockManager);
when(diskBlockManager.createTempLocalBlock()).thenAnswer(invocationOnMock -> {
TempLocalBlockId blockId = new TempLocalBlockId(UUID.randomUUID());
File file = File.createTempFile("spillFile", ".spill", tempDir);
spillFilesCreated.add(file);
return Tuple2$.MODULE$.apply(blockId, file);
});
when(blockManager.getDiskWriter(
any(BlockId.class),
any(File.class),
any(SerializerInstance.class),
anyInt(),
any(ShuffleWriteMetrics.class))).thenAnswer(invocationOnMock -> {
Object[] args = invocationOnMock.getArguments();
return new DiskBlockObjectWriter(
(File) args[1],
serializerManager,
(SerializerInstance) args[2],
(Integer) args[3],
false,
(ShuffleWriteMetrics) args[4],
(BlockId) args[0]
);
});
}
@After
public void tearDown() {
Utils.deleteRecursively(tempDir);
tempDir = null;
if (taskMemoryManager != null) {
Assert.assertEquals(0L, taskMemoryManager.cleanUpAllAllocatedMemory());
long leakedMemory = taskMemoryManager.getMemoryConsumptionForThisTask();
taskMemoryManager = null;
Assert.assertEquals(0L, leakedMemory);
}
}
protected abstract boolean useOffHeapMemoryAllocator();
private static byte[] getByteArray(Object base, long offset, int size) {
final byte[] arr = new byte[size];
Platform.copyMemory(base, offset, arr, Platform.BYTE_ARRAY_OFFSET, size);
return arr;
}
private byte[] getRandomByteArray(int numWords) {
Assert.assertTrue(numWords >= 0);
final int lengthInBytes = numWords * 8;
final byte[] bytes = new byte[lengthInBytes];
rand.nextBytes(bytes);
return bytes;
}
/**
* Fast equality checking for byte arrays, since these comparisons are a bottleneck
* in our stress tests.
*/
private static boolean arrayEquals(
byte[] expected,
Object base,
long offset,
long actualLengthBytes) {
return (actualLengthBytes == expected.length) && ByteArrayMethods.arrayEquals(
expected,
Platform.BYTE_ARRAY_OFFSET,
base,
offset,
expected.length
);
}
@Test
public void emptyMap() {
BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, 64, PAGE_SIZE_BYTES);
try {
Assert.assertEquals(0, map.numKeys());
final int keyLengthInWords = 10;
final int keyLengthInBytes = keyLengthInWords * 8;
final byte[] key = getRandomByteArray(keyLengthInWords);
Assert.assertFalse(map.lookup(key, Platform.BYTE_ARRAY_OFFSET, keyLengthInBytes).isDefined());
Assert.assertFalse(map.iterator().hasNext());
} finally {
map.free();
}
}
@Test
public void setAndRetrieveAKey() {
BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, 64, PAGE_SIZE_BYTES);
final int recordLengthWords = 10;
final int recordLengthBytes = recordLengthWords * 8;
final byte[] keyData = getRandomByteArray(recordLengthWords);
final byte[] valueData = getRandomByteArray(recordLengthWords);
try {
final BytesToBytesMap.Location loc =
map.lookup(keyData, Platform.BYTE_ARRAY_OFFSET, recordLengthBytes);
Assert.assertFalse(loc.isDefined());
Assert.assertTrue(loc.append(
keyData,
Platform.BYTE_ARRAY_OFFSET,
recordLengthBytes,
valueData,
Platform.BYTE_ARRAY_OFFSET,
recordLengthBytes
));
// After storing the key and value, the other location methods should return results that
// reflect the result of this store without us having to call lookup() again on the same key.
Assert.assertEquals(recordLengthBytes, loc.getKeyLength());
Assert.assertEquals(recordLengthBytes, loc.getValueLength());
Assert.assertArrayEquals(keyData,
getByteArray(loc.getKeyBase(), loc.getKeyOffset(), recordLengthBytes));
Assert.assertArrayEquals(valueData,
getByteArray(loc.getValueBase(), loc.getValueOffset(), recordLengthBytes));
// After calling lookup() the location should still point to the correct data.
Assert.assertTrue(
map.lookup(keyData, Platform.BYTE_ARRAY_OFFSET, recordLengthBytes).isDefined());
Assert.assertEquals(recordLengthBytes, loc.getKeyLength());
Assert.assertEquals(recordLengthBytes, loc.getValueLength());
Assert.assertArrayEquals(keyData,
getByteArray(loc.getKeyBase(), loc.getKeyOffset(), recordLengthBytes));
Assert.assertArrayEquals(valueData,
getByteArray(loc.getValueBase(), loc.getValueOffset(), recordLengthBytes));
try {
Assert.assertTrue(loc.append(
keyData,
Platform.BYTE_ARRAY_OFFSET,
recordLengthBytes,
valueData,
Platform.BYTE_ARRAY_OFFSET,
recordLengthBytes
));
Assert.fail("Should not be able to set a new value for a key");
} catch (AssertionError e) {
// Expected exception; do nothing.
}
} finally {
map.free();
}
}
private void iteratorTestBase(boolean destructive) throws Exception {
final int size = 4096;
BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, size / 2, PAGE_SIZE_BYTES);
try {
for (long i = 0; i < size; i++) {
final long[] value = new long[] { i };
final BytesToBytesMap.Location loc =
map.lookup(value, Platform.LONG_ARRAY_OFFSET, 8);
Assert.assertFalse(loc.isDefined());
// Ensure that we store some zero-length keys
if (i % 5 == 0) {
Assert.assertTrue(loc.append(
null,
Platform.LONG_ARRAY_OFFSET,
0,
value,
Platform.LONG_ARRAY_OFFSET,
8
));
} else {
Assert.assertTrue(loc.append(
value,
Platform.LONG_ARRAY_OFFSET,
8,
value,
Platform.LONG_ARRAY_OFFSET,
8
));
}
}
final java.util.BitSet valuesSeen = new java.util.BitSet(size);
final Iterator<BytesToBytesMap.Location> iter;
if (destructive) {
iter = map.destructiveIterator();
} else {
iter = map.iterator();
}
int numPages = map.getNumDataPages();
int countFreedPages = 0;
while (iter.hasNext()) {
final BytesToBytesMap.Location loc = iter.next();
Assert.assertTrue(loc.isDefined());
final long value = Platform.getLong(loc.getValueBase(), loc.getValueOffset());
final long keyLength = loc.getKeyLength();
if (keyLength == 0) {
Assert.assertTrue("value " + value + " was not divisible by 5", value % 5 == 0);
} else {
final long key = Platform.getLong(loc.getKeyBase(), loc.getKeyOffset());
Assert.assertEquals(value, key);
}
valuesSeen.set((int) value);
if (destructive) {
// The iterator moves onto next page and frees previous page
if (map.getNumDataPages() < numPages) {
numPages = map.getNumDataPages();
countFreedPages++;
}
}
}
if (destructive) {
// Latest page is not freed by iterator but by map itself
Assert.assertEquals(countFreedPages, numPages - 1);
}
Assert.assertEquals(size, valuesSeen.cardinality());
} finally {
map.free();
}
}
@Test
public void iteratorTest() throws Exception {
iteratorTestBase(false);
}
@Test
public void destructiveIteratorTest() throws Exception {
iteratorTestBase(true);
}
@Test
public void iteratingOverDataPagesWithWastedSpace() throws Exception {
final int NUM_ENTRIES = 1000 * 1000;
final int KEY_LENGTH = 24;
final int VALUE_LENGTH = 40;
final BytesToBytesMap map =
new BytesToBytesMap(taskMemoryManager, NUM_ENTRIES, PAGE_SIZE_BYTES);
// Each record will take 8 + 24 + 40 = 72 bytes of space in the data page. Our 64-megabyte
// pages won't be evenly-divisible by records of this size, which will cause us to waste some
// space at the end of the page. This is necessary in order for us to take the end-of-record
// handling branch in iterator().
try {
for (int i = 0; i < NUM_ENTRIES; i++) {
final long[] key = new long[] { i, i, i }; // 3 * 8 = 24 bytes
final long[] value = new long[] { i, i, i, i, i }; // 5 * 8 = 40 bytes
final BytesToBytesMap.Location loc = map.lookup(
key,
Platform.LONG_ARRAY_OFFSET,
KEY_LENGTH
);
Assert.assertFalse(loc.isDefined());
Assert.assertTrue(loc.append(
key,
Platform.LONG_ARRAY_OFFSET,
KEY_LENGTH,
value,
Platform.LONG_ARRAY_OFFSET,
VALUE_LENGTH
));
}
Assert.assertEquals(2, map.getNumDataPages());
final java.util.BitSet valuesSeen = new java.util.BitSet(NUM_ENTRIES);
final Iterator<BytesToBytesMap.Location> iter = map.iterator();
final long[] key = new long[KEY_LENGTH / 8];
final long[] value = new long[VALUE_LENGTH / 8];
while (iter.hasNext()) {
final BytesToBytesMap.Location loc = iter.next();
Assert.assertTrue(loc.isDefined());
Assert.assertEquals(KEY_LENGTH, loc.getKeyLength());
Assert.assertEquals(VALUE_LENGTH, loc.getValueLength());
Platform.copyMemory(
loc.getKeyBase(),
loc.getKeyOffset(),
key,
Platform.LONG_ARRAY_OFFSET,
KEY_LENGTH
);
Platform.copyMemory(
loc.getValueBase(),
loc.getValueOffset(),
value,
Platform.LONG_ARRAY_OFFSET,
VALUE_LENGTH
);
for (long j : key) {
Assert.assertEquals(key[0], j);
}
for (long j : value) {
Assert.assertEquals(key[0], j);
}
valuesSeen.set((int) key[0]);
}
Assert.assertEquals(NUM_ENTRIES, valuesSeen.cardinality());
} finally {
map.free();
}
}
@Test
public void randomizedStressTest() {
final int size = 32768;
// Java arrays' hashCodes() aren't based on the arrays' contents, so we need to wrap arrays
// into ByteBuffers in order to use them as keys here.
final Map<ByteBuffer, byte[]> expected = new HashMap<>();
final BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, size, PAGE_SIZE_BYTES);
try {
// Fill the map to 90% full so that we can trigger probing
for (int i = 0; i < size * 0.9; i++) {
final byte[] key = getRandomByteArray(rand.nextInt(256) + 1);
final byte[] value = getRandomByteArray(rand.nextInt(256) + 1);
if (!expected.containsKey(ByteBuffer.wrap(key))) {
expected.put(ByteBuffer.wrap(key), value);
final BytesToBytesMap.Location loc = map.lookup(
key,
Platform.BYTE_ARRAY_OFFSET,
key.length
);
Assert.assertFalse(loc.isDefined());
Assert.assertTrue(loc.append(
key,
Platform.BYTE_ARRAY_OFFSET,
key.length,
value,
Platform.BYTE_ARRAY_OFFSET,
value.length
));
// After calling putNewKey, the following should be true, even before calling
// lookup():
Assert.assertTrue(loc.isDefined());
Assert.assertEquals(key.length, loc.getKeyLength());
Assert.assertEquals(value.length, loc.getValueLength());
Assert.assertTrue(arrayEquals(key, loc.getKeyBase(), loc.getKeyOffset(), key.length));
Assert.assertTrue(
arrayEquals(value, loc.getValueBase(), loc.getValueOffset(), value.length));
}
}
for (Map.Entry<ByteBuffer, byte[]> entry : expected.entrySet()) {
final byte[] key = JavaUtils.bufferToArray(entry.getKey());
final byte[] value = entry.getValue();
final BytesToBytesMap.Location loc =
map.lookup(key, Platform.BYTE_ARRAY_OFFSET, key.length);
Assert.assertTrue(loc.isDefined());
Assert.assertTrue(
arrayEquals(key, loc.getKeyBase(), loc.getKeyOffset(), loc.getKeyLength()));
Assert.assertTrue(
arrayEquals(value, loc.getValueBase(), loc.getValueOffset(), loc.getValueLength()));
}
} finally {
map.free();
}
}
@Test
public void randomizedTestWithRecordsLargerThanPageSize() {
final long pageSizeBytes = 128;
final BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, 64, pageSizeBytes);
// Java arrays' hashCodes() aren't based on the arrays' contents, so we need to wrap arrays
// into ByteBuffers in order to use them as keys here.
final Map<ByteBuffer, byte[]> expected = new HashMap<>();
try {
for (int i = 0; i < 1000; i++) {
final byte[] key = getRandomByteArray(rand.nextInt(128));
final byte[] value = getRandomByteArray(rand.nextInt(128));
if (!expected.containsKey(ByteBuffer.wrap(key))) {
expected.put(ByteBuffer.wrap(key), value);
final BytesToBytesMap.Location loc = map.lookup(
key,
Platform.BYTE_ARRAY_OFFSET,
key.length
);
Assert.assertFalse(loc.isDefined());
Assert.assertTrue(loc.append(
key,
Platform.BYTE_ARRAY_OFFSET,
key.length,
value,
Platform.BYTE_ARRAY_OFFSET,
value.length
));
// After calling putNewKey, the following should be true, even before calling
// lookup():
Assert.assertTrue(loc.isDefined());
Assert.assertEquals(key.length, loc.getKeyLength());
Assert.assertEquals(value.length, loc.getValueLength());
Assert.assertTrue(arrayEquals(key, loc.getKeyBase(), loc.getKeyOffset(), key.length));
Assert.assertTrue(
arrayEquals(value, loc.getValueBase(), loc.getValueOffset(), value.length));
}
}
for (Map.Entry<ByteBuffer, byte[]> entry : expected.entrySet()) {
final byte[] key = JavaUtils.bufferToArray(entry.getKey());
final byte[] value = entry.getValue();
final BytesToBytesMap.Location loc =
map.lookup(key, Platform.BYTE_ARRAY_OFFSET, key.length);
Assert.assertTrue(loc.isDefined());
Assert.assertTrue(
arrayEquals(key, loc.getKeyBase(), loc.getKeyOffset(), loc.getKeyLength()));
Assert.assertTrue(
arrayEquals(value, loc.getValueBase(), loc.getValueOffset(), loc.getValueLength()));
}
} finally {
map.free();
}
}
@Test
public void failureToAllocateFirstPage() {
memoryManager.limit(1024); // longArray
BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, 1, PAGE_SIZE_BYTES);
try {
final long[] emptyArray = new long[0];
final BytesToBytesMap.Location loc =
map.lookup(emptyArray, Platform.LONG_ARRAY_OFFSET, 0);
Assert.assertFalse(loc.isDefined());
Assert.assertFalse(loc.append(
emptyArray, Platform.LONG_ARRAY_OFFSET, 0, emptyArray, Platform.LONG_ARRAY_OFFSET, 0));
} finally {
map.free();
}
}
@Test
public void failureToGrow() {
BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, 1, 1024);
try {
boolean success = true;
int i;
for (i = 0; i < 127; i++) {
if (i > 0) {
memoryManager.limit(0);
}
final long[] arr = new long[]{i};
final BytesToBytesMap.Location loc = map.lookup(arr, Platform.LONG_ARRAY_OFFSET, 8);
success =
loc.append(arr, Platform.LONG_ARRAY_OFFSET, 8, arr, Platform.LONG_ARRAY_OFFSET, 8);
if (!success) {
break;
}
}
Assert.assertThat(i, greaterThan(0));
Assert.assertFalse(success);
} finally {
map.free();
}
}
@Test
public void spillInIterator() throws IOException {
BytesToBytesMap map = new BytesToBytesMap(
taskMemoryManager, blockManager, serializerManager, 1, 0.75, 1024);
try {
int i;
for (i = 0; i < 1024; i++) {
final long[] arr = new long[]{i};
final BytesToBytesMap.Location loc = map.lookup(arr, Platform.LONG_ARRAY_OFFSET, 8);
loc.append(arr, Platform.LONG_ARRAY_OFFSET, 8, arr, Platform.LONG_ARRAY_OFFSET, 8);
}
BytesToBytesMap.MapIterator iter = map.iterator();
for (i = 0; i < 100; i++) {
iter.next();
}
// Non-destructive iterator is not spillable
Assert.assertEquals(0, iter.spill(1024L * 10));
for (i = 100; i < 1024; i++) {
iter.next();
}
BytesToBytesMap.MapIterator iter2 = map.destructiveIterator();
for (i = 0; i < 100; i++) {
iter2.next();
}
Assert.assertTrue(iter2.spill(1024) >= 1024);
for (i = 100; i < 1024; i++) {
iter2.next();
}
assertFalse(iter2.hasNext());
} finally {
map.free();
for (File spillFile : spillFilesCreated) {
assertFalse("Spill file " + spillFile.getPath() + " was not cleaned up",
spillFile.exists());
}
}
}
@Test
public void multipleValuesForSameKey() {
BytesToBytesMap map =
new BytesToBytesMap(taskMemoryManager, blockManager, serializerManager, 1, 0.5, 1024);
try {
int i;
for (i = 0; i < 1024; i++) {
final long[] arr = new long[]{i};
map.lookup(arr, Platform.LONG_ARRAY_OFFSET, 8)
.append(arr, Platform.LONG_ARRAY_OFFSET, 8, arr, Platform.LONG_ARRAY_OFFSET, 8);
}
assert map.numKeys() == 1024;
assert map.numValues() == 1024;
for (i = 0; i < 1024; i++) {
final long[] arr = new long[]{i};
map.lookup(arr, Platform.LONG_ARRAY_OFFSET, 8)
.append(arr, Platform.LONG_ARRAY_OFFSET, 8, arr, Platform.LONG_ARRAY_OFFSET, 8);
}
assert map.numKeys() == 1024;
assert map.numValues() == 2048;
for (i = 0; i < 1024; i++) {
final long[] arr = new long[]{i};
final BytesToBytesMap.Location loc = map.lookup(arr, Platform.LONG_ARRAY_OFFSET, 8);
assert loc.isDefined();
assert loc.nextValue();
assert !loc.nextValue();
}
BytesToBytesMap.MapIterator iter = map.iterator();
for (i = 0; i < 2048; i++) {
assert iter.hasNext();
final BytesToBytesMap.Location loc = iter.next();
assert loc.isDefined();
}
} finally {
map.free();
}
}
@Test
public void initialCapacityBoundsChecking() {
try {
new BytesToBytesMap(taskMemoryManager, 0, PAGE_SIZE_BYTES);
Assert.fail("Expected IllegalArgumentException to be thrown");
} catch (IllegalArgumentException e) {
// expected exception
}
try {
new BytesToBytesMap(
taskMemoryManager,
BytesToBytesMap.MAX_CAPACITY + 1,
PAGE_SIZE_BYTES);
Assert.fail("Expected IllegalArgumentException to be thrown");
} catch (IllegalArgumentException e) {
// expected exception
}
try {
new BytesToBytesMap(
taskMemoryManager,
1,
TaskMemoryManager.MAXIMUM_PAGE_SIZE_BYTES + 1);
Assert.fail("Expected IllegalArgumentException to be thrown");
} catch (IllegalArgumentException e) {
// expected exception
}
}
@Test
public void testPeakMemoryUsed() {
final long recordLengthBytes = 32;
final long pageSizeBytes = 256 + 8; // 8 bytes for end-of-page marker
final long numRecordsPerPage = (pageSizeBytes - 8) / recordLengthBytes;
final BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, 1024, pageSizeBytes);
// Since BytesToBytesMap is append-only, we expect the total memory consumption to be
// monotonically increasing. More specifically, every time we allocate a new page it
// should increase by exactly the size of the page. In this regard, the memory usage
// at any given time is also the peak memory used.
long previousPeakMemory = map.getPeakMemoryUsedBytes();
long newPeakMemory;
try {
for (long i = 0; i < numRecordsPerPage * 10; i++) {
final long[] value = new long[]{i};
map.lookup(value, Platform.LONG_ARRAY_OFFSET, 8).append(
value,
Platform.LONG_ARRAY_OFFSET,
8,
value,
Platform.LONG_ARRAY_OFFSET,
8);
newPeakMemory = map.getPeakMemoryUsedBytes();
if (i % numRecordsPerPage == 0) {
// We allocated a new page for this record, so peak memory should change
assertEquals(previousPeakMemory + pageSizeBytes, newPeakMemory);
} else {
assertEquals(previousPeakMemory, newPeakMemory);
}
previousPeakMemory = newPeakMemory;
}
// Freeing the map should not change the peak memory
map.free();
newPeakMemory = map.getPeakMemoryUsedBytes();
assertEquals(previousPeakMemory, newPeakMemory);
} finally {
map.free();
}
}
}
|
core/src/test/java/org/apache/spark/unsafe/map/AbstractBytesToBytesMapSuite.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.unsafe.map;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import scala.Tuple2$;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.apache.spark.SparkConf;
import org.apache.spark.executor.ShuffleWriteMetrics;
import org.apache.spark.memory.TaskMemoryManager;
import org.apache.spark.memory.TestMemoryManager;
import org.apache.spark.network.util.JavaUtils;
import org.apache.spark.serializer.JavaSerializer;
import org.apache.spark.serializer.SerializerInstance;
import org.apache.spark.serializer.SerializerManager;
import org.apache.spark.storage.*;
import org.apache.spark.unsafe.Platform;
import org.apache.spark.unsafe.array.ByteArrayMethods;
import org.apache.spark.util.Utils;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Answers.RETURNS_SMART_NULLS;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.when;
public abstract class AbstractBytesToBytesMapSuite {
private final Random rand = new Random(42);
private TestMemoryManager memoryManager;
private TaskMemoryManager taskMemoryManager;
private SerializerManager serializerManager = new SerializerManager(
new JavaSerializer(new SparkConf()),
new SparkConf().set("spark.shuffle.spill.compress", "false"));
private static final long PAGE_SIZE_BYTES = 1L << 26; // 64 megabytes
final LinkedList<File> spillFilesCreated = new LinkedList<>();
File tempDir;
@Mock(answer = RETURNS_SMART_NULLS) BlockManager blockManager;
@Mock(answer = RETURNS_SMART_NULLS) DiskBlockManager diskBlockManager;
@Before
public void setup() {
memoryManager =
new TestMemoryManager(
new SparkConf()
.set("spark.memory.offHeap.enabled", "" + useOffHeapMemoryAllocator())
.set("spark.memory.offHeap.size", "256mb")
.set("spark.shuffle.spill.compress", "false")
.set("spark.shuffle.compress", "false"));
taskMemoryManager = new TaskMemoryManager(memoryManager, 0);
tempDir = Utils.createTempDir(System.getProperty("java.io.tmpdir"), "unsafe-test");
spillFilesCreated.clear();
MockitoAnnotations.initMocks(this);
when(blockManager.diskBlockManager()).thenReturn(diskBlockManager);
when(diskBlockManager.createTempLocalBlock()).thenAnswer(invocationOnMock -> {
TempLocalBlockId blockId = new TempLocalBlockId(UUID.randomUUID());
File file = File.createTempFile("spillFile", ".spill", tempDir);
spillFilesCreated.add(file);
return Tuple2$.MODULE$.apply(blockId, file);
});
when(blockManager.getDiskWriter(
any(BlockId.class),
any(File.class),
any(SerializerInstance.class),
anyInt(),
any(ShuffleWriteMetrics.class))).thenAnswer(invocationOnMock -> {
Object[] args = invocationOnMock.getArguments();
return new DiskBlockObjectWriter(
(File) args[1],
serializerManager,
(SerializerInstance) args[2],
(Integer) args[3],
false,
(ShuffleWriteMetrics) args[4],
(BlockId) args[0]
);
});
}
@After
public void tearDown() {
Utils.deleteRecursively(tempDir);
tempDir = null;
if (taskMemoryManager != null) {
Assert.assertEquals(0L, taskMemoryManager.cleanUpAllAllocatedMemory());
long leakedMemory = taskMemoryManager.getMemoryConsumptionForThisTask();
taskMemoryManager = null;
Assert.assertEquals(0L, leakedMemory);
}
}
protected abstract boolean useOffHeapMemoryAllocator();
private static byte[] getByteArray(Object base, long offset, int size) {
final byte[] arr = new byte[size];
Platform.copyMemory(base, offset, arr, Platform.BYTE_ARRAY_OFFSET, size);
return arr;
}
private byte[] getRandomByteArray(int numWords) {
Assert.assertTrue(numWords >= 0);
final int lengthInBytes = numWords * 8;
final byte[] bytes = new byte[lengthInBytes];
rand.nextBytes(bytes);
return bytes;
}
/**
* Fast equality checking for byte arrays, since these comparisons are a bottleneck
* in our stress tests.
*/
private static boolean arrayEquals(
byte[] expected,
Object base,
long offset,
long actualLengthBytes) {
return (actualLengthBytes == expected.length) && ByteArrayMethods.arrayEquals(
expected,
Platform.BYTE_ARRAY_OFFSET,
base,
offset,
expected.length
);
}
@Test
public void emptyMap() {
BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, 64, PAGE_SIZE_BYTES);
try {
Assert.assertEquals(0, map.numKeys());
final int keyLengthInWords = 10;
final int keyLengthInBytes = keyLengthInWords * 8;
final byte[] key = getRandomByteArray(keyLengthInWords);
Assert.assertFalse(map.lookup(key, Platform.BYTE_ARRAY_OFFSET, keyLengthInBytes).isDefined());
Assert.assertFalse(map.iterator().hasNext());
} finally {
map.free();
}
}
@Test
public void setAndRetrieveAKey() {
BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, 64, PAGE_SIZE_BYTES);
final int recordLengthWords = 10;
final int recordLengthBytes = recordLengthWords * 8;
final byte[] keyData = getRandomByteArray(recordLengthWords);
final byte[] valueData = getRandomByteArray(recordLengthWords);
try {
final BytesToBytesMap.Location loc =
map.lookup(keyData, Platform.BYTE_ARRAY_OFFSET, recordLengthBytes);
Assert.assertFalse(loc.isDefined());
Assert.assertTrue(loc.append(
keyData,
Platform.BYTE_ARRAY_OFFSET,
recordLengthBytes,
valueData,
Platform.BYTE_ARRAY_OFFSET,
recordLengthBytes
));
// After storing the key and value, the other location methods should return results that
// reflect the result of this store without us having to call lookup() again on the same key.
Assert.assertEquals(recordLengthBytes, loc.getKeyLength());
Assert.assertEquals(recordLengthBytes, loc.getValueLength());
Assert.assertArrayEquals(keyData,
getByteArray(loc.getKeyBase(), loc.getKeyOffset(), recordLengthBytes));
Assert.assertArrayEquals(valueData,
getByteArray(loc.getValueBase(), loc.getValueOffset(), recordLengthBytes));
// After calling lookup() the location should still point to the correct data.
Assert.assertTrue(
map.lookup(keyData, Platform.BYTE_ARRAY_OFFSET, recordLengthBytes).isDefined());
Assert.assertEquals(recordLengthBytes, loc.getKeyLength());
Assert.assertEquals(recordLengthBytes, loc.getValueLength());
Assert.assertArrayEquals(keyData,
getByteArray(loc.getKeyBase(), loc.getKeyOffset(), recordLengthBytes));
Assert.assertArrayEquals(valueData,
getByteArray(loc.getValueBase(), loc.getValueOffset(), recordLengthBytes));
try {
Assert.assertTrue(loc.append(
keyData,
Platform.BYTE_ARRAY_OFFSET,
recordLengthBytes,
valueData,
Platform.BYTE_ARRAY_OFFSET,
recordLengthBytes
));
Assert.fail("Should not be able to set a new value for a key");
} catch (AssertionError e) {
// Expected exception; do nothing.
}
} finally {
map.free();
}
}
private void iteratorTestBase(boolean destructive) throws Exception {
final int size = 4096;
BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, size / 2, PAGE_SIZE_BYTES);
try {
for (long i = 0; i < size; i++) {
final long[] value = new long[] { i };
final BytesToBytesMap.Location loc =
map.lookup(value, Platform.LONG_ARRAY_OFFSET, 8);
Assert.assertFalse(loc.isDefined());
// Ensure that we store some zero-length keys
if (i % 5 == 0) {
Assert.assertTrue(loc.append(
null,
Platform.LONG_ARRAY_OFFSET,
0,
value,
Platform.LONG_ARRAY_OFFSET,
8
));
} else {
Assert.assertTrue(loc.append(
value,
Platform.LONG_ARRAY_OFFSET,
8,
value,
Platform.LONG_ARRAY_OFFSET,
8
));
}
}
final java.util.BitSet valuesSeen = new java.util.BitSet(size);
final Iterator<BytesToBytesMap.Location> iter;
if (destructive) {
iter = map.destructiveIterator();
} else {
iter = map.iterator();
}
int numPages = map.getNumDataPages();
int countFreedPages = 0;
while (iter.hasNext()) {
final BytesToBytesMap.Location loc = iter.next();
Assert.assertTrue(loc.isDefined());
final long value = Platform.getLong(loc.getValueBase(), loc.getValueOffset());
final long keyLength = loc.getKeyLength();
if (keyLength == 0) {
Assert.assertTrue("value " + value + " was not divisible by 5", value % 5 == 0);
} else {
final long key = Platform.getLong(loc.getKeyBase(), loc.getKeyOffset());
Assert.assertEquals(value, key);
}
valuesSeen.set((int) value);
if (destructive) {
// The iterator moves onto next page and frees previous page
if (map.getNumDataPages() < numPages) {
numPages = map.getNumDataPages();
countFreedPages++;
}
}
}
if (destructive) {
// Latest page is not freed by iterator but by map itself
Assert.assertEquals(countFreedPages, numPages - 1);
}
Assert.assertEquals(size, valuesSeen.cardinality());
} finally {
map.free();
}
}
@Test
public void iteratorTest() throws Exception {
iteratorTestBase(false);
}
@Test
public void destructiveIteratorTest() throws Exception {
iteratorTestBase(true);
}
@Test
public void iteratingOverDataPagesWithWastedSpace() throws Exception {
final int NUM_ENTRIES = 1000 * 1000;
final int KEY_LENGTH = 24;
final int VALUE_LENGTH = 40;
final BytesToBytesMap map =
new BytesToBytesMap(taskMemoryManager, NUM_ENTRIES, PAGE_SIZE_BYTES);
// Each record will take 8 + 24 + 40 = 72 bytes of space in the data page. Our 64-megabyte
// pages won't be evenly-divisible by records of this size, which will cause us to waste some
// space at the end of the page. This is necessary in order for us to take the end-of-record
// handling branch in iterator().
try {
for (int i = 0; i < NUM_ENTRIES; i++) {
final long[] key = new long[] { i, i, i }; // 3 * 8 = 24 bytes
final long[] value = new long[] { i, i, i, i, i }; // 5 * 8 = 40 bytes
final BytesToBytesMap.Location loc = map.lookup(
key,
Platform.LONG_ARRAY_OFFSET,
KEY_LENGTH
);
Assert.assertFalse(loc.isDefined());
Assert.assertTrue(loc.append(
key,
Platform.LONG_ARRAY_OFFSET,
KEY_LENGTH,
value,
Platform.LONG_ARRAY_OFFSET,
VALUE_LENGTH
));
}
Assert.assertEquals(2, map.getNumDataPages());
final java.util.BitSet valuesSeen = new java.util.BitSet(NUM_ENTRIES);
final Iterator<BytesToBytesMap.Location> iter = map.iterator();
final long[] key = new long[KEY_LENGTH / 8];
final long[] value = new long[VALUE_LENGTH / 8];
while (iter.hasNext()) {
final BytesToBytesMap.Location loc = iter.next();
Assert.assertTrue(loc.isDefined());
Assert.assertEquals(KEY_LENGTH, loc.getKeyLength());
Assert.assertEquals(VALUE_LENGTH, loc.getValueLength());
Platform.copyMemory(
loc.getKeyBase(),
loc.getKeyOffset(),
key,
Platform.LONG_ARRAY_OFFSET,
KEY_LENGTH
);
Platform.copyMemory(
loc.getValueBase(),
loc.getValueOffset(),
value,
Platform.LONG_ARRAY_OFFSET,
VALUE_LENGTH
);
for (long j : key) {
Assert.assertEquals(key[0], j);
}
for (long j : value) {
Assert.assertEquals(key[0], j);
}
valuesSeen.set((int) key[0]);
}
Assert.assertEquals(NUM_ENTRIES, valuesSeen.cardinality());
} finally {
map.free();
}
}
@Test
public void randomizedStressTest() {
final int size = 32768;
// Java arrays' hashCodes() aren't based on the arrays' contents, so we need to wrap arrays
// into ByteBuffers in order to use them as keys here.
final Map<ByteBuffer, byte[]> expected = new HashMap<>();
final BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, size, PAGE_SIZE_BYTES);
try {
// Fill the map to 90% full so that we can trigger probing
for (int i = 0; i < size * 0.9; i++) {
final byte[] key = getRandomByteArray(rand.nextInt(256) + 1);
final byte[] value = getRandomByteArray(rand.nextInt(256) + 1);
if (!expected.containsKey(ByteBuffer.wrap(key))) {
expected.put(ByteBuffer.wrap(key), value);
final BytesToBytesMap.Location loc = map.lookup(
key,
Platform.BYTE_ARRAY_OFFSET,
key.length
);
Assert.assertFalse(loc.isDefined());
Assert.assertTrue(loc.append(
key,
Platform.BYTE_ARRAY_OFFSET,
key.length,
value,
Platform.BYTE_ARRAY_OFFSET,
value.length
));
// After calling putNewKey, the following should be true, even before calling
// lookup():
Assert.assertTrue(loc.isDefined());
Assert.assertEquals(key.length, loc.getKeyLength());
Assert.assertEquals(value.length, loc.getValueLength());
Assert.assertTrue(arrayEquals(key, loc.getKeyBase(), loc.getKeyOffset(), key.length));
Assert.assertTrue(
arrayEquals(value, loc.getValueBase(), loc.getValueOffset(), value.length));
}
}
for (Map.Entry<ByteBuffer, byte[]> entry : expected.entrySet()) {
final byte[] key = JavaUtils.bufferToArray(entry.getKey());
final byte[] value = entry.getValue();
final BytesToBytesMap.Location loc =
map.lookup(key, Platform.BYTE_ARRAY_OFFSET, key.length);
Assert.assertTrue(loc.isDefined());
Assert.assertTrue(
arrayEquals(key, loc.getKeyBase(), loc.getKeyOffset(), loc.getKeyLength()));
Assert.assertTrue(
arrayEquals(value, loc.getValueBase(), loc.getValueOffset(), loc.getValueLength()));
}
} finally {
map.free();
}
}
@Test
public void randomizedTestWithRecordsLargerThanPageSize() {
final long pageSizeBytes = 128;
final BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, 64, pageSizeBytes);
// Java arrays' hashCodes() aren't based on the arrays' contents, so we need to wrap arrays
// into ByteBuffers in order to use them as keys here.
final Map<ByteBuffer, byte[]> expected = new HashMap<>();
try {
for (int i = 0; i < 1000; i++) {
final byte[] key = getRandomByteArray(rand.nextInt(128));
final byte[] value = getRandomByteArray(rand.nextInt(128));
if (!expected.containsKey(ByteBuffer.wrap(key))) {
expected.put(ByteBuffer.wrap(key), value);
final BytesToBytesMap.Location loc = map.lookup(
key,
Platform.BYTE_ARRAY_OFFSET,
key.length
);
Assert.assertFalse(loc.isDefined());
Assert.assertTrue(loc.append(
key,
Platform.BYTE_ARRAY_OFFSET,
key.length,
value,
Platform.BYTE_ARRAY_OFFSET,
value.length
));
// After calling putNewKey, the following should be true, even before calling
// lookup():
Assert.assertTrue(loc.isDefined());
Assert.assertEquals(key.length, loc.getKeyLength());
Assert.assertEquals(value.length, loc.getValueLength());
Assert.assertTrue(arrayEquals(key, loc.getKeyBase(), loc.getKeyOffset(), key.length));
Assert.assertTrue(
arrayEquals(value, loc.getValueBase(), loc.getValueOffset(), value.length));
}
}
for (Map.Entry<ByteBuffer, byte[]> entry : expected.entrySet()) {
final byte[] key = JavaUtils.bufferToArray(entry.getKey());
final byte[] value = entry.getValue();
final BytesToBytesMap.Location loc =
map.lookup(key, Platform.BYTE_ARRAY_OFFSET, key.length);
Assert.assertTrue(loc.isDefined());
Assert.assertTrue(
arrayEquals(key, loc.getKeyBase(), loc.getKeyOffset(), loc.getKeyLength()));
Assert.assertTrue(
arrayEquals(value, loc.getValueBase(), loc.getValueOffset(), loc.getValueLength()));
}
} finally {
map.free();
}
}
@Test
public void failureToAllocateFirstPage() {
memoryManager.limit(1024); // longArray
BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, 1, PAGE_SIZE_BYTES);
try {
final long[] emptyArray = new long[0];
final BytesToBytesMap.Location loc =
map.lookup(emptyArray, Platform.LONG_ARRAY_OFFSET, 0);
Assert.assertFalse(loc.isDefined());
Assert.assertFalse(loc.append(
emptyArray, Platform.LONG_ARRAY_OFFSET, 0, emptyArray, Platform.LONG_ARRAY_OFFSET, 0));
} finally {
map.free();
}
}
@Test
public void failureToGrow() {
BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, 1, 1024);
try {
boolean success = true;
int i;
for (i = 0; i < 127; i++) {
if (i > 0) {
memoryManager.limit(0);
}
final long[] arr = new long[]{i};
final BytesToBytesMap.Location loc = map.lookup(arr, Platform.LONG_ARRAY_OFFSET, 8);
success =
loc.append(arr, Platform.LONG_ARRAY_OFFSET, 8, arr, Platform.LONG_ARRAY_OFFSET, 8);
if (!success) {
break;
}
}
Assert.assertThat(i, greaterThan(0));
Assert.assertFalse(success);
} finally {
map.free();
}
}
@Test
public void spillInIterator() throws IOException {
BytesToBytesMap map = new BytesToBytesMap(
taskMemoryManager, blockManager, serializerManager, 1, 0.75, 1024);
try {
int i;
for (i = 0; i < 1024; i++) {
final long[] arr = new long[]{i};
final BytesToBytesMap.Location loc = map.lookup(arr, Platform.LONG_ARRAY_OFFSET, 8);
loc.append(arr, Platform.LONG_ARRAY_OFFSET, 8, arr, Platform.LONG_ARRAY_OFFSET, 8);
}
BytesToBytesMap.MapIterator iter = map.iterator();
for (i = 0; i < 100; i++) {
iter.next();
}
// Non-destructive iterator is not spillable
Assert.assertEquals(0, iter.spill(1024L * 10));
for (i = 100; i < 1024; i++) {
iter.next();
}
BytesToBytesMap.MapIterator iter2 = map.destructiveIterator();
for (i = 0; i < 100; i++) {
iter2.next();
}
Assert.assertTrue(iter2.spill(1024) >= 1024);
for (i = 100; i < 1024; i++) {
iter2.next();
}
assertFalse(iter2.hasNext());
} finally {
map.free();
for (File spillFile : spillFilesCreated) {
assertFalse("Spill file " + spillFile.getPath() + " was not cleaned up",
spillFile.exists());
}
}
}
@Test
public void multipleValuesForSameKey() {
BytesToBytesMap map =
new BytesToBytesMap(taskMemoryManager, blockManager, serializerManager, 1, 0.5, 1024);
try {
int i;
for (i = 0; i < 1024; i++) {
final long[] arr = new long[]{i};
map.lookup(arr, Platform.LONG_ARRAY_OFFSET, 8)
.append(arr, Platform.LONG_ARRAY_OFFSET, 8, arr, Platform.LONG_ARRAY_OFFSET, 8);
}
assert map.numKeys() == 1024;
assert map.numValues() == 1024;
for (i = 0; i < 1024; i++) {
final long[] arr = new long[]{i};
map.lookup(arr, Platform.LONG_ARRAY_OFFSET, 8)
.append(arr, Platform.LONG_ARRAY_OFFSET, 8, arr, Platform.LONG_ARRAY_OFFSET, 8);
}
assert map.numKeys() == 1024;
assert map.numValues() == 2048;
for (i = 0; i < 1024; i++) {
final long[] arr = new long[]{i};
final BytesToBytesMap.Location loc = map.lookup(arr, Platform.LONG_ARRAY_OFFSET, 8);
assert loc.isDefined();
assert loc.nextValue();
assert !loc.nextValue();
}
BytesToBytesMap.MapIterator iter = map.iterator();
for (i = 0; i < 2048; i++) {
assert iter.hasNext();
final BytesToBytesMap.Location loc = iter.next();
assert loc.isDefined();
}
} finally {
map.free();
}
}
@Test
public void initialCapacityBoundsChecking() {
try {
new BytesToBytesMap(taskMemoryManager, 0, PAGE_SIZE_BYTES);
Assert.fail("Expected IllegalArgumentException to be thrown");
} catch (IllegalArgumentException e) {
// expected exception
}
try {
new BytesToBytesMap(
taskMemoryManager,
BytesToBytesMap.MAX_CAPACITY + 1,
PAGE_SIZE_BYTES);
Assert.fail("Expected IllegalArgumentException to be thrown");
} catch (IllegalArgumentException e) {
// expected exception
}
}
@Test
public void testPeakMemoryUsed() {
final long recordLengthBytes = 32;
final long pageSizeBytes = 256 + 8; // 8 bytes for end-of-page marker
final long numRecordsPerPage = (pageSizeBytes - 8) / recordLengthBytes;
final BytesToBytesMap map = new BytesToBytesMap(taskMemoryManager, 1024, pageSizeBytes);
// Since BytesToBytesMap is append-only, we expect the total memory consumption to be
// monotonically increasing. More specifically, every time we allocate a new page it
// should increase by exactly the size of the page. In this regard, the memory usage
// at any given time is also the peak memory used.
long previousPeakMemory = map.getPeakMemoryUsedBytes();
long newPeakMemory;
try {
for (long i = 0; i < numRecordsPerPage * 10; i++) {
final long[] value = new long[]{i};
map.lookup(value, Platform.LONG_ARRAY_OFFSET, 8).append(
value,
Platform.LONG_ARRAY_OFFSET,
8,
value,
Platform.LONG_ARRAY_OFFSET,
8);
newPeakMemory = map.getPeakMemoryUsedBytes();
if (i % numRecordsPerPage == 0) {
// We allocated a new page for this record, so peak memory should change
assertEquals(previousPeakMemory + pageSizeBytes, newPeakMemory);
} else {
assertEquals(previousPeakMemory, newPeakMemory);
}
previousPeakMemory = newPeakMemory;
}
// Freeing the map should not change the peak memory
map.free();
newPeakMemory = map.getPeakMemoryUsedBytes();
assertEquals(previousPeakMemory, newPeakMemory);
} finally {
map.free();
}
}
}
|
[SPARK-26286][TEST] Add MAXIMUM_PAGE_SIZE_BYTES exception bound unit test
## What changes were proposed in this pull request?
Add MAXIMUM_PAGE_SIZE_BYTES Exception test
## How was this patch tested?
Existing tests
(Please explain how this patch was tested. E.g. unit tests, integration tests, manual tests)
(If this patch involves UI changes, please attach a screenshot; otherwise, remove this)
Please review http://spark.apache.org/contributing.html before opening a pull request.
Closes #23226 from wangjiaochun/BytesToBytesMapSuite.
Authored-by: 10087686 <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
|
core/src/test/java/org/apache/spark/unsafe/map/AbstractBytesToBytesMapSuite.java
|
[SPARK-26286][TEST] Add MAXIMUM_PAGE_SIZE_BYTES exception bound unit test
|
<ide><path>ore/src/test/java/org/apache/spark/unsafe/map/AbstractBytesToBytesMapSuite.java
<ide> } catch (IllegalArgumentException e) {
<ide> // expected exception
<ide> }
<add>
<add> try {
<add> new BytesToBytesMap(
<add> taskMemoryManager,
<add> 1,
<add> TaskMemoryManager.MAXIMUM_PAGE_SIZE_BYTES + 1);
<add> Assert.fail("Expected IllegalArgumentException to be thrown");
<add> } catch (IllegalArgumentException e) {
<add> // expected exception
<add> }
<add>
<ide> }
<ide>
<ide> @Test
|
|
JavaScript
|
mit
|
5981ddf89f57344161d5567553ce053e474ff1a2
| 0 |
luisbrito/paper.js,ClaireRutkoske/paper.js,fredoche/paper.js,mcanthony/paper.js,byte-foundry/paper.js,chad-autry/paper.js,baiyanghese/paper.js,superjudge/paper.js,nancymark/paper.js,lehni/paper.js,byte-foundry/paper.js,lehni/paper.js,iconexperience/paper.js,JunaidPaul/paper.js,li0t/paper.js,EskenderDev/paper.js,rgordeev/paper.js,byte-foundry/paper.js,nancymark/paper.js,fredoche/paper.js,JunaidPaul/paper.js,li0t/paper.js,mcanthony/paper.js,lehni/paper.js,li0t/paper.js,Olegas/paper.js,EskenderDev/paper.js,rgordeev/paper.js,legendvijay/paper.js,baiyanghese/paper.js,mcanthony/paper.js,proofme/paper.js,iconexperience/paper.js,legendvijay/paper.js,rgordeev/paper.js,proofme/paper.js,ClaireRutkoske/paper.js,JunaidPaul/paper.js,superjudge/paper.js,superjudge/paper.js,luisbrito/paper.js,nancymark/paper.js,luisbrito/paper.js,proofme/paper.js,fredoche/paper.js,legendvijay/paper.js,Olegas/paper.js,ClaireRutkoske/paper.js,baiyanghese/paper.js,Olegas/paper.js,EskenderDev/paper.js,iconexperience/paper.js
|
/*
* Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
* http://paperjs.org/
*
* Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*/
/**
* @name Raster
*
* @class The Raster item represents an image in a Paper.js project.
*
* @extends Item
*/
var Raster = Item.extend(/** @lends Raster# */{
_class: 'Raster',
_transformContent: false,
// Raster doesn't make the distinction between the different bounds,
// so use the same name for all of them
_boundsGetter: 'getBounds',
_boundsSelected: true,
_serializeFields: {
source: null
},
// TODO: Implement type, width, height.
// TODO: Have PlacedSymbol & Raster inherit from a shared class?
/**
* Creates a new raster item from the passed argument, and places it in the
* active layer. {@code object} can either be a DOM Image, a Canvas, or a
* string describing the URL to load the image from, or the ID of a DOM
* element to get the image from (either a DOM Image or a Canvas).
*
* @param {HTMLImageElement|Canvas|String} [source] the source of the raster
* @param {HTMLImageElement|Canvas|String} [position] the center position at
* which the raster item is placed.
*
* @example {@paperscript height=300} // Creating a raster using a url
* var url = 'http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png';
* var raster = new Raster(url);
*
* // If you create a Raster using a url, you can use the onLoad
* // handler to do something once it is loaded:
* raster.onLoad = function() {
* console.log('The image has loaded.');
* };
*
* @example // Creating a raster using the id of a DOM Image:
*
* // Create a raster using the id of the image:
* var raster = new Raster('art');
*
* @example // Creating a raster using a DOM Image:
*
* // Find the element using its id:
* var imageElement = document.getElementById('art');
*
* // Create the raster:
* var raster = new Raster(imageElement);
*
* @example {@paperscript height=300}
* var raster = new Raster({
* source: 'http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png',
* position: view.center
* });
*
* raster.scale(0.5);
* raster.rotate(10);
*/
initialize: function Raster(object, position) {
// Support two forms of item initialization: Passing one object literal
// describing all the different properties to be set, or an image
// (object) and a point where it should be placed (point).
// If _initialize can set properties through object literal, we're done.
// Otherwise we need to check the type of object:
if (!this._initialize(object,
position !== undefined && Point.read(arguments, 1))) {
if (object.getContext) {
this.setCanvas(object);
} else if (typeof object === 'string') {
// Both data-urls and normal urls are supported here!
this.setSource(object);
} else {
this.setImage(object);
}
}
if (!this._size)
this._size = new Size();
},
clone: function(insert) {
var param = { insert: false },
image = this._image;
if (image) {
param.image = image;
} else if (this._canvas) {
// If the Raster contains a Canvas object, we need to create
// a new one and draw this raster's canvas on it.
var canvas = param.canvas = CanvasProvider.getCanvas(this._size);
canvas.getContext('2d').drawImage(this._canvas, 0, 0);
}
return this._clone(new Raster(param), insert);
},
/**
* The size of the raster in pixels.
*
* @type Size
* @bean
*/
getSize: function() {
var size = this._size;
return new LinkedSize(size.width, size.height, this, 'setSize');
},
setSize: function(/* size */) {
var size = Size.read(arguments);
if (!this._size.equals(size)) {
// Get reference to image before changing canvas
var element = this.getElement();
// Setting canvas internally sets _size
this.setCanvas(CanvasProvider.getCanvas(size));
// Draw element back onto new canvas
if (element)
this.getContext(true).drawImage(element, 0, 0,
size.width, size.height);
}
},
/**
* The width of the raster in pixels.
*
* @type Number
* @bean
*/
getWidth: function() {
return this._size.width;
},
/**
* The height of the raster in pixels.
*
* @type Number
* @bean
*/
getHeight: function() {
return this._size.height;
},
isEmpty: function() {
return this._size.width == 0 && this._size.height == 0;
},
/**
* Pixels per inch of the raster at its current size.
*
* @type Size
* @bean
*/
getPpi: function() {
var matrix = this._matrix,
orig = new Point(0, 0).transform(matrix),
u = new Point(1, 0).transform(matrix).subtract(orig),
v = new Point(0, 1).transform(matrix).subtract(orig);
return new Size(
72 / u.getLength(),
72 / v.getLength()
);
},
/**
* The Canvas 2d drawing context of the raster.
*
* @type Context
* @bean
*/
getContext: function(/* modify */) {
if (!this._context)
this._context = this.getCanvas().getContext('2d');
// Support a hidden parameter that indicates if the context will be used
// to modify the Raster object. We can notify such changes ahead since
// they are only used afterwards for redrawing.
if (arguments[0]) {
// Also set _image to null since the Raster stops representing it.
// NOTE: This should theoretically be in our own _changed() handler
// for ChangeFlag.PIXELS, but since it's only happening in one place
// this is fine:
this._image = null;
this._changed(/*#=*/ Change.PIXELS);
}
return this._context;
},
setContext: function(context) {
this._context = context;
},
getCanvas: function() {
if (!this._canvas) {
var ctx = CanvasProvider.getContext(this._size);
// Since drawimage images into canvases might fail based on security
// policies, wrap the call in try-catch and only set _canvas if we
// succeeded.
try {
if (this._image)
ctx.drawImage(this._image, 0, 0);
this._canvas = ctx.canvas;
} catch (e) {
CanvasProvider.release(ctx);
}
}
return this._canvas;
},
setCanvas: function(canvas) {
if (this._canvas)
CanvasProvider.release(this._canvas);
this._canvas = canvas;
this._size = new Size(canvas.width, canvas.height);
this._image = null;
this._context = null;
this._changed(/*#=*/ Change.GEOMETRY | /*#=*/ Change.PIXELS);
},
/**
* The HTMLImageElement of the raster, if one is associated.
*
* @type HTMLImageElement|Canvas
* @bean
*/
getImage: function() {
return this._image;
},
setImage: function(image) {
if (this._canvas)
CanvasProvider.release(this._canvas);
this._image = image;
this._size = new Size(image.width, image.height);
this._canvas = null;
this._context = null;
this._changed(/*#=*/ Change.GEOMETRY);
},
/**
* The source of the raster, which can be set using a DOM Image, a Canvas,
* a data url, a string describing the URL to load the image from, or the
* ID of a DOM element to get the image from (either a DOM Image or a
* Canvas). Reading this property will return the url of the source image or
* a data-url.
*
* @bean
* @type HTMLImageElement|Canvas|String
*
* @example {@paperscript}
* var raster = new Raster();
* raster.source = 'http://paperjs.org/about/resources/paper-js.gif';
* raster.position = view.center;
*
* @example {@paperscript}
* var raster = new Raster({
* source: 'http://paperjs.org/about/resources/paper-js.gif',
* position: view.center
* });
*/
getSource: function() {
return this._image && this._image.src || this.toDataURL();
},
setSource: function(src) {
/*#*/ if (options.browser) {
var that = this,
// src can be an URL or a DOM ID to load the image from
image = document.getElementById(src) || new Image();
function loaded() {
that.fire('load');
if (that._project.view)
that._project.view.draw(true);
}
if (image.width && image.height) {
// Fire load event delayed, so behavior is the same as when it's
// actually loaded and we give the code time to install event
setTimeout(loaded, 0);
} else if (!image.src) {
// Trigger the onLoad event on the image once it's loaded
DomEvent.add(image, {
load: function() {
that.setImage(image);
loaded();
}
});
image.src = src;
}
this.setImage(image);
/*#*/ } else if (options.node) {
var image = new Image();
// If we're running on the server and it's a string,
// check if it is a data URL
if (/^data:/.test(src)) {
// Preserve the data in this._data since canvas-node eats it.
// TODO: Fix canvas-node instead
image.src = this._data = src;
} else {
// Load it from disk:
// TODO: load images async, calling setImage once loaded as above.
image.src = fs.readFileSync(src);
}
this.setImage(image);
/*#*/ } // options.node
},
// DOCS: document Raster#getElement
getElement: function() {
return this._canvas || this._image;
},
/**
* Extracts a part of the Raster's content as a sub image, and returns it as
* a Canvas object.
*
* @param {Rectangle} rect the boundaries of the sub image in pixel
* coordinates
*
* @return {Canvas} the sub image as a Canvas object
*/
getSubImage: function(rect) {
rect = Rectangle.read(arguments);
var ctx = CanvasProvider.getContext(rect.getSize());
ctx.drawImage(this.getCanvas(), rect.x, rect.y,
rect.width, rect.height, 0, 0, rect.width, rect.height);
return ctx.canvas;
},
/**
* Extracts a part of the raster item's content as a new raster item, placed
* in exactly the same place as the original content.
*
* @param {Rectangle} rect the boundaries of the sub raster in pixel
* coordinates
*
* @return {Raster} the sub raster as a newly created raster item
*/
getSubRaster: function(rect) {
rect = Rectangle.read(arguments);
var raster = new Raster(this.getSubImage(rect));
raster.translate(rect.getCenter().subtract(this.getSize().divide(2)));
raster._matrix.preConcatenate(this._matrix);
return raster;
},
/**
* Returns a Base 64 encoded {@code data:} URL representation of the raster.
*
* @return {String}
*/
toDataURL: function() {
// See if the linked image is base64 encoded already, if so reuse it,
// otherwise try using canvas.toDataURL()
/*#*/ if (options.node) {
if (this._data)
return this._data;
/*#*/ } else {
var src = this._image && this._image.src;
if (/^data:/.test(src))
return src;
/*#*/ }
var canvas = this.getCanvas();
return canvas ? canvas.toDataURL() : null;
},
/**
* Draws an image on the raster.
*
* @param {HTMLImageELement|Canvas} image
* @param {Point} point the offset of the image as a point in pixel
* coordinates
*/
drawImage: function(image, point) {
point = Point.read(arguments, 1);
this.getContext(true).drawImage(image, point.x, point.y);
},
/**
* Calculates the average color of the image within the given path,
* rectangle or point. This can be used for creating raster image
* effects.
*
* @param {Path|Rectangle|Point} object
* @return {Color} the average color contained in the area covered by the
* specified path, rectangle or point.
*/
getAverageColor: function(object) {
var bounds, path;
if (!object) {
bounds = this.getBounds();
} else if (object instanceof PathItem) {
// TODO: What if the path is smaller than 1 px?
// TODO: How about rounding of bounds.size?
path = object;
bounds = object.getBounds();
} else if (object.width) {
bounds = new Rectangle(object);
} else if (object.x) {
// Create a rectangle of 1px size around the specified coordinates
bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1);
}
// Use a sample size of max 32 x 32 pixels, into which the path is
// scaled as a clipping path, and then the actual image is drawn in and
// sampled.
var sampleSize = 32,
width = Math.min(bounds.width, sampleSize),
height = Math.min(bounds.height, sampleSize);
// Reuse the same sample context for speed. Memory consumption is low
// since it's only 32 x 32 pixels.
var ctx = Raster._sampleContext;
if (!ctx) {
ctx = Raster._sampleContext = CanvasProvider.getContext(
new Size(sampleSize));
} else {
// Clear the sample canvas:
ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1);
}
ctx.save();
// Scale the context so that the bounds ends up at the given sample size
var matrix = new Matrix()
.scale(width / bounds.width, height / bounds.height)
.translate(-bounds.x, -bounds.y);
matrix.applyToContext(ctx);
// If a path was passed, draw it as a clipping mask:
// See Project#draw() for an explanation of Base.merge()
if (path)
path.draw(ctx, Base.merge({ clip: true, transforms: [matrix] }));
// Now draw the image clipped into it.
this._matrix.applyToContext(ctx);
ctx.drawImage(this.getElement(),
-this._size.width / 2, -this._size.height / 2);
ctx.restore();
// Get pixel data from the context and calculate the average color value
// from it, taking alpha into account.
var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
Math.ceil(height)).data,
channels = [0, 0, 0],
total = 0;
for (var i = 0, l = pixels.length; i < l; i += 4) {
var alpha = pixels[i + 3];
total += alpha;
alpha /= 255;
channels[0] += pixels[i] * alpha;
channels[1] += pixels[i + 1] * alpha;
channels[2] += pixels[i + 2] * alpha;
}
for (var i = 0; i < 3; i++)
channels[i] /= total;
return total ? Color.read(channels) : null;
},
/**
* {@grouptitle Pixels}
* Gets the color of a pixel in the raster.
*
* @name Raster#getPixel
* @function
* @param x the x offset of the pixel in pixel coordinates
* @param y the y offset of the pixel in pixel coordinates
* @return {Color} the color of the pixel
*/
/**
* Gets the color of a pixel in the raster.
*
* @name Raster#getPixel
* @function
* @param point the offset of the pixel as a point in pixel coordinates
* @return {Color} the color of the pixel
*/
getPixel: function(point) {
point = Point.read(arguments);
var data = this.getContext().getImageData(point.x, point.y, 1, 1).data;
// Alpha is separate now:
return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255],
data[3] / 255);
},
/**
* Sets the color of the specified pixel to the specified color.
*
* @name Raster#setPixel
* @function
* @param x the x offset of the pixel in pixel coordinates
* @param y the y offset of the pixel in pixel coordinates
* @param color the color that the pixel will be set to
*/
/**
* Sets the color of the specified pixel to the specified color.
*
* @name Raster#setPixel
* @function
* @param point the offset of the pixel as a point in pixel coordinates
* @param color the color that the pixel will be set to
*/
setPixel: function(/* point, color */) {
var point = Point.read(arguments),
color = Color.read(arguments),
components = color._convert('rgb'),
alpha = color._alpha,
ctx = this.getContext(true),
imageData = ctx.createImageData(1, 1),
data = imageData.data;
data[0] = components[0] * 255;
data[1] = components[1] * 255;
data[2] = components[2] * 255;
data[3] = alpha != null ? alpha * 255 : 255;
ctx.putImageData(imageData, point.x, point.y);
},
// DOCS: document Raster#createImageData
/**
* {@grouptitle Image Data}
* @param {Size} size
* @return {ImageData}
*/
createImageData: function(size) {
size = Size.read(arguments);
return this.getContext().createImageData(size.width, size.height);
},
// DOCS: document Raster#getImageData
/**
* @param {Rectangle} rect
* @return {ImageData}
*/
getImageData: function(rect) {
rect = Rectangle.read(arguments);
if (rect.isEmpty())
rect = new Rectangle(this._size);
return this.getContext().getImageData(rect.x, rect.y,
rect.width, rect.height);
},
// DOCS: document Raster#setImageData
/**
* @param {ImageData} data
* @param {Point} point
* @return {ImageData}
*/
setImageData: function(data, point) {
point = Point.read(arguments, 1);
this.getContext(true).putImageData(data, point.x, point.y);
},
_getBounds: function(getter, matrix) {
var rect = new Rectangle(this._size).setCenter(0, 0);
return matrix ? matrix._transformBounds(rect) : rect;
},
_hitTest: function(point) {
if (this._contains(point)) {
var that = this;
return new HitResult('pixel', that, {
offset: point.add(that._size.divide(2)).round(),
// Inject as Bootstrap accessor, so #toString renders well too
color: {
get: function() {
return that.getPixel(this.offset);
}
}
});
}
},
_draw: function(ctx) {
var element = this.getElement();
if (element) {
// Handle opacity for Rasters separately from the rest, since
// Rasters never draw a stroke. See Item#draw().
ctx.globalAlpha = this._opacity;
ctx.drawImage(element,
-this._size.width / 2, -this._size.height / 2);
}
},
_canComposite: function() {
return true;
}
});
|
src/item/Raster.js
|
/*
* Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
* http://paperjs.org/
*
* Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*/
/**
* @name Raster
*
* @class The Raster item represents an image in a Paper.js project.
*
* @extends Item
*/
var Raster = Item.extend(/** @lends Raster# */{
_class: 'Raster',
_transformContent: false,
// Raster doesn't make the distinction between the different bounds,
// so use the same name for all of them
_boundsGetter: 'getBounds',
_boundsSelected: true,
_serializeFields: {
source: null
},
// TODO: Implement type, width, height.
// TODO: Have PlacedSymbol & Raster inherit from a shared class?
/**
* Creates a new raster item from the passed argument, and places it in the
* active layer. {@code object} can either be a DOM Image, a Canvas, or a
* string describing the URL to load the image from, or the ID of a DOM
* element to get the image from (either a DOM Image or a Canvas).
*
* @param {HTMLImageElement|Canvas|String} [source] the source of the raster
* @param {HTMLImageElement|Canvas|String} [position] the center position at
* which the raster item is placed.
*
* @example {@paperscript height=300} // Creating a raster using a url
* var url = 'http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png';
* var raster = new Raster(url);
*
* // If you create a Raster using a url, you can use the onLoad
* // handler to do something once it is loaded:
* raster.onLoad = function() {
* console.log('The image has loaded.');
* };
*
* @example // Creating a raster using the id of a DOM Image:
*
* // Create a raster using the id of the image:
* var raster = new Raster('art');
*
* @example // Creating a raster using a DOM Image:
*
* // Find the element using its id:
* var imageElement = document.getElementById('art');
*
* // Create the raster:
* var raster = new Raster(imageElement);
*
* @example {@paperscript height=300}
* var raster = new Raster({
* source: 'http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png',
* position: view.center
* });
*
* raster.scale(0.5);
* raster.rotate(10);
*/
initialize: function Raster(object, position) {
// Support two forms of item initialization: Passing one object literal
// describing all the different properties to be set, or an image
// (object) and a point where it should be placed (point).
// If _initialize can set properties through object literal, we're done.
// Otherwise we need to check the type of object:
if (!this._initialize(object,
position !== undefined && Point.read(arguments, 1))) {
if (object.getContext) {
this.setCanvas(object);
} else if (typeof object === 'string') {
// Both data-urls and normal urls are supported here!
this.setSource(object);
} else {
this.setImage(object);
}
}
if (!this._size)
this._size = new Size();
},
clone: function(insert) {
var param = { insert: false },
image = this._image;
if (image) {
param.image = image;
} else if (this._canvas) {
// If the Raster contains a Canvas object, we need to create
// a new one and draw this raster's canvas on it.
var canvas = param.canvas = CanvasProvider.getCanvas(this._size);
canvas.getContext('2d').drawImage(this._canvas, 0, 0);
}
return this._clone(new Raster(param), insert);
},
/**
* The size of the raster in pixels.
*
* @type Size
* @bean
*/
getSize: function() {
var size = this._size;
return new LinkedSize(size.width, size.height, this, 'setSize');
},
setSize: function(/* size */) {
var size = Size.read(arguments);
if (!this._size.equals(size)) {
// Get reference to image before changing canvas
var element = this.getElement();
// Setting canvas internally sets _size
this.setCanvas(CanvasProvider.getCanvas(size));
// Draw element back onto new canvas
if (element)
this.getContext(true).drawImage(element, 0, 0,
size.width, size.height);
}
},
/**
* The width of the raster in pixels.
*
* @type Number
* @bean
*/
getWidth: function() {
return this._size.width;
},
/**
* The height of the raster in pixels.
*
* @type Number
* @bean
*/
getHeight: function() {
return this._size.height;
},
isEmpty: function() {
return this._size.width == 0 && this._size.height == 0;
},
/**
* Pixels per inch of the raster at its current size.
*
* @type Size
* @bean
*/
getPpi: function() {
var matrix = this._matrix,
orig = new Point(0, 0).transform(matrix),
u = new Point(1, 0).transform(matrix).subtract(orig),
v = new Point(0, 1).transform(matrix).subtract(orig);
return new Size(
72 / u.getLength(),
72 / v.getLength()
);
},
/**
* The Canvas 2d drawing context of the raster.
*
* @type Context
* @bean
*/
getContext: function(/* modify */) {
if (!this._context)
this._context = this.getCanvas().getContext('2d');
// Support a hidden parameter that indicates if the context will be used
// to modify the Raster object. We can notify such changes ahead since
// they are only used afterwards for redrawing.
if (arguments[0]) {
// Also set _image to null since the Raster stops representing it.
// NOTE: This should theoretically be in our own _changed() handler
// for ChangeFlag.PIXELS, but since it's only happening in one place
// this is fine:
this._image = null;
this._changed(/*#=*/ Change.PIXELS);
}
return this._context;
},
setContext: function(context) {
this._context = context;
},
getCanvas: function() {
if (!this._canvas) {
var ctx = CanvasProvider.getContext(this._size);
// Since drawimage images into canvases might fail based on security
// policies, wrap the call in try-catch and only set _canvas if we
// succeeded.
try {
if (this._image)
ctx.drawImage(this._image, 0, 0);
this._canvas = ctx.canvas;
} catch (e) {
CanvasProvider.release(ctx);
}
}
return this._canvas;
},
setCanvas: function(canvas) {
if (this._canvas)
CanvasProvider.release(this._canvas);
this._canvas = canvas;
this._size = new Size(canvas.width, canvas.height);
this._image = null;
this._context = null;
this._changed(/*#=*/ Change.GEOMETRY | /*#=*/ Change.PIXELS);
},
/**
* The HTMLImageElement of the raster, if one is associated.
*
* @type HTMLImageElement|Canvas
* @bean
*/
getImage: function() {
return this._image;
},
setImage: function(image) {
if (this._canvas)
CanvasProvider.release(this._canvas);
this._image = image;
this._size = new Size(image.width, image.height);
this._canvas = null;
this._context = null;
this._changed(/*#=*/ Change.GEOMETRY);
},
/**
* The source of the raster, which can be set using a DOM Image, a Canvas,
* a data url, a string describing the URL to load the image from, or the
* ID of a DOM element to get the image from (either a DOM Image or a Canvas).
* Reading this property will return the url of the source image or a data-url.
*
* @bean
* @type HTMLImageElement|Canvas|String
*
* @example {@paperscript}
* var raster = new Raster();
* raster.source = 'http://paperjs.org/about/resources/paper-js.gif';
* raster.position = view.center;
*
* @example {@paperscript}
* var raster = new Raster({
* source: 'http://paperjs.org/about/resources/paper-js.gif',
* position: view.center
* });
*/
getSource: function() {
return this._image && this._image.src || this.toDataURL();
},
setSource: function(src) {
/*#*/ if (options.browser) {
var that = this,
// src can be an URL or a DOM ID to load the image from
image = document.getElementById(src) || new Image();
function loaded() {
that.fire('load');
if (that._project.view)
that._project.view.draw(true);
}
if (image.width && image.height) {
// Fire load event delayed, so behavior is the same as when it's
// actually loaded and we give the code time to install event
setTimeout(loaded, 0);
} else if (!image.src) {
// Trigger the onLoad event on the image once it's loaded
DomEvent.add(image, {
load: function() {
that.setImage(image);
loaded();
}
});
image.src = src;
}
this.setImage(image);
/*#*/ } else if (options.node) {
var image = new Image();
// If we're running on the server and it's a string,
// check if it is a data URL
if (/^data:/.test(src)) {
// Preserve the data in this._data since canvas-node eats it.
// TODO: Fix canvas-node instead
image.src = this._data = src;
} else {
// Load it from disk:
// TODO: load images async, calling setImage once loaded as above.
image.src = fs.readFileSync(src);
}
this.setImage(image);
/*#*/ } // options.node
},
// DOCS: document Raster#getElement
getElement: function() {
return this._canvas || this._image;
},
// DOCS: document Raster#getSubImage
/**
* @param {Rectangle} rect the boundaries of the sub image in pixel
* coordinates
*
* @return {Canvas}
*/
getSubImage: function(rect) {
rect = Rectangle.read(arguments);
var ctx = CanvasProvider.getContext(rect.getSize());
ctx.drawImage(this.getCanvas(), rect.x, rect.y,
rect.width, rect.height, 0, 0, rect.width, rect.height);
return ctx.canvas;
},
/**
* Returns a Base 64 encoded {@code data:} URL representation of the raster.
*
* @return {String}
*/
toDataURL: function() {
// See if the linked image is base64 encoded already, if so reuse it,
// otherwise try using canvas.toDataURL()
/*#*/ if (options.node) {
if (this._data)
return this._data;
/*#*/ } else {
var src = this._image && this._image.src;
if (/^data:/.test(src))
return src;
/*#*/ }
var canvas = this.getCanvas();
return canvas ? canvas.toDataURL() : null;
},
/**
* Draws an image on the raster.
*
* @param {HTMLImageELement|Canvas} image
* @param {Point} point the offset of the image as a point in pixel
* coordinates
*/
drawImage: function(image, point) {
point = Point.read(arguments, 1);
this.getContext(true).drawImage(image, point.x, point.y);
},
/**
* Calculates the average color of the image within the given path,
* rectangle or point. This can be used for creating raster image
* effects.
*
* @param {Path|Rectangle|Point} object
* @return {Color} the average color contained in the area covered by the
* specified path, rectangle or point.
*/
getAverageColor: function(object) {
var bounds, path;
if (!object) {
bounds = this.getBounds();
} else if (object instanceof PathItem) {
// TODO: What if the path is smaller than 1 px?
// TODO: How about rounding of bounds.size?
path = object;
bounds = object.getBounds();
} else if (object.width) {
bounds = new Rectangle(object);
} else if (object.x) {
// Create a rectangle of 1px size around the specified coordinates
bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1);
}
// Use a sample size of max 32 x 32 pixels, into which the path is
// scaled as a clipping path, and then the actual image is drawn in and
// sampled.
var sampleSize = 32,
width = Math.min(bounds.width, sampleSize),
height = Math.min(bounds.height, sampleSize);
// Reuse the same sample context for speed. Memory consumption is low
// since it's only 32 x 32 pixels.
var ctx = Raster._sampleContext;
if (!ctx) {
ctx = Raster._sampleContext = CanvasProvider.getContext(
new Size(sampleSize));
} else {
// Clear the sample canvas:
ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1);
}
ctx.save();
// Scale the context so that the bounds ends up at the given sample size
var matrix = new Matrix()
.scale(width / bounds.width, height / bounds.height)
.translate(-bounds.x, -bounds.y);
matrix.applyToContext(ctx);
// If a path was passed, draw it as a clipping mask:
// See Project#draw() for an explanation of Base.merge()
if (path)
path.draw(ctx, Base.merge({ clip: true, transforms: [matrix] }));
// Now draw the image clipped into it.
this._matrix.applyToContext(ctx);
ctx.drawImage(this.getElement(),
-this._size.width / 2, -this._size.height / 2);
ctx.restore();
// Get pixel data from the context and calculate the average color value
// from it, taking alpha into account.
var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
Math.ceil(height)).data,
channels = [0, 0, 0],
total = 0;
for (var i = 0, l = pixels.length; i < l; i += 4) {
var alpha = pixels[i + 3];
total += alpha;
alpha /= 255;
channels[0] += pixels[i] * alpha;
channels[1] += pixels[i + 1] * alpha;
channels[2] += pixels[i + 2] * alpha;
}
for (var i = 0; i < 3; i++)
channels[i] /= total;
return total ? Color.read(channels) : null;
},
/**
* {@grouptitle Pixels}
* Gets the color of a pixel in the raster.
*
* @name Raster#getPixel
* @function
* @param x the x offset of the pixel in pixel coordinates
* @param y the y offset of the pixel in pixel coordinates
* @return {Color} the color of the pixel
*/
/**
* Gets the color of a pixel in the raster.
*
* @name Raster#getPixel
* @function
* @param point the offset of the pixel as a point in pixel coordinates
* @return {Color} the color of the pixel
*/
getPixel: function(point) {
point = Point.read(arguments);
var data = this.getContext().getImageData(point.x, point.y, 1, 1).data;
// Alpha is separate now:
return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255],
data[3] / 255);
},
/**
* Sets the color of the specified pixel to the specified color.
*
* @name Raster#setPixel
* @function
* @param x the x offset of the pixel in pixel coordinates
* @param y the y offset of the pixel in pixel coordinates
* @param color the color that the pixel will be set to
*/
/**
* Sets the color of the specified pixel to the specified color.
*
* @name Raster#setPixel
* @function
* @param point the offset of the pixel as a point in pixel coordinates
* @param color the color that the pixel will be set to
*/
setPixel: function(/* point, color */) {
var point = Point.read(arguments),
color = Color.read(arguments),
components = color._convert('rgb'),
alpha = color._alpha,
ctx = this.getContext(true),
imageData = ctx.createImageData(1, 1),
data = imageData.data;
data[0] = components[0] * 255;
data[1] = components[1] * 255;
data[2] = components[2] * 255;
data[3] = alpha != null ? alpha * 255 : 255;
ctx.putImageData(imageData, point.x, point.y);
},
// DOCS: document Raster#createImageData
/**
* {@grouptitle Image Data}
* @param {Size} size
* @return {ImageData}
*/
createImageData: function(size) {
size = Size.read(arguments);
return this.getContext().createImageData(size.width, size.height);
},
// DOCS: document Raster#getImageData
/**
* @param {Rectangle} rect
* @return {ImageData}
*/
getImageData: function(rect) {
rect = Rectangle.read(arguments);
if (rect.isEmpty())
rect = new Rectangle(this._size);
return this.getContext().getImageData(rect.x, rect.y,
rect.width, rect.height);
},
// DOCS: document Raster#setImageData
/**
* @param {ImageData} data
* @param {Point} point
* @return {ImageData}
*/
setImageData: function(data, point) {
point = Point.read(arguments, 1);
this.getContext(true).putImageData(data, point.x, point.y);
},
_getBounds: function(getter, matrix) {
var rect = new Rectangle(this._size).setCenter(0, 0);
return matrix ? matrix._transformBounds(rect) : rect;
},
_hitTest: function(point) {
if (this._contains(point)) {
var that = this;
return new HitResult('pixel', that, {
offset: point.add(that._size.divide(2)).round(),
// Inject as Bootstrap accessor, so #toString renders well too
color: {
get: function() {
return that.getPixel(this.offset);
}
}
});
}
},
_draw: function(ctx) {
var element = this.getElement();
if (element) {
// Handle opacity for Rasters separately from the rest, since
// Rasters never draw a stroke. See Item#draw().
ctx.globalAlpha = this._opacity;
ctx.drawImage(element,
-this._size.width / 2, -this._size.height / 2);
}
},
_canComposite: function() {
return true;
}
});
|
Implement Raster#getSubRaster() and document both #getSubImage() and #getSubRaster().
|
src/item/Raster.js
|
Implement Raster#getSubRaster() and document both #getSubImage() and #getSubRaster().
|
<ide><path>rc/item/Raster.js
<ide> /**
<ide> * The source of the raster, which can be set using a DOM Image, a Canvas,
<ide> * a data url, a string describing the URL to load the image from, or the
<del> * ID of a DOM element to get the image from (either a DOM Image or a Canvas).
<del> * Reading this property will return the url of the source image or a data-url.
<add> * ID of a DOM element to get the image from (either a DOM Image or a
<add> * Canvas). Reading this property will return the url of the source image or
<add> * a data-url.
<ide> *
<ide> * @bean
<ide> * @type HTMLImageElement|Canvas|String
<ide> return this._canvas || this._image;
<ide> },
<ide>
<del> // DOCS: document Raster#getSubImage
<del> /**
<add> /**
<add> * Extracts a part of the Raster's content as a sub image, and returns it as
<add> * a Canvas object.
<add> *
<ide> * @param {Rectangle} rect the boundaries of the sub image in pixel
<ide> * coordinates
<ide> *
<del> * @return {Canvas}
<add> * @return {Canvas} the sub image as a Canvas object
<ide> */
<ide> getSubImage: function(rect) {
<ide> rect = Rectangle.read(arguments);
<ide> ctx.drawImage(this.getCanvas(), rect.x, rect.y,
<ide> rect.width, rect.height, 0, 0, rect.width, rect.height);
<ide> return ctx.canvas;
<add> },
<add>
<add> /**
<add> * Extracts a part of the raster item's content as a new raster item, placed
<add> * in exactly the same place as the original content.
<add> *
<add> * @param {Rectangle} rect the boundaries of the sub raster in pixel
<add> * coordinates
<add> *
<add> * @return {Raster} the sub raster as a newly created raster item
<add> */
<add> getSubRaster: function(rect) {
<add> rect = Rectangle.read(arguments);
<add> var raster = new Raster(this.getSubImage(rect));
<add> raster.translate(rect.getCenter().subtract(this.getSize().divide(2)));
<add> raster._matrix.preConcatenate(this._matrix);
<add> return raster;
<ide> },
<ide>
<ide> /**
|
|
JavaScript
|
isc
|
b73ad95da2584f8db1ed2576b2549302173b8915
| 0 |
medikoo/es5-ext
|
'use strict';
var numIsNaN = require('../../Number/is-nan')
, ois = require('../../Object/is')
, value = require('../../Object/valid-value')
, lastIndexOf = Array.prototype.lastIndexOf
, hasOwnProperty = Object.prototype.hasOwnProperty;
module.exports = function (searchElement/*, fromIndex*/) {
var i, fromIndex;
if (searchElement || (!numIsNaN(searchElement) && (searchElement !== 0))) {
return lastIndexOf.apply(this, arguments);
}
value(this);
fromIndex = arguments[1];
fromIndex = isNaN(fromIndex) ? ((this.length >>> 0) - 1) : (fromIndex >>> 0);
for (i = fromIndex; i >= 0; --i) {
if (hasOwnProperty.call(this, i) && ois(searchElement, this[i])) return i;
}
return -1;
};
|
lib/Array/prototype/e-last-index-of.js
|
'use strict';
var numIsNaN = require('../../Number/is-nan')
, ois = require('../../Object/is')
, value = require('../../Object/valid-value')
, lastIndexOf = Array.prototype.lastIndexOf;
module.exports = function (searchElement/*, fromIndex*/) {
var i, fromIndex;
if (!numIsNaN(searchElement) && (searchElement !== 0)) {
return lastIndexOf.apply(this, arguments);
}
value(this);
fromIndex = Number(arguments[1]);
fromIndex = numIsNaN(fromIndex) ? ((this.length >>> 0) - 1) : fromIndex;
for (i = fromIndex; i >= 0; --i) {
if (this.hasOwnProperty(i) && ois(searchElement, this[i])) {
return i;
}
}
return -1;
};
|
Improve internal logic of Array#eLastIndexOf
|
lib/Array/prototype/e-last-index-of.js
|
Improve internal logic of Array#eLastIndexOf
|
<ide><path>ib/Array/prototype/e-last-index-of.js
<ide> , ois = require('../../Object/is')
<ide> , value = require('../../Object/valid-value')
<ide>
<del> , lastIndexOf = Array.prototype.lastIndexOf;
<add> , lastIndexOf = Array.prototype.lastIndexOf
<add> , hasOwnProperty = Object.prototype.hasOwnProperty;
<ide>
<ide> module.exports = function (searchElement/*, fromIndex*/) {
<ide> var i, fromIndex;
<del> if (!numIsNaN(searchElement) && (searchElement !== 0)) {
<add> if (searchElement || (!numIsNaN(searchElement) && (searchElement !== 0))) {
<ide> return lastIndexOf.apply(this, arguments);
<ide> }
<ide>
<ide> value(this);
<del> fromIndex = Number(arguments[1]);
<del> fromIndex = numIsNaN(fromIndex) ? ((this.length >>> 0) - 1) : fromIndex;
<add> fromIndex = arguments[1];
<add> fromIndex = isNaN(fromIndex) ? ((this.length >>> 0) - 1) : (fromIndex >>> 0);
<ide> for (i = fromIndex; i >= 0; --i) {
<del> if (this.hasOwnProperty(i) && ois(searchElement, this[i])) {
<del> return i;
<del> }
<add> if (hasOwnProperty.call(this, i) && ois(searchElement, this[i])) return i;
<ide> }
<ide> return -1;
<ide> };
|
|
Java
|
apache-2.0
|
1fbfe5501c44ff7276f6d2191f54f42f26509666
| 0 |
microstrat/alfresco-sdk,loftuxab/alfresco-sdk,Alfresco/alfresco-sdk,microstrat/alfresco-sdk,adrianopatrick/alfresco-sdk,Alfresco/alfresco-sdk,adrianopatrick/alfresco-sdk,microstrat/alfresco-sdk,Alfresco/alfresco-sdk,AFaust/alfresco-sdk,bhagyas/alfresco-sdk,abhinavmishra14/alfresco-sdk,loftuxab/alfresco-sdk,Alfresco/alfresco-sdk,AFaust/alfresco-sdk,adrianopatrick/alfresco-sdk,AFaust/alfresco-sdk,abhinavmishra14/alfresco-sdk,abhinavmishra14/alfresco-sdk,abhinavmishra14/alfresco-sdk,AFaust/alfresco-sdk,bhagyas/alfresco-sdk,adrianopatrick/alfresco-sdk,bhagyas/alfresco-sdk,bhagyas/alfresco-sdk,microstrat/alfresco-sdk,loftuxab/alfresco-sdk,loftuxab/alfresco-sdk
|
package org.alfresco.maven.plugin.amp;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.alfresco.maven.plugin.amp.overlay.OverlayManager;
import org.alfresco.maven.plugin.amp.packaging.AmpPackagingContext;
import org.alfresco.maven.plugin.amp.packaging.AmpPackagingTask;
import org.alfresco.maven.plugin.amp.packaging.AmpPostPackagingTask;
import org.alfresco.maven.plugin.amp.packaging.AmpProjectPackagingTask;
import org.alfresco.maven.plugin.amp.packaging.OverlayPackagingTask;
import org.alfresco.maven.plugin.amp.packaging.SaveAmpStructurePostPackagingTask;
import org.alfresco.maven.plugin.amp.util.AmpStructure;
import org.alfresco.maven.plugin.amp.util.AmpStructureSerializer;
import org.alfresco.maven.plugin.amp.util.CompositeMap;
import org.alfresco.maven.plugin.amp.util.PropertyUtils;
import org.alfresco.maven.plugin.amp.util.ReflectionProperties;
import org.apache.maven.archiver.MavenArchiveConfiguration;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.archiver.jar.JarArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public abstract class AbstractAmpMojo extends AbstractMojo
{
/**
* Returns a string array of the classes and resources to be excluded from the jar excludes to be used
* when assembling/copying the AMP.
*
* @return an array of tokens to exclude
*/
protected String[] getExcludes()
{
List excludeList = new ArrayList();
if ( StringUtils.isNotEmpty( mAmpJarExcludes ) )
{
excludeList.addAll( Arrays.asList( StringUtils.split( mAmpJarExcludes, "," ) ) );
}
return (String[]) excludeList.toArray( EMPTY_STRING_ARRAY );
}
/**
* Returns a string array of the classes and resources to be included from the jar assembling/copying the war.
*
* @return an array of tokens to include
*/
protected String[] getIncludes()
{
return StringUtils.split( StringUtils.defaultString( mAmpJarIncludes ), "," );
}
/**
* Returns a string array of the resources to be included in the AMP web/ folder.
*
* @return an array of tokens to include
*/
protected String[] getWebIncludes()
{
return StringUtils.split( StringUtils.defaultString( mAmpWebIncludes ), "," );
}
/**
* Returns a string array of the resources to be excluded in the AMP web/ folder.
*
* @return an array of tokens to exclude
*/
protected String[] getWebExcludes()
{
List excludeList = new ArrayList();
if ( StringUtils.isNotEmpty( mAmpWebExcludes ) )
{
excludeList.addAll( Arrays.asList( StringUtils.split( mAmpWebExcludes, "," ) ) );
}
return (String[]) excludeList.toArray( EMPTY_STRING_ARRAY );
}
/**
* Returns a string array of the excludes to be used
* when adding dependent AMPs as an overlay onto this AMP.
*
* @return an array of tokens to exclude
*/
protected String[] getDependentAmpExcludes()
{
String[] excludes;
if ( StringUtils.isNotEmpty( dependentAmpExcludes ) )
{
excludes = StringUtils.split( dependentAmpExcludes, "," );
}
else
{
excludes = EMPTY_STRING_ARRAY;
}
return excludes;
}
/**
* Returns a string array of the includes to be used
* when adding dependent AMP as an overlay onto this AMP.
*
* @return an array of tokens to include
*/
protected String[] getDependentAmpIncludes()
{
return StringUtils.split( StringUtils.defaultString( dependentAmpIncludes ), "," );
}
public void buildExplodedAmp( File webappDirectory )
throws MojoExecutionException, MojoFailureException
{
webappDirectory.mkdirs();
try
{
buildAmp( mProject, webappDirectory );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Could not build AMP", e );
}
}
/**
* Builds the webapp for the specified project with the new packaging task
* thingy
* <p/>
* Classes, libraries and tld files are copied to
* the <tt>webappDirectory</tt> during this phase.
*
* @param project the maven project
* @param webappDirectory the target directory
* @throws MojoExecutionException if an error occured while packaging the webapp
* @throws MojoFailureException if an unexpected error occured while packaging the webapp
* @throws IOException if an error occured while copying the files
*/
public void buildAmp( MavenProject project, File webappDirectory )
throws MojoExecutionException, MojoFailureException, IOException
{
AmpStructure cache;
if ( mUseCache && mCacheFile.exists() )
{
cache = new AmpStructure( webappStructureSerialier.fromXml( mCacheFile ) );
}
else
{
cache = new AmpStructure( null );
}
final long startTime = System.currentTimeMillis();
getLog().info( "Assembling AMP [" + project.getArtifactId() + "] in [" + webappDirectory + "]" );
final OverlayManager overlayManager =
new OverlayManager( mOverlays, project, dependentAmpIncludes, dependentAmpExcludes );
final List packagingTasks = getPackagingTasks( overlayManager );
final AmpPackagingContext context = new DefaultAmpPackagingContext( webappDirectory, cache, overlayManager );
final Iterator it = packagingTasks.iterator();
while ( it.hasNext() )
{
AmpPackagingTask ampPackagingTask = (AmpPackagingTask) it.next();
ampPackagingTask.performPackaging( context );
}
// Post packaging
final List postPackagingTasks = getPostPackagingTasks();
final Iterator it2 = postPackagingTasks.iterator();
while ( it2.hasNext() )
{
AmpPostPackagingTask task = (AmpPostPackagingTask) it2.next();
task.performPostPackaging( context );
}
getLog().info( "AMP assembled in[" + ( System.currentTimeMillis() - startTime ) + " msecs]" );
}
/**
* Returns a <tt>List</tt> of the {@link org.alfresco.maven.plugin.amp.packaging.AmpPackagingTask}
* instances to invoke to perform the packaging.
*
* @param overlayManager the overlay manager
* @return the list of packaging tasks
* @throws MojoExecutionException if the packaging tasks could not be built
*/
private List getPackagingTasks( OverlayManager overlayManager )
throws MojoExecutionException
{
final List packagingTasks = new ArrayList();
final List resolvedOverlays = overlayManager.getOverlays();
final Iterator it = resolvedOverlays.iterator();
while ( it.hasNext() )
{
Overlay overlay = (Overlay) it.next();
if ( overlay.isCurrentProject() )
{
packagingTasks.add( new AmpProjectPackagingTask( mAmpResources, mModuleProperties, mFileMappingProperties) );
}
else
{
packagingTasks.add( new OverlayPackagingTask( overlay ) );
}
}
return packagingTasks;
}
/**
* Returns a <tt>List</tt> of the {@link org.alfresco.maven.plugin.amp.packaging.AmpPostPackagingTask}
* instances to invoke to perform the post-packaging.
*
* @return the list of post packaging tasks
*/
private List getPostPackagingTasks()
{
final List postPackagingTasks = new ArrayList();
if ( mUseCache )
{
postPackagingTasks.add( new SaveAmpStructurePostPackagingTask( mCacheFile ) );
}
// TODO add lib scanning to detect duplicates
return postPackagingTasks;
}
/**
* The maven project.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject mProject;
/**
* The directory containing generated classes.
*
* @parameter expression="${project.build.outputDirectory}"
* @required
* @readonly
*/
private File mClassesDirectory;
/**
* The Jar archiver needed for archiving classes directory into jar file under WEB-INF/lib.
*
* @component role="org.codehaus.plexus.archiver.Archiver" role-hint="jar"
* @required
*/
private JarArchiver mJarArchiver;
/**
* The directory where the webapp is built.
*
* @parameter expression="${project.build.directory}/${project.build.finalName}"
* @required
*/
private File mAmpDirectory;
/**
* Single directory for extra files to include in the AMP.
*
* @parameter expression="${project.build.outputDirectory}"
* @required
*/
private File mAmpConfigDirectory;
/**
* Single directory for extra files to include in the AMP.
*
* @parameter expression="${basedir}/src/main/webapp"
* @required
*/
private File mAmpWebDirectory;
/**
* The list of webResources we want to transfer.
*
* @parameter
*/
private Resource[] mAmpResources;
/**
* Filters (property files) to include during the interpolation of the pom.xml.
*
* @parameter expression="${project.build.filters}"
*/
private List filters;
/**
* The path to the web.xml file to use.
*
* @parameter expression="${maven.amp.moduleProperties}" default-value="${project.basedir}/module.properties"
*/
private File mModuleProperties;
/**
* The path to the file-mapping.properties file to use.
*
* @parameter expression="${maven.amp.fileMappingProperties}" default-value="${project.basedir}/file-mapping.properties"
*/
private File mFileMappingProperties;
/**
* Directory to unpack dependent AMPs into if needed
*
* @parameter expression="${project.build.directory}/amp/work"
* @required
*/
private File mWorkDirectory;
/**
* The file name mapping to use to copy libraries and tlds. If no file mapping is
* set (default) the file is copied with its standard name.
*
* @parameter
* @since 2.0.3
*/
private String mOutputFileNameMapping;
/**
* The file containing the webapp structure cache.
*
* @parameter expression="${project.build.directory}/amp/work/amp-cache.xml"
* @required
* @since 2.1
*/
private File mCacheFile;
/**
* Whether the cache should be used to save the status of the webapp
* accross multiple runs.
*
* @parameter expression="${useCache}" default-value="true"
* @since 2.1
*/
private boolean mUseCache = true;
/**
* To look up Archiver/UnArchiver implementations
*
* @component role="org.codehaus.plexus.archiver.manager.ArchiverManager"
* @required
*/
protected ArchiverManager mArchiverManager;
private static final String META_INF = "META-INF";
public static final String DEFAULT_FILE_NAME_MAPPING_CLASSIFIER =
"${artifactId}-${version}-${classifier}.${extension}";
public static final String DEFAULT_FILE_NAME_MAPPING = "${artifactId}-${version}.${extension}";
/**
* The comma separated list of tokens to include in the AMP internal JAR. Default **.
* Default is '**'.
*
* @parameter alias="includes"
*/
private String mAmpJarIncludes = "**/*.class,META-INF/**";
/**
* The comma separated list of tokens to exclude from the AMP created JAR file
*
* @parameter alias="excludes" default-value=""
*/
private String mAmpJarExcludes;
/**
* The comma separated list of tokens to include in the AMP internal JAR. Default **.
* Default is '**'.
*
* @parameter alias="webIncludes" default-value="**"
*/
private String mAmpWebIncludes;
/**
* The comma separated list of tokens to exclude from the AMP created JAR file. By default module configuration is left outside jars.
*
* @parameter alias="webExcludes"
*/
private String mAmpWebExcludes;
/**
* The comma separated list of tokens to include when doing
* a AMP overlay.
* Default is '**'
*
* @parameter
*/
private String dependentAmpIncludes = "**/**";
/**
* The comma separated list of tokens to exclude when doing
* a AMP overlay.
*
* @parameter
*/
private String dependentAmpExcludes = "META-INF/**";
/**
* The overlays to apply.
*
* @parameter
* @since 2.1
*/
private List mOverlays = new ArrayList();
/**
* The maven archive configuration to use.
*
* @parameter
*/
protected MavenArchiveConfiguration archive = new MavenArchiveConfiguration();
private static final String[] EMPTY_STRING_ARRAY = {};
private final AmpStructureSerializer webappStructureSerialier = new AmpStructureSerializer();
// AMP packaging implementation
private class DefaultAmpPackagingContext
implements AmpPackagingContext
{
private final AmpStructure webappStructure;
private final File mAmpDirectory;
private final OverlayManager overlayManager;
public DefaultAmpPackagingContext( File webappDirectory, final AmpStructure webappStructure,
final OverlayManager overlayManager )
{
this.mAmpDirectory = webappDirectory;
this.webappStructure = webappStructure;
this.overlayManager = overlayManager;
// This is kinda stupid but if we loop over the current overlays and we request the path structure
// it will register it. This will avoid wrong warning messages in a later phase
final Iterator it = overlayManager.getOverlayIds().iterator();
while ( it.hasNext() )
{
String overlayId = (String) it.next();
webappStructure.getStructure( overlayId );
}
}
public MavenProject getProject()
{
return mProject;
}
public File getAmpDirectory()
{
return mAmpDirectory;
}
public File getClassesDirectory()
{
return mClassesDirectory;
}
public Log getLog()
{
return AbstractAmpMojo.this.getLog();
}
public String getOutputFileNameMapping()
{
return mOutputFileNameMapping;
}
public File getAmpWebDirectory()
{
return mAmpWebDirectory;
}
public String[] getAmpJarIncludes()
{
return getIncludes();
}
public String[] getAmpJarExcludes()
{
return getExcludes();
}
public File getOverlaysWorkDirectory()
{
return mWorkDirectory;
}
public ArchiverManager getArchiverManager()
{
return mArchiverManager;
}
public MavenArchiveConfiguration getArchive()
{
return archive;
}
public JarArchiver getJarArchiver()
{
return mJarArchiver;
}
public List getFilters()
{
return filters;
}
public Map getFilterProperties()
throws MojoExecutionException
{
Map filterProperties = new Properties();
// System properties
filterProperties.putAll( System.getProperties() );
// Project properties
filterProperties.putAll( mProject.getProperties() );
for ( Iterator i = filters.iterator(); i.hasNext(); )
{
String filtersfile = (String) i.next();
try
{
Properties properties = PropertyUtils.loadPropertyFile( new File( filtersfile ), true, true );
filterProperties.putAll( properties );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error loading property file '" + filtersfile + "'", e );
}
}
// can't putAll, as ReflectionProperties doesn't enumerate - so we make a composite map with the project variables as dominant
return new CompositeMap( new ReflectionProperties( mProject ), filterProperties );
}
public AmpStructure getAmpStructure()
{
return webappStructure;
}
public List getOwnerIds()
{
return overlayManager.getOverlayIds();
}
/**
* @see org.alfresco.maven.plugin.amp.packaging.AmpPackagingContext#getAmpConfigDirectory()
*/
public File getAmpConfigDirectory()
{
return mAmpConfigDirectory;
}
public String[] getAmpWebExcludes() {
return getWebExcludes();
}
public String[] getAmpWebIncludes() {
return getWebIncludes();
}
}
public MavenProject getProject()
{
return mProject;
}
public void setProject( MavenProject project )
{
this.mProject = project;
}
public File getClassesDirectory()
{
return mClassesDirectory;
}
public void setClassesDirectory( File classesDirectory )
{
this.mClassesDirectory = classesDirectory;
}
public File getAmpDirectory()
{
return mAmpDirectory;
}
public void setAmpDirectory( File webappDirectory )
{
this.mAmpDirectory = webappDirectory;
}
public File getAmpSourceDirectory()
{
return mAmpWebDirectory;
}
public void setAmpSourceDirectory( File ampSourceDirectory )
{
this.mAmpWebDirectory = ampSourceDirectory;
}
public File getWebXml()
{
return mModuleProperties;
}
public void setWebXml( File webXml )
{
this.mModuleProperties = webXml;
}
public File getmFileMappingProperties()
{
return mFileMappingProperties;
}
public void setmFileMappingProperties(File mFileMappingProperties)
{
this.mFileMappingProperties = mFileMappingProperties;
}
public String getOutputFileNameMapping()
{
return mOutputFileNameMapping;
}
public void setOutputFileNameMapping( String outputFileNameMapping )
{
this.mOutputFileNameMapping = outputFileNameMapping;
}
public List getOverlays()
{
return mOverlays;
}
public void setOverlays( List overlays )
{
this.mOverlays = overlays;
}
public void addOverlay( Overlay overlay )
{
mOverlays.add( overlay );
}
public JarArchiver getJarArchiver()
{
return mJarArchiver;
}
public void setJarArchiver( JarArchiver jarArchiver )
{
this.mJarArchiver = jarArchiver;
}
public Resource[] getAmpResources()
{
return mAmpResources;
}
public void setAmpResources( Resource[] webResources )
{
this.mAmpResources = webResources;
}
public List getFilters()
{
return filters;
}
public void setFilters( List filters )
{
this.filters = filters;
}
public File getWorkDirectory()
{
return mWorkDirectory;
}
public void setWorkDirectory( File workDirectory )
{
this.mWorkDirectory = workDirectory;
}
public File getCacheFile()
{
return mCacheFile;
}
public void setCacheFile( File cacheFile )
{
this.mCacheFile = cacheFile;
}
public void setAmpSourceIncludes( String ampSourceIncludes )
{
this.mAmpJarIncludes = ampSourceIncludes;
}
public String getAmpJarExcludes()
{
return mAmpJarExcludes;
}
public void setAmpJarExcludes( String ampJarExcludes )
{
this.mAmpJarExcludes = ampJarExcludes;
}
public boolean isUseCache()
{
return mUseCache;
}
public void setUseCache( boolean useCache )
{
this.mUseCache = useCache;
}
}
|
plugins/maven-amp-plugin/src/main/java/org/alfresco/maven/plugin/amp/AbstractAmpMojo.java
|
package org.alfresco.maven.plugin.amp;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.alfresco.maven.plugin.amp.overlay.OverlayManager;
import org.alfresco.maven.plugin.amp.packaging.AmpPackagingContext;
import org.alfresco.maven.plugin.amp.packaging.AmpPackagingTask;
import org.alfresco.maven.plugin.amp.packaging.AmpPostPackagingTask;
import org.alfresco.maven.plugin.amp.packaging.AmpProjectPackagingTask;
import org.alfresco.maven.plugin.amp.packaging.OverlayPackagingTask;
import org.alfresco.maven.plugin.amp.packaging.SaveAmpStructurePostPackagingTask;
import org.alfresco.maven.plugin.amp.util.AmpStructure;
import org.alfresco.maven.plugin.amp.util.AmpStructureSerializer;
import org.alfresco.maven.plugin.amp.util.CompositeMap;
import org.alfresco.maven.plugin.amp.util.PropertyUtils;
import org.alfresco.maven.plugin.amp.util.ReflectionProperties;
import org.apache.maven.archiver.MavenArchiveConfiguration;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.archiver.jar.JarArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public abstract class AbstractAmpMojo extends AbstractMojo
{
/**
* Returns a string array of the classes and resources to be excluded from the jar excludes to be used
* when assembling/copying the AMP.
*
* @return an array of tokens to exclude
*/
protected String[] getExcludes()
{
List excludeList = new ArrayList();
if ( StringUtils.isNotEmpty( mAmpJarExcludes ) )
{
excludeList.addAll( Arrays.asList( StringUtils.split( mAmpJarExcludes, "," ) ) );
}
return (String[]) excludeList.toArray( EMPTY_STRING_ARRAY );
}
/**
* Returns a string array of the classes and resources to be included from the jar assembling/copying the war.
*
* @return an array of tokens to include
*/
protected String[] getIncludes()
{
return StringUtils.split( StringUtils.defaultString( mAmpJarIncludes ), "," );
}
/**
* Returns a string array of the resources to be included in the AMP web/ folder.
*
* @return an array of tokens to include
*/
protected String[] getWebIncludes()
{
return StringUtils.split( StringUtils.defaultString( mAmpWebIncludes ), "," );
}
/**
* Returns a string array of the resources to be excluded in the AMP web/ folder.
*
* @return an array of tokens to exclude
*/
protected String[] getWebExcludes()
{
List excludeList = new ArrayList();
if ( StringUtils.isNotEmpty( mAmpWebExcludes ) )
{
excludeList.addAll( Arrays.asList( StringUtils.split( mAmpWebExcludes, "," ) ) );
}
return (String[]) excludeList.toArray( EMPTY_STRING_ARRAY );
}
/**
* Returns a string array of the excludes to be used
* when adding dependent AMPs as an overlay onto this AMP.
*
* @return an array of tokens to exclude
*/
protected String[] getDependentAmpExcludes()
{
String[] excludes;
if ( StringUtils.isNotEmpty( dependentAmpExcludes ) )
{
excludes = StringUtils.split( dependentAmpExcludes, "," );
}
else
{
excludes = EMPTY_STRING_ARRAY;
}
return excludes;
}
/**
* Returns a string array of the includes to be used
* when adding dependent AMP as an overlay onto this AMP.
*
* @return an array of tokens to include
*/
protected String[] getDependentAmpIncludes()
{
return StringUtils.split( StringUtils.defaultString( dependentAmpIncludes ), "," );
}
public void buildExplodedAmp( File webappDirectory )
throws MojoExecutionException, MojoFailureException
{
webappDirectory.mkdirs();
try
{
buildAmp( mProject, webappDirectory );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Could not build AMP", e );
}
}
/**
* Builds the webapp for the specified project with the new packaging task
* thingy
* <p/>
* Classes, libraries and tld files are copied to
* the <tt>webappDirectory</tt> during this phase.
*
* @param project the maven project
* @param webappDirectory the target directory
* @throws MojoExecutionException if an error occured while packaging the webapp
* @throws MojoFailureException if an unexpected error occured while packaging the webapp
* @throws IOException if an error occured while copying the files
*/
public void buildAmp( MavenProject project, File webappDirectory )
throws MojoExecutionException, MojoFailureException, IOException
{
AmpStructure cache;
if ( mUseCache && mCacheFile.exists() )
{
cache = new AmpStructure( webappStructureSerialier.fromXml( mCacheFile ) );
}
else
{
cache = new AmpStructure( null );
}
final long startTime = System.currentTimeMillis();
getLog().info( "Assembling AMP [" + project.getArtifactId() + "] in [" + webappDirectory + "]" );
final OverlayManager overlayManager =
new OverlayManager( mOverlays, project, dependentAmpIncludes, dependentAmpExcludes );
final List packagingTasks = getPackagingTasks( overlayManager );
final AmpPackagingContext context = new DefaultAmpPackagingContext( webappDirectory, cache, overlayManager );
final Iterator it = packagingTasks.iterator();
while ( it.hasNext() )
{
AmpPackagingTask ampPackagingTask = (AmpPackagingTask) it.next();
ampPackagingTask.performPackaging( context );
}
// Post packaging
final List postPackagingTasks = getPostPackagingTasks();
final Iterator it2 = postPackagingTasks.iterator();
while ( it2.hasNext() )
{
AmpPostPackagingTask task = (AmpPostPackagingTask) it2.next();
task.performPostPackaging( context );
}
getLog().info( "AMP assembled in[" + ( System.currentTimeMillis() - startTime ) + " msecs]" );
}
/**
* Returns a <tt>List</tt> of the {@link org.alfresco.maven.plugin.amp.packaging.AmpPackagingTask}
* instances to invoke to perform the packaging.
*
* @param overlayManager the overlay manager
* @return the list of packaging tasks
* @throws MojoExecutionException if the packaging tasks could not be built
*/
private List getPackagingTasks( OverlayManager overlayManager )
throws MojoExecutionException
{
final List packagingTasks = new ArrayList();
final List resolvedOverlays = overlayManager.getOverlays();
final Iterator it = resolvedOverlays.iterator();
while ( it.hasNext() )
{
Overlay overlay = (Overlay) it.next();
if ( overlay.isCurrentProject() )
{
packagingTasks.add( new AmpProjectPackagingTask( mAmpResources, mModuleProperties, mFileMappingProperties) );
}
else
{
packagingTasks.add( new OverlayPackagingTask( overlay ) );
}
}
return packagingTasks;
}
/**
* Returns a <tt>List</tt> of the {@link org.alfresco.maven.plugin.amp.packaging.AmpPostPackagingTask}
* instances to invoke to perform the post-packaging.
*
* @return the list of post packaging tasks
*/
private List getPostPackagingTasks()
{
final List postPackagingTasks = new ArrayList();
if ( mUseCache )
{
postPackagingTasks.add( new SaveAmpStructurePostPackagingTask( mCacheFile ) );
}
// TODO add lib scanning to detect duplicates
return postPackagingTasks;
}
/**
* The maven project.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject mProject;
/**
* The directory containing generated classes.
*
* @parameter expression="${project.build.outputDirectory}"
* @required
* @readonly
*/
private File mClassesDirectory;
/**
* The Jar archiver needed for archiving classes directory into jar file under WEB-INF/lib.
*
* @component role="org.codehaus.plexus.archiver.Archiver" role-hint="jar"
* @required
*/
private JarArchiver mJarArchiver;
/**
* The directory where the webapp is built.
*
* @parameter expression="${project.build.directory}/${project.build.finalName}"
* @required
*/
private File mAmpDirectory;
/**
* Single directory for extra files to include in the AMP.
*
* @parameter expression="${project.build.outputDirectory}"
* @required
*/
private File mAmpConfigDirectory;
/**
* Single directory for extra files to include in the AMP.
*
* @parameter expression="${basedir}/src/main/webapp"
* @required
*/
private File mAmpWebDirectory;
/**
* The list of webResources we want to transfer.
*
* @parameter
*/
private Resource[] mAmpResources;
/**
* Filters (property files) to include during the interpolation of the pom.xml.
*
* @parameter expression="${project.build.filters}"
*/
private List filters;
/**
* The path to the web.xml file to use.
*
* @parameter expression="${maven.amp.moduleProperties}" default-value="${project.basedir}/module.properties"
*/
private File mModuleProperties;
/**
* The path to the web.xml file to use.
*
* @parameter expression="${maven.amp.fileMappingProperties}" default-value="${project.basedir}/file-mapping.properties"
*/
private File mFileMappingProperties;
/**
* Directory to unpack dependent AMPs into if needed
*
* @parameter expression="${project.build.directory}/amp/work"
* @required
*/
private File mWorkDirectory;
/**
* The file name mapping to use to copy libraries and tlds. If no file mapping is
* set (default) the file is copied with its standard name.
*
* @parameter
* @since 2.0.3
*/
private String mOutputFileNameMapping;
/**
* The file containing the webapp structure cache.
*
* @parameter expression="${project.build.directory}/amp/work/amp-cache.xml"
* @required
* @since 2.1
*/
private File mCacheFile;
/**
* Whether the cache should be used to save the status of the webapp
* accross multiple runs.
*
* @parameter expression="${useCache}" default-value="true"
* @since 2.1
*/
private boolean mUseCache = true;
/**
* To look up Archiver/UnArchiver implementations
*
* @component role="org.codehaus.plexus.archiver.manager.ArchiverManager"
* @required
*/
protected ArchiverManager mArchiverManager;
private static final String META_INF = "META-INF";
public static final String DEFAULT_FILE_NAME_MAPPING_CLASSIFIER =
"${artifactId}-${version}-${classifier}.${extension}";
public static final String DEFAULT_FILE_NAME_MAPPING = "${artifactId}-${version}.${extension}";
/**
* The comma separated list of tokens to include in the AMP internal JAR. Default **.
* Default is '**'.
*
* @parameter alias="includes"
*/
private String mAmpJarIncludes = "**/*.class,META-INF/**";
/**
* The comma separated list of tokens to exclude from the AMP created JAR file
*
* @parameter alias="excludes" default-value=""
*/
private String mAmpJarExcludes;
/**
* The comma separated list of tokens to include in the AMP internal JAR. Default **.
* Default is '**'.
*
* @parameter alias="webIncludes" default-value="**"
*/
private String mAmpWebIncludes;
/**
* The comma separated list of tokens to exclude from the AMP created JAR file. By default module configuration is left outside jars.
*
* @parameter alias="webExcludes"
*/
private String mAmpWebExcludes;
/**
* The comma separated list of tokens to include when doing
* a AMP overlay.
* Default is '**'
*
* @parameter
*/
private String dependentAmpIncludes = "**/**";
/**
* The comma separated list of tokens to exclude when doing
* a AMP overlay.
*
* @parameter
*/
private String dependentAmpExcludes = "META-INF/**";
/**
* The overlays to apply.
*
* @parameter
* @since 2.1
*/
private List mOverlays = new ArrayList();
/**
* The maven archive configuration to use.
*
* @parameter
*/
protected MavenArchiveConfiguration archive = new MavenArchiveConfiguration();
private static final String[] EMPTY_STRING_ARRAY = {};
private final AmpStructureSerializer webappStructureSerialier = new AmpStructureSerializer();
// AMP packaging implementation
private class DefaultAmpPackagingContext
implements AmpPackagingContext
{
private final AmpStructure webappStructure;
private final File mAmpDirectory;
private final OverlayManager overlayManager;
public DefaultAmpPackagingContext( File webappDirectory, final AmpStructure webappStructure,
final OverlayManager overlayManager )
{
this.mAmpDirectory = webappDirectory;
this.webappStructure = webappStructure;
this.overlayManager = overlayManager;
// This is kinda stupid but if we loop over the current overlays and we request the path structure
// it will register it. This will avoid wrong warning messages in a later phase
final Iterator it = overlayManager.getOverlayIds().iterator();
while ( it.hasNext() )
{
String overlayId = (String) it.next();
webappStructure.getStructure( overlayId );
}
}
public MavenProject getProject()
{
return mProject;
}
public File getAmpDirectory()
{
return mAmpDirectory;
}
public File getClassesDirectory()
{
return mClassesDirectory;
}
public Log getLog()
{
return AbstractAmpMojo.this.getLog();
}
public String getOutputFileNameMapping()
{
return mOutputFileNameMapping;
}
public File getAmpWebDirectory()
{
return mAmpWebDirectory;
}
public String[] getAmpJarIncludes()
{
return getIncludes();
}
public String[] getAmpJarExcludes()
{
return getExcludes();
}
public File getOverlaysWorkDirectory()
{
return mWorkDirectory;
}
public ArchiverManager getArchiverManager()
{
return mArchiverManager;
}
public MavenArchiveConfiguration getArchive()
{
return archive;
}
public JarArchiver getJarArchiver()
{
return mJarArchiver;
}
public List getFilters()
{
return filters;
}
public Map getFilterProperties()
throws MojoExecutionException
{
Map filterProperties = new Properties();
// System properties
filterProperties.putAll( System.getProperties() );
// Project properties
filterProperties.putAll( mProject.getProperties() );
for ( Iterator i = filters.iterator(); i.hasNext(); )
{
String filtersfile = (String) i.next();
try
{
Properties properties = PropertyUtils.loadPropertyFile( new File( filtersfile ), true, true );
filterProperties.putAll( properties );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error loading property file '" + filtersfile + "'", e );
}
}
// can't putAll, as ReflectionProperties doesn't enumerate - so we make a composite map with the project variables as dominant
return new CompositeMap( new ReflectionProperties( mProject ), filterProperties );
}
public AmpStructure getAmpStructure()
{
return webappStructure;
}
public List getOwnerIds()
{
return overlayManager.getOverlayIds();
}
/**
* @see org.alfresco.maven.plugin.amp.packaging.AmpPackagingContext#getAmpConfigDirectory()
*/
public File getAmpConfigDirectory()
{
return mAmpConfigDirectory;
}
public String[] getAmpWebExcludes() {
return getWebExcludes();
}
public String[] getAmpWebIncludes() {
return getWebIncludes();
}
}
public MavenProject getProject()
{
return mProject;
}
public void setProject( MavenProject project )
{
this.mProject = project;
}
public File getClassesDirectory()
{
return mClassesDirectory;
}
public void setClassesDirectory( File classesDirectory )
{
this.mClassesDirectory = classesDirectory;
}
public File getAmpDirectory()
{
return mAmpDirectory;
}
public void setAmpDirectory( File webappDirectory )
{
this.mAmpDirectory = webappDirectory;
}
public File getAmpSourceDirectory()
{
return mAmpWebDirectory;
}
public void setAmpSourceDirectory( File ampSourceDirectory )
{
this.mAmpWebDirectory = ampSourceDirectory;
}
public File getWebXml()
{
return mModuleProperties;
}
public void setWebXml( File webXml )
{
this.mModuleProperties = webXml;
}
public File getmFileMappingProperties()
{
return mFileMappingProperties;
}
public void setmFileMappingProperties(File mFileMappingProperties)
{
this.mFileMappingProperties = mFileMappingProperties;
}
public String getOutputFileNameMapping()
{
return mOutputFileNameMapping;
}
public void setOutputFileNameMapping( String outputFileNameMapping )
{
this.mOutputFileNameMapping = outputFileNameMapping;
}
public List getOverlays()
{
return mOverlays;
}
public void setOverlays( List overlays )
{
this.mOverlays = overlays;
}
public void addOverlay( Overlay overlay )
{
mOverlays.add( overlay );
}
public JarArchiver getJarArchiver()
{
return mJarArchiver;
}
public void setJarArchiver( JarArchiver jarArchiver )
{
this.mJarArchiver = jarArchiver;
}
public Resource[] getAmpResources()
{
return mAmpResources;
}
public void setAmpResources( Resource[] webResources )
{
this.mAmpResources = webResources;
}
public List getFilters()
{
return filters;
}
public void setFilters( List filters )
{
this.filters = filters;
}
public File getWorkDirectory()
{
return mWorkDirectory;
}
public void setWorkDirectory( File workDirectory )
{
this.mWorkDirectory = workDirectory;
}
public File getCacheFile()
{
return mCacheFile;
}
public void setCacheFile( File cacheFile )
{
this.mCacheFile = cacheFile;
}
public void setAmpSourceIncludes( String ampSourceIncludes )
{
this.mAmpJarIncludes = ampSourceIncludes;
}
public String getAmpJarExcludes()
{
return mAmpJarExcludes;
}
public void setAmpJarExcludes( String ampJarExcludes )
{
this.mAmpJarExcludes = ampJarExcludes;
}
public boolean isUseCache()
{
return mUseCache;
}
public void setUseCache( boolean useCache )
{
this.mUseCache = useCache;
}
}
|
Fixed mFileMappingProperties javadoc
git-svn-id: 3771f9d834ba6679eb9500b45ad9b91a192b895f@498 04253f4f-3451-0410-a141-5562f1e59037
|
plugins/maven-amp-plugin/src/main/java/org/alfresco/maven/plugin/amp/AbstractAmpMojo.java
|
Fixed mFileMappingProperties javadoc
|
<ide><path>lugins/maven-amp-plugin/src/main/java/org/alfresco/maven/plugin/amp/AbstractAmpMojo.java
<ide> private File mModuleProperties;
<ide>
<ide> /**
<del> * The path to the web.xml file to use.
<add> * The path to the file-mapping.properties file to use.
<ide> *
<ide> * @parameter expression="${maven.amp.fileMappingProperties}" default-value="${project.basedir}/file-mapping.properties"
<ide> */
|
|
Java
|
bsd-2-clause
|
a98c7e85f4148554ae628db16a0c8f6a64a463a1
| 0 |
kruss/Juggernaut,kruss/Juggernaut,kruss/Juggernaut
|
package data;
import java.util.ArrayList;
import lifecycle.StatusManager.Status;
public class Artifact implements Comparable<Artifact> {
public static final String DEFAULT_TYPE = "DEFAULT";
public enum Action { KEEP, COPY, MOVE }
public String type;
public String name;
public String description;
public Status status;
public ArrayList<Attachment> attachments;
public Artifact(String name){
this.name = name;
type = DEFAULT_TYPE;
description = "";
status = Status.UNDEFINED;
attachments = new ArrayList<Attachment>();
}
public class Attachment {
public String name;
public String description;
public String path;
public Action action;
public Attachment(String name, String path, Action action){
this.name = name;
description = "";
this.path = path;
this.action = action;
}
}
@Override
public int compareTo(Artifact o) {
return (type+"::"+name).compareTo((o.type+"::"+o.name));
}
}
|
src/data/Artifact.java
|
package data;
import java.util.ArrayList;
import lifecycle.StatusManager.Status;
public class Artifact implements Comparable<Artifact> {
public enum Type { GENERATED, RESULT }
public enum Action { LEAVE, COPY, MOVE }
public String type;
public String name;
public String description;
public Status status;
public ArrayList<Attachment> attachments;
public Artifact(String type, String name){
this.type = type;
this.name = name;
description = "";
status = Status.UNDEFINED;
attachments = new ArrayList<Attachment>();
}
public class Attachment {
public String name;
public String description;
public String path;
public Action action;
public Attachment(String name, String path, Action action){
this.name = name;
description = "";
this.path = path;
this.action = action;
}
}
@Override
public int compareTo(Artifact o) {
return (type+"::"+name).compareTo((o.type+"::"+o.name));
}
}
|
chaged artifact for default type
|
src/data/Artifact.java
|
chaged artifact for default type
|
<ide><path>rc/data/Artifact.java
<ide>
<ide> public class Artifact implements Comparable<Artifact> {
<ide>
<del> public enum Type { GENERATED, RESULT }
<del> public enum Action { LEAVE, COPY, MOVE }
<add> public static final String DEFAULT_TYPE = "DEFAULT";
<add>
<add> public enum Action { KEEP, COPY, MOVE }
<ide>
<ide> public String type;
<ide> public String name;
<ide>
<ide> public ArrayList<Attachment> attachments;
<ide>
<del> public Artifact(String type, String name){
<add> public Artifact(String name){
<ide>
<del> this.type = type;
<ide> this.name = name;
<add> type = DEFAULT_TYPE;
<ide> description = "";
<ide> status = Status.UNDEFINED;
<ide> attachments = new ArrayList<Attachment>();
|
|
Java
|
agpl-3.0
|
48bc9e0775574179aa48ced3fc6f426ffc0aaefd
| 0 |
ozwillo/ozwillo-kernel,ozwillo/ozwillo-kernel,ozwillo/ozwillo-kernel
|
/**
* Ozwillo Kernel
* Copyright (C) 2015 Atol Conseils & Développements
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package oasis.jongo.applications.v2;
import java.util.Map;
import javax.inject.Inject;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import com.mongodb.DuplicateKeyException;
import oasis.jongo.JongoBootstrapper;
import oasis.model.InvalidVersionException;
import oasis.model.applications.v2.Service;
import oasis.model.applications.v2.ServiceRepository;
import oasis.auth.AuthModule;
public class JongoServiceRepository implements ServiceRepository, JongoBootstrapper {
private static final Logger logger = LoggerFactory.getLogger(ServiceRepository.class);
static final String SERVICES_COLLECTION = "services";
private final Jongo jongo;
@Inject
JongoServiceRepository(Jongo jongo) {
this.jongo = jongo;
}
private MongoCollection getServicesCollection() {
return jongo.getCollection(SERVICES_COLLECTION);
}
@Override
public Service createService(Service service) {
JongoService jongoService = new JongoService(service);
jongoService.initCreated();
try {
getServicesCollection().insert(jongoService);
} catch (DuplicateKeyException e) {
return null;
}
return jongoService;
}
@Override
public Service getService(String serviceId) {
return getServicesCollection()
.findOne("{ id: # }", serviceId)
.as(JongoService.class);
}
public Iterable<JongoService> getAllInCatalog() {
return getServicesCollection()
.find("{ visible: true, $or: [ { restricted: { $exists: 0 } }, { restricted: false } ], status: { $ne: # } }", Service.Status.NOT_AVAILABLE)
.as(JongoService.class);
}
@Override
@SuppressWarnings("unchecked")
public Iterable<Service> getServicesOfInstance(String instanceId) {
return (Iterable<Service>) (Iterable<?>) getServicesCollection()
.find("{ instance_id: # }", instanceId)
.as(JongoService.class);
}
@Override
public Service getServiceByRedirectUri(String instanceId, String redirect_uri) {
return getServicesCollection()
.findOne("{ instance_id: #, redirect_uris: # }", instanceId, redirect_uri)
.as(JongoService.class);
}
@Override
public Service getServiceByPostLogoutRedirectUri(String instanceId, String post_logout_redirect_uri) {
return getServicesCollection()
.findOne("{ instance_id: #, post_logout_redirect_uris: # }", instanceId, post_logout_redirect_uri)
.as(JongoService.class);
}
@Override
public boolean deleteService(String serviceId, long[] versions) throws InvalidVersionException {
int n = getServicesCollection()
.remove("{ id: #, modified: { $in: # } }", serviceId, Longs.asList(versions))
.getN();
if (n == 0) {
if (getServicesCollection().count("{ id: # }", serviceId) > 0) {
throw new InvalidVersionException("service", serviceId);
}
return false;
}
if (n > 1) {
logger.error("Deleted {} services with ID {}, that shouldn't have happened", n, serviceId);
}
return true;
}
@Override
@SuppressWarnings("deprecation")
public Service updateService(Service service, long[] versions) throws InvalidVersionException {
String serviceId = service.getId();
Preconditions.checkArgument(!Strings.isNullOrEmpty(serviceId));
// Copy to get the modified field, then reset ID (not copied over) to make sure we won't generate a new one
service = new JongoService(service);
service.setId(serviceId);
// XXX: don't allow updating those properties (should we return an error if attempted?)
service.setLocal_id(null);
service.setInstance_id(null);
service.setProvider_id(null);
// FIXME: allow unsetting properties; for now only support visible/restricted
Map<String, Boolean> unsetObject = Maps.newLinkedHashMap();
if (service.getVisible() == null) {
unsetObject.put("visible", true);
}
if (service.getRestricted() == null) {
unsetObject.put("restricted", true);
}
service = getServicesCollection()
.findAndModify("{ id: #, modified: { $in: # } }", serviceId, Longs.asList(versions))
.with("{ $set: #, $unset: # }", service, unsetObject)
.returnNew()
.as(JongoService.class);
if (service == null) {
if (getServicesCollection().count("{ id: # }", serviceId) > 0) {
throw new InvalidVersionException("service", serviceId);
}
return null;
}
return service;
}
@Override
public int deleteServicesOfInstance(String instanceId) {
return getServicesCollection()
.remove("{ instance_id: # }", instanceId)
.getN();
}
@Override
public int changeServicesStatusForInstance(String instanceId, Service.Status status) {
return getServicesCollection()
.update("{ instance_id: # }", instanceId)
.multi()
.with("{ $set: { status: #, modified: # } }", status, System.currentTimeMillis())
.getN();
}
@Override
public void bootstrap() {
getServicesCollection().ensureIndex("{ id: 1 }", "{ unique: 1 }");
getServicesCollection().ensureIndex("{ instance_id: 1, local_id: 1 }", "{ unique: 1, sparse: 1 }");
getServicesCollection().ensureIndex("{ instance_id: 1, redirect_uris: 1 }", "{ unique: 1, sparse: 1 }");
// We cannot make this index unique as that would rule out having several services,
// for the same instance, without post_logout_redirect_uri at all.
// XXX: we should probably move post_logout_redirect_uris to app_instances eventually.
getServicesCollection().ensureIndex("{ instance_id: 1, post_logout_redirect_uris: 1 }", "{ sparse: 1 }");
}
}
|
oasis-webapp/src/main/java/oasis/jongo/applications/v2/JongoServiceRepository.java
|
/**
* Ozwillo Kernel
* Copyright (C) 2015 Atol Conseils & Développements
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package oasis.jongo.applications.v2;
import javax.inject.Inject;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.primitives.Longs;
import com.mongodb.DuplicateKeyException;
import oasis.jongo.JongoBootstrapper;
import oasis.model.InvalidVersionException;
import oasis.model.applications.v2.Service;
import oasis.model.applications.v2.ServiceRepository;
import oasis.auth.AuthModule;
public class JongoServiceRepository implements ServiceRepository, JongoBootstrapper {
private static final Logger logger = LoggerFactory.getLogger(ServiceRepository.class);
static final String SERVICES_COLLECTION = "services";
private final Jongo jongo;
private final AuthModule.Settings settings;
@Inject
JongoServiceRepository(Jongo jongo, AuthModule.Settings settings) {
this.jongo = jongo;
this.settings = settings;
}
private MongoCollection getServicesCollection() {
return jongo.getCollection(SERVICES_COLLECTION);
}
@Override
public Service createService(Service service) {
JongoService jongoService = new JongoService(service);
jongoService.initCreated();
try {
getServicesCollection().insert(jongoService);
} catch (DuplicateKeyException e) {
return null;
}
return jongoService;
}
@Override
public Service getService(String serviceId) {
return getServicesCollection()
.findOne("{ id: # }", serviceId)
.as(JongoService.class);
}
public Iterable<JongoService> getAllInCatalog() {
return getServicesCollection()
.find("{ visible: true, $or: [ { restricted: { $exists: 0 } }, { restricted: false } ], status: { $ne: # } }", Service.Status.NOT_AVAILABLE)
.as(JongoService.class);
}
@Override
@SuppressWarnings("unchecked")
public Iterable<Service> getServicesOfInstance(String instanceId) {
return (Iterable<Service>) (Iterable<?>) getServicesCollection()
.find("{ instance_id: # }", instanceId)
.as(JongoService.class);
}
@Override
public Service getServiceByRedirectUri(String instanceId, String redirect_uri) {
return getServicesCollection()
.findOne("{ instance_id: #, redirect_uris: # }", instanceId, redirect_uri)
.as(JongoService.class);
}
@Override
public Service getServiceByPostLogoutRedirectUri(String instanceId, String post_logout_redirect_uri) {
return getServicesCollection()
.findOne("{ instance_id: #, post_logout_redirect_uris: # }", instanceId, post_logout_redirect_uri)
.as(JongoService.class);
}
@Override
public boolean deleteService(String serviceId, long[] versions) throws InvalidVersionException {
int n = getServicesCollection()
.remove("{ id: #, modified: { $in: # } }", serviceId, Longs.asList(versions))
.getN();
if (n == 0) {
if (getServicesCollection().count("{ id: # }", serviceId) > 0) {
throw new InvalidVersionException("service", serviceId);
}
return false;
}
if (n > 1) {
logger.error("Deleted {} services with ID {}, that shouldn't have happened", n, serviceId);
}
return true;
}
@Override
public Service updateService(Service service, long[] versions) throws InvalidVersionException {
String serviceId = service.getId();
Preconditions.checkArgument(!Strings.isNullOrEmpty(serviceId));
// Copy to get the modified field, then reset ID (not copied over) to make sure we won't generate a new one
service = new JongoService(service);
service.setId(serviceId);
// XXX: don't allow updating those properties (should we return an error if attempted?)
service.setLocal_id(null);
service.setInstance_id(null);
service.setProvider_id(null);
// FIXME: allow unsetting properties
service = getServicesCollection()
.findAndModify("{ id: #, modified: { $in: # } }", serviceId, Longs.asList(versions))
.with("{ $set: # }", service)
.returnNew()
.as(JongoService.class);
if (service == null) {
if (getServicesCollection().count("{ id: # }", serviceId) > 0) {
throw new InvalidVersionException("service", serviceId);
}
return null;
}
return service;
}
@Override
public int deleteServicesOfInstance(String instanceId) {
return getServicesCollection()
.remove("{ instance_id: # }", instanceId)
.getN();
}
@Override
public int changeServicesStatusForInstance(String instanceId, Service.Status status) {
return getServicesCollection()
.update("{ instance_id: # }", instanceId)
.multi()
.with("{ $set: { status: #, modified: # } }", status, System.currentTimeMillis())
.getN();
}
@Override
public void bootstrap() {
getServicesCollection().ensureIndex("{ id: 1 }", "{ unique: 1 }");
getServicesCollection().ensureIndex("{ instance_id: 1, local_id: 1 }", "{ unique: 1, sparse: 1 }");
getServicesCollection().ensureIndex("{ instance_id: 1, redirect_uris: 1 }", "{ unique: 1, sparse: 1 }");
// We cannot make this index unique as that would rule out having several services,
// for the same instance, without post_logout_redirect_uri at all.
// XXX: we should probably move post_logout_redirect_uris to app_instances eventually.
getServicesCollection().ensureIndex("{ instance_id: 1, post_logout_redirect_uris: 1 }", "{ sparse: 1 }");
}
}
|
Unset visible/restricted in MongoDB when necessary.
If we don't do that, and given that 'visible' was a 'boolean' (so was
never null, and always present in MongoDB), a service being updated to
use the new properties would continue to use the old settings, as they
wouldn't be removed from MongoDB (and they take priority when present).
Change-Id: I509e2b380a6e8fe01bdef233eea2e15954c8cffa
|
oasis-webapp/src/main/java/oasis/jongo/applications/v2/JongoServiceRepository.java
|
Unset visible/restricted in MongoDB when necessary.
|
<ide><path>asis-webapp/src/main/java/oasis/jongo/applications/v2/JongoServiceRepository.java
<ide> */
<ide> package oasis.jongo.applications.v2;
<ide>
<add>import java.util.Map;
<add>
<ide> import javax.inject.Inject;
<ide>
<ide> import org.jongo.Jongo;
<ide>
<ide> import com.google.common.base.Preconditions;
<ide> import com.google.common.base.Strings;
<add>import com.google.common.collect.Maps;
<ide> import com.google.common.primitives.Longs;
<ide> import com.mongodb.DuplicateKeyException;
<ide>
<ide> static final String SERVICES_COLLECTION = "services";
<ide>
<ide> private final Jongo jongo;
<del> private final AuthModule.Settings settings;
<ide>
<ide> @Inject
<del> JongoServiceRepository(Jongo jongo, AuthModule.Settings settings) {
<add> JongoServiceRepository(Jongo jongo) {
<ide> this.jongo = jongo;
<del> this.settings = settings;
<ide> }
<ide>
<ide> private MongoCollection getServicesCollection() {
<ide> }
<ide>
<ide> @Override
<add> @SuppressWarnings("deprecation")
<ide> public Service updateService(Service service, long[] versions) throws InvalidVersionException {
<ide> String serviceId = service.getId();
<ide> Preconditions.checkArgument(!Strings.isNullOrEmpty(serviceId));
<ide> service.setLocal_id(null);
<ide> service.setInstance_id(null);
<ide> service.setProvider_id(null);
<del> // FIXME: allow unsetting properties
<add> // FIXME: allow unsetting properties; for now only support visible/restricted
<add> Map<String, Boolean> unsetObject = Maps.newLinkedHashMap();
<add> if (service.getVisible() == null) {
<add> unsetObject.put("visible", true);
<add> }
<add> if (service.getRestricted() == null) {
<add> unsetObject.put("restricted", true);
<add> }
<ide> service = getServicesCollection()
<ide> .findAndModify("{ id: #, modified: { $in: # } }", serviceId, Longs.asList(versions))
<del> .with("{ $set: # }", service)
<add> .with("{ $set: #, $unset: # }", service, unsetObject)
<ide> .returnNew()
<ide> .as(JongoService.class);
<ide> if (service == null) {
|
|
JavaScript
|
mit
|
95e0c4619d97a197435b6afb42a662e090b9aa2c
| 0 |
pagesjaunes/curiosity,ErwanPigneul/curiosity,pagesjaunes/curiosity,joebordes/curiosity,ErwanPigneul/curiosity,ErwanPigneul/curiosity,joebordes/curiosity,joebordes/curiosity,pagesjaunes/curiosity
|
var globalConf = {
defaultServer : 'http://localhost:9200',
confServer : 'http://localhost:9200',
confIndex : "curiosity-config",
defaultConfDocumentType : "conf-doc",
}
|
conf.js
|
var globalConf = {
defaultServer : 'http://localhost:9200',
confServer : 'http://localhost:10200',
confIndex : "curiosity-config",
defaultConfDocumentType : "conf-doc",
}
|
Oubli du chnagement de port
|
conf.js
|
Oubli du chnagement de port
|
<ide><path>onf.js
<ide> var globalConf = {
<ide> defaultServer : 'http://localhost:9200',
<del> confServer : 'http://localhost:10200',
<add> confServer : 'http://localhost:9200',
<ide> confIndex : "curiosity-config",
<ide> defaultConfDocumentType : "conf-doc",
<ide> }
|
|
Java
|
mit
|
error: pathspec 'eclipse/src/dynamake/collections/Categorizer.java' did not match any file(s) known to git
|
419aa8d697e38ae03a02109dc343cca266111a8e
| 1 |
jakobehmsen/dynamake
|
package dynamake.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
public class Categorizer<T, U> {
private Hashtable<T, List<U>> categories = new Hashtable<T, List<U>>();
public void add(T category, U item) {
List<U> itemsInCategory = categories.get(category);
if(itemsInCategory == null) {
itemsInCategory = new ArrayList<U>();
categories.put(category, itemsInCategory);
}
itemsInCategory.add(item);
}
public void remove(T category, U item) {
List<U> itemsInCategory = categories.get(category);
if(itemsInCategory != null)
itemsInCategory.remove(category);
}
public List<U> getItems(T category) {
List<U> itemsInCategory = categories.get(category);
if(itemsInCategory != null)
return new ArrayList<U>(itemsInCategory);
return Collections.emptyList();
}
}
|
eclipse/src/dynamake/collections/Categorizer.java
|
Added collection type Categorizer to categorize collections of items.
Signed-off-by: Jakob Brandsborg Ehmsen <[email protected]>
|
eclipse/src/dynamake/collections/Categorizer.java
|
Added collection type Categorizer to categorize collections of items.
|
<ide><path>clipse/src/dynamake/collections/Categorizer.java
<add>package dynamake.collections;
<add>
<add>import java.util.ArrayList;
<add>import java.util.Collections;
<add>import java.util.Hashtable;
<add>import java.util.List;
<add>
<add>public class Categorizer<T, U> {
<add> private Hashtable<T, List<U>> categories = new Hashtable<T, List<U>>();
<add>
<add> public void add(T category, U item) {
<add> List<U> itemsInCategory = categories.get(category);
<add> if(itemsInCategory == null) {
<add> itemsInCategory = new ArrayList<U>();
<add> categories.put(category, itemsInCategory);
<add> }
<add> itemsInCategory.add(item);
<add> }
<add>
<add> public void remove(T category, U item) {
<add> List<U> itemsInCategory = categories.get(category);
<add> if(itemsInCategory != null)
<add> itemsInCategory.remove(category);
<add> }
<add>
<add> public List<U> getItems(T category) {
<add> List<U> itemsInCategory = categories.get(category);
<add> if(itemsInCategory != null)
<add> return new ArrayList<U>(itemsInCategory);
<add> return Collections.emptyList();
<add> }
<add>}
|
|
Java
|
bsd-2-clause
|
error: pathspec 'Commons/G3MSharedSDK/src/org/glob3/mobile/generated/TileMillLayer.java' did not match any file(s) known to git
|
6f4fb816cf8a7af0f84d8ff09021b8157d70f0e7
| 1 |
AeroGlass/g3m,AeroGlass/g3m,octavianiLocator/g3m,AeroGlass/g3m,octavianiLocator/g3m,AeroGlass/g3m,octavianiLocator/g3m,octavianiLocator/g3m,octavianiLocator/g3m,octavianiLocator/g3m,AeroGlass/g3m,AeroGlass/g3m
|
package org.glob3.mobile.generated;
//
// TileMillLayer.cpp
// G3MiOSSDK
//
// Created by Vidal Toboso on 19/02/13.
//
//
//
// TileMillLayer.hpp
// G3MiOSSDK
//
// Created by Vidal Toboso on 19/02/13.
//
//
public class TileMillLayer extends Layer
{
private final Sector _sector ;
private URL _mapServerURL = new URL();
private final String _dataBaseMBTiles;
public TileMillLayer(String layerName, URL mapServerURL, LayerCondition condition, Sector sector, String dataBaseMBTiles, TimeInterval timeToCache)
{
super(condition, layerName, timeToCache);
_sector = new Sector(sector);
_mapServerURL = new URL(mapServerURL);
_dataBaseMBTiles = dataBaseMBTiles;
}
public final java.util.ArrayList<Petition> getMapPetitions(G3MRenderContext rc, Tile tile, int width, int height)
{
java.util.ArrayList<Petition> petitions = new java.util.ArrayList<Petition>();
final Sector tileSector = tile.getSector();
if (!_sector.touchesWith(tileSector))
{
return petitions;
}
final Sector sector = tileSector.intersection(_sector);
String req = _mapServerURL.getPath();
//If the server refer to itself as localhost...
int pos = req.indexOf("localhost");
if (pos != -1)
{
req = req.substring(pos+9);
int pos2 = req.indexOf("/", 8);
String newHost = req.substring(0, pos2);
req = newHost + req;
}
IStringBuilder isb = IStringBuilder.newStringBuilder();
isb.addString(req);
isb.addString("db=");
isb.addString(_dataBaseMBTiles);
isb.addString("&z=");
isb.addInt(tile.getLevel()+1);
isb.addString("&x=");
isb.addInt(tile.getColumn());
isb.addString("&y=");
isb.addInt(tile.getRow());
ILogger.instance().logInfo("%s", isb.getString());
petitions.add(new Petition(sector, new URL(isb.getString(), false), _timeToCache));
return petitions;
}
public final URL getFeatureInfoURL(Geodetic2D g, IFactory factory, Sector tileSector, int width, int height)
{
return URL.nullURL();
}
}
|
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/TileMillLayer.java
|
Generated
|
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/TileMillLayer.java
|
Generated
|
<ide><path>ommons/G3MSharedSDK/src/org/glob3/mobile/generated/TileMillLayer.java
<add>package org.glob3.mobile.generated;
<add>//
<add>// TileMillLayer.cpp
<add>// G3MiOSSDK
<add>//
<add>// Created by Vidal Toboso on 19/02/13.
<add>//
<add>//
<add>
<add>//
<add>// TileMillLayer.hpp
<add>// G3MiOSSDK
<add>//
<add>// Created by Vidal Toboso on 19/02/13.
<add>//
<add>//
<add>
<add>
<add>
<add>public class TileMillLayer extends Layer
<add>{
<add> private final Sector _sector ;
<add> private URL _mapServerURL = new URL();
<add> private final String _dataBaseMBTiles;
<add>
<add> public TileMillLayer(String layerName, URL mapServerURL, LayerCondition condition, Sector sector, String dataBaseMBTiles, TimeInterval timeToCache)
<add> {
<add> super(condition, layerName, timeToCache);
<add> _sector = new Sector(sector);
<add> _mapServerURL = new URL(mapServerURL);
<add> _dataBaseMBTiles = dataBaseMBTiles;
<add>
<add> }
<add>
<add> public final java.util.ArrayList<Petition> getMapPetitions(G3MRenderContext rc, Tile tile, int width, int height)
<add> {
<add> java.util.ArrayList<Petition> petitions = new java.util.ArrayList<Petition>();
<add> final Sector tileSector = tile.getSector();
<add>
<add> if (!_sector.touchesWith(tileSector))
<add> {
<add> return petitions;
<add> }
<add> final Sector sector = tileSector.intersection(_sector);
<add> String req = _mapServerURL.getPath();
<add> //If the server refer to itself as localhost...
<add> int pos = req.indexOf("localhost");
<add>
<add> if (pos != -1)
<add> {
<add> req = req.substring(pos+9);
<add> int pos2 = req.indexOf("/", 8);
<add> String newHost = req.substring(0, pos2);
<add> req = newHost + req;
<add> }
<add> IStringBuilder isb = IStringBuilder.newStringBuilder();
<add> isb.addString(req);
<add> isb.addString("db=");
<add> isb.addString(_dataBaseMBTiles);
<add> isb.addString("&z=");
<add> isb.addInt(tile.getLevel()+1);
<add> isb.addString("&x=");
<add> isb.addInt(tile.getColumn());
<add> isb.addString("&y=");
<add> isb.addInt(tile.getRow());
<add>
<add> ILogger.instance().logInfo("%s", isb.getString());
<add>
<add> petitions.add(new Petition(sector, new URL(isb.getString(), false), _timeToCache));
<add>
<add> return petitions;
<add> }
<add> public final URL getFeatureInfoURL(Geodetic2D g, IFactory factory, Sector tileSector, int width, int height)
<add> {
<add> return URL.nullURL();
<add>
<add> }
<add>
<add>
<add>
<add>
<add>}
|
|
JavaScript
|
bsd-2-clause
|
a2d8a317024cfda426100488cf44aa56c9405f31
| 0 |
importre/generator-atomapp
|
'use strict';
module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);
var atomShellVersion = '<%= atomShellVersion %>';
var outDir = 'out';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
'download-atom-shell': {
version: atomShellVersion,
outputDir: outDir,
rebuild: true
},
watch: {
scripts: {
options: {
livereload: true
},
files: [
'Gruntfile.js',
'app/**/*.js',
'app/**/*.html',
'app/**/*.css'
]
}
},
shell: {
mac: {
command: outDir + '/Atom.app/Contents/MacOS/Atom app'
},
linux: {
command: [
'chmod +x ' + outDir + '/atom',
outDir + '/atom app'
].join('&&')
},
win: {
command: outDir + '\\atom.exe app'
},
copyMacApp: {
command: [
'cp -a ' + outDir + ' dist',
'cp -a app/ dist/Atom.app/Contents/Resources/app'
].join('&&')
},
copyLinuxApp: {
command: [
'cp -R ' + outDir + ' dist',
'cp -R app/ dist/resources/app'
].join('&&')
},
copyWinApp: {
command: [
'echo d | xcopy /e /y /k /h ' + outDir + ' dist',
'echo d | xcopy /e /y /k /h app dist\\resources\\app'
].join('&&')
}
},
parallel: {
options: {
stream: true
},
mix: {
tasks: [
{
grunt: true,
args: ['watch']
},
{
grunt: true,
args: ['run']
}
]
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'app/scripts/**/*.js'
]
}
});
grunt.registerTask('run', 'run...', function () {
if (process.platform === 'darwin') {
grunt.task.run('shell:mac');
} else if (process.platform === 'win32') {
grunt.task.run('shell:win');
} else {
grunt.task.run('shell:linux');
}
});
grunt.registerTask('dist', 'dist...', function () {
if (process.platform === 'darwin') {
grunt.task.run('shell:copyMacApp');
} else if (process.platform === 'win32') {
grunt.task.run('shell:copyWinApp');
} else {
grunt.task.run('shell:copyLinuxApp');
}
});
grunt.registerTask('default', [
'download-atom-shell',
'jshint',
'parallel'
]);
};
|
app/templates/Gruntfile.js
|
'use strict';
module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);
var atomShellVersion = '<%= atomShellVersion %>';
var outDir = 'out';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
'download-atom-shell': {
version: atomShellVersion,
outputDir: outDir,
rebuild: true
},
watch: {
scripts: {
options: {
livereload: true
},
files: [
'**/*.js',
'**/*.html',
'**/*.css'
]
}
},
shell: {
mac: {
command: outDir + '/Atom.app/Contents/MacOS/Atom app'
},
linux: {
command: [
'chmod +x ' + outDir + '/atom',
outDir + '/atom app'
].join('&&')
},
win: {
command: outDir + '\\atom.exe app'
},
copyMacApp: {
command: [
'cp -a ' + outDir + ' dist',
'cp -a app/ dist/Atom.app/Contents/Resources/app'
].join('&&')
},
copyLinuxApp: {
command: [
'cp -R ' + outDir + ' dist',
'cp -R app/ dist/resources/app'
].join('&&')
},
copyWinApp: {
command: [
'echo d | xcopy /e /y /k /h ' + outDir + ' dist',
'echo d | xcopy /e /y /k /h app dist\\resources\\app'
].join('&&')
}
},
parallel: {
options: {
stream: true
},
mix: {
tasks: [
{
grunt: true,
args: ['watch']
},
{
grunt: true,
args: ['run']
}
]
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'app/scripts/**/*.js'
]
}
});
grunt.registerTask('run', 'run...', function () {
if (process.platform === 'darwin') {
grunt.task.run('shell:mac');
} else if (process.platform === 'win32') {
grunt.task.run('shell:win');
} else {
grunt.task.run('shell:linux');
}
});
grunt.registerTask('dist', 'dist...', function () {
if (process.platform === 'darwin') {
grunt.task.run('shell:copyMacApp');
} else if (process.platform === 'win32') {
grunt.task.run('shell:copyWinApp');
} else {
grunt.task.run('shell:copyLinuxApp');
}
});
grunt.registerTask('default', [
'download-atom-shell',
'jshint',
'parallel'
]);
};
|
Change watch target list
Do not need to watch necessary files
|
app/templates/Gruntfile.js
|
Change watch target list
|
<ide><path>pp/templates/Gruntfile.js
<ide> livereload: true
<ide> },
<ide> files: [
<del> '**/*.js',
<del> '**/*.html',
<del> '**/*.css'
<add> 'Gruntfile.js',
<add> 'app/**/*.js',
<add> 'app/**/*.html',
<add> 'app/**/*.css'
<ide> ]
<ide> }
<ide> },
|
|
Java
|
apache-2.0
|
7e294b49ec84ff99b82cf62ecda62e22ff093dc0
| 0 |
mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData
|
package uk.ac.ebi.phenotype.repository;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.mousephenotype.cda.annotations.ComponentScanNonParticipant;
import org.mousephenotype.cda.owl.OntologyParser;
import org.mousephenotype.cda.owl.OntologyParserFactory;
import org.mousephenotype.cda.owl.OntologyTermDTO;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
* Created by ckchen on 17/03/2017.
*/
@Component
@ComponentScanNonParticipant
public class Loader implements CommandLineRunner {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
@Qualifier("komp2DataSource")
DataSource komp2DataSource;
@Autowired
@Qualifier("phenodigmDataSource")
DataSource phenodigmDataSource;
// @NotNull
// @Value("${neo4jDbPath}")
// private String neo4jDbPath;
@NotNull
@Value("${allele2File}")
private String pathToAlleleFile;
@NotNull
@Value("${human2mouseFilename}")
private String pathToHuman2mouseFilename;
// @NotNull
// @Value("${mpListPath}")
// private String mpListPath;
@NotNull
@Value("${owlpath}")
protected String owlpath;
@Autowired
GeneRepository geneRepository;
@Autowired
AlleleRepository alleleRepository;
@Autowired
EnsemblGeneIdRepository ensemblGeneIdRepository;
@Autowired
MarkerSynonymRepository markerSynonymRepository;
@Autowired
HumanGeneSymbolRepository humanGeneSymbolRepository;
@Autowired
MpRepository mpRepository;
@Autowired
HpRepository hpRepository;
@Autowired
OntoSynonymRepository ontoSynonymRepository;
@Autowired
DiseaseGeneRepository diseaseGeneRepository;
@Autowired
DiseaseModelRepository diseaseModelRepository;
@Autowired
MouseModelRepository mouseModelRepository;
OntologyParserFactory ontologyParserFactory;
Map<String, Allele> loadedAlleles = new HashMap<>();
Map<String, Gene> loadedGenes = new HashMap<>();
Map<String, Gene> loadedMouseSymbolGenes = new HashMap<>();
Map<String, Mp> loadedMps = new HashMap<>();
Map<String, Hp> loadedHps = new HashMap<>();
// Map<String, DiseaseGene> loadedDiseaseGenes = new HashMap<>();
Map<Integer, MouseModel> loadedMouseModels = new HashMap<>();
Map<String, EnsemblGeneId> ensGidEnsemblGeneIdMap = new HashMap<>();
Map<Integer, Set<Mp>> mouseModelIdMpMap = new HashMap<>();
Map<String, String> hpIdTermMap = new HashMap<>();
Map<String, Set<Hp>> bestMpIdHpMap = new HashMap<>();
Map<String, Set<Hp>> diseaseIdPhenotypeMap = new HashMap<>();
private OntologyParser mpHpParser;
private OntologyParser mpParser;
private static final int LEVELS_FOR_NARROW_SYNONYMS = 2;
public Loader() {}
@Override
public void run(String... strings) throws Exception {
ontologyParserFactory = new OntologyParserFactory(komp2DataSource, owlpath);
// NOTE that deleting repositories takes lots of memory
// would be way faster to just remove the db directory
logger.info("Start deleting all repositories ...");
//FileUtils.deleteDirectory(new File(neo4jDbPath));
geneRepository.deleteAll();
alleleRepository.deleteAll();
ensemblGeneIdRepository.deleteAll();
markerSynonymRepository.deleteAll();
ontoSynonymRepository.deleteAll();
humanGeneSymbolRepository.deleteAll();
mpRepository.deleteAll();
hpRepository.deleteAll();
diseaseGeneRepository.deleteAll();
diseaseModelRepository.deleteAll();
mouseModelRepository.deleteAll();
logger.info("Done deleting all repositories");
Connection komp2Conn = komp2DataSource.getConnection();
Connection diseaseConn = phenodigmDataSource.getConnection();
//----------- STEP 1 -----------//
// loading Gene, Allele, EnsemblGeneId, MarkerSynonym, human orthologs
// based on Peter's allele2 flatfile
loadGenes();
//----------- STEP 2 -----------//
populateHpIdTermMap(); // STEP 2.1
populateBestMpIdHpMap(); // STEP 2.2
extendLoadedHpAndConnectHp2Mp(); // STEP 2.3
loadMousePhenotypes(); // STEP 2.4
//----------- STEP 3 -----------//
populateMouseModelIdMpMap(); // run this before loadMouseModel()
loadMouseModels();
//----------- STEP 4 -----------//
// load disease and Gene, Hp, Mp relationships
populateDiseaseIdPhenotypeMap();
//loadDiseaseGenes();
//----------- STEP 5 -----------//
loadDiseaseModels();
}
public void loadGenes() throws IOException, SolrServerException {
long begin = System.currentTimeMillis();
final Map<String, String> ES_CELL_STATUS_MAPPINGS = new HashMap<>();
ES_CELL_STATUS_MAPPINGS.put("No ES Cell Production", "Not Assigned for ES Cell Production");
ES_CELL_STATUS_MAPPINGS.put("ES Cell Production in Progress", "Assigned for ES Cell Production");
ES_CELL_STATUS_MAPPINGS.put("ES Cell Targeting Confirmed", "ES Cells Produced");
final Map<String, String> MOUSE_STATUS_MAPPINGS = new HashMap<>();
MOUSE_STATUS_MAPPINGS.put("Chimeras obtained", "Assigned for Mouse Production and Phenotyping");
MOUSE_STATUS_MAPPINGS.put("Micro-injection in progress", "Assigned for Mouse Production and Phenotyping");
MOUSE_STATUS_MAPPINGS.put("Cre Excision Started", "Mice Produced");
MOUSE_STATUS_MAPPINGS.put("Rederivation Complete", "Mice Produced");
MOUSE_STATUS_MAPPINGS.put("Rederivation Started", "Mice Produced");
MOUSE_STATUS_MAPPINGS.put("Genotype confirmed", "Mice Produced");
MOUSE_STATUS_MAPPINGS.put("Cre Excision Complete", "Mice Produced");
MOUSE_STATUS_MAPPINGS.put("Phenotype Attempt Registered", "Mice Produced");
Map<String, Integer> columns = new HashMap<>();
BufferedReader in = new BufferedReader(new FileReader(new File(pathToAlleleFile)));
BufferedReader in2 = new BufferedReader(new FileReader(new File(pathToAlleleFile)));
String[] header = in.readLine().split("\t");
for (int i = 0; i < header.length; i++){
columns.put(header[i], i);
}
int geneCount = 0;
int alleleCount = 0;
String line = in.readLine();
while (line != null) {
// System.out.println(line);
String[] array = line.split("\t", -1);
if (array.length == 1) {
continue;
}
if (array[columns.get("allele_design_project")].equals("IMPC")
&& ! array[columns.get("latest_project_status")].isEmpty()
&& array[columns.get("type")].equals("Gene")
&& ! array[columns.get("marker_type")].isEmpty()) {
String mgiAcc = array[columns.get("mgi_accession_id")];
Gene gene = new Gene();
gene.setMgiAccessionId(mgiAcc);
String thisSymbol = null;
if (! array[columns.get("marker_symbol")].isEmpty()) {
thisSymbol = array[columns.get("marker_symbol")];
gene.setMarkerSymbol(thisSymbol);
}
if (! array[columns.get("feature_type")].isEmpty()) {
gene.setMarkerType(array[columns.get("feature_type")]);
}
if (! array[columns.get("marker_name")].isEmpty()) {
gene.setMarkerName(array[columns.get("marker_name")]);
}
if (! array[columns.get("synonym")].isEmpty()) {
List<String> syms = Arrays.asList(StringUtils.split(array[columns.get("synonym")], "|"));
Set<MarkerSynonym> mss = new HashSet<>();
for (String sym : syms) {
MarkerSynonym ms = new MarkerSynonym();
ms.setMarkerSynonym(sym);
// ms rel to gene
ms.setGene(gene);
mss.add(ms);
}
gene.setMarkerSynonyms(mss);
}
if (! array[columns.get("feature_chromosome")].isEmpty()) {
gene.setChrId(array[columns.get("feature_chromosome")]);
gene.setChrStart(array[columns.get("feature_coord_start")]);
gene.setChrEnd(array[columns.get("feature_coord_end")]);
gene.setChrStrand(array[columns.get("feature_strand")]);
}
if (! array[columns.get("gene_model_ids")].isEmpty()) {
Set<EnsemblGeneId> ensgs = new HashSet<>();
String[] ids = StringUtils.split(array[columns.get("gene_model_ids")], "|");
for (int j = 0; j < ids.length; j++) {
String thisId = ids[j];
if (thisId.startsWith("ensembl_ids") || thisId.startsWith("\"ensembl_ids")) {
String[] vals = StringUtils.split(thisId, ":");
if (vals.length == 2) {
String ensgId = vals[1];
//System.out.println("Found " + ensgId);
EnsemblGeneId ensg = new EnsemblGeneId();
if (! ensGidEnsemblGeneIdMap.containsKey(ensgId)) {
ensg.setEnsemblGeneId(ensgId);
// ensg rel to gene
ensg.setGene(gene);
ensGidEnsemblGeneIdMap.put(ensgId, ensg);
} else {
ensg = ensGidEnsemblGeneIdMap.get(ensgId);
}
ensgs.add(ensg);
}
}
}
if (ensgs.size() > 0){
gene.setEnsemblGeneIds(ensgs);
}
}
geneRepository.save(gene);
loadedGenes.put(mgiAcc, gene);
loadedMouseSymbolGenes.put(thisSymbol, gene);
geneCount++;
if (geneCount % 5000 == 0) {
logger.info("Loaded {} Gene nodes", geneCount);
}
}
line = in.readLine();
}
logger.info("Loaded total of {} Gene nodes", geneCount);
String line2 = in2.readLine();
while (line2 != null) {
//System.out.println(line);
String[] array = line2.split("\t", -1);
if (array.length == 1) {
continue;
}
String mgiAcc = array[columns.get("mgi_accession_id")];
if (array[columns.get("allele_design_project")].equals("IMPC")
&& array[columns.get("type")].equals("Allele")
&& loadedGenes.containsKey(mgiAcc)
&& ! array[columns.get("allele_mgi_accession_id")].isEmpty()) {
Gene gene = loadedGenes.get(mgiAcc);
String alleleAcc = array[columns.get("allele_mgi_accession_id")];
Allele allele = new Allele();
allele.setAlleleMgiAccessionId(alleleAcc);
// allele rel to gene
allele.setGene(gene);
if (!array[columns.get("allele_symbol")].isEmpty()) {
allele.setAlleleSymbol(array[columns.get("allele_symbol")]);
}
if (!array[columns.get("allele_description")].isEmpty()) {
allele.setAlleleDescription(array[columns.get("allele_description")]);
}
if (!array[columns.get("mutation_type")].isEmpty()) {
allele.setMutationType(array[columns.get("mutation_type")]);
}
if (!array[columns.get("es_cell_status")].isEmpty()) {
allele.setEsCellStatus(ES_CELL_STATUS_MAPPINGS.get(array[columns.get("es_cell_status")]));
}
if (!array[columns.get("mouse_status")].isEmpty()) {
allele.setMouseStatus(MOUSE_STATUS_MAPPINGS.get(array[columns.get("mouse_status")]));
}
if (!array[columns.get("phenotype_status")].isEmpty()) {
allele.setPhenotypeStatus(array[columns.get("phenotype_status")]);
}
if (gene.getAlleles() == null){
gene.setAlleles(new HashSet<Allele>());
}
gene.getAlleles().add(allele);
alleleRepository.save(allele);
loadedAlleles.put(allele.getAlleleSymbol(), allele);
alleleCount++;
if (alleleCount % 5000 == 0){
logger.info("Loaded {} Allele nodes", alleleCount);
}
}
line2 = in2.readLine();
}
logger.info("Loaded total of {} Allele nodes", alleleCount);
String job = "Gene, Allele, MarkerSynonym and EnsemblGeneId nodes";
loadTime(begin, System.currentTimeMillis(), job);
// based on MGI report HMD_HumanPhenotype.rpt
// Mouse/Human Orthology with Phenotype Annotations (tab-delimited)
loadHumanOrtholog();
}
public void loadMousePhenotypes() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, SQLException, URISyntaxException, SolrServerException {
long begin = System.currentTimeMillis();
mpParser = ontologyParserFactory.getMpParser();
logger.info("Loaded mp parser");
// mpHpParser = ontologyParserFactory.getMpHpParser();
// logger.info("Loaded mp hp parser");
int mpCount = 0;
for (String mpId: mpParser.getTermsInSlim()) {
OntologyTermDTO mpDTO = mpParser.getOntologyTerm(mpId);
String termId = mpDTO.getAccessionId();
Mp mp = mpRepository.findByMpId(termId);
if (mp == null){
mp = new Mp();
mp.setMpId(termId);
}
if (mp.getMpTerm() == null) {
mp.setMpTerm(mpDTO.getName());
}
if (mp.getMpDefinition() == null) {
mp.setMpDefinition(mpDTO.getDefinition());
}
if (mp.getOntoSynonyms() == null) {
for (String mpsym : mpDTO.getSynonyms()) {
OntoSynonym ms = new OntoSynonym();
ms.setOntoSynonym(mpsym);
ms.setMousePhenotype(mp);
//ontoSynonymRepository.save(ms);
if (mp.getOntoSynonyms() == null) {
mp.setOntoSynonyms(new HashSet<OntoSynonym>());
}
mp.getOntoSynonyms().add(ms);
}
}
// PARENT
if (mp.getMpParentIds() == null) {
if ( mpDTO.getParentIds() != null) {
Set<Mp> parentMps = new HashSet<>();
for (String parId : mpDTO.getParentIds()) {
Mp thisMp = mpRepository.findByMpId(parId);
if (thisMp == null) {
thisMp = new Mp();
}
thisMp.setMpId(parId);
parentMps.add(thisMp);
}
if (parentMps.size() > 0) {
mp.setMpParentIds(parentMps);
}
}
}
// MARK MP WHICH IS TOP LEVEL
if (mpDTO.getTopLevelIds() == null || mpDTO.getTopLevelIds().size() == 0){
// add self as top level
mp.setTopLevelStatus(true);
}
// BEST MP to HP mapping
Set<Hp> hps = new HashSet<>();
if (bestMpIdHpMap.containsKey(termId)){
for(Hp hp : bestMpIdHpMap.get(termId)) {
hps.add(hp);
}
if (hps.size() > 0) {
mp.setHumanPhenotypes(hps);
}
}
// add mp-hp mapping using Monarch's mp-hp hybrid ontology: gets the narrow synonym
// TO DO
mpRepository.save(mp);
loadedMps.put(mp.getMpId(), mp);
mpCount++;
if (mpCount % 1000 == 0) {
logger.info("Added {} mp nodes", mpCount);
}
}
logger.info("Added total of {} mp nodes", mpCount);
String job = "loadMousePhenotypes";
loadTime(begin, System.currentTimeMillis(), job);
}
public void populateBestMpIdHpMap() throws SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT hp_id, hp_term, mp_id FROM best_impc_mp_hp_mapping ";
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query)) {
ResultSet r = p.executeQuery();
while (r.next()) {
String mpId = r.getString("mp_id");
String hpId = r.getString("hp_id");
String hpTerm = r.getString("hp_term");
if (! loadedHps.containsKey(hpId)){
Hp hp = new Hp();
hp.setHpId(hpId);
hp.setHpTerm(hpTerm);
loadedHps.put(hpId, hp);
}
if (! bestMpIdHpMap.containsKey(mpId)){
bestMpIdHpMap.put(mpId, new HashSet<Hp>());
}
bestMpIdHpMap.get(mpId).add(loadedHps.get(hpId));
}
}
String job = "populateBestMpIdHpMap";
loadTime(begin, System.currentTimeMillis(), job);
}
public void extendLoadedHpAndConnectHp2Mp() throws SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT hp_id, hp_term, mp_id FROM best_impc_hp_mp_mapping ";
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query)) {
ResultSet r = p.executeQuery();
while (r.next()) {
String mpId = r.getString("mp_id");
String hpId = r.getString("hp_id");
String hpTerm = r.getString("hp_term");
// extend loadedHps
Hp hp = new Hp();
if (! loadedHps.containsKey(hpId)) {
hp.setHpId(hpId);
hp.setHpTerm(hpTerm);
loadedHps.put(hpId, hp);
}
else {
hp = loadedHps.get(hpId);
}
if (loadedMps.containsKey(mpId)){
Mp mp = loadedMps.get(mpId);
if (hp.getMousePhenotypes() == null){
hp.setMousePhenotypes(new HashSet<Mp>());
}
hp.getMousePhenotypes().add(mp);
}
hpRepository.save(hp);
}
}
String job = "extendLoadedHpAndConnectHp2Mp";
loadTime(begin, System.currentTimeMillis(), job);
}
public void populateHpIdTermMap() throws SolrServerException, IOException, SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT DISTINCT hp_id, term FROM hp ";
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query)) {
ResultSet r = p.executeQuery();
while (r.next()) {
String hpId = r.getString("hp_id");
String hpTerm = r.getString("term");
// human Phenotype id to term mapping
hpIdTermMap.put(hpId, hpTerm);
}
}
String job = "populateHpIdTermMap";
loadTime(begin, System.currentTimeMillis(), job);
}
public void populateMouseModelIdMpMap() throws SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT mm.model_id, mmm.mp_id FROM mouse_model_mp mmm, mouse_model mm WHERE mmm.model_id=mm.model_id AND mm.source LIKE '%IMPC%'";
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
ResultSet r = p.executeQuery();
while (r.next()) {
Integer id = r.getInt("model_id");
if (!mouseModelIdMpMap.containsKey(id)) {
mouseModelIdMpMap.put(id, new HashSet<Mp>());
}
String mpId = r.getString("mp_id");
// only want MPs that IMPC knows about
if (loadedMps.containsKey(mpId)){
mouseModelIdMpMap.get(id).add(loadedMps.get(mpId));
}
}
String job = "populateMouseModelIdMpMap";
loadTime(begin, System.currentTimeMillis(), job);
}
}
public void loadMouseModels() throws SQLException {
// only MouseModels from IMPC
long begin = System.currentTimeMillis();
String query = "SELECT " +
" 'mouse_model' AS type, " +
" mm.model_id AS model_id, " +
" mgo.model_gene_id AS model_gene_id, " +
" mgo.model_gene_symbol AS model_gene_symbol, " +
" mm.source, " +
" mm.allelic_composition, " +
" mm.genetic_background, " +
" mm.allele_ids, " +
" mm.hom_het " +
"FROM mouse_model mm " +
" JOIN mouse_model_gene_ortholog mmgo ON mmgo.model_id = mm.model_id " +
" JOIN mouse_gene_ortholog mgo ON mgo.model_gene_id = mmgo.model_gene_id " +
"WHERE mm.source = 'IMPC'";
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
int mmCount = 0;
ResultSet r = p.executeQuery();
while (r.next()) {
int modelId = r.getInt("model_id");
MouseModel mm = new MouseModel();
mm.setModelId(modelId);
String mgiAcc = r.getString("model_gene_id");
// only want Genes that IMPC knows about
if (loadedGenes.containsKey(mgiAcc)) {
mm.setGene(loadedGenes.get(mgiAcc));
}
mm.setAllelicComposition(r.getString("allelic_composition"));
mm.setGeneticBackground(r.getString("genetic_background"));
mm.setHomHet(r.getString("hom_het"));
// mouse Phenotype associated with this mouseModel
if (mouseModelIdMpMap.containsKey(modelId)) {
for (Mp mp : mouseModelIdMpMap.get(modelId)) {
if (mm.getMousePhenotypes() == null) {
mm.setMousePhenotypes(new HashSet<Mp>());
}
mm.getMousePhenotypes().add(mp);
}
}
mmCount++;
mouseModelRepository.save(mm);
loadedMouseModels.put(mm.getModelId(), mm);
if (mmCount % 1000 == 0) {
logger.info("Added {} MouseModel nodes", mmCount);
}
}
logger.info("Added total of {} MouseModel nodes", mmCount);
String job = "MouseeModel nodes";
loadTime(begin, System.currentTimeMillis(), job);
}
}
public void populateDiseaseIdPhenotypeMap() throws SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT DISTINCT dh.disease_id, dh.hp_id FROM disease d " +
"LEFT JOIN disease_hp dh ON d.disease_id=dh.disease_id " +
"LEFT JOIN mouse_disease_summary mds ON mds.disease_id=d.disease_id";
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query)) {
ResultSet r = p.executeQuery();
while (r.next()) {
String diseaseId = r.getString("disease_id");
if (! diseaseIdPhenotypeMap.containsKey(diseaseId)) {
diseaseIdPhenotypeMap.put(diseaseId, new HashSet<Hp>());
}
String hpId = r.getString("hp_id");
if (loadedHps.containsKey(hpId)){
diseaseIdPhenotypeMap.get(diseaseId).add(loadedHps.get(hpId));
}
else {
Hp hp = new Hp();
hp.setHpId(hpId);
hp.setHpTerm(hpIdTermMap.get(hpId));
loadedHps.put(hpId, hp);
diseaseIdPhenotypeMap.get(diseaseId).add(hp);
}
}
String job = "populateDiseaseIdPhenotypeMap";
loadTime(begin, System.currentTimeMillis(), job);
}
}
public void loadDiseaseGenes() throws SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT" +
" 'disease_gene_summary' AS type, " +
" d.disease_id, " +
" disease_term, " +
" disease_alts, " +
" disease_locus, " +
" disease_classes AS disease_classes, " +
" mgo.model_gene_id AS model_gene_id, " +
" mgo.model_gene_symbol AS model_gene_symbol, " +
" mgo.hgnc_id AS hgnc_gene_id, " +
" mgo.hgnc_gene_symbol, " +
" human_curated, " +
" mod_curated AS mod_curated, " +
" in_locus, " +
" max_mod_disease_to_model_perc_score AS max_mod_disease_to_model_perc_score, " +
" max_mod_model_to_disease_perc_score AS max_mod_model_to_disease_perc_score, " +
" max_htpc_disease_to_model_perc_score AS max_htpc_disease_to_model_perc_score, " +
" max_htpc_model_to_disease_perc_score AS max_htpc_model_to_disease_perc_score, " +
" mod_raw_score AS raw_mod_score, " +
" htpc_raw_score AS raw_htpc_score, " +
" mod_predicted AS mod_predicted, " +
" mod_predicted_known_gene AS mod_predicted_known_gene, " +
" novel_mod_predicted_in_locus AS novel_mod_predicted_in_locus, " +
" htpc_predicted AS htpc_predicted, " +
" htpc_predicted_known_gene AS htpc_predicted_known_gene, " +
" novel_htpc_predicted_in_locus AS novel_htpc_predicted_in_locus " +
"FROM " +
" mouse_disease_gene_summary_high_quality mdgshq " +
" LEFT JOIN disease d ON d.disease_id = mdgshq.disease_id" +
" JOIN (SELECT DISTINCT model_gene_id, model_gene_symbol, hgnc_id, hgnc_gene_symbol FROM mouse_gene_ortholog) mgo ON mgo.model_gene_id = mdgshq.model_gene_id " +
" WHERE d.disease_id IS NOT NULL";
logger.info("DISEASE GENE SUMMARY QUERY: " + query);
int dCount = 0;
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
ResultSet r = p.executeQuery();
while (r.next()) {
String diseaseId = r.getString("disease_id");
DiseaseGene d = new DiseaseGene();
d.setDiseaseId(diseaseId);
d.setDiseaseTerm(r.getString("disease_term"));
d.setDiseaseLocus(r.getString("disease_locus"));
//doc.setDiseaseAlts(Arrays.asList(r.getString("disease_alts").split("\\|")));
d.setDiseaseClasses(r.getString("disease_classes"));
d.setHumanCurated(r.getBoolean("human_curated"));
d.setMouseCurated(r.getBoolean("mod_curated"));
// <!--summary fields for faceting-->
d.setMgiPredicted(r.getBoolean("mod_predicted"));
d.setImpcPredicted(r.getBoolean("htpc_predicted"));
d.setInLocus(r.getBoolean("in_locus"));
// mouse gene model for the human disease
String mgiAcc = r.getString("model_gene_id");
if (loadedGenes.containsKey(mgiAcc)) {
Gene g = loadedGenes.get(mgiAcc);
d.setGene(g);
// doing this takes ca. 4h
// if (g.getDiseases() == null){
// g.setDiseases(new HashSet<Disease>());
// }
// g.getDiseases().add(d);
}
d.setHgncGeneId(r.getString("hgnc_gene_id"));
d.setHgncGeneSymbol(r.getString("hgnc_gene_symbol"));
// <!--model organism database (MGI) scores-->
d.setMaxMgiD2mScore(getDoubleDefaultZero(r, "max_mod_disease_to_model_perc_score"));
d.setMaxMgiM2dScore(getDoubleDefaultZero(r, "max_mod_model_to_disease_perc_score"));
// <!--IMPC scores-->
d.setMaxImpcD2mScore(getDoubleDefaultZero(r, "max_htpc_disease_to_model_perc_score"));
d.setMaxImpcM2dScore(getDoubleDefaultZero(r, "max_htpc_model_to_disease_perc_score"));
// <!--raw scores-->
d.setRawModScore(getDoubleDefaultZero(r, "raw_mod_score"));
d.setRawHtpcScore(getDoubleDefaultZero(r, "raw_htpc_score"));
d.setMgiPredictedKnownGene(r.getBoolean("mod_predicted_known_gene"));
d.setImpcPredictedKnownGene(r.getBoolean("htpc_predicted_known_gene"));
d.setMgiNovelPredictedInLocus(r.getBoolean("novel_mod_predicted_in_locus"));
d.setImpcNovelPredictedInLocus(r.getBoolean("novel_htpc_predicted_in_locus"));
// Disease human phenotype associations
Set<Hp> hps = new HashSet<>();
if ( diseaseIdPhenotypeMap.containsKey(diseaseId)) {
for (Hp hp : diseaseIdPhenotypeMap.get(diseaseId)) {
hps.add(hp);
}
}
if (hps.size() > 0) {
d.setHumanPhenotypes(hps);
}
dCount++;
diseaseGeneRepository.save(d);
//loadedDiseaseGenes.put(d.getDiseaseId(), d);
if (dCount % 5000 == 0) {
logger.info("Added {} DiseaseGene nodes", dCount);
}
}
logger.info("Added total of {} DiseaseGene nodes", dCount);
String job = "DiseaseGene nodes";
loadTime(begin, System.currentTimeMillis(), job);
}
}
public void loadDiseaseModels() throws SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT " +
" 'disease_model_association' AS type, " +
" mdgshq.disease_id, " +
" d.disease_term, " +
" d.disease_classes, " +
" mmgo.model_gene_id AS model_gene_id, " +
" mmgo.model_id, " +
" mdma.lit_model, " +
" mdma.disease_to_model_perc_score AS disease_to_model_perc_score, " +
" mdma.model_to_disease_perc_score AS model_to_disease_perc_score, " +
" mdma.raw_score, " +
" mdma.hp_matched_terms, " +
" mdma.mp_matched_terms, " +
" mdgshq.mod_predicted, " +
" mdgshq.htpc_predicted " +
"FROM mouse_disease_gene_summary_high_quality mdgshq " +
" JOIN mouse_model_gene_ortholog mmgo ON mdgshq.model_gene_id = mmgo.model_gene_id " +
" JOIN mouse_disease_model_association mdma ON mdgshq.disease_id = mdma.disease_id AND mmgo.model_id = mdma.model_id " +
" JOIN disease d ON d.disease_id = mdgshq.disease_id" ;
logger.info("DISEASE MODEL ASSOC QUERY: " + query);
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
ResultSet r = p.executeQuery();
int dmCount = 0;
while (r.next()) {
int modelId = r.getInt("model_id");
// only want IMPC related mouse models
if (loadedMouseModels.containsKey(modelId)) {
MouseModel mm = loadedMouseModels.get(modelId);
String diseaseId = r.getString("disease_id");
DiseaseModel d = new DiseaseModel();
d.setDiseaseId(diseaseId);
d.setDiseaseTerm(r.getString("disease_term"));
d.setDiseaseClasses(r.getString("disease_classes"));
d.setMouseModel(mm);
String mgiAcc = r.getString("model_gene_id");
if (loadedGenes.containsKey(mgiAcc)) {
d.setGene(loadedGenes.get(mgiAcc));
}
List<String> hpIds = Arrays.asList(r.getString("hp_matched_terms").split(","));
Set<Hp> hps = new HashSet<>();
for (String hpId : hpIds) {
if (loadedHps.containsKey(hpId)) {
Hp hp = loadedHps.get(hpId);
hps.add(hp);
}
}
if (hps.size() > 0) {
d.setHumanPhenotypes(hps);
}
List<String> mpIds = Arrays.asList(r.getString("mp_matched_terms").split(","));
Set<Mp> mps = new HashSet<>();
for (String mpId : mpIds) {
if (loadedMps.containsKey(mpId)) {
Mp mp = loadedMps.get(mpId);
mps.add(mp);
}
}
if (mps.size() > 0) {
d.setMousePhenotypes(mps);
}
d.setDiseaseToModelScore(getDoubleDefaultZero(r, "disease_to_model_perc_score"));
d.setModelToDiseaseScore(getDoubleDefaultZero(r, "model_to_disease_perc_score"));
// connects a DiseaseModel to allele
// allelicComposition: Nes<tm1b(KOMP)Wtsi>/Nes<tm1b(KOMP)Wtsi>
// allele symbol: Nes<tm1b(KOMP)Wtsi>
String allelicComposition = mm.getAllelicComposition();
String[] diploids = StringUtils.split(allelicComposition, "/");
String alleleSymbol = !diploids[0].equals("+") ? diploids[0] : diploids[1];
if (loadedAlleles.containsKey(alleleSymbol)){
d.setAllele(loadedAlleles.get(alleleSymbol));
}
diseaseModelRepository.save(d);
dmCount++;
if (dmCount % 5000 == 0) {
logger.info("Added {} DiseaseModel nodes", dmCount);
}
}
}
logger.info("Added total of {} DiseaseModel nodes", dmCount);
String job = "loadDiseaseModels";
loadTime(begin, System.currentTimeMillis(), job);
}
}
public void loadHumanOrtholog() throws IOException {
long begin = System.currentTimeMillis();
Map<String, HumanGeneSymbol> loadedHumanSymbolHGS = new HashMap<>();
BufferedReader in = new BufferedReader(new FileReader(new File(pathToHuman2mouseFilename)));
int symcount = 0;
String line = in.readLine();
while (line != null) {
//System.out.println(line);
String[] array = line.split("\t");
if (! array[0].isEmpty() && ! array[4].isEmpty()) {
String humanSym = array[0];
String mouseSym = array[4];
// only want IMPC gene symbols
if (loadedMouseSymbolGenes.containsKey(mouseSym)) {
Gene gene = loadedMouseSymbolGenes.get(mouseSym);
HumanGeneSymbol hgs = new HumanGeneSymbol();
if (! loadedHumanSymbolHGS.containsKey(humanSym)) {
hgs.setHumanGeneSymbol(humanSym);
loadedHumanSymbolHGS.put(humanSym, hgs);
symcount++;
}
else {
hgs = loadedHumanSymbolHGS.get(humanSym);
}
if (hgs.getGenes() == null){
hgs.setGenes(new HashSet<Gene>());
}
// one human symbol can be associated with multiple mouse symbols
// hgs to gene relationship
hgs.getGenes().add(gene);
if (gene.getHumanGeneSymbols() == null) {
gene.setHumanGeneSymbols(new HashSet<HumanGeneSymbol>());
}
gene.getHumanGeneSymbols().add(hgs);
//humanGeneSymbolRepository.save(hgs);
geneRepository.save(gene);
if (symcount % 5000 == 0) {
logger.info("Loaded {} HumanGeneSymbol nodes", symcount);
}
}
}
line = in.readLine();
}
logger.info("Loaded total of {} HumanGeneSymbol nodes", symcount);
String job = "HumanGeneSymbol nodes";
loadTime(begin, System.currentTimeMillis(), job);
}
public void loadTime(long begin, long end, String job){
long elapsedTimeMillis = end - begin;
int seconds = (int) (elapsedTimeMillis / 1000) % 60 ;
int minutes = (int) ((elapsedTimeMillis / (1000*60)) % 60);
int hours = (int) ((elapsedTimeMillis / (1000*60*60)) % 24);
logger.info("Time taken to load {}: {}hr:{}min:{}sec", job, hours, minutes, seconds);
}
private Double getDoubleDefaultZero(ResultSet r, String field) throws SQLException {
Double v = r.getDouble(field);
return r.wasNull() ? 0.0 : v;
}
}
|
web/src/main/java/uk/ac/ebi/phenotype/repository/Loader.java
|
package uk.ac.ebi.phenotype.repository;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.mousephenotype.cda.annotations.ComponentScanNonParticipant;
import org.mousephenotype.cda.owl.OntologyParser;
import org.mousephenotype.cda.owl.OntologyParserFactory;
import org.mousephenotype.cda.owl.OntologyTermDTO;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
* Created by ckchen on 17/03/2017.
*/
@Component
@ComponentScanNonParticipant
public class Loader implements CommandLineRunner {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
@Qualifier("komp2DataSource")
DataSource komp2DataSource;
@Autowired
@Qualifier("phenodigmDataSource")
DataSource phenodigmDataSource;
// @NotNull
// @Value("${neo4jDbPath}")
// private String neo4jDbPath;
@NotNull
@Value("${allele2File}")
private String pathToAlleleFile;
@NotNull
@Value("${human2mouseFilename}")
private String pathToHuman2mouseFilename;
// @NotNull
// @Value("${mpListPath}")
// private String mpListPath;
@NotNull
@Value("${owlpath}")
protected String owlpath;
@Autowired
GeneRepository geneRepository;
@Autowired
AlleleRepository alleleRepository;
@Autowired
EnsemblGeneIdRepository ensemblGeneIdRepository;
@Autowired
MarkerSynonymRepository markerSynonymRepository;
@Autowired
HumanGeneSymbolRepository humanGeneSymbolRepository;
@Autowired
MpRepository mpRepository;
@Autowired
HpRepository hpRepository;
@Autowired
OntoSynonymRepository ontoSynonymRepository;
@Autowired
DiseaseGeneRepository diseaseGeneRepository;
@Autowired
DiseaseModelRepository diseaseModelRepository;
@Autowired
MouseModelRepository mouseModelRepository;
OntologyParserFactory ontologyParserFactory;
Map<String, Allele> loadedAlleles = new HashMap<>();
Map<String, Gene> loadedGenes = new HashMap<>();
Map<String, Gene> loadedMouseSymbolGenes = new HashMap<>();
Map<String, Mp> loadedMps = new HashMap<>();
Map<String, Hp> loadedHps = new HashMap<>();
// Map<String, DiseaseGene> loadedDiseaseGenes = new HashMap<>();
Map<Integer, MouseModel> loadedMouseModels = new HashMap<>();
Map<String, EnsemblGeneId> ensGidEnsemblGeneIdMap = new HashMap<>();
Map<Integer, Set<Mp>> mouseModelIdMpMap = new HashMap<>();
Map<String, String> hpIdTermMap = new HashMap<>();
Map<String, Set<Hp>> bestMpIdHpMap = new HashMap<>();
Map<String, Set<Hp>> diseaseIdPhenotypeMap = new HashMap<>();
private OntologyParser mpHpParser;
private OntologyParser mpParser;
private static final int LEVELS_FOR_NARROW_SYNONYMS = 2;
public Loader() {}
@Override
public void run(String... strings) throws Exception {
ontologyParserFactory = new OntologyParserFactory(komp2DataSource, owlpath);
// NOTE that deleting repositories takes lots of memory
// would be way faster to just remove the db directory
logger.info("Start deleting all repositories ...");
//FileUtils.deleteDirectory(new File(neo4jDbPath));
geneRepository.deleteAll();
alleleRepository.deleteAll();
ensemblGeneIdRepository.deleteAll();
markerSynonymRepository.deleteAll();
ontoSynonymRepository.deleteAll();
humanGeneSymbolRepository.deleteAll();
mpRepository.deleteAll();
hpRepository.deleteAll();
diseaseGeneRepository.deleteAll();
diseaseModelRepository.deleteAll();
mouseModelRepository.deleteAll();
logger.info("Done deleting all repositories");
Connection komp2Conn = komp2DataSource.getConnection();
Connection diseaseConn = phenodigmDataSource.getConnection();
//----------- STEP 1 -----------//
// loading Gene, Allele, EnsemblGeneId, MarkerSynonym, human orthologs
// based on Peter's allele2 flatfile
loadGenes();
//----------- STEP 2 -----------//
populateHpIdTermMap(); // STEP 2.1
populateBestMpIdHpMap(); // STEP 2.2
extendLoadedHpAndConnectHp2Mp(); // STEP 2.4
loadMousePhenotypes(); // STEP 2.4
//----------- STEP 3 -----------//
populateMouseModelIdMpMap(); // run this before loadMouseModel()
loadMouseModels();
//----------- STEP 4 -----------//
// load disease and Gene, Hp, Mp relationships
populateDiseaseIdPhenotypeMap();
//loadDiseaseGenes();
//----------- STEP 5 -----------//
loadDiseaseModels();
}
public void loadGenes() throws IOException, SolrServerException {
long begin = System.currentTimeMillis();
final Map<String, String> ES_CELL_STATUS_MAPPINGS = new HashMap<>();
ES_CELL_STATUS_MAPPINGS.put("No ES Cell Production", "Not Assigned for ES Cell Production");
ES_CELL_STATUS_MAPPINGS.put("ES Cell Production in Progress", "Assigned for ES Cell Production");
ES_CELL_STATUS_MAPPINGS.put("ES Cell Targeting Confirmed", "ES Cells Produced");
final Map<String, String> MOUSE_STATUS_MAPPINGS = new HashMap<>();
MOUSE_STATUS_MAPPINGS.put("Chimeras obtained", "Assigned for Mouse Production and Phenotyping");
MOUSE_STATUS_MAPPINGS.put("Micro-injection in progress", "Assigned for Mouse Production and Phenotyping");
MOUSE_STATUS_MAPPINGS.put("Cre Excision Started", "Mice Produced");
MOUSE_STATUS_MAPPINGS.put("Rederivation Complete", "Mice Produced");
MOUSE_STATUS_MAPPINGS.put("Rederivation Started", "Mice Produced");
MOUSE_STATUS_MAPPINGS.put("Genotype confirmed", "Mice Produced");
MOUSE_STATUS_MAPPINGS.put("Cre Excision Complete", "Mice Produced");
MOUSE_STATUS_MAPPINGS.put("Phenotype Attempt Registered", "Mice Produced");
Map<String, Integer> columns = new HashMap<>();
BufferedReader in = new BufferedReader(new FileReader(new File(pathToAlleleFile)));
BufferedReader in2 = new BufferedReader(new FileReader(new File(pathToAlleleFile)));
String[] header = in.readLine().split("\t");
for (int i = 0; i < header.length; i++){
columns.put(header[i], i);
}
int geneCount = 0;
int alleleCount = 0;
String line = in.readLine();
while (line != null) {
// System.out.println(line);
String[] array = line.split("\t", -1);
if (array.length == 1) {
continue;
}
if (array[columns.get("allele_design_project")].equals("IMPC")
&& ! array[columns.get("latest_project_status")].isEmpty()
&& array[columns.get("type")].equals("Gene")
&& ! array[columns.get("marker_type")].isEmpty()) {
String mgiAcc = array[columns.get("mgi_accession_id")];
Gene gene = new Gene();
gene.setMgiAccessionId(mgiAcc);
String thisSymbol = null;
if (! array[columns.get("marker_symbol")].isEmpty()) {
thisSymbol = array[columns.get("marker_symbol")];
gene.setMarkerSymbol(thisSymbol);
}
if (! array[columns.get("feature_type")].isEmpty()) {
gene.setMarkerType(array[columns.get("feature_type")]);
}
if (! array[columns.get("marker_name")].isEmpty()) {
gene.setMarkerName(array[columns.get("marker_name")]);
}
if (! array[columns.get("synonym")].isEmpty()) {
List<String> syms = Arrays.asList(StringUtils.split(array[columns.get("synonym")], "|"));
Set<MarkerSynonym> mss = new HashSet<>();
for (String sym : syms) {
MarkerSynonym ms = new MarkerSynonym();
ms.setMarkerSynonym(sym);
// ms rel to gene
ms.setGene(gene);
mss.add(ms);
}
gene.setMarkerSynonyms(mss);
}
if (! array[columns.get("feature_chromosome")].isEmpty()) {
gene.setChrId(array[columns.get("feature_chromosome")]);
gene.setChrStart(array[columns.get("feature_coord_start")]);
gene.setChrEnd(array[columns.get("feature_coord_end")]);
gene.setChrStrand(array[columns.get("feature_strand")]);
}
if (! array[columns.get("gene_model_ids")].isEmpty()) {
Set<EnsemblGeneId> ensgs = new HashSet<>();
String[] ids = StringUtils.split(array[columns.get("gene_model_ids")], "|");
for (int j = 0; j < ids.length; j++) {
String thisId = ids[j];
if (thisId.startsWith("ensembl_ids") || thisId.startsWith("\"ensembl_ids")) {
String[] vals = StringUtils.split(thisId, ":");
if (vals.length == 2) {
String ensgId = vals[1];
//System.out.println("Found " + ensgId);
EnsemblGeneId ensg = new EnsemblGeneId();
if (! ensGidEnsemblGeneIdMap.containsKey(ensgId)) {
ensg.setEnsemblGeneId(ensgId);
// ensg rel to gene
ensg.setGene(gene);
ensGidEnsemblGeneIdMap.put(ensgId, ensg);
} else {
ensg = ensGidEnsemblGeneIdMap.get(ensgId);
}
ensgs.add(ensg);
}
}
}
if (ensgs.size() > 0){
gene.setEnsemblGeneIds(ensgs);
}
}
geneRepository.save(gene);
loadedGenes.put(mgiAcc, gene);
loadedMouseSymbolGenes.put(thisSymbol, gene);
geneCount++;
if (geneCount % 5000 == 0) {
logger.info("Loaded {} Gene nodes", geneCount);
}
}
line = in.readLine();
}
logger.info("Loaded total of {} Gene nodes", geneCount);
String line2 = in2.readLine();
while (line2 != null) {
//System.out.println(line);
String[] array = line2.split("\t", -1);
if (array.length == 1) {
continue;
}
String mgiAcc = array[columns.get("mgi_accession_id")];
if (array[columns.get("allele_design_project")].equals("IMPC")
&& array[columns.get("type")].equals("Allele")
&& loadedGenes.containsKey(mgiAcc)
&& ! array[columns.get("allele_mgi_accession_id")].isEmpty()) {
Gene gene = loadedGenes.get(mgiAcc);
String alleleAcc = array[columns.get("allele_mgi_accession_id")];
Allele allele = new Allele();
allele.setAlleleMgiAccessionId(alleleAcc);
// allele rel to gene
allele.setGene(gene);
if (!array[columns.get("allele_symbol")].isEmpty()) {
allele.setAlleleSymbol(array[columns.get("allele_symbol")]);
}
if (!array[columns.get("allele_description")].isEmpty()) {
allele.setAlleleDescription(array[columns.get("allele_description")]);
}
if (!array[columns.get("mutation_type")].isEmpty()) {
allele.setMutationType(array[columns.get("mutation_type")]);
}
if (!array[columns.get("es_cell_status")].isEmpty()) {
allele.setEsCellStatus(ES_CELL_STATUS_MAPPINGS.get(array[columns.get("es_cell_status")]));
}
if (!array[columns.get("mouse_status")].isEmpty()) {
allele.setMouseStatus(MOUSE_STATUS_MAPPINGS.get(array[columns.get("mouse_status")]));
}
if (!array[columns.get("phenotype_status")].isEmpty()) {
allele.setPhenotypeStatus(array[columns.get("phenotype_status")]);
}
if (gene.getAlleles() == null){
gene.setAlleles(new HashSet<Allele>());
}
gene.getAlleles().add(allele);
alleleRepository.save(allele);
loadedAlleles.put(allele.getAlleleSymbol(), allele);
alleleCount++;
if (alleleCount % 5000 == 0){
logger.info("Loaded {} Allele nodes", alleleCount);
}
}
line2 = in2.readLine();
}
logger.info("Loaded total of {} Allele nodes", alleleCount);
String job = "Gene, Allele, MarkerSynonym and EnsemblGeneId nodes";
loadTime(begin, System.currentTimeMillis(), job);
// based on MGI report HMD_HumanPhenotype.rpt
// Mouse/Human Orthology with Phenotype Annotations (tab-delimited)
loadHumanOrtholog();
}
public void loadMousePhenotypes() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, SQLException, URISyntaxException, SolrServerException {
long begin = System.currentTimeMillis();
mpParser = ontologyParserFactory.getMpParser();
logger.info("Loaded mp parser");
// mpHpParser = ontologyParserFactory.getMpHpParser();
// logger.info("Loaded mp hp parser");
int mpCount = 0;
for (String mpId: mpParser.getTermsInSlim()) {
OntologyTermDTO mpDTO = mpParser.getOntologyTerm(mpId);
String termId = mpDTO.getAccessionId();
Mp mp = mpRepository.findByMpId(termId);
if (mp == null){
mp = new Mp();
mp.setMpId(termId);
}
if (mp.getMpTerm() == null) {
mp.setMpTerm(mpDTO.getName());
}
if (mp.getMpDefinition() == null) {
mp.setMpDefinition(mpDTO.getDefinition());
}
if (mp.getOntoSynonyms() == null) {
for (String mpsym : mpDTO.getSynonyms()) {
OntoSynonym ms = new OntoSynonym();
ms.setOntoSynonym(mpsym);
ms.setMousePhenotype(mp);
//ontoSynonymRepository.save(ms);
if (mp.getOntoSynonyms() == null) {
mp.setOntoSynonyms(new HashSet<OntoSynonym>());
}
mp.getOntoSynonyms().add(ms);
}
}
// PARENT
if (mp.getMpParentIds() == null) {
if ( mpDTO.getParentIds() != null) {
Set<Mp> parentMps = new HashSet<>();
for (String parId : mpDTO.getParentIds()) {
Mp thisMp = mpRepository.findByMpId(parId);
if (thisMp == null) {
thisMp = new Mp();
}
thisMp.setMpId(parId);
parentMps.add(thisMp);
}
if (parentMps.size() > 0) {
mp.setMpParentIds(parentMps);
}
}
}
// MARK MP WHICH IS TOP LEVEL
if (mpDTO.getTopLevelIds() == null || mpDTO.getTopLevelIds().size() == 0){
// add self as top level
mp.setTopLevelStatus(true);
}
// BEST MP to HP mapping
Set<Hp> hps = new HashSet<>();
if (bestMpIdHpMap.containsKey(termId)){
for(Hp hp : bestMpIdHpMap.get(termId)) {
hps.add(hp);
}
if (hps.size() > 0) {
mp.setHumanPhenotypes(hps);
}
}
// add mp-hp mapping using Monarch's mp-hp hybrid ontology: gets the narrow synonym
// TO DO
mpRepository.save(mp);
loadedMps.put(mp.getMpId(), mp);
mpCount++;
if (mpCount % 1000 == 0) {
logger.info("Added {} mp nodes", mpCount);
}
}
logger.info("Added total of {} mp nodes", mpCount);
String job = "loadMousePhenotypes";
loadTime(begin, System.currentTimeMillis(), job);
}
public void populateBestMpIdHpMap() throws SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT hp_id, hp_term, mp_id FROM best_impc_mp_hp_mapping ";
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query)) {
ResultSet r = p.executeQuery();
while (r.next()) {
String mpId = r.getString("mp_id");
String hpId = r.getString("hp_id");
String hpTerm = r.getString("hp_term");
if (! loadedHps.containsKey(hpId)){
Hp hp = new Hp();
hp.setHpId(hpId);
hp.setHpTerm(hpTerm);
loadedHps.put(hpId, hp);
}
if (! bestMpIdHpMap.containsKey(mpId)){
bestMpIdHpMap.put(mpId, new HashSet<Hp>());
}
bestMpIdHpMap.get(mpId).add(loadedHps.get(hpId));
}
}
String job = "populateBestMpIdHpMap";
loadTime(begin, System.currentTimeMillis(), job);
}
public void extendLoadedHpAndConnectHp2Mp() throws SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT hp_id, hp_term, mp_id FROM best_impc_hp_mp_mapping ";
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query)) {
ResultSet r = p.executeQuery();
while (r.next()) {
String mpId = r.getString("mp_id");
String hpId = r.getString("hp_id");
String hpTerm = r.getString("hp_term");
// extend loadedHps
Hp hp = new Hp();
if (! loadedHps.containsKey(hpId)) {
hp.setHpId(hpId);
hp.setHpTerm(hpTerm);
loadedHps.put(hpId, hp);
}
else {
hp = loadedHps.get(hpId);
}
if (loadedMps.containsKey(mpId)){
Mp mp = loadedMps.get(mpId);
if (hp.getMousePhenotypes() == null){
hp.setMousePhenotypes(new HashSet<Mp>());
}
hp.getMousePhenotypes().add(mp);
}
hpRepository.save(hp);
}
}
String job = "extendLoadedHpAndConnectHp2Mp";
loadTime(begin, System.currentTimeMillis(), job);
}
public void populateHpIdTermMap() throws SolrServerException, IOException, SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT DISTINCT hp_id, term FROM hp ";
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query)) {
ResultSet r = p.executeQuery();
while (r.next()) {
String hpId = r.getString("hp_id");
String hpTerm = r.getString("term");
// human Phenotype id to term mapping
hpIdTermMap.put(hpId, hpTerm);
}
}
String job = "populateHpIdTermMap";
loadTime(begin, System.currentTimeMillis(), job);
}
public void populateMouseModelIdMpMap() throws SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT mm.model_id, mmm.mp_id FROM mouse_model_mp mmm, mouse_model mm WHERE mmm.model_id=mm.model_id AND mm.source LIKE '%IMPC%'";
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
ResultSet r = p.executeQuery();
while (r.next()) {
Integer id = r.getInt("model_id");
if (!mouseModelIdMpMap.containsKey(id)) {
mouseModelIdMpMap.put(id, new HashSet<Mp>());
}
String mpId = r.getString("mp_id");
// only want MPs that IMPC knows about
if (loadedMps.containsKey(mpId)){
mouseModelIdMpMap.get(id).add(loadedMps.get(mpId));
}
}
String job = "populateMouseModelIdMpMap";
loadTime(begin, System.currentTimeMillis(), job);
}
}
public void loadMouseModels() throws SQLException {
// only MouseModels from IMPC
long begin = System.currentTimeMillis();
String query = "SELECT " +
" 'mouse_model' AS type, " +
" mm.model_id AS model_id, " +
" mgo.model_gene_id AS model_gene_id, " +
" mgo.model_gene_symbol AS model_gene_symbol, " +
" mm.source, " +
" mm.allelic_composition, " +
" mm.genetic_background, " +
" mm.allele_ids, " +
" mm.hom_het " +
"FROM mouse_model mm " +
" JOIN mouse_model_gene_ortholog mmgo ON mmgo.model_id = mm.model_id " +
" JOIN mouse_gene_ortholog mgo ON mgo.model_gene_id = mmgo.model_gene_id " +
"WHERE mm.source = 'IMPC'";
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
int mmCount = 0;
ResultSet r = p.executeQuery();
while (r.next()) {
int modelId = r.getInt("model_id");
MouseModel mm = new MouseModel();
mm.setModelId(modelId);
String mgiAcc = r.getString("model_gene_id");
// only want Genes that IMPC knows about
if (loadedGenes.containsKey(mgiAcc)) {
mm.setGene(loadedGenes.get(mgiAcc));
}
mm.setAllelicComposition(r.getString("allelic_composition"));
mm.setGeneticBackground(r.getString("genetic_background"));
mm.setHomHet(r.getString("hom_het"));
// mouse Phenotype associated with this mouseModel
if (mouseModelIdMpMap.containsKey(modelId)) {
for (Mp mp : mouseModelIdMpMap.get(modelId)) {
if (mm.getMousePhenotypes() == null) {
mm.setMousePhenotypes(new HashSet<Mp>());
}
mm.getMousePhenotypes().add(mp);
}
}
mmCount++;
mouseModelRepository.save(mm);
loadedMouseModels.put(mm.getModelId(), mm);
if (mmCount % 1000 == 0) {
logger.info("Added {} MouseModel nodes", mmCount);
}
}
logger.info("Added total of {} MouseModel nodes", mmCount);
String job = "MouseeModel nodes";
loadTime(begin, System.currentTimeMillis(), job);
}
}
public void populateDiseaseIdPhenotypeMap() throws SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT DISTINCT dh.disease_id, dh.hp_id FROM disease d " +
"LEFT JOIN disease_hp dh ON d.disease_id=dh.disease_id " +
"LEFT JOIN mouse_disease_summary mds ON mds.disease_id=d.disease_id";
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query)) {
ResultSet r = p.executeQuery();
while (r.next()) {
String diseaseId = r.getString("disease_id");
if (! diseaseIdPhenotypeMap.containsKey(diseaseId)) {
diseaseIdPhenotypeMap.put(diseaseId, new HashSet<Hp>());
}
String hpId = r.getString("hp_id");
if (loadedHps.containsKey(hpId)){
diseaseIdPhenotypeMap.get(diseaseId).add(loadedHps.get(hpId));
}
else {
Hp hp = new Hp();
hp.setHpId(hpId);
hp.setHpTerm(hpIdTermMap.get(hpId));
loadedHps.put(hpId, hp);
diseaseIdPhenotypeMap.get(diseaseId).add(hp);
}
}
String job = "populateDiseaseIdPhenotypeMap";
loadTime(begin, System.currentTimeMillis(), job);
}
}
public void loadDiseaseGenes() throws SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT" +
" 'disease_gene_summary' AS type, " +
" d.disease_id, " +
" disease_term, " +
" disease_alts, " +
" disease_locus, " +
" disease_classes AS disease_classes, " +
" mgo.model_gene_id AS model_gene_id, " +
" mgo.model_gene_symbol AS model_gene_symbol, " +
" mgo.hgnc_id AS hgnc_gene_id, " +
" mgo.hgnc_gene_symbol, " +
" human_curated, " +
" mod_curated AS mod_curated, " +
" in_locus, " +
" max_mod_disease_to_model_perc_score AS max_mod_disease_to_model_perc_score, " +
" max_mod_model_to_disease_perc_score AS max_mod_model_to_disease_perc_score, " +
" max_htpc_disease_to_model_perc_score AS max_htpc_disease_to_model_perc_score, " +
" max_htpc_model_to_disease_perc_score AS max_htpc_model_to_disease_perc_score, " +
" mod_raw_score AS raw_mod_score, " +
" htpc_raw_score AS raw_htpc_score, " +
" mod_predicted AS mod_predicted, " +
" mod_predicted_known_gene AS mod_predicted_known_gene, " +
" novel_mod_predicted_in_locus AS novel_mod_predicted_in_locus, " +
" htpc_predicted AS htpc_predicted, " +
" htpc_predicted_known_gene AS htpc_predicted_known_gene, " +
" novel_htpc_predicted_in_locus AS novel_htpc_predicted_in_locus " +
"FROM " +
" mouse_disease_gene_summary_high_quality mdgshq " +
" LEFT JOIN disease d ON d.disease_id = mdgshq.disease_id" +
" JOIN (SELECT DISTINCT model_gene_id, model_gene_symbol, hgnc_id, hgnc_gene_symbol FROM mouse_gene_ortholog) mgo ON mgo.model_gene_id = mdgshq.model_gene_id " +
" WHERE d.disease_id IS NOT NULL";
logger.info("DISEASE GENE SUMMARY QUERY: " + query);
int dCount = 0;
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
ResultSet r = p.executeQuery();
while (r.next()) {
String diseaseId = r.getString("disease_id");
DiseaseGene d = new DiseaseGene();
d.setDiseaseId(diseaseId);
d.setDiseaseTerm(r.getString("disease_term"));
d.setDiseaseLocus(r.getString("disease_locus"));
//doc.setDiseaseAlts(Arrays.asList(r.getString("disease_alts").split("\\|")));
d.setDiseaseClasses(r.getString("disease_classes"));
d.setHumanCurated(r.getBoolean("human_curated"));
d.setMouseCurated(r.getBoolean("mod_curated"));
// <!--summary fields for faceting-->
d.setMgiPredicted(r.getBoolean("mod_predicted"));
d.setImpcPredicted(r.getBoolean("htpc_predicted"));
d.setInLocus(r.getBoolean("in_locus"));
// mouse gene model for the human disease
String mgiAcc = r.getString("model_gene_id");
if (loadedGenes.containsKey(mgiAcc)) {
Gene g = loadedGenes.get(mgiAcc);
d.setGene(g);
// doing this takes ca. 4h
// if (g.getDiseases() == null){
// g.setDiseases(new HashSet<Disease>());
// }
// g.getDiseases().add(d);
}
d.setHgncGeneId(r.getString("hgnc_gene_id"));
d.setHgncGeneSymbol(r.getString("hgnc_gene_symbol"));
// <!--model organism database (MGI) scores-->
d.setMaxMgiD2mScore(getDoubleDefaultZero(r, "max_mod_disease_to_model_perc_score"));
d.setMaxMgiM2dScore(getDoubleDefaultZero(r, "max_mod_model_to_disease_perc_score"));
// <!--IMPC scores-->
d.setMaxImpcD2mScore(getDoubleDefaultZero(r, "max_htpc_disease_to_model_perc_score"));
d.setMaxImpcM2dScore(getDoubleDefaultZero(r, "max_htpc_model_to_disease_perc_score"));
// <!--raw scores-->
d.setRawModScore(getDoubleDefaultZero(r, "raw_mod_score"));
d.setRawHtpcScore(getDoubleDefaultZero(r, "raw_htpc_score"));
d.setMgiPredictedKnownGene(r.getBoolean("mod_predicted_known_gene"));
d.setImpcPredictedKnownGene(r.getBoolean("htpc_predicted_known_gene"));
d.setMgiNovelPredictedInLocus(r.getBoolean("novel_mod_predicted_in_locus"));
d.setImpcNovelPredictedInLocus(r.getBoolean("novel_htpc_predicted_in_locus"));
// Disease human phenotype associations
Set<Hp> hps = new HashSet<>();
if ( diseaseIdPhenotypeMap.containsKey(diseaseId)) {
for (Hp hp : diseaseIdPhenotypeMap.get(diseaseId)) {
hps.add(hp);
}
}
if (hps.size() > 0) {
d.setHumanPhenotypes(hps);
}
dCount++;
diseaseGeneRepository.save(d);
//loadedDiseaseGenes.put(d.getDiseaseId(), d);
if (dCount % 5000 == 0) {
logger.info("Added {} DiseaseGene nodes", dCount);
}
}
logger.info("Added total of {} DiseaseGene nodes", dCount);
String job = "DiseaseGene nodes";
loadTime(begin, System.currentTimeMillis(), job);
}
}
public void loadDiseaseModels() throws SQLException {
long begin = System.currentTimeMillis();
String query = "SELECT " +
" 'disease_model_association' AS type, " +
" mdgshq.disease_id, " +
" d.disease_term, " +
" d.disease_classes, " +
" mmgo.model_gene_id AS model_gene_id, " +
" mmgo.model_id, " +
" mdma.lit_model, " +
" mdma.disease_to_model_perc_score AS disease_to_model_perc_score, " +
" mdma.model_to_disease_perc_score AS model_to_disease_perc_score, " +
" mdma.raw_score, " +
" mdma.hp_matched_terms, " +
" mdma.mp_matched_terms, " +
" mdgshq.mod_predicted, " +
" mdgshq.htpc_predicted " +
"FROM mouse_disease_gene_summary_high_quality mdgshq " +
" JOIN mouse_model_gene_ortholog mmgo ON mdgshq.model_gene_id = mmgo.model_gene_id " +
" JOIN mouse_disease_model_association mdma ON mdgshq.disease_id = mdma.disease_id AND mmgo.model_id = mdma.model_id " +
" JOIN disease d ON d.disease_id = mdgshq.disease_id" ;
logger.info("DISEASE MODEL ASSOC QUERY: " + query);
try (Connection connection = phenodigmDataSource.getConnection();
PreparedStatement p = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
ResultSet r = p.executeQuery();
int dmCount = 0;
while (r.next()) {
int modelId = r.getInt("model_id");
// only want IMPC related mouse models
if (loadedMouseModels.containsKey(modelId)) {
MouseModel mm = loadedMouseModels.get(modelId);
String diseaseId = r.getString("disease_id");
DiseaseModel d = new DiseaseModel();
d.setDiseaseId(diseaseId);
d.setDiseaseTerm(r.getString("disease_term"));
d.setDiseaseClasses(r.getString("disease_classes"));
d.setMouseModel(mm);
String mgiAcc = r.getString("model_gene_id");
if (loadedGenes.containsKey(mgiAcc)) {
d.setGene(loadedGenes.get(mgiAcc));
}
List<String> hpIds = Arrays.asList(r.getString("hp_matched_terms").split(","));
Set<Hp> hps = new HashSet<>();
for (String hpId : hpIds) {
if (loadedHps.containsKey(hpId)) {
Hp hp = loadedHps.get(hpId);
hps.add(hp);
}
}
if (hps.size() > 0) {
d.setHumanPhenotypes(hps);
}
List<String> mpIds = Arrays.asList(r.getString("mp_matched_terms").split(","));
Set<Mp> mps = new HashSet<>();
for (String mpId : mpIds) {
if (loadedMps.containsKey(mpId)) {
Mp mp = loadedMps.get(mpId);
mps.add(mp);
}
}
if (mps.size() > 0) {
d.setMousePhenotypes(mps);
}
d.setDiseaseToModelScore(getDoubleDefaultZero(r, "disease_to_model_perc_score"));
d.setModelToDiseaseScore(getDoubleDefaultZero(r, "model_to_disease_perc_score"));
// connects a DiseaseModel to allele
// allelicComposition: Nes<tm1b(KOMP)Wtsi>/Nes<tm1b(KOMP)Wtsi>
// allele symbol: Nes<tm1b(KOMP)Wtsi>
String allelicComposition = mm.getAllelicComposition();
String[] diploids = StringUtils.split(allelicComposition, "/");
String alleleSymbol = !diploids[0].equals("+") ? diploids[0] : diploids[1];
if (loadedAlleles.containsKey(alleleSymbol)){
d.setAllele(loadedAlleles.get(alleleSymbol));
}
diseaseModelRepository.save(d);
dmCount++;
if (dmCount % 5000 == 0) {
logger.info("Added {} DiseaseModel nodes", dmCount);
}
}
}
logger.info("Added total of {} DiseaseModel nodes", dmCount);
String job = "loadDiseaseModels";
loadTime(begin, System.currentTimeMillis(), job);
}
}
public void loadHumanOrtholog() throws IOException {
long begin = System.currentTimeMillis();
Map<String, HumanGeneSymbol> loadedHumanSymbolHGS = new HashMap<>();
BufferedReader in = new BufferedReader(new FileReader(new File(pathToHuman2mouseFilename)));
int symcount = 0;
String line = in.readLine();
while (line != null) {
//System.out.println(line);
String[] array = line.split("\t");
if (! array[0].isEmpty() && ! array[4].isEmpty()) {
String humanSym = array[0];
String mouseSym = array[4];
// only want IMPC gene symbols
if (loadedMouseSymbolGenes.containsKey(mouseSym)) {
Gene gene = loadedMouseSymbolGenes.get(mouseSym);
HumanGeneSymbol hgs = new HumanGeneSymbol();
if (! loadedHumanSymbolHGS.containsKey(humanSym)) {
hgs.setHumanGeneSymbol(humanSym);
loadedHumanSymbolHGS.put(humanSym, hgs);
symcount++;
}
else {
hgs = loadedHumanSymbolHGS.get(humanSym);
}
if (hgs.getGenes() == null){
hgs.setGenes(new HashSet<Gene>());
}
// one human symbol can be associated with multiple mouse symbols
// hgs to gene relationship
hgs.getGenes().add(gene);
if (gene.getHumanGeneSymbols() == null) {
gene.setHumanGeneSymbols(new HashSet<HumanGeneSymbol>());
}
gene.getHumanGeneSymbols().add(hgs);
//humanGeneSymbolRepository.save(hgs);
geneRepository.save(gene);
if (symcount % 5000 == 0) {
logger.info("Loaded {} HumanGeneSymbol nodes", symcount);
}
}
}
line = in.readLine();
}
logger.info("Loaded total of {} HumanGeneSymbol nodes", symcount);
String job = "HumanGeneSymbol nodes";
loadTime(begin, System.currentTimeMillis(), job);
}
public void loadTime(long begin, long end, String job){
long elapsedTimeMillis = end - begin;
int seconds = (int) (elapsedTimeMillis / 1000) % 60 ;
int minutes = (int) ((elapsedTimeMillis / (1000*60)) % 60);
int hours = (int) ((elapsedTimeMillis / (1000*60*60)) % 24);
logger.info("Time taken to load {}: {}hr:{}min:{}sec", job, hours, minutes, seconds);
}
private Double getDoubleDefaultZero(ResultSet r, String field) throws SQLException {
Double v = r.getDouble(field);
return r.wasNull() ? 0.0 : v;
}
}
|
updated loader comment
|
web/src/main/java/uk/ac/ebi/phenotype/repository/Loader.java
|
updated loader comment
|
<ide><path>eb/src/main/java/uk/ac/ebi/phenotype/repository/Loader.java
<ide> //----------- STEP 2 -----------//
<ide> populateHpIdTermMap(); // STEP 2.1
<ide> populateBestMpIdHpMap(); // STEP 2.2
<del> extendLoadedHpAndConnectHp2Mp(); // STEP 2.4
<add> extendLoadedHpAndConnectHp2Mp(); // STEP 2.3
<ide> loadMousePhenotypes(); // STEP 2.4
<ide>
<ide> //----------- STEP 3 -----------//
|
|
Java
|
apache-2.0
|
424aa9e95ac80a6bb208ed3f471d99251dbf3e52
| 0 |
MatthewTamlin/Mixtape
|
/*
* Copyright 2017 Matthew Tamlin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.matthewtamlin.mixtape.example.activities;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.matthewtamlin.mixtape.example.R;
import com.matthewtamlin.mixtape.example.data.Mp3Album;
import com.matthewtamlin.mixtape.example.data.Mp3AlbumDataSource;
import com.matthewtamlin.mixtape.library.base_mvp.BaseDataSource;
import com.matthewtamlin.mixtape.library.caching.LibraryItemCache;
import com.matthewtamlin.mixtape.library.caching.LruLibraryItemCache;
import com.matthewtamlin.mixtape.library.data.DisplayableDefaults;
import com.matthewtamlin.mixtape.library.data.ImmutableDisplayableDefaults;
import com.matthewtamlin.mixtape.library.data.LibraryItem;
import com.matthewtamlin.mixtape.library.data.LibraryReadException;
import com.matthewtamlin.mixtape.library.databinders.ArtworkBinder;
import com.matthewtamlin.mixtape.library.databinders.SubtitleBinder;
import com.matthewtamlin.mixtape.library.databinders.TitleBinder;
import com.matthewtamlin.mixtape.library.mixtape_body.BodyContract;
import com.matthewtamlin.mixtape.library.mixtape_body.GridBody;
import com.matthewtamlin.mixtape.library.mixtape_body.RecyclerViewBodyPresenter;
import com.matthewtamlin.mixtape.library.mixtape_coordinator.CoordinatedMixtapeContainer;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class AlbumsActivity extends AppCompatActivity {
private GridBody body;
private CoordinatedMixtapeContainer rootView;
private Mp3AlbumDataSource dataSource;
private RecyclerViewBodyPresenter<Mp3Album, Mp3AlbumDataSource> presenter;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Albums");
setupView();
setupDataSource();
setupPresenter();
precacheText();
}
private void setupView() {
setContentView(R.layout.example_layout);
body = new GridBody(this);
body.setContextualMenuResource(R.menu.album_menu);
rootView = (CoordinatedMixtapeContainer) findViewById(R.id.example_layout_coordinator);
rootView.setBody(body);
}
private void setupDataSource() {
dataSource = new Mp3AlbumDataSource(getResources());
}
private void setupPresenter() {
final Bitmap defaultArtwork = BitmapFactory.decodeResource(getResources(), R.raw
.default_artwork);
final DisplayableDefaults defaults = new ImmutableDisplayableDefaults(
"Unknown title",
"Unknown subtitle",
new BitmapDrawable(getResources(), defaultArtwork));
final LibraryItemCache cache = new LruLibraryItemCache(10000, 10000, 10000000);
final TitleBinder titleBinder = new TitleBinder(cache, defaults);
final SubtitleBinder subtitleBinder = new SubtitleBinder(cache, defaults);
final ArtworkBinder artworkBinder = new ArtworkBinder(cache, defaults);
presenter = new RecyclerViewBodyPresenter<Mp3Album, Mp3AlbumDataSource>
(titleBinder, subtitleBinder, artworkBinder) {
@Override
public void onContextualMenuItemSelected(final BodyContract.View bodyView,
final LibraryItem libraryItem, final MenuItem menuItem) {
handleContextualMenuClick(libraryItem, menuItem);
}
@Override
public void onLibraryItemSelected(final BodyContract.View bodyView, final LibraryItem item) {
handleItemClick(item);
}
};
presenter.setView(body);
presenter.setDataSource(dataSource);
}
private void precacheText() {
final LibraryItemCache bodyTitleCache = presenter.getTitleDataBinder().getCache();
final LibraryItemCache bodySubtitleCache = presenter.getSubtitleDataBinder().getCache();
dataSource.loadData(true, new BaseDataSource.DataLoadedListener<List<Mp3Album>>() {
@Override
public void onDataLoaded(final BaseDataSource<List<Mp3Album>> source,
final List<Mp3Album> data) {
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
final Executor cacheExecutor = Executors.newCachedThreadPool();
for (final Mp3Album album : data) {
cacheExecutor.execute(new Runnable() {
@Override
public void run() {
bodyTitleCache.cacheTitle(album, true);
bodySubtitleCache.cacheSubtitle(album, true);
}
});
}
}
});
}
@Override
public void onLoadDataFailed(final BaseDataSource<List<Mp3Album>> source) {
// Do nothing
}
});
}
private void handleContextualMenuClick(final LibraryItem item, final MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.album_menu_playNext: {
try {
displayMessage("Playing \"" + item.getTitle() + "\" next");
} catch (LibraryReadException e) {
displayMessage("Playing \"untitled\" next");
}
break;
}
case R.id.album_menu_addToQueue: {
try {
displayMessage("Added \"" + item.getTitle() + "\" to queue");
} catch (LibraryReadException e) {
displayMessage("Added \"untitled\" to queue");
}
break;
}
case R.id.album_menu_remove: {
try {
displayMessage("Deleted \"" + item.getTitle() + "\"");
} catch (LibraryReadException e) {
displayMessage("Deleted \"untitled\"");
}
dataSource.deleteItem((Mp3Album) item);
}
}
}
private void handleItemClick(final LibraryItem item) {
try {
displayMessage("Playing \"" + item.getTitle() + "\"...");
} catch (LibraryReadException e) {
displayMessage("Playing \"untitled\"...");
}
}
private void displayMessage(final String message) {
Snackbar.make(rootView, message, Snackbar.LENGTH_LONG).show();
}
}
|
example/src/main/java/com/matthewtamlin/mixtape/example/activities/AlbumsActivity.java
|
/*
* Copyright 2017 Matthew Tamlin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.matthewtamlin.mixtape.example.activities;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.matthewtamlin.mixtape.example.R;
import com.matthewtamlin.mixtape.example.data.Mp3Album;
import com.matthewtamlin.mixtape.example.data.Mp3AlbumDataSource;
import com.matthewtamlin.mixtape.library.base_mvp.BaseDataSource;
import com.matthewtamlin.mixtape.library.caching.LibraryItemCache;
import com.matthewtamlin.mixtape.library.caching.LruLibraryItemCache;
import com.matthewtamlin.mixtape.library.data.DisplayableDefaults;
import com.matthewtamlin.mixtape.library.data.ImmutableDisplayableDefaults;
import com.matthewtamlin.mixtape.library.data.LibraryItem;
import com.matthewtamlin.mixtape.library.data.LibraryReadException;
import com.matthewtamlin.mixtape.library.databinders.ArtworkBinder;
import com.matthewtamlin.mixtape.library.databinders.SubtitleBinder;
import com.matthewtamlin.mixtape.library.databinders.TitleBinder;
import com.matthewtamlin.mixtape.library.mixtape_body.BodyContract;
import com.matthewtamlin.mixtape.library.mixtape_body.GridBody;
import com.matthewtamlin.mixtape.library.mixtape_body.RecyclerViewBodyPresenter;
import com.matthewtamlin.mixtape.library.mixtape_coordinator.CoordinatedMixtapeContainer;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class AlbumsActivity extends AppCompatActivity {
private GridBody body;
private CoordinatedMixtapeContainer rootView;
private Mp3AlbumDataSource dataSource;
private RecyclerViewBodyPresenter<Mp3Album, Mp3AlbumDataSource> presenter;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Albums");
setupView();
setupDataSource();
setupPresenter();
precacheText();
}
private void setupView() {
setContentView(R.layout.example_layout);
body = new GridBody(this);
body.setContextualMenuResource(R.menu.album_menu);
rootView = (CoordinatedMixtapeContainer) findViewById(R.id.example_layout_coordinator);
rootView.setBody(body);
}
private void setupDataSource() {
dataSource = new Mp3AlbumDataSource();
}
private void setupPresenter() {
final Bitmap defaultArtwork = BitmapFactory.decodeResource(getResources(), R.raw
.default_artwork);
final DisplayableDefaults defaults = new ImmutableDisplayableDefaults(
"Unknown title",
"Unknown subtitle",
new BitmapDrawable(getResources(), defaultArtwork));
final LibraryItemCache cache = new LruLibraryItemCache(10000, 10000, 10000000);
final TitleBinder titleBinder = new TitleBinder(cache, defaults);
final SubtitleBinder subtitleBinder = new SubtitleBinder(cache, defaults);
final ArtworkBinder artworkBinder = new ArtworkBinder(cache, defaults);
presenter = new RecyclerViewBodyPresenter<Mp3Album, Mp3AlbumDataSource>
(titleBinder, subtitleBinder, artworkBinder) {
@Override
public void onContextualMenuItemSelected(final BodyContract.View bodyView,
final LibraryItem libraryItem, final MenuItem menuItem) {
handleContextualMenuClick(libraryItem, menuItem);
}
@Override
public void onLibraryItemSelected(final BodyContract.View bodyView, final LibraryItem item) {
handleItemClick(item);
}
};
presenter.setView(body);
presenter.setDataSource(dataSource);
}
private void precacheText() {
final LibraryItemCache bodyTitleCache = presenter.getTitleDataBinder().getCache();
final LibraryItemCache bodySubtitleCache = presenter.getSubtitleDataBinder().getCache();
dataSource.loadData(true, new BaseDataSource.DataLoadedListener<List<Mp3Album>>() {
@Override
public void onDataLoaded(final BaseDataSource<List<Mp3Album>> source,
final List<Mp3Album> data) {
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
final Executor cacheExecutor = Executors.newCachedThreadPool();
for (final Mp3Album album : data) {
cacheExecutor.execute(new Runnable() {
@Override
public void run() {
bodyTitleCache.cacheTitle(album, true);
bodySubtitleCache.cacheSubtitle(album, true);
}
});
}
}
});
}
@Override
public void onLoadDataFailed(final BaseDataSource<List<Mp3Album>> source) {
// Do nothing
}
});
}
private void handleContextualMenuClick(final LibraryItem item, final MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.album_menu_playNext: {
try {
displayMessage("Playing \"" + item.getTitle() + "\" next");
} catch (LibraryReadException e) {
displayMessage("Playing \"untitled\" next");
}
break;
}
case R.id.album_menu_addToQueue: {
try {
displayMessage("Added \"" + item.getTitle() + "\" to queue");
} catch (LibraryReadException e) {
displayMessage("Added \"untitled\" to queue");
}
break;
}
case R.id.album_menu_remove: {
try {
displayMessage("Deleted \"" + item.getTitle() + "\"");
} catch (LibraryReadException e) {
displayMessage("Deleted \"untitled\"");
}
dataSource.deleteItem((Mp3Album) item);
}
}
}
private void handleItemClick(final LibraryItem item) {
try {
displayMessage("Playing \"" + item.getTitle() + "\"...");
} catch (LibraryReadException e) {
displayMessage("Playing \"untitled\"...");
}
}
private void displayMessage(final String message) {
Snackbar.make(rootView, message, Snackbar.LENGTH_LONG).show();
}
}
|
Added support for change to Mp3AlbumDataSource
|
example/src/main/java/com/matthewtamlin/mixtape/example/activities/AlbumsActivity.java
|
Added support for change to Mp3AlbumDataSource
|
<ide><path>xample/src/main/java/com/matthewtamlin/mixtape/example/activities/AlbumsActivity.java
<ide> }
<ide>
<ide> private void setupDataSource() {
<del> dataSource = new Mp3AlbumDataSource();
<add> dataSource = new Mp3AlbumDataSource(getResources());
<ide> }
<ide>
<ide> private void setupPresenter() {
|
|
Java
|
apache-2.0
|
86d69c6a2568fd94855f3094d21dfcbdda97745a
| 0 |
kwakuzigah/android-autoupdater,arashmidos/android-autoupdater,treejames/android-autoupdater,nikunjkacha/android-autoupdater,heenwang/android-autoupdater,danielZhang0601/android-autoupdater,hiagodotme/android-autoupdater,rafaelwkerr/android-autoupdater,lobo12/android-autoupdater,BraveAction/android-autoupdater,moziqi/android-autoupdater
|
package com.github.snowdream.android.app.updater;
import android.text.TextUtils;
import com.github.snowdream.android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
/**
* Created by snowdream on 1/3/14.
*/
public class UpdateXmlParser extends AbstractParser {
/**
* Parse the UpdateInfo form the string
*
* @param content
* @return UpdateInfo
* @throws UpdateException
*/
@Override
public UpdateInfo parse(String content) throws UpdateException {
UpdateInfo info = null;
if (TextUtils.isEmpty(content)) {
throw new UpdateException(UpdateException.PARSE_ERROR);
}
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(content));
info = parseUpdateInfo(xpp);
} catch (XmlPullParserException e) {
e.printStackTrace();
Log.e("XmlPullParserException", e);
throw new UpdateException(UpdateException.PARSE_ERROR);
} catch (IOException e) {
e.printStackTrace();
Log.e("IOException", e);
throw new UpdateException(UpdateException.PARSE_ERROR);
}
return info;
}
/**
* Parse UpdateInfo
*
* @param xpp
* @return
* @throws XmlPullParserException
* @throws IOException
*/
private UpdateInfo parseUpdateInfo(XmlPullParser xpp) throws XmlPullParserException, IOException {
UpdateInfo info = null;
String currentTag = null;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
currentTag = xpp.getName();
if (currentTag.equals(TAG_UPDATE_INFO)) {
info = new UpdateInfo();
} else if (currentTag.equals(TAG_APP_NAME)) {
if (info != null) {
info.setAppName(xpp.nextText());
}
} else if (currentTag.equals(TAG_APP_DESCRIPTION)) {
if (info != null) {
info.setAppDescription(xpp.nextText());
}
} else if (currentTag.equals(TAG_PACKAGE_NAME)) {
if (info != null) {
info.setPackageName(xpp.nextText());
}
} else if (currentTag.equals(TAG_VERSION_CODE)) {
if (info != null) {
info.setVersionCode(xpp.nextText());
}
} else if (currentTag.equals(TAG_VERSION_NAME)) {
if (info != null) {
info.setVersionName(xpp.nextText());
}
} else if (currentTag.equals(TAG_FORCE_UPDATE)) {
if (info != null) {
String str = xpp.nextText();
info.setForceUpdate( (!TextUtils.isEmpty(str)&& str.equalsIgnoreCase("true")) ? true : false);
}
} else if (currentTag.equals(TAG_AUTO_UPDATE)) {
if (info != null) {
String str = xpp.nextText();
info.setForceUpdate((!TextUtils.isEmpty(str) && str.equalsIgnoreCase("true")) ? true : false);
}
} else if (currentTag.equals(TAG_APK_URL)) {
if (info != null) {
info.setApkUrl(xpp.nextText());
}
} else if (currentTag.equals(TAG_UPDATE_TIPS)) {
Map<String, String> map = parseUpdateTips(xpp);
if (info != null) {
info.setUpdateTips(map);
}
}
break;
case XmlPullParser.END_TAG:
break;
case XmlPullParser.TEXT:
break;
default:
break;
}
eventType = xpp.next();
}
return info;
}
/**
* Parse UpdateTips
*
* @param xpp
* @return
* @throws XmlPullParserException
* @throws IOException
*/
private Map<String, String> parseUpdateTips(XmlPullParser xpp) throws XmlPullParserException, IOException {
Map<String, String> updateTips = new HashMap<String, String>();
String currentTag = null;
String currentValue = null;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
currentTag = xpp.getName();
if (currentTag.equals(TAG_UPDATE_TIPS)) {
updateTips = new HashMap<String, String>();
} else {
currentValue = xpp.nextText();
updateTips.put(currentTag, currentValue);
}
break;
case XmlPullParser.END_TAG:
break;
case XmlPullParser.TEXT:
break;
default:
break;
}
eventType = xpp.next();
}
return updateTips;
}
}
|
client/src/main/java/com/github/snowdream/android/app/updater/UpdateXmlParser.java
|
package com.github.snowdream.android.app.updater;
import android.text.TextUtils;
import com.github.snowdream.android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
/**
* Created by snowdream on 1/3/14.
*/
public class UpdateXmlParser extends AbstractParser {
/**
* Parse the UpdateInfo form the string
*
* @param content
* @return UpdateInfo
* @throws UpdateException
*/
@Override
public UpdateInfo parse(String content) throws UpdateException {
UpdateInfo info = null;
if (TextUtils.isEmpty(content)) {
throw new UpdateException(UpdateException.PARSE_ERROR);
}
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(content));
info = parseUpdateInfo(xpp);
} catch (XmlPullParserException e) {
e.printStackTrace();
Log.e("XmlPullParserException", e);
throw new UpdateException(UpdateException.PARSE_ERROR);
} catch (IOException e) {
e.printStackTrace();
Log.e("IOException", e);
throw new UpdateException(UpdateException.PARSE_ERROR);
}
return info;
}
/**
* Parse UpdateInfo
*
* @param xpp
* @return
* @throws XmlPullParserException
* @throws IOException
*/
private UpdateInfo parseUpdateInfo(XmlPullParser xpp) throws XmlPullParserException, IOException {
UpdateInfo info = null;
String currentTag = null;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
currentTag = xpp.getName();
if (currentTag.equals(TAG_UPDATE_INFO)) {
info = new UpdateInfo();
} else if (currentTag.equals(TAG_APP_NAME)) {
if (info != null) {
info.setAppName(xpp.nextText());
}
} else if (currentTag.equals(TAG_APP_DESCRIPTION)) {
if (info != null) {
info.setAppDescription(xpp.nextText());
}
} else if (currentTag.equals(TAG_PACKAGE_NAME)) {
if (info != null) {
info.setPackageName(xpp.nextText());
}
} else if (currentTag.equals(TAG_VERSION_CODE)) {
if (info != null) {
info.setVersionCode(xpp.nextText());
}
} else if (currentTag.equals(TAG_VERSION_NAME)) {
if (info != null) {
info.setVersionName(xpp.nextText());
}
} else if (currentTag.equals(TAG_FORCE_UPDATE)) {
if (info != null) {
info.setForceUpdate(xpp.nextText() == "true" ? true : false);
}
} else if (currentTag.equals(TAG_AUTO_UPDATE)) {
if (info != null) {
info.setAutoUpdate(xpp.nextText() == "true" ? true : false);
}
} else if (currentTag.equals(TAG_APK_URL)) {
if (info != null) {
info.setApkUrl(xpp.nextText());
}
} else if (currentTag.equals(TAG_UPDATE_TIPS)) {
Map<String, String> map = parseUpdateTips(xpp);
if (info != null) {
info.setUpdateTips(map);
}
}
break;
case XmlPullParser.END_TAG:
break;
case XmlPullParser.TEXT:
break;
default:
break;
}
eventType = xpp.next();
}
return info;
}
/**
* Parse UpdateTips
*
* @param xpp
* @return
* @throws XmlPullParserException
* @throws IOException
*/
private Map<String, String> parseUpdateTips(XmlPullParser xpp) throws XmlPullParserException, IOException {
Map<String, String> updateTips = new HashMap<String, String>();
String currentTag = null;
String currentValue = null;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
currentTag = xpp.getName();
if (currentTag.equals(TAG_UPDATE_TIPS)) {
updateTips = new HashMap<String, String>();
} else {
currentValue = xpp.nextText();
updateTips.put(currentTag, currentValue);
}
break;
case XmlPullParser.END_TAG:
break;
case XmlPullParser.TEXT:
break;
default:
break;
}
eventType = xpp.next();
}
return updateTips;
}
}
|
Fixed: String value compare via == operator? :D
on : UpdateXmlParser
at line : 97 and 101
|
client/src/main/java/com/github/snowdream/android/app/updater/UpdateXmlParser.java
|
Fixed: String value compare via == operator? :D on : UpdateXmlParser at line : 97 and 101
|
<ide><path>lient/src/main/java/com/github/snowdream/android/app/updater/UpdateXmlParser.java
<ide> }
<ide> } else if (currentTag.equals(TAG_FORCE_UPDATE)) {
<ide> if (info != null) {
<del> info.setForceUpdate(xpp.nextText() == "true" ? true : false);
<add> String str = xpp.nextText();
<add> info.setForceUpdate( (!TextUtils.isEmpty(str)&& str.equalsIgnoreCase("true")) ? true : false);
<ide> }
<ide> } else if (currentTag.equals(TAG_AUTO_UPDATE)) {
<ide> if (info != null) {
<del> info.setAutoUpdate(xpp.nextText() == "true" ? true : false);
<add> String str = xpp.nextText();
<add> info.setForceUpdate((!TextUtils.isEmpty(str) && str.equalsIgnoreCase("true")) ? true : false);
<ide> }
<ide> } else if (currentTag.equals(TAG_APK_URL)) {
<ide> if (info != null) {
|
|
Java
|
apache-2.0
|
2a7a29211eec4b72bda34da96be677bee1a07f31
| 0 |
vital-ai/beaker-notebook,ScottPJones/beaker-notebook,ScottPJones/beaker-notebook,vital-ai/beaker-notebook,vital-ai/beaker-notebook,vital-ai/beaker-notebook,ScottPJones/beaker-notebook,vital-ai/beaker-notebook,vital-ai/beaker-notebook,ScottPJones/beaker-notebook,vital-ai/beaker-notebook,ScottPJones/beaker-notebook
|
/*
* Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twosigma.beaker.chart.xychart;
import com.twosigma.beaker.chart.Color;
import com.twosigma.beaker.chart.xychart.plotitem.Line;
import com.twosigma.beaker.chart.xychart.plotitem.Points;
import com.twosigma.beaker.chart.xychart.plotitem.XYGraphics;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
public class SimpleTimePlot extends TimePlot {
private List<Map<String, Object>> data;
private String timeColumn = "time";
private List<String> columns;
private List<String> displayNames;
private List<Object> colors;
private boolean displayLines = true;
private boolean displayPoints = false;
//saturation 75%
//brightness 85%
private static final Color[] NICE_COLORS = {
new Color(33, 87, 141), // blue
new Color(140, 29, 23), // red
new Color(150, 130, 54),// yellow
new Color(20, 30, 120), // violet
new Color(54, 100, 54), // green
new Color(60, 30, 50), // dark
};
public SimpleTimePlot(List<Map<String, Object>> data, List<String> columns) {
this(null, data, columns);
}
public SimpleTimePlot(Map<String, Object> parameters,
List<Map<String, Object>> data,
List<String> columns) {
this.data = data;
this.columns = columns;
//default values
setUseToolTip(true);
setShowLegend(true);
setXLabel("Time");
if (parameters != null) {
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
ReflectionUtils.set(this, fieldName, fieldValue);
}
}
//default the names for the lines and points to the same as the column
if (displayNames == null || displayNames.size() == 0) {
displayNames = columns;
}
reinitialize();
}
private List<Color> getChartColors() {
if (colors != null) {
List<Color> chartColors = new ArrayList<>();
for (int i = 0; i < columns.size(); i++) {
Color color = null;
if (i < colors.size()) {
color = createChartColor(colors.get(i));
}
if (color == null) {
color = createNiceColor();
while (chartColors.contains(color)) {
color = createNiceColor();
}
}
chartColors.add(color);
}
return chartColors;
}
return getNiceColors(columns.size());
}
private List<Color> getNiceColors(int n) {
List<Color> colors = new ArrayList<>();
for (int i = 0; i < n; i++)
if (i < NICE_COLORS.length)
colors.add(NICE_COLORS[i]);
else {
Color color = createNiceColor();
while (colors.contains(color)) {
color = createNiceColor();
}
colors.add(color);
}
return colors;
}
private Color createChartColor(Object color) {
if (color instanceof List) {
try {
return new Color((int) ((List) color).get(0),
(int) ((List) color).get(1),
(int) ((List) color).get(2));
} catch (IndexOutOfBoundsException x) {
throw new RuntimeException("Color list too short");
}
}
String colorAsStr = (String) color;
if (colorAsStr.indexOf("#") == 0) {
return Color.decode(colorAsStr);
}
return colorFromName(colorAsStr);
}
private Color colorFromName(String color) {
try {
Field field = Class.forName("com.twosigma.beaker.chart.Color").getField(color);
return (Color) field.get(null);
} catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException x) {
throw new RuntimeException(String.format("Can not parse color '%s'", color), x);
}
}
private Color createNiceColor() {
Random random = new Random();
final float hue = random.nextFloat();
final float saturation = 0.75f;
final float luminance = 0.85f;
return new Color(java.awt.Color.getHSBColor(hue, saturation, luminance).getRGB());
}
private void reinitialize() {
List<XYGraphics> graphics = getGraphics();
filter(graphics, new Predicate<XYGraphics>() {
public boolean test(XYGraphics graphic) {
return !(graphic instanceof Line || graphic instanceof Points);
}
});
List<Number> xs = new ArrayList<>();
List<List<Number>> yss = new ArrayList<>();
if (data != null && columns != null) {
for (Map<String, Object> row : data) {
xs.add((Number) row.get(timeColumn));
for (int i = 0; i < columns.size(); i++) {
String column = columns.get(i);
if (i >= yss.size()) {
yss.add(new ArrayList<Number>());
}
yss.get(i).add((Number) row.get(column));
}
}
List<Color> colors = getChartColors();
for (int i = 0; i < yss.size(); i++) {
List<Number> ys = yss.get(i);
if (displayLines) {
Line line = new Line();
line.setX(xs);
line.setY(ys);
if (displayNames != null && i < displayNames.size()) {
line.setDisplayName(displayNames.get(i));
} else {
line.setDisplayName(columns.get(i));
}
line.setColor(colors.get(i));
add(line);
}
if (displayPoints) {
Points points = new Points();
points.setX(xs);
points.setY(ys);
if (displayNames != null && i < displayNames.size()) {
points.setDisplayName(displayNames.get(i));
} else {
points.setDisplayName(columns.get(i));
}
points.setColor(colors.get(i));
add(points);
}
}
}
}
public List<Map<String, Object>> getData() {
return data;
}
public void setData(List<Map<String, Object>> data) {
this.data = data;
reinitialize();
}
public List<String> getColumns() {
return columns;
}
public void setColumns(List<String> columns) {
this.columns = columns;
reinitialize();
}
public void setDisplayNames(List<String> displayNames) {
this.displayNames = displayNames;
if (displayNames != null) {
List<XYGraphics> graphics = getGraphics();
int i = 0;
for (XYGraphics graphic : graphics) {
if (graphic instanceof Line) {
graphic.setDisplayName(displayNames.get(++i));
}
}
}
}
public List<String> getDisplayNames() {
return displayNames;
}
public void setColors(List<Object> colors) {
this.colors = colors;
}
public List<Object> getColors() {
return colors;
}
public String getTimeColumn() {
return timeColumn;
}
public void setTimeColumn(String timeColumn) {
this.timeColumn = timeColumn;
reinitialize();
}
public boolean isDisplayLines() {
return displayLines;
}
public void setDisplayLines(boolean displayLines) {
this.displayLines = displayLines;
reinitialize();
}
public boolean isDisplayPoints() {
return displayPoints;
}
public void setDisplayPoints(boolean displayPoints) {
this.displayPoints = displayPoints;
reinitialize();
}
private interface Predicate<T> {
boolean test(T o);
}
private static <T> void filter(Collection<T> collection, Predicate<T> predicate) {
if ((collection != null) && (predicate != null)) {
Iterator<T> itr = collection.iterator();
while (itr.hasNext()) {
T obj = itr.next();
if (!predicate.test(obj)) {
itr.remove();
}
}
}
}
private static class ReflectionUtils {
private static Map<String, Method> SETTERS_MAP = new HashMap<String, Method>();
static boolean set(Object object, String fieldName, Object fieldValue) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
return true;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
} catch (Exception expected) {
//nothing to do
}
}
return callSetter(object, fieldName, fieldValue);
}
private static boolean callSetter(Object obj, String fieldName, Object fieldValue) {
String key = String.format("%s.%s(%s)", obj.getClass().getName(),
fieldName, fieldValue.getClass().getName());
Method m = null;
if (!SETTERS_MAP.containsKey(key)) {
m = findMethod(obj, fieldName, fieldValue);
SETTERS_MAP.put(key, m);
} else {
m = SETTERS_MAP.get(key);
}
if (m != null) {
try {
m.invoke(obj, fieldValue);
return true;
} catch (Throwable ignored) {
//expected
}
}
return false;
}
private static Method findMethod(Object obj, String fieldName, Object fieldValue) {
Method m = null;
Class<?> theClass = obj.getClass();
String setter = String.format("set%C%s",
fieldName.charAt(0), fieldName.substring(1));
Class paramType = fieldValue.getClass();
while (paramType != null) {
try {
m = theClass.getMethod(setter, paramType);
return m;
} catch (NoSuchMethodException ex) {
// try on the interfaces of this class
for (Class iface : paramType.getInterfaces()) {
try {
m = theClass.getMethod(setter, iface);
return m;
} catch (NoSuchMethodException ignored) {
}
}
paramType = paramType.getSuperclass();
}
}
return m;
}
}
}
|
plugin/jvm/src/main/java/com/twosigma/beaker/chart/xychart/SimpleTimePlot.java
|
/*
* Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twosigma.beaker.chart.xychart;
import com.twosigma.beaker.chart.Color;
import com.twosigma.beaker.chart.xychart.plotitem.Line;
import com.twosigma.beaker.chart.xychart.plotitem.Points;
import com.twosigma.beaker.chart.xychart.plotitem.XYGraphics;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
public class SimpleTimePlot extends TimePlot {
private List<Map<String, Object>> data;
private String timeColumn = "time";
private List<String> columns;
private List<String> displayNames;
private List<Object> colors;
private boolean displayLines = true;
private boolean displayPoints = false;
//saturation 75%
//brightness 85%
private static final Color[] NICE_COLORS = {
new Color(54, 54, 217), //blue hue = 240
new Color(216, 54, 54), //red hue = 0
new Color(54, 216, 54), //green hue = 120
new Color(192, 54, 216), //purple hue = 291
new Color(54, 126, 186), //cyan hue = 169
new Color(216, 178, 54), //yellow hue = 46
};
public SimpleTimePlot(List<Map<String, Object>> data, List<String> columns) {
this(null, data, columns);
}
public SimpleTimePlot(Map<String, Object> parameters,
List<Map<String, Object>> data,
List<String> columns) {
this.data = data;
this.columns = columns;
//default values
setUseToolTip(true);
setShowLegend(true);
setXLabel("Time");
if (parameters != null) {
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
ReflectionUtils.set(this, fieldName, fieldValue);
}
}
//default the names for the lines and points to the same as the column
if (displayNames == null || displayNames.size() == 0) {
displayNames = columns;
}
reinitialize();
}
private List<Color> getChartColors() {
if (colors != null) {
List<Color> chartColors = new ArrayList<>();
for (int i = 0; i < columns.size(); i++) {
Color color = null;
if (i < colors.size()) {
color = createChartColor(colors.get(i));
}
if (color == null) {
color = createNiceColor();
while (chartColors.contains(color)) {
color = createNiceColor();
}
}
chartColors.add(color);
}
return chartColors;
}
return getNiceColors(columns.size());
}
private List<Color> getNiceColors(int n) {
List<Color> colors = new ArrayList<>();
for (int i = 0; i < n; i++)
if (i < NICE_COLORS.length)
colors.add(NICE_COLORS[i]);
else {
Color color = createNiceColor();
while (colors.contains(color)) {
color = createNiceColor();
}
colors.add(color);
}
return colors;
}
private Color createChartColor(Object color) {
if (color instanceof List) {
try {
return new Color((int) ((List) color).get(0),
(int) ((List) color).get(1),
(int) ((List) color).get(2));
} catch (IndexOutOfBoundsException x) {
throw new RuntimeException("Color list too short");
}
}
String colorAsStr = (String) color;
if (colorAsStr.indexOf("#") == 0) {
return Color.decode(colorAsStr);
}
return colorFromName(colorAsStr);
}
private Color colorFromName(String color) {
try {
Field field = Class.forName("com.twosigma.beaker.chart.Color").getField(color);
return (Color) field.get(null);
} catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException x) {
throw new RuntimeException(String.format("Can not parse color '%s'", color), x);
}
}
private Color createNiceColor() {
Random random = new Random();
final float hue = random.nextFloat();
final float saturation = 0.75f;
final float luminance = 0.85f;
return new Color(java.awt.Color.getHSBColor(hue, saturation, luminance).getRGB());
}
private void reinitialize() {
List<XYGraphics> graphics = getGraphics();
filter(graphics, new Predicate<XYGraphics>() {
public boolean test(XYGraphics graphic) {
return !(graphic instanceof Line || graphic instanceof Points);
}
});
List<Number> xs = new ArrayList<>();
List<List<Number>> yss = new ArrayList<>();
if (data != null && columns != null) {
for (Map<String, Object> row : data) {
xs.add((Number) row.get(timeColumn));
for (int i = 0; i < columns.size(); i++) {
String column = columns.get(i);
if (i >= yss.size()) {
yss.add(new ArrayList<Number>());
}
yss.get(i).add((Number) row.get(column));
}
}
List<Color> colors = getChartColors();
for (int i = 0; i < yss.size(); i++) {
List<Number> ys = yss.get(i);
if (displayLines) {
Line line = new Line();
line.setX(xs);
line.setY(ys);
if (displayNames != null && i < displayNames.size()) {
line.setDisplayName(displayNames.get(i));
} else {
line.setDisplayName(columns.get(i));
}
line.setColor(colors.get(i));
add(line);
}
if (displayPoints) {
Points points = new Points();
points.setX(xs);
points.setY(ys);
if (displayNames != null && i < displayNames.size()) {
points.setDisplayName(displayNames.get(i));
} else {
points.setDisplayName(columns.get(i));
}
points.setColor(colors.get(i));
add(points);
}
}
}
}
public List<Map<String, Object>> getData() {
return data;
}
public void setData(List<Map<String, Object>> data) {
this.data = data;
reinitialize();
}
public List<String> getColumns() {
return columns;
}
public void setColumns(List<String> columns) {
this.columns = columns;
reinitialize();
}
public void setDisplayNames(List<String> displayNames) {
this.displayNames = displayNames;
if (displayNames != null) {
List<XYGraphics> graphics = getGraphics();
int i = 0;
for (XYGraphics graphic : graphics) {
if (graphic instanceof Line) {
graphic.setDisplayName(displayNames.get(++i));
}
}
}
}
public List<String> getDisplayNames() {
return displayNames;
}
public void setColors(List<Object> colors) {
this.colors = colors;
}
public List<Object> getColors() {
return colors;
}
public String getTimeColumn() {
return timeColumn;
}
public void setTimeColumn(String timeColumn) {
this.timeColumn = timeColumn;
reinitialize();
}
public boolean isDisplayLines() {
return displayLines;
}
public void setDisplayLines(boolean displayLines) {
this.displayLines = displayLines;
reinitialize();
}
public boolean isDisplayPoints() {
return displayPoints;
}
public void setDisplayPoints(boolean displayPoints) {
this.displayPoints = displayPoints;
reinitialize();
}
private interface Predicate<T> {
boolean test(T o);
}
private static <T> void filter(Collection<T> collection, Predicate<T> predicate) {
if ((collection != null) && (predicate != null)) {
Iterator<T> itr = collection.iterator();
while (itr.hasNext()) {
T obj = itr.next();
if (!predicate.test(obj)) {
itr.remove();
}
}
}
}
private static class ReflectionUtils {
private static Map<String, Method> SETTERS_MAP = new HashMap<String, Method>();
static boolean set(Object object, String fieldName, Object fieldValue) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
return true;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
} catch (Exception expected) {
//nothing to do
}
}
return callSetter(object, fieldName, fieldValue);
}
private static boolean callSetter(Object obj, String fieldName, Object fieldValue) {
String key = String.format("%s.%s(%s)", obj.getClass().getName(),
fieldName, fieldValue.getClass().getName());
Method m = null;
if (!SETTERS_MAP.containsKey(key)) {
m = findMethod(obj, fieldName, fieldValue);
SETTERS_MAP.put(key, m);
} else {
m = SETTERS_MAP.get(key);
}
if (m != null) {
try {
m.invoke(obj, fieldValue);
return true;
} catch (Throwable ignored) {
//expected
}
}
return false;
}
private static Method findMethod(Object obj, String fieldName, Object fieldValue) {
Method m = null;
Class<?> theClass = obj.getClass();
String setter = String.format("set%C%s",
fieldName.charAt(0), fieldName.substring(1));
Class paramType = fieldValue.getClass();
while (paramType != null) {
try {
m = theClass.getMethod(setter, paramType);
return m;
} catch (NoSuchMethodException ex) {
// try on the interfaces of this class
for (Class iface : paramType.getInterfaces()) {
try {
m = theClass.getMethod(setter, iface);
return m;
} catch (NoSuchMethodException ignored) {
}
}
paramType = paramType.getSuperclass();
}
}
return m;
}
}
}
|
fix default colors for SimpleTimePlot
|
plugin/jvm/src/main/java/com/twosigma/beaker/chart/xychart/SimpleTimePlot.java
|
fix default colors for SimpleTimePlot
|
<ide><path>lugin/jvm/src/main/java/com/twosigma/beaker/chart/xychart/SimpleTimePlot.java
<ide> //saturation 75%
<ide> //brightness 85%
<ide> private static final Color[] NICE_COLORS = {
<del> new Color(54, 54, 217), //blue hue = 240
<del> new Color(216, 54, 54), //red hue = 0
<del> new Color(54, 216, 54), //green hue = 120
<del> new Color(192, 54, 216), //purple hue = 291
<del> new Color(54, 126, 186), //cyan hue = 169
<del> new Color(216, 178, 54), //yellow hue = 46
<add> new Color(33, 87, 141), // blue
<add> new Color(140, 29, 23), // red
<add> new Color(150, 130, 54),// yellow
<add> new Color(20, 30, 120), // violet
<add> new Color(54, 100, 54), // green
<add> new Color(60, 30, 50), // dark
<ide> };
<ide>
<ide> public SimpleTimePlot(List<Map<String, Object>> data, List<String> columns) {
|
|
Java
|
apache-2.0
|
8f23295afc1ccfd2ccdc23a5067e18663207c9e5
| 0 |
FangStarNet/symphonyx,FangStarNet/symphonyx,FangStarNet/symphonyx
|
/*
* Copyright (c) 2012-2016, b3log.org & hacpai.com & fangstar.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.symphony.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import org.b3log.latke.Keys;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Pagination;
import org.b3log.latke.model.User;
import org.b3log.latke.repository.CompositeFilter;
import org.b3log.latke.repository.CompositeFilterOperator;
import org.b3log.latke.repository.Filter;
import org.b3log.latke.repository.FilterOperator;
import org.b3log.latke.repository.PropertyFilter;
import org.b3log.latke.repository.Query;
import org.b3log.latke.repository.RepositoryException;
import org.b3log.latke.repository.SortDirection;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service;
import org.b3log.symphony.model.Article;
import org.b3log.symphony.model.Comment;
import org.b3log.symphony.model.Common;
import org.b3log.symphony.model.Notification;
import org.b3log.symphony.model.Pointtransfer;
import org.b3log.symphony.model.Reward;
import org.b3log.symphony.model.UserExt;
import org.b3log.symphony.repository.ArticleRepository;
import org.b3log.symphony.repository.CommentRepository;
import org.b3log.symphony.repository.NotificationRepository;
import org.b3log.symphony.repository.PointtransferRepository;
import org.b3log.symphony.repository.RewardRepository;
import org.b3log.symphony.repository.UserRepository;
import org.b3log.symphony.util.Emotions;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Notification query service.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.4.1.4, Feb 26, 2016
* @since 0.2.5
*/
@Service
public class NotificationQueryService {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(NotificationQueryService.class.getName());
/**
* Notification repository.
*/
@Inject
private NotificationRepository notificationRepository;
/**
* Article repository.
*/
@Inject
private ArticleRepository articleRepository;
/**
* Comment query service.
*/
@Inject
private CommentQueryService commentQueryService;
/**
* User repository.
*/
@Inject
private UserRepository userRepository;
/**
* Comment repository.
*/
@Inject
private CommentRepository commentRepository;
/**
* Reward repository.
*/
@Inject
private RewardRepository rewardRepository;
/**
* Pointtransfer repository.
*/
@Inject
private PointtransferRepository pointtransferRepository;
/**
* Avatar query service.
*/
@Inject
private AvatarQueryService avatarQueryService;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Gets the count of unread notifications of a user specified with the given user id.
*
* @param userId the given user id
* @return count of unread notifications, returns {@code 0} if occurs exception
*/
public int getUnreadNotificationCount(final String userId) {
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_HAS_READ, FilterOperator.EQUAL, false));
final Query query = new Query();
query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).addProjection(Keys.OBJECT_ID, String.class);
try {
final JSONObject result = notificationRepository.get(query);
return result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets unread notification count failed [userId=" + userId + "]", e);
return 0;
}
}
/**
* Gets the count of unread notifications of a user specified with the given user id and data type.
*
* @param userId the given user id
* @param notificationDataType the specified notification data type
* @return count of unread notifications, returns {@code 0} if occurs exception
* @see Notification#DATA_TYPE_C_ARTICLE
* @see Notification#DATA_TYPE_C_AT
* @see Notification#DATA_TYPE_C_COMMENT
* @see Notification#DATA_TYPE_C_COMMENTED
* @see Notification#DATA_TYPE_C_BROADCAST
*/
public int getUnreadNotificationCountByType(final String userId, final int notificationDataType) {
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_HAS_READ, FilterOperator.EQUAL, false));
filters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL, notificationDataType));
final Query query = new Query();
query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).addProjection(Keys.OBJECT_ID, String.class);
try {
final JSONObject result = notificationRepository.get(query);
return result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [commented] notification count failed [userId=" + userId + "]", e);
return 0;
}
}
/**
* Gets the count of unread 'point' notifications of a user specified with the given user id.
*
* @param userId the given user id
* @return count of unread notifications, returns {@code 0} if occurs exception
* @see Notification#DATA_TYPE_C_POINT_ARTICLE_REWARD
* @see Notification#DATA_TYPE_C_POINT_CHARGE
* @see Notification#DATA_TYPE_C_POINT_EXCHANGE
* @see Notification#DATA_TYPE_C_ABUSE_POINT_DEDUCT
* @see Notification#DATA_TYPE_C_POINT_COMMENT_THANK
* @see Notification#DATA_TYPE_C_POINT_TRANSFER
*/
public int getUnreadPointNotificationCount(final String userId) {
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_HAS_READ, FilterOperator.EQUAL, false));
final List<Filter> subFilters = new ArrayList<Filter>();
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_ARTICLE_REWARD));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_CHARGE));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_EXCHANGE));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_ABUSE_POINT_DEDUCT));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_COMMENT_THANK));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_TRANSFER));
filters.add(new CompositeFilter(CompositeFilterOperator.OR, subFilters));
final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
try {
final JSONObject result = notificationRepository.get(query);
return result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [commented] notification count failed [userId=" + userId + "]", e);
return 0;
}
}
/**
* Gets 'point' type notifications with the specified user id, current page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return result json object, for example, <pre>
* {
* "paginationRecordCount": int,
* "rslts": java.util.List[{
* "oId": "", // notification record id
* "description": int,
* "hasRead": boolean
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getPointNotifications(final String userId, final int currentPageNum, final int pageSize)
throws ServiceException {
final JSONObject ret = new JSONObject();
final List<JSONObject> rslts = new ArrayList<JSONObject>();
ret.put(Keys.RESULTS, (Object) rslts);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
final List<Filter> subFilters = new ArrayList<Filter>();
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_ARTICLE_REWARD));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_CHARGE));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_EXCHANGE));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_ABUSE_POINT_DEDUCT));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_COMMENT_THANK));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_TRANSFER));
filters.add(new CompositeFilter(CompositeFilterOperator.OR, subFilters));
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).
setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).
addSort(Notification.NOTIFICATION_HAS_READ, SortDirection.ASCENDING).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
try {
final JSONObject queryResult = notificationRepository.get(query);
final JSONArray results = queryResult.optJSONArray(Keys.RESULTS);
ret.put(Pagination.PAGINATION_RECORD_COUNT,
queryResult.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT));
for (int i = 0; i < results.length(); i++) {
final JSONObject notification = results.optJSONObject(i);
final String dataId = notification.optString(Notification.NOTIFICATION_DATA_ID);
final int dataType = notification.optInt(Notification.NOTIFICATION_DATA_TYPE);
String desTemplate = "";
switch (dataType) {
case Notification.DATA_TYPE_C_POINT_ARTICLE_REWARD:
desTemplate = langPropsService.get("notificationArticleRewardLabel");
final JSONObject reward7 = rewardRepository.get(dataId);
final String senderId7 = reward7.optString(Reward.SENDER_ID);
final JSONObject user7 = userRepository.get(senderId7);
final String articleId7 = reward7.optString(Reward.DATA_ID);
final JSONObject article7 = articleRepository.get(articleId7);
final String userLink7 = "<a href=\"/member/" + user7.optString(User.USER_NAME) + "\">"
+ user7.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", userLink7);
final String articleLink7 = "<a href=\""
+ article7.optString(Article.ARTICLE_PERMALINK) + "\">"
+ article7.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", articleLink7);
break;
case Notification.DATA_TYPE_C_POINT_CHARGE:
desTemplate = langPropsService.get("notificationPointChargeLabel");
final JSONObject transfer5 = pointtransferRepository.get(dataId);
final int sum5 = transfer5.optInt(Pointtransfer.SUM);
final String memo5 = transfer5.optString(Pointtransfer.DATA_ID);
final String yuan = memo5.split("-")[0];
desTemplate = desTemplate.replace("{yuan}", yuan);
desTemplate = desTemplate.replace("{point}", String.valueOf(sum5));
break;
case Notification.DATA_TYPE_C_POINT_EXCHANGE:
desTemplate = langPropsService.get("notificationPointExchangeLabel");
final JSONObject transfer6 = pointtransferRepository.get(dataId);
final int sum6 = transfer6.optInt(Pointtransfer.SUM);
final String yuan6 = transfer6.optString(Pointtransfer.DATA_ID);
desTemplate = desTemplate.replace("{yuan}", yuan6);
desTemplate = desTemplate.replace("{point}", String.valueOf(sum6));
break;
case Notification.DATA_TYPE_C_ABUSE_POINT_DEDUCT:
desTemplate = langPropsService.get("notificationAbusePointDeductLabel");
final JSONObject transfer7 = pointtransferRepository.get(dataId);
final int sum7 = transfer7.optInt(Pointtransfer.SUM);
final String memo7 = transfer7.optString(Pointtransfer.DATA_ID);
desTemplate = desTemplate.replace("{action}", memo7);
desTemplate = desTemplate.replace("{point}", String.valueOf(sum7));
break;
case Notification.DATA_TYPE_C_POINT_COMMENT_THANK:
desTemplate = langPropsService.get("notificationCmtThankLabel");
final JSONObject reward8 = rewardRepository.get(dataId);
final String senderId8 = reward8.optString(Reward.SENDER_ID);
final JSONObject user8 = userRepository.get(senderId8);
final JSONObject comment8 = commentRepository.get(reward8.optString(Reward.DATA_ID));
final String articleId8 = comment8.optString(Comment.COMMENT_ON_ARTICLE_ID);
final JSONObject article8 = articleRepository.get(articleId8);
final String userLink8 = "<a href=\"/member/" + user8.optString(User.USER_NAME) + "\">"
+ user8.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", userLink8);
final String articleLink8 = "<a href=\""
+ article8.optString(Article.ARTICLE_PERMALINK) + "\">"
+ article8.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", articleLink8);
break;
case Notification.DATA_TYPE_C_POINT_TRANSFER:
desTemplate = langPropsService.get("notificationPointTransferLabel");
final JSONObject transfer101 = pointtransferRepository.get(dataId);
final String fromId101 = transfer101.optString(Pointtransfer.FROM_ID);
final JSONObject user101 = userRepository.get(fromId101);
final int sum101 = transfer101.optInt(Pointtransfer.SUM);
final String userLink101 = "<a href=\"/member/" + user101.optString(User.USER_NAME) + "\">"
+ user101.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", userLink101);
desTemplate = desTemplate.replace("{amount}", String.valueOf(sum101));
break;
default:
throw new AssertionError();
}
notification.put(Common.DESCRIPTION, desTemplate);
rslts.add(notification);
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [commented] notifications", e);
throw new ServiceException(e);
}
}
/**
* Gets 'commented' type notifications with the specified user id, current page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return result json object, for example, <pre>
* {
* "paginationRecordCount": int,
* "rslts": java.util.List[{
* "oId": "", // notification record id
* "commentAuthorName": "",
* "commentContent": "",
* "commentAuthorThumbnailURL": "",
* "commentArticleTitle": "",
* "commentArticleType": int,
* "commentSharpURL": "",
* "commentCreateTime": java.util.Date,
* "hasRead": boolean
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getCommentedNotifications(final String userId, final int currentPageNum, final int pageSize)
throws ServiceException {
final JSONObject ret = new JSONObject();
final List<JSONObject> rslts = new ArrayList<JSONObject>();
ret.put(Keys.RESULTS, (Object) rslts);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL, Notification.DATA_TYPE_C_COMMENTED));
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).
setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).
addSort(Notification.NOTIFICATION_HAS_READ, SortDirection.ASCENDING).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
try {
final JSONObject queryResult = notificationRepository.get(query);
final JSONArray results = queryResult.optJSONArray(Keys.RESULTS);
ret.put(Pagination.PAGINATION_RECORD_COUNT,
queryResult.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT));
for (int i = 0; i < results.length(); i++) {
final JSONObject notification = results.optJSONObject(i);
final String commentId = notification.optString(Notification.NOTIFICATION_DATA_ID);
final JSONObject comment = commentQueryService.getCommentById(commentId);
final Query q = new Query().setPageCount(1).
addProjection(Article.ARTICLE_TITLE, String.class).
addProjection(Article.ARTICLE_TYPE, Integer.class).
setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL,
comment.optString(Comment.COMMENT_ON_ARTICLE_ID)));
final JSONArray rlts = articleRepository.get(q).optJSONArray(Keys.RESULTS);
final JSONObject article = rlts.optJSONObject(0);
final String articleTitle = article.optString(Article.ARTICLE_TITLE);
final int articleType = article.optInt(Article.ARTICLE_TYPE);
final JSONObject commentedNotification = new JSONObject();
commentedNotification.put(Keys.OBJECT_ID, notification.optString(Keys.OBJECT_ID));
commentedNotification.put(Comment.COMMENT_T_AUTHOR_NAME, comment.optString(Comment.COMMENT_T_AUTHOR_NAME));
commentedNotification.put(Comment.COMMENT_CONTENT, comment.optString(Comment.COMMENT_CONTENT));
commentedNotification.put(Comment.COMMENT_T_AUTHOR_THUMBNAIL_URL,
comment.optString(Comment.COMMENT_T_AUTHOR_THUMBNAIL_URL));
commentedNotification.put(Common.THUMBNAIL_UPDATE_TIME, comment.optJSONObject(Comment.COMMENT_T_COMMENTER).
optLong(UserExt.USER_UPDATE_TIME));
commentedNotification.put(Comment.COMMENT_T_ARTICLE_TITLE, Emotions.convert(articleTitle));
commentedNotification.put(Comment.COMMENT_T_ARTICLE_TYPE, articleType);
commentedNotification.put(Comment.COMMENT_SHARP_URL, comment.optString(Comment.COMMENT_SHARP_URL));
commentedNotification.put(Comment.COMMENT_CREATE_TIME, comment.opt(Comment.COMMENT_CREATE_TIME));
commentedNotification.put(Notification.NOTIFICATION_HAS_READ, notification.optBoolean(Notification.NOTIFICATION_HAS_READ));
rslts.add(commentedNotification);
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [commented] notifications", e);
throw new ServiceException(e);
}
}
/**
* Gets 'at' type notifications with the specified user id, current page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return result json object, for example, <pre>
* {
* "paginationRecordCount": int,
* "rslts": java.util.List[{
* "oId": "", // notification record id
* "authorName": "",
* "content": "",
* "thumbnailURL": "",
* "articleTitle": "",
* "articleType": int,
* "url": "",
* "createTime": java.util.Date,
* "hasRead": boolean,
* "atInArticle": boolean,
* "articleTags": "", // if atInArticle is true
* "articleCommentCnt": int // if atInArticle is true
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getAtNotifications(final String userId, final int currentPageNum, final int pageSize)
throws ServiceException {
final JSONObject ret = new JSONObject();
final List<JSONObject> rslts = new ArrayList<JSONObject>();
ret.put(Keys.RESULTS, (Object) rslts);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL, Notification.DATA_TYPE_C_AT));
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).
setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).
addSort(Notification.NOTIFICATION_HAS_READ, SortDirection.ASCENDING).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
try {
final JSONObject queryResult = notificationRepository.get(query);
final JSONArray results = queryResult.optJSONArray(Keys.RESULTS);
ret.put(Pagination.PAGINATION_RECORD_COUNT,
queryResult.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT));
for (int i = 0; i < results.length(); i++) {
final JSONObject notification = results.optJSONObject(i);
final String commentId = notification.optString(Notification.NOTIFICATION_DATA_ID);
final JSONObject comment = commentQueryService.getCommentById(commentId);
if (null != comment) {
final Query q = new Query().setPageCount(1).
addProjection(Article.ARTICLE_TITLE, String.class).
addProjection(Article.ARTICLE_TYPE, Integer.class).
setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL,
comment.optString(Comment.COMMENT_ON_ARTICLE_ID)));
final JSONArray rlts = articleRepository.get(q).optJSONArray(Keys.RESULTS);
final JSONObject article = rlts.optJSONObject(0);
final String articleTitle = article.optString(Article.ARTICLE_TITLE);
final int articleType = article.optInt(Article.ARTICLE_TYPE);
final JSONObject atNotification = new JSONObject();
atNotification.put(Keys.OBJECT_ID, notification.optString(Keys.OBJECT_ID));
atNotification.put(Common.AUTHOR_NAME, comment.optString(Comment.COMMENT_T_AUTHOR_NAME));
atNotification.put(Common.CONTENT, comment.optString(Comment.COMMENT_CONTENT));
atNotification.put(Common.THUMBNAIL_URL,
comment.optString(Comment.COMMENT_T_AUTHOR_THUMBNAIL_URL));
atNotification.put(Common.THUMBNAIL_UPDATE_TIME, comment.optJSONObject(Comment.COMMENT_T_COMMENTER).
optLong(UserExt.USER_UPDATE_TIME));
atNotification.put(Article.ARTICLE_TITLE, articleTitle);
atNotification.put(Article.ARTICLE_TYPE, articleType);
atNotification.put(Common.URL, comment.optString(Comment.COMMENT_SHARP_URL));
atNotification.put(Common.CREATE_TIME, comment.opt(Comment.COMMENT_CREATE_TIME));
atNotification.put(Notification.NOTIFICATION_HAS_READ, notification.optBoolean(Notification.NOTIFICATION_HAS_READ));
atNotification.put(Notification.NOTIFICATION_T_AT_IN_ARTICLE, false);
rslts.add(atNotification);
} else { // The 'at' in article content
final JSONObject article = articleRepository.get(commentId);
final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject articleAuthor = userRepository.get(articleAuthorId);
final JSONObject atNotification = new JSONObject();
atNotification.put(Keys.OBJECT_ID, notification.optString(Keys.OBJECT_ID));
atNotification.put(Common.AUTHOR_NAME, articleAuthor.optString(User.USER_NAME));
atNotification.put(Common.CONTENT, "");
final String thumbnailURL = avatarQueryService.getAvatarURL(articleAuthor.optString(User.USER_EMAIL));
atNotification.put(Common.THUMBNAIL_URL, thumbnailURL);
atNotification.put(Common.THUMBNAIL_UPDATE_TIME, articleAuthor.optLong(UserExt.USER_UPDATE_TIME));
atNotification.put(Article.ARTICLE_TITLE, Emotions.convert(article.optString(Article.ARTICLE_TITLE)));
atNotification.put(Article.ARTICLE_TYPE, article.optInt(Article.ARTICLE_TYPE));
atNotification.put(Common.URL, article.optString(Article.ARTICLE_PERMALINK));
atNotification.put(Common.CREATE_TIME, new Date(article.optLong(Article.ARTICLE_CREATE_TIME)));
atNotification.put(Notification.NOTIFICATION_HAS_READ, notification.optBoolean(Notification.NOTIFICATION_HAS_READ));
atNotification.put(Notification.NOTIFICATION_T_AT_IN_ARTICLE, true);
atNotification.put(Article.ARTICLE_TAGS, article.optString(Article.ARTICLE_TAGS));
atNotification.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT));
rslts.add(atNotification);
}
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [at] notifications", e);
throw new ServiceException(e);
}
}
/**
* Gets 'followingUser' type notifications with the specified user id, current page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return result json object, for example, <pre>
* {
* "paginationRecordCount": int,
* "rslts": java.util.List[{
* "oId": "", // notification record id
* "authorName": "",
* "content": "",
* "thumbnailURL": "",
* "articleTitle": "",
* "articleType": int,
* "articleTags": "",
* "articleCommentCnt": int,
* "url": "",
* "createTime": java.util.Date,
* "hasRead": boolean,
* "type": "", // article/comment
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getFollowingUserNotifications(final String userId, final int currentPageNum, final int pageSize)
throws ServiceException {
final JSONObject ret = new JSONObject();
final List<JSONObject> rslts = new ArrayList<JSONObject>();
ret.put(Keys.RESULTS, (Object) rslts);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL, Notification.DATA_TYPE_C_FOLLOWING_USER));
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).
setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).
addSort(Notification.NOTIFICATION_HAS_READ, SortDirection.ASCENDING).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
try {
final JSONObject queryResult = notificationRepository.get(query);
final JSONArray results = queryResult.optJSONArray(Keys.RESULTS);
ret.put(Pagination.PAGINATION_RECORD_COUNT,
queryResult.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT));
for (int i = 0; i < results.length(); i++) {
final JSONObject notification = results.optJSONObject(i);
final String articleId = notification.optString(Notification.NOTIFICATION_DATA_ID);
final Query q = new Query().setPageCount(1).
addProjection(Article.ARTICLE_TITLE, String.class).
addProjection(Article.ARTICLE_TYPE, Integer.class).
addProjection(Article.ARTICLE_AUTHOR_EMAIL, String.class).
addProjection(Article.ARTICLE_PERMALINK, String.class).
addProjection(Article.ARTICLE_CREATE_TIME, Long.class).
addProjection(Article.ARTICLE_TAGS, String.class).
addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class).
setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL, articleId));
final JSONArray rlts = articleRepository.get(q).optJSONArray(Keys.RESULTS);
final JSONObject article = rlts.optJSONObject(0);
if (null == article) {
LOGGER.warn("Not found article[id=" + articleId + ']');
continue;
}
final String articleTitle = article.optString(Article.ARTICLE_TITLE);
final String articleAuthorEmail = article.optString(Article.ARTICLE_AUTHOR_EMAIL);
final JSONObject author = userRepository.getByEmail(articleAuthorEmail);
if (null == author) {
LOGGER.warn("Not found user[email=" + articleAuthorEmail + ']');
continue;
}
final JSONObject followingUserNotification = new JSONObject();
followingUserNotification.put(Keys.OBJECT_ID, notification.optString(Keys.OBJECT_ID));
followingUserNotification.put(Common.AUTHOR_NAME, author.optString(User.USER_NAME));
followingUserNotification.put(Common.CONTENT, "");
followingUserNotification.put(Common.THUMBNAIL_URL, avatarQueryService.getAvatarURL(articleAuthorEmail));
followingUserNotification.put(Common.THUMBNAIL_UPDATE_TIME, author.optLong(UserExt.USER_UPDATE_TIME));
followingUserNotification.put(Article.ARTICLE_TITLE, Emotions.convert(articleTitle));
followingUserNotification.put(Common.URL, article.optString(Article.ARTICLE_PERMALINK));
followingUserNotification.put(Common.CREATE_TIME, new Date(article.optLong(Article.ARTICLE_CREATE_TIME)));
followingUserNotification.put(Notification.NOTIFICATION_HAS_READ,
notification.optBoolean(Notification.NOTIFICATION_HAS_READ));
followingUserNotification.put(Common.TYPE, Article.ARTICLE);
followingUserNotification.put(Article.ARTICLE_TYPE, article.optInt(Article.ARTICLE_TYPE));
followingUserNotification.put(Article.ARTICLE_TAGS, article.optString(Article.ARTICLE_TAGS));
followingUserNotification.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT));
rslts.add(followingUserNotification);
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [followingUser] notifications", e);
throw new ServiceException(e);
}
}
/**
* Gets 'broadcast' type notifications with the specified user id, current page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return result json object, for example, <pre>
* {
* "paginationRecordCount": int,
* "rslts": java.util.List[{
* "oId": "", // notification record id
* "authorName": "",
* "content": "",
* "thumbnailURL": "",
* "articleTitle": "",
* "articleType": int,
* "articleTags": "",
* "articleCommentCnt": int,
* "url": "",
* "createTime": java.util.Date,
* "hasRead": boolean,
* "type": "", // article/comment
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getBroadcastNotifications(final String userId, final int currentPageNum, final int pageSize)
throws ServiceException {
final JSONObject ret = new JSONObject();
final List<JSONObject> rslts = new ArrayList<JSONObject>();
ret.put(Keys.RESULTS, (Object) rslts);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL, Notification.DATA_TYPE_C_BROADCAST));
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).
setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).
addSort(Notification.NOTIFICATION_HAS_READ, SortDirection.ASCENDING).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
try {
final JSONObject queryResult = notificationRepository.get(query);
final JSONArray results = queryResult.optJSONArray(Keys.RESULTS);
ret.put(Pagination.PAGINATION_RECORD_COUNT,
queryResult.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT));
for (int i = 0; i < results.length(); i++) {
final JSONObject notification = results.optJSONObject(i);
final String articleId = notification.optString(Notification.NOTIFICATION_DATA_ID);
final Query q = new Query().setPageCount(1).
addProjection(Article.ARTICLE_TITLE, String.class).
addProjection(Article.ARTICLE_TYPE, Integer.class).
addProjection(Article.ARTICLE_AUTHOR_EMAIL, String.class).
addProjection(Article.ARTICLE_PERMALINK, String.class).
addProjection(Article.ARTICLE_CREATE_TIME, Long.class).
addProjection(Article.ARTICLE_TAGS, String.class).
addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class).
setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL, articleId));
final JSONArray rlts = articleRepository.get(q).optJSONArray(Keys.RESULTS);
final JSONObject article = rlts.optJSONObject(0);
if (null == article) {
LOGGER.warn("Not found article[id=" + articleId + ']');
continue;
}
final String articleTitle = article.optString(Article.ARTICLE_TITLE);
final String articleAuthorEmail = article.optString(Article.ARTICLE_AUTHOR_EMAIL);
final JSONObject author = userRepository.getByEmail(articleAuthorEmail);
if (null == author) {
LOGGER.warn("Not found user[email=" + articleAuthorEmail + ']');
continue;
}
final JSONObject broadcastNotification = new JSONObject();
broadcastNotification.put(Keys.OBJECT_ID, notification.optString(Keys.OBJECT_ID));
broadcastNotification.put(Common.AUTHOR_NAME, author.optString(User.USER_NAME));
broadcastNotification.put(Common.CONTENT, "");
broadcastNotification.put(Common.THUMBNAIL_URL, avatarQueryService.getAvatarURL(articleAuthorEmail));
broadcastNotification.put(Common.THUMBNAIL_UPDATE_TIME, author.optLong(UserExt.USER_UPDATE_TIME));
broadcastNotification.put(Article.ARTICLE_TITLE, articleTitle);
broadcastNotification.put(Common.URL, article.optString(Article.ARTICLE_PERMALINK));
broadcastNotification.put(Common.CREATE_TIME, new Date(article.optLong(Article.ARTICLE_CREATE_TIME)));
broadcastNotification.put(Notification.NOTIFICATION_HAS_READ,
notification.optBoolean(Notification.NOTIFICATION_HAS_READ));
broadcastNotification.put(Common.TYPE, Article.ARTICLE);
broadcastNotification.put(Article.ARTICLE_TYPE, article.optInt(Article.ARTICLE_TYPE));
broadcastNotification.put(Article.ARTICLE_TAGS, article.optString(Article.ARTICLE_TAGS));
broadcastNotification.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT));
rslts.add(broadcastNotification);
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [broadcast] notifications", e);
throw new ServiceException(e);
}
}
}
|
src/main/java/org/b3log/symphony/service/NotificationQueryService.java
|
/*
* Copyright (c) 2012-2016, b3log.org & hacpai.com & fangstar.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.symphony.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import org.b3log.latke.Keys;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Pagination;
import org.b3log.latke.model.User;
import org.b3log.latke.repository.CompositeFilter;
import org.b3log.latke.repository.CompositeFilterOperator;
import org.b3log.latke.repository.Filter;
import org.b3log.latke.repository.FilterOperator;
import org.b3log.latke.repository.PropertyFilter;
import org.b3log.latke.repository.Query;
import org.b3log.latke.repository.RepositoryException;
import org.b3log.latke.repository.SortDirection;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service;
import org.b3log.symphony.model.Article;
import org.b3log.symphony.model.Comment;
import org.b3log.symphony.model.Common;
import org.b3log.symphony.model.Notification;
import org.b3log.symphony.model.Pointtransfer;
import org.b3log.symphony.model.Reward;
import org.b3log.symphony.model.UserExt;
import org.b3log.symphony.repository.ArticleRepository;
import org.b3log.symphony.repository.CommentRepository;
import org.b3log.symphony.repository.NotificationRepository;
import org.b3log.symphony.repository.PointtransferRepository;
import org.b3log.symphony.repository.RewardRepository;
import org.b3log.symphony.repository.UserRepository;
import org.b3log.symphony.util.Emotions;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Notification query service.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.4.0.4, Feb 23, 2016
* @since 0.2.5
*/
@Service
public class NotificationQueryService {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(NotificationQueryService.class.getName());
/**
* Notification repository.
*/
@Inject
private NotificationRepository notificationRepository;
/**
* Article repository.
*/
@Inject
private ArticleRepository articleRepository;
/**
* Comment query service.
*/
@Inject
private CommentQueryService commentQueryService;
/**
* User repository.
*/
@Inject
private UserRepository userRepository;
/**
* Comment repository.
*/
@Inject
private CommentRepository commentRepository;
/**
* Reward repository.
*/
@Inject
private RewardRepository rewardRepository;
/**
* Pointtransfer repository.
*/
@Inject
private PointtransferRepository pointtransferRepository;
/**
* Avatar query service.
*/
@Inject
private AvatarQueryService avatarQueryService;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Gets the count of unread notifications of a user specified with the given user id.
*
* @param userId the given user id
* @return count of unread notifications, returns {@code 0} if occurs exception
*/
public int getUnreadNotificationCount(final String userId) {
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_HAS_READ, FilterOperator.EQUAL, false));
final Query query = new Query();
query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).addProjection(Keys.OBJECT_ID, String.class);
try {
final JSONObject result = notificationRepository.get(query);
return result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets unread notification count failed [userId=" + userId + "]", e);
return 0;
}
}
/**
* Gets the count of unread notifications of a user specified with the given user id and data type.
*
* @param userId the given user id
* @param notificationDataType the specified notification data type
* @return count of unread notifications, returns {@code 0} if occurs exception
* @see Notification#DATA_TYPE_C_ARTICLE
* @see Notification#DATA_TYPE_C_AT
* @see Notification#DATA_TYPE_C_COMMENT
* @see Notification#DATA_TYPE_C_COMMENTED
* @see Notification#DATA_TYPE_C_BROADCAST
*/
public int getUnreadNotificationCountByType(final String userId, final int notificationDataType) {
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_HAS_READ, FilterOperator.EQUAL, false));
filters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL, notificationDataType));
final Query query = new Query();
query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).addProjection(Keys.OBJECT_ID, String.class);
try {
final JSONObject result = notificationRepository.get(query);
return result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [commented] notification count failed [userId=" + userId + "]", e);
return 0;
}
}
/**
* Gets the count of unread 'point' notifications of a user specified with the given user id.
*
* @param userId the given user id
* @return count of unread notifications, returns {@code 0} if occurs exception
* @see Notification#DATA_TYPE_C_POINT_ARTICLE_REWARD
* @see Notification#DATA_TYPE_C_POINT_CHARGE
* @see Notification#DATA_TYPE_C_POINT_EXCHANGE
* @see Notification#DATA_TYPE_C_ABUSE_POINT_DEDUCT
* @see Notification#DATA_TYPE_C_POINT_COMMENT_THANK
* @see Notification#DATA_TYPE_C_POINT_TRANSFER
*/
public int getUnreadPointNotificationCount(final String userId) {
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_HAS_READ, FilterOperator.EQUAL, false));
final List<Filter> subFilters = new ArrayList<Filter>();
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_ARTICLE_REWARD));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_CHARGE));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_EXCHANGE));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_ABUSE_POINT_DEDUCT));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_COMMENT_THANK));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_TRANSFER));
filters.add(new CompositeFilter(CompositeFilterOperator.OR, subFilters));
final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
try {
final JSONObject result = notificationRepository.get(query);
return result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [commented] notification count failed [userId=" + userId + "]", e);
return 0;
}
}
/**
* Gets 'point' type notifications with the specified user id, current page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return result json object, for example, <pre>
* {
* "paginationRecordCount": int,
* "rslts": java.util.List[{
* "oId": "", // notification record id
* "description": int,
* "hasRead": boolean
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getPointNotifications(final String userId, final int currentPageNum, final int pageSize)
throws ServiceException {
final JSONObject ret = new JSONObject();
final List<JSONObject> rslts = new ArrayList<JSONObject>();
ret.put(Keys.RESULTS, (Object) rslts);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
final List<Filter> subFilters = new ArrayList<Filter>();
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_ARTICLE_REWARD));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_CHARGE));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_EXCHANGE));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_ABUSE_POINT_DEDUCT));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_COMMENT_THANK));
subFilters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL,
Notification.DATA_TYPE_C_POINT_TRANSFER));
filters.add(new CompositeFilter(CompositeFilterOperator.OR, subFilters));
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).
setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).
addSort(Notification.NOTIFICATION_HAS_READ, SortDirection.ASCENDING).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
try {
final JSONObject queryResult = notificationRepository.get(query);
final JSONArray results = queryResult.optJSONArray(Keys.RESULTS);
ret.put(Pagination.PAGINATION_RECORD_COUNT,
queryResult.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT));
for (int i = 0; i < results.length(); i++) {
final JSONObject notification = results.optJSONObject(i);
final String dataId = notification.optString(Notification.NOTIFICATION_DATA_ID);
final int dataType = notification.optInt(Notification.NOTIFICATION_DATA_TYPE);
String desTemplate = "";
switch (dataType) {
case Notification.DATA_TYPE_C_POINT_ARTICLE_REWARD:
desTemplate = langPropsService.get("notificationArticleRewardLabel");
final JSONObject reward7 = rewardRepository.get(dataId);
final String senderId7 = reward7.optString(Reward.SENDER_ID);
final JSONObject user7 = userRepository.get(senderId7);
final String articleId7 = reward7.optString(Reward.DATA_ID);
final JSONObject article7 = articleRepository.get(articleId7);
final String userLink7 = "<a href=\"/member/" + user7.optString(User.USER_NAME) + "\">"
+ user7.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", userLink7);
final String articleLink7 = "<a href=\""
+ article7.optString(Article.ARTICLE_PERMALINK) + "\">"
+ article7.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", articleLink7);
break;
case Notification.DATA_TYPE_C_POINT_CHARGE:
desTemplate = langPropsService.get("notificationPointChargeLabel");
final JSONObject transfer5 = pointtransferRepository.get(dataId);
final int sum5 = transfer5.optInt(Pointtransfer.SUM);
final String memo5 = transfer5.optString(Pointtransfer.DATA_ID);
final String yuan = memo5.split("-")[0];
desTemplate = desTemplate.replace("{yuan}", yuan);
desTemplate = desTemplate.replace("{point}", String.valueOf(sum5));
break;
case Notification.DATA_TYPE_C_POINT_EXCHANGE:
desTemplate = langPropsService.get("notificationPointExchangeLabel");
final JSONObject transfer6 = pointtransferRepository.get(dataId);
final int sum6 = transfer6.optInt(Pointtransfer.SUM);
final String yuan6 = transfer6.optString(Pointtransfer.DATA_ID);
desTemplate = desTemplate.replace("{yuan}", yuan6);
desTemplate = desTemplate.replace("{point}", String.valueOf(sum6));
break;
case Notification.DATA_TYPE_C_ABUSE_POINT_DEDUCT:
desTemplate = langPropsService.get("notificationAbusePointDeductLabel");
final JSONObject transfer7 = pointtransferRepository.get(dataId);
final int sum7 = transfer7.optInt(Pointtransfer.SUM);
final String memo7 = transfer7.optString(Pointtransfer.DATA_ID);
desTemplate = desTemplate.replace("{action}", memo7);
desTemplate = desTemplate.replace("{point}", String.valueOf(sum7));
break;
case Notification.DATA_TYPE_C_POINT_COMMENT_THANK:
desTemplate = langPropsService.get("notificationCmtThankLabel");
final JSONObject reward8 = rewardRepository.get(dataId);
final String senderId8 = reward8.optString(Reward.SENDER_ID);
final JSONObject user8 = userRepository.get(senderId8);
final JSONObject comment8 = commentRepository.get(reward8.optString(Reward.DATA_ID));
final String articleId8 = comment8.optString(Comment.COMMENT_ON_ARTICLE_ID);
final JSONObject article8 = articleRepository.get(articleId8);
final String userLink8 = "<a href=\"/member/" + user8.optString(User.USER_NAME) + "\">"
+ user8.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", userLink8);
final String articleLink8 = "<a href=\""
+ article8.optString(Article.ARTICLE_PERMALINK) + "\">"
+ article8.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", articleLink8);
break;
case Notification.DATA_TYPE_C_POINT_TRANSFER:
desTemplate = langPropsService.get("notificationPointTransferLabel");
final JSONObject transfer101 = pointtransferRepository.get(dataId);
final String fromId101 = transfer101.optString(Pointtransfer.FROM_ID);
final JSONObject user101 = userRepository.get(fromId101);
final int sum101 = transfer101.optInt(Pointtransfer.SUM);
final String userLink101 = "<a href=\"/member/" + user101.optString(User.USER_NAME) + "\">"
+ user101.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", userLink101);
desTemplate = desTemplate.replace("{amount}", String.valueOf(sum101));
break;
default:
throw new AssertionError();
}
notification.put(Common.DESCRIPTION, desTemplate);
rslts.add(notification);
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [commented] notifications", e);
throw new ServiceException(e);
}
}
/**
* Gets 'commented' type notifications with the specified user id, current page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return result json object, for example, <pre>
* {
* "paginationRecordCount": int,
* "rslts": java.util.List[{
* "oId": "", // notification record id
* "commentAuthorName": "",
* "commentContent": "",
* "commentAuthorThumbnailURL": "",
* "commentArticleTitle": "",
* "commentArticleType": int,
* "commentSharpURL": "",
* "commentCreateTime": java.util.Date,
* "hasRead": boolean
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getCommentedNotifications(final String userId, final int currentPageNum, final int pageSize)
throws ServiceException {
final JSONObject ret = new JSONObject();
final List<JSONObject> rslts = new ArrayList<JSONObject>();
ret.put(Keys.RESULTS, (Object) rslts);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL, Notification.DATA_TYPE_C_COMMENTED));
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).
setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).
addSort(Notification.NOTIFICATION_HAS_READ, SortDirection.ASCENDING).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
try {
final JSONObject queryResult = notificationRepository.get(query);
final JSONArray results = queryResult.optJSONArray(Keys.RESULTS);
ret.put(Pagination.PAGINATION_RECORD_COUNT,
queryResult.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT));
for (int i = 0; i < results.length(); i++) {
final JSONObject notification = results.optJSONObject(i);
final String commentId = notification.optString(Notification.NOTIFICATION_DATA_ID);
final JSONObject comment = commentQueryService.getCommentById(commentId);
final Query q = new Query().setPageCount(1).
addProjection(Article.ARTICLE_TITLE, String.class).
addProjection(Article.ARTICLE_TYPE, Integer.class).
setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL,
comment.optString(Comment.COMMENT_ON_ARTICLE_ID)));
final JSONArray rlts = articleRepository.get(q).optJSONArray(Keys.RESULTS);
final JSONObject article = rlts.optJSONObject(0);
final String articleTitle = article.optString(Article.ARTICLE_TITLE);
final int articleType = article.optInt(Article.ARTICLE_TYPE);
final JSONObject commentedNotification = new JSONObject();
commentedNotification.put(Keys.OBJECT_ID, notification.optString(Keys.OBJECT_ID));
commentedNotification.put(Comment.COMMENT_T_AUTHOR_NAME, comment.optString(Comment.COMMENT_T_AUTHOR_NAME));
commentedNotification.put(Comment.COMMENT_CONTENT, comment.optString(Comment.COMMENT_CONTENT));
commentedNotification.put(Comment.COMMENT_T_AUTHOR_THUMBNAIL_URL,
comment.optString(Comment.COMMENT_T_AUTHOR_THUMBNAIL_URL));
commentedNotification.put(Common.THUMBNAIL_UPDATE_TIME, comment.optJSONObject(Comment.COMMENT_T_COMMENTER).
optLong(UserExt.USER_UPDATE_TIME));
commentedNotification.put(Comment.COMMENT_T_ARTICLE_TITLE, Emotions.convert(articleTitle));
commentedNotification.put(Comment.COMMENT_T_ARTICLE_TYPE, articleType);
commentedNotification.put(Comment.COMMENT_SHARP_URL, comment.optString(Comment.COMMENT_SHARP_URL));
commentedNotification.put(Comment.COMMENT_CREATE_TIME, comment.opt(Comment.COMMENT_CREATE_TIME));
commentedNotification.put(Notification.NOTIFICATION_HAS_READ, notification.optBoolean(Notification.NOTIFICATION_HAS_READ));
rslts.add(commentedNotification);
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [commented] notifications", e);
throw new ServiceException(e);
}
}
/**
* Gets 'at' type notifications with the specified user id, current page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return result json object, for example, <pre>
* {
* "paginationRecordCount": int,
* "rslts": java.util.List[{
* "oId": "", // notification record id
* "authorName": "",
* "content": "",
* "thumbnailURL": "",
* "articleTitle": "",
* "articleType": int,
* "url": "",
* "createTime": java.util.Date,
* "hasRead": boolean,
* "atInArticle": boolean,
* "articleTags": "", // if atInArticle is true
* "articleCommentCnt": int // if atInArticle is true
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getAtNotifications(final String userId, final int currentPageNum, final int pageSize)
throws ServiceException {
final JSONObject ret = new JSONObject();
final List<JSONObject> rslts = new ArrayList<JSONObject>();
ret.put(Keys.RESULTS, (Object) rslts);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL, Notification.DATA_TYPE_C_AT));
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).
setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).
addSort(Notification.NOTIFICATION_HAS_READ, SortDirection.ASCENDING).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
try {
final JSONObject queryResult = notificationRepository.get(query);
final JSONArray results = queryResult.optJSONArray(Keys.RESULTS);
ret.put(Pagination.PAGINATION_RECORD_COUNT,
queryResult.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT));
for (int i = 0; i < results.length(); i++) {
final JSONObject notification = results.optJSONObject(i);
final String commentId = notification.optString(Notification.NOTIFICATION_DATA_ID);
final JSONObject comment = commentQueryService.getCommentById(commentId);
if (null != comment) {
final Query q = new Query().setPageCount(1).
addProjection(Article.ARTICLE_TITLE, String.class).
addProjection(Article.ARTICLE_TYPE, Integer.class).
setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL,
comment.optString(Comment.COMMENT_ON_ARTICLE_ID)));
final JSONArray rlts = articleRepository.get(q).optJSONArray(Keys.RESULTS);
final JSONObject article = rlts.optJSONObject(0);
final String articleTitle = article.optString(Article.ARTICLE_TITLE);
final int articleType = article.optInt(Article.ARTICLE_TYPE);
final JSONObject atNotification = new JSONObject();
atNotification.put(Keys.OBJECT_ID, notification.optString(Keys.OBJECT_ID));
atNotification.put(Common.AUTHOR_NAME, comment.optString(Comment.COMMENT_T_AUTHOR_NAME));
atNotification.put(Common.CONTENT, comment.optString(Comment.COMMENT_CONTENT));
atNotification.put(Common.THUMBNAIL_URL,
comment.optString(Comment.COMMENT_T_AUTHOR_THUMBNAIL_URL));
atNotification.put(Common.THUMBNAIL_UPDATE_TIME, comment.optJSONObject(Comment.COMMENT_T_COMMENTER).
optLong(UserExt.USER_UPDATE_TIME));
atNotification.put(Article.ARTICLE_TITLE, articleTitle);
atNotification.put(Article.ARTICLE_TYPE, articleType);
atNotification.put(Common.URL, comment.optString(Comment.COMMENT_SHARP_URL));
atNotification.put(Common.CREATE_TIME, comment.opt(Comment.COMMENT_CREATE_TIME));
atNotification.put(Notification.NOTIFICATION_HAS_READ, notification.optBoolean(Notification.NOTIFICATION_HAS_READ));
atNotification.put(Notification.NOTIFICATION_T_AT_IN_ARTICLE, false);
rslts.add(atNotification);
} else { // The 'at' in article content
final JSONObject article = articleRepository.get(commentId);
final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject articleAuthor = userRepository.get(articleAuthorId);
final JSONObject atNotification = new JSONObject();
atNotification.put(Keys.OBJECT_ID, notification.optString(Keys.OBJECT_ID));
atNotification.put(Common.AUTHOR_NAME, articleAuthor.optString(User.USER_NAME));
atNotification.put(Common.CONTENT, "");
final String thumbnailURL = avatarQueryService.getAvatarURL(articleAuthor.optString(User.USER_EMAIL));
atNotification.put(Common.THUMBNAIL_URL, thumbnailURL);
atNotification.put(Common.THUMBNAIL_UPDATE_TIME, articleAuthor.optLong(UserExt.USER_UPDATE_TIME));
atNotification.put(Article.ARTICLE_TITLE, article.optString(Article.ARTICLE_TITLE));
atNotification.put(Article.ARTICLE_TYPE, article.optInt(Article.ARTICLE_TYPE));
atNotification.put(Common.URL, article.optString(Article.ARTICLE_PERMALINK));
atNotification.put(Common.CREATE_TIME, new Date(article.optLong(Article.ARTICLE_CREATE_TIME)));
atNotification.put(Notification.NOTIFICATION_HAS_READ, notification.optBoolean(Notification.NOTIFICATION_HAS_READ));
atNotification.put(Notification.NOTIFICATION_T_AT_IN_ARTICLE, true);
atNotification.put(Article.ARTICLE_TAGS, article.optString(Article.ARTICLE_TAGS));
atNotification.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT));
rslts.add(atNotification);
}
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [at] notifications", e);
throw new ServiceException(e);
}
}
/**
* Gets 'followingUser' type notifications with the specified user id, current page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return result json object, for example, <pre>
* {
* "paginationRecordCount": int,
* "rslts": java.util.List[{
* "oId": "", // notification record id
* "authorName": "",
* "content": "",
* "thumbnailURL": "",
* "articleTitle": "",
* "articleType": int,
* "articleTags": "",
* "articleCommentCnt": int,
* "url": "",
* "createTime": java.util.Date,
* "hasRead": boolean,
* "type": "", // article/comment
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getFollowingUserNotifications(final String userId, final int currentPageNum, final int pageSize)
throws ServiceException {
final JSONObject ret = new JSONObject();
final List<JSONObject> rslts = new ArrayList<JSONObject>();
ret.put(Keys.RESULTS, (Object) rslts);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL, Notification.DATA_TYPE_C_FOLLOWING_USER));
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).
setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).
addSort(Notification.NOTIFICATION_HAS_READ, SortDirection.ASCENDING).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
try {
final JSONObject queryResult = notificationRepository.get(query);
final JSONArray results = queryResult.optJSONArray(Keys.RESULTS);
ret.put(Pagination.PAGINATION_RECORD_COUNT,
queryResult.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT));
for (int i = 0; i < results.length(); i++) {
final JSONObject notification = results.optJSONObject(i);
final String articleId = notification.optString(Notification.NOTIFICATION_DATA_ID);
final Query q = new Query().setPageCount(1).
addProjection(Article.ARTICLE_TITLE, String.class).
addProjection(Article.ARTICLE_TYPE, Integer.class).
addProjection(Article.ARTICLE_AUTHOR_EMAIL, String.class).
addProjection(Article.ARTICLE_PERMALINK, String.class).
addProjection(Article.ARTICLE_CREATE_TIME, Long.class).
addProjection(Article.ARTICLE_TAGS, String.class).
addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class).
setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL, articleId));
final JSONArray rlts = articleRepository.get(q).optJSONArray(Keys.RESULTS);
final JSONObject article = rlts.optJSONObject(0);
if (null == article) {
LOGGER.warn("Not found article[id=" + articleId + ']');
continue;
}
final String articleTitle = article.optString(Article.ARTICLE_TITLE);
final String articleAuthorEmail = article.optString(Article.ARTICLE_AUTHOR_EMAIL);
final JSONObject author = userRepository.getByEmail(articleAuthorEmail);
if (null == author) {
LOGGER.warn("Not found user[email=" + articleAuthorEmail + ']');
continue;
}
final JSONObject followingUserNotification = new JSONObject();
followingUserNotification.put(Keys.OBJECT_ID, notification.optString(Keys.OBJECT_ID));
followingUserNotification.put(Common.AUTHOR_NAME, author.optString(User.USER_NAME));
followingUserNotification.put(Common.CONTENT, "");
followingUserNotification.put(Common.THUMBNAIL_URL, avatarQueryService.getAvatarURL(articleAuthorEmail));
followingUserNotification.put(Common.THUMBNAIL_UPDATE_TIME, author.optLong(UserExt.USER_UPDATE_TIME));
followingUserNotification.put(Article.ARTICLE_TITLE, articleTitle);
followingUserNotification.put(Common.URL, article.optString(Article.ARTICLE_PERMALINK));
followingUserNotification.put(Common.CREATE_TIME, new Date(article.optLong(Article.ARTICLE_CREATE_TIME)));
followingUserNotification.put(Notification.NOTIFICATION_HAS_READ,
notification.optBoolean(Notification.NOTIFICATION_HAS_READ));
followingUserNotification.put(Common.TYPE, Article.ARTICLE);
followingUserNotification.put(Article.ARTICLE_TYPE, article.optInt(Article.ARTICLE_TYPE));
followingUserNotification.put(Article.ARTICLE_TAGS, article.optString(Article.ARTICLE_TAGS));
followingUserNotification.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT));
rslts.add(followingUserNotification);
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [followingUser] notifications", e);
throw new ServiceException(e);
}
}
/**
* Gets 'broadcast' type notifications with the specified user id, current page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return result json object, for example, <pre>
* {
* "paginationRecordCount": int,
* "rslts": java.util.List[{
* "oId": "", // notification record id
* "authorName": "",
* "content": "",
* "thumbnailURL": "",
* "articleTitle": "",
* "articleType": int,
* "articleTags": "",
* "articleCommentCnt": int,
* "url": "",
* "createTime": java.util.Date,
* "hasRead": boolean,
* "type": "", // article/comment
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getBroadcastNotifications(final String userId, final int currentPageNum, final int pageSize)
throws ServiceException {
final JSONObject ret = new JSONObject();
final List<JSONObject> rslts = new ArrayList<JSONObject>();
ret.put(Keys.RESULTS, (Object) rslts);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL, Notification.DATA_TYPE_C_BROADCAST));
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).
setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).
addSort(Notification.NOTIFICATION_HAS_READ, SortDirection.ASCENDING).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
try {
final JSONObject queryResult = notificationRepository.get(query);
final JSONArray results = queryResult.optJSONArray(Keys.RESULTS);
ret.put(Pagination.PAGINATION_RECORD_COUNT,
queryResult.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT));
for (int i = 0; i < results.length(); i++) {
final JSONObject notification = results.optJSONObject(i);
final String articleId = notification.optString(Notification.NOTIFICATION_DATA_ID);
final Query q = new Query().setPageCount(1).
addProjection(Article.ARTICLE_TITLE, String.class).
addProjection(Article.ARTICLE_TYPE, Integer.class).
addProjection(Article.ARTICLE_AUTHOR_EMAIL, String.class).
addProjection(Article.ARTICLE_PERMALINK, String.class).
addProjection(Article.ARTICLE_CREATE_TIME, Long.class).
addProjection(Article.ARTICLE_TAGS, String.class).
addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class).
setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL, articleId));
final JSONArray rlts = articleRepository.get(q).optJSONArray(Keys.RESULTS);
final JSONObject article = rlts.optJSONObject(0);
if (null == article) {
LOGGER.warn("Not found article[id=" + articleId + ']');
continue;
}
final String articleTitle = article.optString(Article.ARTICLE_TITLE);
final String articleAuthorEmail = article.optString(Article.ARTICLE_AUTHOR_EMAIL);
final JSONObject author = userRepository.getByEmail(articleAuthorEmail);
if (null == author) {
LOGGER.warn("Not found user[email=" + articleAuthorEmail + ']');
continue;
}
final JSONObject broadcastNotification = new JSONObject();
broadcastNotification.put(Keys.OBJECT_ID, notification.optString(Keys.OBJECT_ID));
broadcastNotification.put(Common.AUTHOR_NAME, author.optString(User.USER_NAME));
broadcastNotification.put(Common.CONTENT, "");
broadcastNotification.put(Common.THUMBNAIL_URL, avatarQueryService.getAvatarURL(articleAuthorEmail));
broadcastNotification.put(Common.THUMBNAIL_UPDATE_TIME, author.optLong(UserExt.USER_UPDATE_TIME));
broadcastNotification.put(Article.ARTICLE_TITLE, articleTitle);
broadcastNotification.put(Common.URL, article.optString(Article.ARTICLE_PERMALINK));
broadcastNotification.put(Common.CREATE_TIME, new Date(article.optLong(Article.ARTICLE_CREATE_TIME)));
broadcastNotification.put(Notification.NOTIFICATION_HAS_READ,
notification.optBoolean(Notification.NOTIFICATION_HAS_READ));
broadcastNotification.put(Common.TYPE, Article.ARTICLE);
broadcastNotification.put(Article.ARTICLE_TYPE, article.optInt(Article.ARTICLE_TYPE));
broadcastNotification.put(Article.ARTICLE_TAGS, article.optString(Article.ARTICLE_TAGS));
broadcastNotification.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT));
rslts.add(broadcastNotification);
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets [broadcast] notifications", e);
throw new ServiceException(e);
}
}
}
|
完善通知中的 emoji 处理
|
src/main/java/org/b3log/symphony/service/NotificationQueryService.java
|
完善通知中的 emoji 处理
|
<ide><path>rc/main/java/org/b3log/symphony/service/NotificationQueryService.java
<ide> * Notification query service.
<ide> *
<ide> * @author <a href="http://88250.b3log.org">Liang Ding</a>
<del> * @version 1.4.0.4, Feb 23, 2016
<add> * @version 1.4.1.4, Feb 26, 2016
<ide> * @since 0.2.5
<ide> */
<ide> @Service
<ide> final String thumbnailURL = avatarQueryService.getAvatarURL(articleAuthor.optString(User.USER_EMAIL));
<ide> atNotification.put(Common.THUMBNAIL_URL, thumbnailURL);
<ide> atNotification.put(Common.THUMBNAIL_UPDATE_TIME, articleAuthor.optLong(UserExt.USER_UPDATE_TIME));
<del> atNotification.put(Article.ARTICLE_TITLE, article.optString(Article.ARTICLE_TITLE));
<add> atNotification.put(Article.ARTICLE_TITLE, Emotions.convert(article.optString(Article.ARTICLE_TITLE)));
<ide> atNotification.put(Article.ARTICLE_TYPE, article.optInt(Article.ARTICLE_TYPE));
<ide> atNotification.put(Common.URL, article.optString(Article.ARTICLE_PERMALINK));
<ide> atNotification.put(Common.CREATE_TIME, new Date(article.optLong(Article.ARTICLE_CREATE_TIME)));
<ide> followingUserNotification.put(Common.CONTENT, "");
<ide> followingUserNotification.put(Common.THUMBNAIL_URL, avatarQueryService.getAvatarURL(articleAuthorEmail));
<ide> followingUserNotification.put(Common.THUMBNAIL_UPDATE_TIME, author.optLong(UserExt.USER_UPDATE_TIME));
<del> followingUserNotification.put(Article.ARTICLE_TITLE, articleTitle);
<add> followingUserNotification.put(Article.ARTICLE_TITLE, Emotions.convert(articleTitle));
<ide> followingUserNotification.put(Common.URL, article.optString(Article.ARTICLE_PERMALINK));
<ide> followingUserNotification.put(Common.CREATE_TIME, new Date(article.optLong(Article.ARTICLE_CREATE_TIME)));
<ide> followingUserNotification.put(Notification.NOTIFICATION_HAS_READ,
|
|
JavaScript
|
mit
|
781bda3a27cd7034fd406f685bacba083a530f5f
| 0 |
Ajnasz/hupper,Ajnasz/hupper
|
/*jshint esnext:true*/
/*global chrome*/
(function (req) {
'use strict';
let func = req('func');
let modBlocks = req('blocks');
let modArticles = req('articles');
let modHupperBlock = req('hupper-block');
function addHupperBlock() {
return new Promise(function (resolve) {
modHupperBlock.addHupperBlock();
document.getElementById('block-hupper').addEventListener('click', function (e) {
let event = modBlocks.onBlockControlClick(e);
if (event) {
chrome.runtime.sendMessage({'event': 'block.action', data: event});
}
}, false);
resolve();
});
}
function onGetArticles() {
let articles = modArticles.parseArticles();
if (articles.length > 0) {
chrome.runtime.sendMessage({'event': 'gotArticles', data: articles});
}
}
function onArticlesMarkNew(data) {
data.articles.map(modArticles.articleStructToArticleNodeStruct)
.forEach(func.partial(modArticles.markNewArticle, data.text));
}
function onArticleAddNextPrev(item) {
if (item.prevId) {
modArticles.addLinkToPrevArticle(item.id, item.prevId);
}
if (item.nextId) {
modArticles.addLinkToNextArticle(item.id, item.nextId);
}
}
function onAddCategoryHideButton(items) {
modArticles.onAddCategoryHideButton(items);
}
function onArticlesHide(articles) {
modArticles.hideArticles(articles);
}
function onGetComments(options) {
let commentsContainer = document.getElementById('comments');
if (!commentsContainer) {
return;
}
let modComment = req('comment');
let modCommentTree = req('commenttree');
console.log('subscribe');
document.querySelector('body').addEventListener('click', modComment.onBodyClick, false);
commentsContainer.addEventListener('click', modComment.onCommentsContainerClick, false);
chrome.runtime.sendMessage({
event: 'gotComments',
data: modComment.convertComments(modCommentTree.getCommentTree(), options)
});
}
function onGetBlocks() {
chrome.runtime.sendMessage({
event: 'gotBlocks',
data: modBlocks.getBlocks()
});
}
function onCommentSetNew(newComments) {
req('comment').onCommentSetNew(newComments);
}
function onCommentAddNextPrev(item) {
req('comment').onCommentAddNextPrev(item);
}
function onBlocakChangeOrderAll(data) {
modBlocks.reorderBlocks(data);
setTimeout(function () {
chrome.runtime.sendMessage({event: 'blocks.change-order-all-done'});
}, 5);
}
function onBlockChangeOrder(data) {
modBlocks.setBlockOrder(data.sidebar, data.blocks);
}
function onBlockChangeColunn(data) {
modBlocks.reorderBlocks(data);
}
function onBlockShow(data) {
modBlocks.show(data);
}
function onBlockHideContent(data) {
modBlocks.hideContent(data);
}
function onBlockShowContent(data) {
modBlocks.showContent(data);
}
function onBlockHide(data) {
modBlocks.hide(data);
}
function onBlockSetTitles(data) {
modBlocks.setTitles(data);
}
function onHighlightUser(data) {
return data;
}
function onUnhighlightUser(data) {
return data;
}
function onTrollUser(data) {
return data;
}
function onUntrollUser(data) {
return data;
}
function onEnableBlockControls(blocks) {
modBlocks.onEnableBlockControls(blocks, function (event) {
chrome.runtime.sendMessage({event: 'block.action', data: event});
});
}
window.addEventListener('DOMContentLoaded', function () {
chrome.runtime.onMessage.addListener(function (request, sender) {
let event = request.event;
let data = request.data;
switch (event) {
case 'getArticles':
onGetArticles(data);
break;
case 'getComments':
onGetComments(data);
break;
case 'getBlocks':
onGetBlocks(data);
break;
case 'comments.update':
req('comment').onCommentUpdate(data);
break;
case 'comment.setNew':
onCommentSetNew(data);
break;
case 'comment.addNextPrev':
onCommentAddNextPrev(data);
break;
case 'comment.addParentLink':
req('comment').addParentLinkToComments(data);
break;
case 'comment.addExpandLink':
req('comment').addExpandLinkToComments(data);
break;
case 'articles.mark-new':
onArticlesMarkNew(data);
break;
case 'articles.addNextPrev':
onArticleAddNextPrev(data);
break;
case 'articles.add-category-hide-button':
onAddCategoryHideButton(data);
break;
case 'articles.hide':
onArticlesHide(data);
break;
case 'block.hide':
onBlockHide(data);
break;
case 'enableBlockControls':
onEnableBlockControls(data);
break;
case 'block.show':
onBlockShow(data);
break;
case 'block.hide-content':
onBlockHideContent(data);
break;
case 'block.show-content':
onBlockShowContent(data);
break;
case 'blocks.change-order-all':
onBlocakChangeOrderAll(data);
break;
case 'block.change-order':
onBlockChangeOrder(data);
break;
case 'block.change-column':
onBlockChangeColunn(data);
break;
case 'blocks.set-titles':
onBlockSetTitles(data);
break;
case 'trolluser':
onTrollUser(data);
break;
case 'untrolluser':
onUntrollUser(data);
break;
case 'highlightuser':
onHighlightUser(data);
break;
case 'unhighlightuser':
onUnhighlightUser(data);
break;
case 'hupper-block.add-menu':
modHupperBlock.addMenuItem(data);
break;
case 'hupper-block.hide-block':
modHupperBlock.addHiddenBlock(data);
break;
case 'hupper-block.show-block':
modHupperBlock.removeHiddenBlock(data);
break;
default:
console.info('Missing event handler for %s', event);
break;
}
console.log('message request', request, sender);
});
document.getElementById('content-both').addEventListener('click', function (e) {
if (e.target.classList.contains('taxonomy-button')) {
let dom = req('dom');
let articleStruct = modArticles.articleElementToStruct(dom.closest(e.target, '.node'));
chrome.runtime.sendMessage({event: 'article.hide-taxonomy', data: articleStruct});
}
}, false);
addHupperBlock().then(function () {
console.log('huper block added');
});
console.log('dom content loaded');
chrome.runtime.sendMessage({'event': 'DOMContentLoaded'});
}, false);
window.addEventListener('unload', function () {
chrome.runtime.sendMessage({'event': 'unload'});
});
}(window.req));
|
chrome/data/hupper.js
|
/*jshint esnext:true*/
/*global chrome*/
(function (req) {
'use strict';
let func = req('func');
let modBlocks = req('blocks');
let modHupperBlock = req('hupper-block');
function addHupperBlock() {
return new Promise(function (resolve) {
modHupperBlock.addHupperBlock();
document.getElementById('block-hupper').addEventListener('click', function (e) {
let event = modBlocks.onBlockControlClick(e);
if (event) {
chrome.runtime.sendMessage({'event': 'block.action', data: event});
}
}, false);
resolve();
});
}
function onGetArticles() {
let modArticles = req('articles');
let articles = modArticles.parseArticles();
if (articles.length > 0) {
chrome.runtime.sendMessage({'event': 'gotArticles', data: articles});
}
}
function onArticlesMarkNew(data) {
let modArticles = req('articles');
data.articles.map(modArticles.articleStructToArticleNodeStruct)
.forEach(func.partial(modArticles.markNewArticle, data.text));
}
function onArticleAddNextPrev(item) {
let modArticles = req('articles');
if (item.prevId) {
modArticles.addLinkToPrevArticle(item.id, item.prevId);
}
if (item.nextId) {
modArticles.addLinkToNextArticle(item.id, item.nextId);
}
}
function onAddCategoryHideButton(items) {
req('articles').onAddCategoryHideButton(items);
}
function onArticlesHide(articles) {
req('articles').hideArticles(articles);
}
function onGetComments(options) {
let commentsContainer = document.getElementById('comments');
if (!commentsContainer) {
return;
}
let modComment = req('comment');
let modCommentTree = req('commenttree');
console.log('subscribe');
document.querySelector('body').addEventListener('click', modComment.onBodyClick, false);
commentsContainer.addEventListener('click', modComment.onCommentsContainerClick, false);
chrome.runtime.sendMessage({
event: 'gotComments',
data: modComment.convertComments(modCommentTree.getCommentTree(), options)
});
}
function onGetBlocks() {
let modBlocks = req('blocks');
chrome.runtime.sendMessage({
event: 'gotBlocks',
data: modBlocks.getBlocks()
});
}
function onCommentSetNew(newComments) {
req('comment').onCommentSetNew(newComments);
}
function onCommentAddNextPrev(item) {
req('comment').onCommentAddNextPrev(item);
}
function onBlocakChangeOrderAll(data) {
let modBlocks = req('blocks');
modBlocks.reorderBlocks(data);
setTimeout(function () {
chrome.runtime.sendMessage({event: 'blocks.change-order-all-done'});
}, 5);
}
function onBlockChangeOrder(data) {
let modBlocks = req('blocks');
modBlocks.setBlockOrder(data.sidebar, data.blocks);
}
function onBlockChangeColunn(data) {
let modBlocks = req('blocks');
modBlocks.reorderBlocks(data);
}
function onBlockShow(data) {
let modBlocks = req('blocks');
modBlocks.show(data);
}
function onBlockHideContent(data) {
let modBlocks = req('blocks');
modBlocks.hideContent(data);
}
function onBlockShowContent(data) {
let modBlocks = req('blocks');
modBlocks.showContent(data);
}
function onBlockHide(data) {
let modBlocks = req('blocks');
modBlocks.hide(data);
}
function onBlockSetTitles(data) {
let modBlocks = req('blocks');
modBlocks.setTitles(data);
}
function onHighlightUser(data) {
return data;
}
function onUnhighlightUser(data) {
return data;
}
function onTrollUser(data) {
return data;
}
function onUntrollUser(data) {
return data;
}
function onEnableBlockControls(blocks) {
modBlocks.onEnableBlockControls(blocks, function (event) {
chrome.runtime.sendMessage({event: 'block.action', data: event});
});
}
window.addEventListener('DOMContentLoaded', function () {
chrome.runtime.onMessage.addListener(function (request, sender) {
let event = request.event;
let data = request.data;
switch (event) {
case 'getArticles':
onGetArticles(data);
break;
case 'getComments':
onGetComments(data);
break;
case 'getBlocks':
onGetBlocks(data);
break;
case 'comments.update':
req('comment').onCommentUpdate(data);
break;
case 'comment.setNew':
onCommentSetNew(data);
break;
case 'comment.addNextPrev':
onCommentAddNextPrev(data);
break;
case 'comment.addParentLink':
req('comment').addParentLinkToComments(data);
break;
case 'comment.addExpandLink':
req('comment').addExpandLinkToComments(data);
break;
case 'articles.mark-new':
onArticlesMarkNew(data);
break;
case 'articles.addNextPrev':
onArticleAddNextPrev(data);
break;
case 'articles.add-category-hide-button':
onAddCategoryHideButton(data);
break;
case 'articles.hide':
onArticlesHide(data);
break;
case 'block.hide':
onBlockHide(data);
break;
case 'enableBlockControls':
onEnableBlockControls(data);
break;
case 'block.show':
onBlockShow(data);
break;
case 'block.hide-content':
onBlockHideContent(data);
break;
case 'block.show-content':
onBlockShowContent(data);
break;
case 'blocks.change-order-all':
onBlocakChangeOrderAll(data);
break;
case 'block.change-order':
onBlockChangeOrder(data);
break;
case 'block.change-column':
onBlockChangeColunn(data);
break;
case 'blocks.set-titles':
onBlockSetTitles(data);
break;
case 'trolluser':
onTrollUser(data);
break;
case 'untrolluser':
onUntrollUser(data);
break;
case 'highlightuser':
onHighlightUser(data);
break;
case 'unhighlightuser':
onUnhighlightUser(data);
break;
case 'hupper-block.add-menu':
modHupperBlock.addMenuItem(data);
break;
case 'hupper-block.hide-block':
modHupperBlock.addHiddenBlock(data);
break;
case 'hupper-block.show-block':
modHupperBlock.removeHiddenBlock(data);
break;
default:
console.info('Missing event handler for %s', event);
break;
}
console.log('message request', request, sender);
});
document.getElementById('content-both').addEventListener('click', function (e) {
if (e.target.classList.contains('taxonomy-button')) {
let modArticles = req('articles');
let dom = req('dom');
let articleStruct = modArticles.articleElementToStruct(dom.closest(e.target, '.node'));
chrome.runtime.sendMessage({event: 'article.hide-taxonomy', data: articleStruct});
}
}, false);
addHupperBlock().then(function () {
console.log('huper block added');
});
console.log('dom content loaded');
chrome.runtime.sendMessage({'event': 'DOMContentLoaded'});
}, false);
window.addEventListener('unload', function () {
chrome.runtime.sendMessage({'event': 'unload'});
});
}(window.req));
|
Load modules on top
|
chrome/data/hupper.js
|
Load modules on top
|
<ide><path>hrome/data/hupper.js
<ide> let func = req('func');
<ide>
<ide> let modBlocks = req('blocks');
<add> let modArticles = req('articles');
<ide> let modHupperBlock = req('hupper-block');
<ide>
<ide> function addHupperBlock() {
<ide> }
<ide>
<ide> function onGetArticles() {
<del> let modArticles = req('articles');
<ide> let articles = modArticles.parseArticles();
<ide>
<ide> if (articles.length > 0) {
<ide> }
<ide>
<ide> function onArticlesMarkNew(data) {
<del> let modArticles = req('articles');
<ide> data.articles.map(modArticles.articleStructToArticleNodeStruct)
<ide> .forEach(func.partial(modArticles.markNewArticle, data.text));
<ide>
<ide> }
<ide>
<ide> function onArticleAddNextPrev(item) {
<del> let modArticles = req('articles');
<del>
<ide> if (item.prevId) {
<ide> modArticles.addLinkToPrevArticle(item.id, item.prevId);
<ide> }
<ide> }
<ide>
<ide> function onAddCategoryHideButton(items) {
<del> req('articles').onAddCategoryHideButton(items);
<add> modArticles.onAddCategoryHideButton(items);
<ide> }
<ide>
<ide> function onArticlesHide(articles) {
<del> req('articles').hideArticles(articles);
<add> modArticles.hideArticles(articles);
<ide> }
<ide>
<ide> function onGetComments(options) {
<ide> }
<ide>
<ide> function onGetBlocks() {
<del> let modBlocks = req('blocks');
<ide> chrome.runtime.sendMessage({
<ide> event: 'gotBlocks',
<ide> data: modBlocks.getBlocks()
<ide> }
<ide>
<ide> function onBlocakChangeOrderAll(data) {
<del> let modBlocks = req('blocks');
<ide> modBlocks.reorderBlocks(data);
<ide> setTimeout(function () {
<ide> chrome.runtime.sendMessage({event: 'blocks.change-order-all-done'});
<ide> }
<ide>
<ide> function onBlockChangeOrder(data) {
<del> let modBlocks = req('blocks');
<ide> modBlocks.setBlockOrder(data.sidebar, data.blocks);
<ide> }
<ide>
<ide> function onBlockChangeColunn(data) {
<del> let modBlocks = req('blocks');
<ide> modBlocks.reorderBlocks(data);
<ide> }
<ide>
<ide> function onBlockShow(data) {
<del> let modBlocks = req('blocks');
<ide> modBlocks.show(data);
<ide> }
<ide>
<ide> function onBlockHideContent(data) {
<del> let modBlocks = req('blocks');
<ide> modBlocks.hideContent(data);
<ide> }
<ide>
<ide> function onBlockShowContent(data) {
<del> let modBlocks = req('blocks');
<ide> modBlocks.showContent(data);
<ide> }
<ide>
<ide> function onBlockHide(data) {
<del> let modBlocks = req('blocks');
<ide> modBlocks.hide(data);
<ide> }
<ide>
<ide> function onBlockSetTitles(data) {
<del> let modBlocks = req('blocks');
<ide> modBlocks.setTitles(data);
<ide> }
<ide>
<ide>
<ide> document.getElementById('content-both').addEventListener('click', function (e) {
<ide> if (e.target.classList.contains('taxonomy-button')) {
<del> let modArticles = req('articles');
<ide> let dom = req('dom');
<ide> let articleStruct = modArticles.articleElementToStruct(dom.closest(e.target, '.node'));
<ide>
|
|
Java
|
apache-2.0
|
6baa139afef4aaa6ca857d54d39e6b187a656a32
| 0 |
tomaszrogalski/gwt-jackson,BenDol/gwt-jackson,BenDol/gwt-jackson,nmorel/gwt-jackson
|
/*
* Copyright 2013 Nicolas Morel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.nmorel.gwtjackson.client;
import com.github.nmorel.gwtjackson.client.exception.JsonDeserializationException;
import com.github.nmorel.gwtjackson.client.exception.JsonSerializationException;
import com.github.nmorel.gwtjackson.client.stream.JsonReader;
import com.github.nmorel.gwtjackson.client.stream.JsonToken;
import com.github.nmorel.gwtjackson.client.stream.JsonWriter;
/**
* Base implementation of {@link ObjectMapper}. It delegates the serialization/deserialization to a serializer/deserializer.
*
* @author Nicolas Morel
*/
public abstract class AbstractObjectMapper<T> implements ObjectMapper<T> {
private final String rootName;
private JsonDeserializer<T> deserializer;
private JsonSerializer<T> serializer;
protected AbstractObjectMapper( String rootName ) {
this.rootName = rootName;
}
@Override
public T read( String in ) throws JsonDeserializationException {
return read( in, new JsonDeserializationContext.Builder().build() );
}
@Override
public T read( String in, JsonDeserializationContext ctx ) throws JsonDeserializationException {
JsonReader reader = ctx.newJsonReader( in );
try {
if ( ctx.isUnwrapRootValue() ) {
if ( JsonToken.BEGIN_OBJECT != reader.peek() ) {
throw ctx.traceError( "Unwrap root value is enabled but the input is not a JSON Object", reader );
}
reader.beginObject();
if ( JsonToken.END_OBJECT == reader.peek() ) {
throw ctx.traceError( "Unwrap root value is enabled but the JSON Object is empty", reader );
}
String name = reader.nextName();
if ( !name.equals( rootName ) ) {
throw ctx.traceError( "Unwrap root value is enabled but the name '" + name + "' don't match the expected rootName " +
"'" + rootName + "'", reader );
}
T result = getDeserializer().deserialize( reader, ctx );
reader.endObject();
return result;
} else {
return getDeserializer().deserialize( reader, ctx );
}
} catch ( JsonDeserializationException e ) {
// already logged, we just throw it
throw e;
} catch ( Exception e ) {
throw ctx.traceError( e, reader );
}
}
protected JsonDeserializer<T> getDeserializer() {
if ( null == deserializer ) {
deserializer = newDeserializer();
}
return deserializer;
}
/**
* Instantiates a new deserializer
*
* @return a new deserializer
*/
protected abstract JsonDeserializer<T> newDeserializer();
@Override
public String write( T value ) throws JsonSerializationException {
return write( value, new JsonSerializationContext.Builder().build() );
}
@Override
public String write( T value, JsonSerializationContext ctx ) throws JsonSerializationException {
JsonWriter writer = ctx.newJsonWriter();
try {
if ( ctx.isWrapRootValue() ) {
writer.beginObject();
writer.name( rootName );
getSerializer().serialize( writer, value, ctx );
writer.endObject();
} else {
getSerializer().serialize( writer, value, ctx );
}
return writer.getOutput();
} catch ( JsonSerializationException e ) {
// already logged, we just throw it
throw e;
} catch ( Exception e ) {
throw ctx.traceError( value, e, writer );
}
}
protected JsonSerializer<T> getSerializer() {
if ( null == serializer ) {
serializer = newSerializer();
}
return serializer;
}
/**
* Instantiates a new serializer
*
* @return a new serializer
*/
protected abstract JsonSerializer<T> newSerializer();
}
|
gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/AbstractObjectMapper.java
|
/*
* Copyright 2013 Nicolas Morel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.nmorel.gwtjackson.client;
import com.github.nmorel.gwtjackson.client.exception.JsonDeserializationException;
import com.github.nmorel.gwtjackson.client.exception.JsonSerializationException;
import com.github.nmorel.gwtjackson.client.stream.JsonReader;
import com.github.nmorel.gwtjackson.client.stream.JsonToken;
import com.github.nmorel.gwtjackson.client.stream.JsonWriter;
/**
* Base implementation of {@link ObjectMapper}. It delegates the serialization/deserialization to a serializer/deserializer.
*
* @author Nicolas Morel
*/
public abstract class AbstractObjectMapper<T> implements ObjectMapper<T> {
private final String rootName;
protected AbstractObjectMapper( String rootName ) {
this.rootName = rootName;
}
@Override
public T read( String in ) throws JsonDeserializationException {
return read( in, new JsonDeserializationContext.Builder().build() );
}
@Override
public T read( String in, JsonDeserializationContext ctx ) throws JsonDeserializationException {
JsonReader reader = ctx.newJsonReader( in );
try {
if ( ctx.isUnwrapRootValue() ) {
if ( JsonToken.BEGIN_OBJECT != reader.peek() ) {
throw ctx.traceError( "Unwrap root value is enabled but the input is not a JSON Object", reader );
}
reader.beginObject();
if ( JsonToken.END_OBJECT == reader.peek() ) {
throw ctx.traceError( "Unwrap root value is enabled but the JSON Object is empty", reader );
}
String name = reader.nextName();
if ( !name.equals( rootName ) ) {
throw ctx.traceError( "Unwrap root value is enabled but the name '" + name + "' don't match the expected rootName " +
"'" + rootName + "'", reader );
}
T result = newDeserializer().deserialize( reader, ctx );
reader.endObject();
return result;
} else {
return newDeserializer().deserialize( reader, ctx );
}
} catch ( JsonDeserializationException e ) {
// already logged, we just throw it
throw e;
} catch ( Exception e ) {
throw ctx.traceError( e, reader );
}
}
/**
* Instantiates a new deserializer
*
* @return a new deserializer
*/
protected abstract JsonDeserializer<T> newDeserializer();
@Override
public String write( T value ) throws JsonSerializationException {
return write( value, new JsonSerializationContext.Builder().build() );
}
@Override
public String write( T value, JsonSerializationContext ctx ) throws JsonSerializationException {
JsonWriter writer = ctx.newJsonWriter();
try {
if ( ctx.isWrapRootValue() ) {
writer.beginObject();
writer.name( rootName );
newSerializer().serialize( writer, value, ctx );
writer.endObject();
} else {
newSerializer().serialize( writer, value, ctx );
}
return writer.getOutput();
} catch ( JsonSerializationException e ) {
// already logged, we just throw it
throw e;
} catch ( Exception e ) {
throw ctx.traceError( value, e, writer );
}
}
/**
* Instantiates a new serializer
*
* @return a new serializer
*/
protected abstract JsonSerializer<T> newSerializer();
}
|
Keep the serializer and deserializer instance in AbstractObjectMapper
To avoid recreating them each time
|
gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/AbstractObjectMapper.java
|
Keep the serializer and deserializer instance in AbstractObjectMapper
|
<ide><path>wt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/AbstractObjectMapper.java
<ide>
<ide> private final String rootName;
<ide>
<add> private JsonDeserializer<T> deserializer;
<add>
<add> private JsonSerializer<T> serializer;
<add>
<ide> protected AbstractObjectMapper( String rootName ) {
<ide> this.rootName = rootName;
<ide> }
<ide> throw ctx.traceError( "Unwrap root value is enabled but the name '" + name + "' don't match the expected rootName " +
<ide> "'" + rootName + "'", reader );
<ide> }
<del> T result = newDeserializer().deserialize( reader, ctx );
<add> T result = getDeserializer().deserialize( reader, ctx );
<ide> reader.endObject();
<ide> return result;
<ide>
<ide> } else {
<ide>
<del> return newDeserializer().deserialize( reader, ctx );
<add> return getDeserializer().deserialize( reader, ctx );
<ide>
<ide> }
<ide>
<ide> } catch ( Exception e ) {
<ide> throw ctx.traceError( e, reader );
<ide> }
<add> }
<add>
<add> protected JsonDeserializer<T> getDeserializer() {
<add> if ( null == deserializer ) {
<add> deserializer = newDeserializer();
<add> }
<add> return deserializer;
<ide> }
<ide>
<ide> /**
<ide> if ( ctx.isWrapRootValue() ) {
<ide> writer.beginObject();
<ide> writer.name( rootName );
<del> newSerializer().serialize( writer, value, ctx );
<add> getSerializer().serialize( writer, value, ctx );
<ide> writer.endObject();
<ide> } else {
<del> newSerializer().serialize( writer, value, ctx );
<add> getSerializer().serialize( writer, value, ctx );
<ide> }
<ide> return writer.getOutput();
<ide> } catch ( JsonSerializationException e ) {
<ide> }
<ide> }
<ide>
<add> protected JsonSerializer<T> getSerializer() {
<add> if ( null == serializer ) {
<add> serializer = newSerializer();
<add> }
<add> return serializer;
<add> }
<add>
<ide> /**
<ide> * Instantiates a new serializer
<ide> *
|
|
Java
|
apache-2.0
|
ac81ebbd3d9116902630d226657bb1fa8ab84c7a
| 0 |
BeikeElectricity/ProjectX,BeikeElectricity/ProjectX,BeikeElectricity/ProjectX
|
package eic.beike.projectx.model;
import java.util.Random;
import eic.beike.projectx.android.event.IGameEventTrigger;
import eic.beike.projectx.network.busdata.BusCollector;
import eic.beike.projectx.network.busdata.SimpleBusCollector;
import eic.beike.projectx.util.GameColor;
/**
* @author Simon
* @author Alex
*/
/**
* This is the model for the game, which handles the representation of the game
*/
public class GameModel implements IGameModel{
private Count count;
private BusCollector busCollector;
/**
* Used to represent the board
*/
private Button[][] buttons;
/**
* Used to represent which button is pressed
*/
private int pressedC = -1;
private int pressedR = -1;
private double percentOfScore = 0;
private int score = 0;
private IGameEventTrigger triggers;
private RoundTracker tracker;
public GameModel(IGameEventTrigger triggers){
super();
busCollector = SimpleBusCollector.getInstance();
this.triggers = triggers;
buttons = generateNewButtons();
//Count up instances and then create a count object.
Count.addRunning();
count = new Count(this);
tracker = new RoundTracker();
tracker.track(this);
}
/**
* Adds points to the score count.
* @param score The new score points.
*/
@Override
public synchronized void addPercentScore(int score){
this.score += score;
triggers.triggerNewBonus(this.score);
}
/**
* Adds to the total scores.
* @param percentOfScore the extra points that should be added.
*/
@Override
public synchronized void addPercentScore(double percentOfScore){
this.percentOfScore = percentOfScore;
triggers.triggerNewScore(percentOfScore);
}
/**
* Used when the stop sign lights up in the bus and the player wants a bigger multiplier
*/
@Override
public void claimFactor() {
Long currentTime = System.currentTimeMillis();
count.count(currentTime);
}
@Override
public Count getCount() {
return count;
}
/**
* Generates new buttons for those that have been pressed
*/
@Override
public void generateButtons() {
Random random = new Random();
int generated;
// While there exists rows or columns of the same color, count them and generate new.
do {
generated = 0;
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons.length; j++) {
if (buttons[i][j].counted) {
buttons[i][j] = new Button(GameColor.color(random.nextInt(3)), random.nextInt(50));
generated++;
triggers.triggerNewButton(i, j, buttons[i][j].color.getAndroidColor());
}
}
}
count.sum(buttons);
} while (generated > 0);
}
/**
* Handles button interaction
* @param row, represents the row of the button pressed
* @param column, represents the column of the button pressed
*/
@Override
public void pressButton(int row, int column) {
if(pressedR < 0 && pressedC < 0) {
//Select button
pressedR = row;
pressedC = column;
triggers.triggerSelectButton(row,column);
} else if(isSame(row, column)) {
//if we have a selected button and it's pressed again, deselect it
triggers.triggerDeselectButton(row, column);
pressedR = -1;
pressedC = -1;
} else if (isNeighbour(row, column)) {
//Valid swap, swap and deselect and remember to update ui
triggers.triggerSwapButtons(row, column, pressedR, pressedC);
swapButtons(row, column);
triggers.triggerDeselectButton(pressedR, pressedC);
pressedR = -1;
pressedC = -1;
count.sum(buttons);
//We might have counted buttons and need to regenerate the board.
generateButtons();
} else {
// Clicked button far away, select it and deselect prev selected.
triggers.triggerDeselectButton(pressedR,pressedC);
pressedR = row;
pressedC = column;
triggers.triggerSelectButton(pressedR, pressedC);
}
}
private boolean isSame(int row, int column) {
return pressedR == row && pressedC == column;
}
private void swapButtons(int row, int column) {
Button temp = buttons[pressedR][pressedC];
buttons[pressedR][pressedC] = buttons[row][column];
buttons[row][column] = temp;
}
/**
* Updates view and resets score.
*/
protected void endRound() {
triggers.triggerEndRound(percentOfScore * (double) score);
score = 0;
percentOfScore = 0;
}
/**
* Abort the round without reporting a score.
*/
public void abortRound(){
if(tracker != null) {
tracker.stopTracking();
}
}
/**
* Generate a new board, without three in a row
* @return, returns a new board
*/
private Button[][] generateNewButtons() {
Button[][] tempList = new Button[3][3];
Random random = new Random();
for (int i = 0; i < tempList.length; i++) {
for (int j = 0; j < tempList.length; j++) {
tempList[i][j] = new Button(GameColor.color(random.nextInt(3)), random.nextInt(50));
}
}
while(hasThreeInRow(tempList)) {
for (int i = 0; i < tempList.length; i++) {
for (int j = 0; j < tempList.length; j++) {
tempList[i][j].color = GameColor.color(random.nextInt(3));
}
}
}
triggerAllNewButtons(tempList);
return tempList;
}
/**
* Tells the view to update all the buttons
* @param tempList, the board to be updated
*/
private void triggerAllNewButtons(Button[][] tempList) {
for (int i = 0; i < tempList.length; i++) {
for (int j = 0; j < tempList.length; j++) {
triggers.triggerNewButton(i, j, tempList[i][j].color.getAndroidColor());
}
}
}
public boolean hasThreeInRow(Button[][] buttons) {
for (int i = 0; i < buttons.length; i++) {
if((buttons[i][0].color == buttons[i][1].color) && (buttons[i][0].color == buttons[i][2].color)) {
return true;
}
if((buttons[0][i].color == buttons[1][i].color) && (buttons[0][i].color == buttons[2][i].color)) {
return true;
}
}
return false;
}
private boolean isNeighbour(int row, int column) {
if(row == pressedR && (column+1 == pressedC || column-1 == pressedC)) {
return true;
} else if(column == pressedC && (row+1 == pressedR || row-1 == pressedR)) {
return true;
} else {
return false;
}
}
public int getScore() {
return score;
}
/*
*Used for testing
*/
public Button[][] getButtons() {
return buttons;
}
public void triggerError(String msg) {
triggers.triggerError(msg);
}
}
|
App/app/src/main/java/eic/beike/projectx/model/GameModel.java
|
package eic.beike.projectx.model;
import java.util.Random;
import eic.beike.projectx.android.event.IGameEventTrigger;
import eic.beike.projectx.network.busdata.BusCollector;
import eic.beike.projectx.network.busdata.SimpleBusCollector;
import eic.beike.projectx.util.GameColor;
/**
* @author Simon
* @author Alex
*/
/**
* This is the model for the game, which handles the representation of the game
*/
public class GameModel implements IGameModel{
private Count count;
private BusCollector busCollector;
/**
* Used to represent the board
*/
private Button[][] buttons;
/**
* Used to represent which button is pressed
*/
private int pressedC = -1;
private int pressedR = -1;
private double percentOfScore = 0;
private int score = 0;
private IGameEventTrigger triggers;
private RoundTracker tracker;
public GameModel(IGameEventTrigger triggers){
super();
busCollector = SimpleBusCollector.getInstance();
busCollector.chooseBus(BusCollector.TEST_BUSS_VIN_NUMBER);
this.triggers = triggers;
buttons = generateNewButtons();
//Count up instances and then create a count object.
Count.addRunning();
count = new Count(this);
tracker = new RoundTracker();
tracker.track(this);
}
/**
* Adds points to the score count.
* @param score The new score points.
*/
@Override
public synchronized void addPercentScore(int score){
this.score += score;
triggers.triggerNewBonus(this.score);
}
/**
* Adds to the total scores.
* @param percentOfScore the extra points that should be added.
*/
@Override
public synchronized void addPercentScore(double percentOfScore){
this.percentOfScore = percentOfScore;
triggers.triggerNewScore(percentOfScore);
}
/**
* Used when the stop sign lights up in the bus and the player wants a bigger multiplier
*/
@Override
public void claimFactor() {
Long currentTime = System.currentTimeMillis();
count.count(currentTime);
}
@Override
public Count getCount() {
return count;
}
/**
* Generates new buttons for those that have been pressed
*/
@Override
public void generateButtons() {
Random random = new Random();
int generated;
// While there exists rows or columns of the same color, count them and generate new.
do {
generated = 0;
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons.length; j++) {
if (buttons[i][j].counted) {
buttons[i][j] = new Button(GameColor.color(random.nextInt(3)), random.nextInt(50));
generated++;
triggers.triggerNewButton(i, j, buttons[i][j].color.getAndroidColor());
}
}
}
count.sum(buttons);
} while (generated > 0);
}
/**
* Handles button interaction
* @param row, represents the row of the button pressed
* @param column, represents the column of the button pressed
*/
@Override
public void pressButton(int row, int column) {
if(pressedR < 0 && pressedC < 0) {
//Select button
pressedR = row;
pressedC = column;
triggers.triggerSelectButton(row,column);
} else if(isSame(row, column)) {
//if we have a selected button and it's pressed again, deselect it
triggers.triggerDeselectButton(row, column);
pressedR = -1;
pressedC = -1;
} else if (isNeighbour(row, column)) {
//Valid swap, swap and deselect and remember to update ui
triggers.triggerSwapButtons(row, column, pressedR, pressedC);
swapButtons(row, column);
triggers.triggerDeselectButton(pressedR, pressedC);
pressedR = -1;
pressedC = -1;
count.sum(buttons);
//We might have counted buttons and need to regenerate the board.
generateButtons();
} else {
// Clicked button far away, select it and deselect prev selected.
triggers.triggerDeselectButton(pressedR,pressedC);
pressedR = row;
pressedC = column;
triggers.triggerSelectButton(pressedR, pressedC);
}
}
private boolean isSame(int row, int column) {
return pressedR == row && pressedC == column;
}
private void swapButtons(int row, int column) {
Button temp = buttons[pressedR][pressedC];
buttons[pressedR][pressedC] = buttons[row][column];
buttons[row][column] = temp;
}
/**
* Updates view and resets score.
*/
protected void endRound() {
triggers.triggerEndRound(percentOfScore * (double) score);
score = 0;
percentOfScore = 0;
}
/**
* Abort the round without reporting a score.
*/
public void abortRound(){
if(tracker != null) {
tracker.stopTracking();
}
}
/**
* Generate a new board, without three in a row
* @return, returns a new board
*/
private Button[][] generateNewButtons() {
Button[][] tempList = new Button[3][3];
Random random = new Random();
for (int i = 0; i < tempList.length; i++) {
for (int j = 0; j < tempList.length; j++) {
tempList[i][j] = new Button(GameColor.color(random.nextInt(3)), random.nextInt(50));
}
}
while(hasThreeInRow(tempList)) {
for (int i = 0; i < tempList.length; i++) {
for (int j = 0; j < tempList.length; j++) {
tempList[i][j].color = GameColor.color(random.nextInt(3));
}
}
}
triggerAllNewButtons(tempList);
return tempList;
}
/**
* Tells the view to update all the buttons
* @param tempList, the board to be updated
*/
private void triggerAllNewButtons(Button[][] tempList) {
for (int i = 0; i < tempList.length; i++) {
for (int j = 0; j < tempList.length; j++) {
triggers.triggerNewButton(i, j, tempList[i][j].color.getAndroidColor());
}
}
}
public boolean hasThreeInRow(Button[][] buttons) {
for (int i = 0; i < buttons.length; i++) {
if((buttons[i][0].color == buttons[i][1].color) && (buttons[i][0].color == buttons[i][2].color)) {
return true;
}
if((buttons[0][i].color == buttons[1][i].color) && (buttons[0][i].color == buttons[2][i].color)) {
return true;
}
}
return false;
}
private boolean isNeighbour(int row, int column) {
if(row == pressedR && (column+1 == pressedC || column-1 == pressedC)) {
return true;
} else if(column == pressedC && (row+1 == pressedR || row-1 == pressedR)) {
return true;
} else {
return false;
}
}
public int getScore() {
return score;
}
/*
*Used for testing
*/
public Button[][] getButtons() {
return buttons;
}
public void triggerError(String msg) {
triggers.triggerError(msg);
}
}
|
Bugfix, BusWaitingActivity should set bus.
GameModel is only created after a bus has been found.
|
App/app/src/main/java/eic/beike/projectx/model/GameModel.java
|
Bugfix, BusWaitingActivity should set bus.
|
<ide><path>pp/app/src/main/java/eic/beike/projectx/model/GameModel.java
<ide> public GameModel(IGameEventTrigger triggers){
<ide> super();
<ide> busCollector = SimpleBusCollector.getInstance();
<del> busCollector.chooseBus(BusCollector.TEST_BUSS_VIN_NUMBER);
<ide> this.triggers = triggers;
<ide> buttons = generateNewButtons();
<ide>
|
|
Java
|
apache-2.0
|
7fe6229fedf9a5036ea4da180b9eb8e943048db4
| 0 |
Scrier/opus,Scrier/opus
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Andreas Joelsson ([email protected])
*/
package io.github.scrier.opus.duke.commander.state;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import io.github.scrier.opus.duke.commander.ClusterDistributorProcedure;
/**
* State handling for Created transactions.
* @author andreas.joelsson
* {@code * -> ABORTED}
*/
public class Created extends State {
private static Logger log = LogManager.getLogger(Created.class);
public Created(ClusterDistributorProcedure parent) {
super(parent);
}
@Override
public void shutDown() {
log.trace("shutDown()");
}
}
|
duke/src/main/java/io/github/scrier/opus/duke/commander/state/Created.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Andreas Joelsson ([email protected])
*/
package io.github.scrier.opus.duke.commander.state;
import io.github.scrier.opus.duke.commander.ClusterDistributorProcedure;
/**
* State handling for Created transactions.
* @author andreas.joelsson
* {@code * -> ABORTED}
*/
public class Created extends State {
public Created(ClusterDistributorProcedure parent) {
super(parent);
}
}
|
Shutdown call terminated the handling, added default handling for created state
|
duke/src/main/java/io/github/scrier/opus/duke/commander/state/Created.java
|
Shutdown call terminated the handling, added default handling for created state
|
<ide><path>uke/src/main/java/io/github/scrier/opus/duke/commander/state/Created.java
<ide> */
<ide> package io.github.scrier.opus.duke.commander.state;
<ide>
<add>import org.apache.logging.log4j.Logger;
<add>import org.apache.logging.log4j.LogManager;
<add>
<ide> import io.github.scrier.opus.duke.commander.ClusterDistributorProcedure;
<ide>
<ide> /**
<ide> * {@code * -> ABORTED}
<ide> */
<ide> public class Created extends State {
<add>
<add> private static Logger log = LogManager.getLogger(Created.class);
<ide>
<ide> public Created(ClusterDistributorProcedure parent) {
<ide> super(parent);
<ide> }
<add>
<add> @Override
<add> public void shutDown() {
<add> log.trace("shutDown()");
<add> }
<ide>
<ide> }
|
|
JavaScript
|
mit
|
5102a03d48840794ad019701292cfd69b0321b90
| 0 |
felixzapata/gulp-axe-webdriver
|
'use strict';
var path = require('path');
var fs = require('fs-path');
var glob = require('glob');
var AxeBuilder = require('axe-webdriverjs');
var WebDriver = require('selenium-webdriver');
var Promise = require('promise');
var fileUrl = require('file-url');
var reporter = require('./lib/reporter');
var chalk = require('chalk');
var request = require('then-request');
require('chromedriver');
module.exports = function (customOptions, done) {
var defaultOptions = {
folderOutputReport: 'aXeReports',
showOnlyViolations: false,
verbose: false,
headless: false,
saveOutputIn: '',
tags: null,
urls: [],
threshold: 0
};
var options = customOptions ? Object.assign(defaultOptions, customOptions) : defaultOptions;
var chromeCapabilities = WebDriver.Capabilities.chrome();
var chromeOptions = options.headless ? { 'args': ['--headless'] } : {};
chromeCapabilities.set('chromeOptions', chromeOptions);
var driver = new WebDriver.Builder().withCapabilities(chromeCapabilities).build();
driver.manage().timeouts().setScriptTimeout(60000);
var tagsAreDefined = (!Array.isArray(options.tags) && options.tags !== null && options.tags !== '') ||
(Array.isArray(options.tags) && options.tags.length > 0);
var isRemoteUrl = function (url) {
return url.indexOf('http://') >= 0 || url.indexOf('https://') >= 0;
};
var flatten = function (arr) {
return [].concat.apply([], arr);
};
var getUrl = function (url) {
return isRemoteUrl(url) ? url : fileUrl(url);
}
var checkNotValidUrls = function (result) {
return new Promise(function (resolve) {
request('GET', result.url, function (error) {
result.status = (error) ? 404 : 200;
resolve(result);
});
});
}
var getRemoteUrls = function (result) {
if (isRemoteUrl(result.url)) {
return result;
}
};
var getLocalUrls = function (result) {
if (!isRemoteUrl(result.url)) {
return result;
}
};
var onlyViolations = function (item) {
return item.violations.length > 0;
};
var removePassesValues = function (item) {
delete item.passes;
return item;
};
var mergeArray = function (coll, item) {
coll.push(item);
return coll;
};
var createResults = function (results) {
var dest = '';
var localUrls = results.filter(getLocalUrls);
var remoteUrls = results.filter(getRemoteUrls);
var promises = remoteUrls.map(checkNotValidUrls);
var resultsForReporter;
Promise.all(promises).then(function (results) {
resultsForReporter = localUrls.reduce(mergeArray, results);
if (options.showOnlyViolations) {
resultsForReporter = resultsForReporter.map(removePassesValues).filter(onlyViolations);
}
if (options.saveOutputIn !== '') {
dest = path.join(options.folderOutputReport, options.saveOutputIn);
fs.writeFileSync(dest, JSON.stringify(resultsForReporter, null, ' '));
}
if (options.verbose) {
console.log(chalk.yellow('Preparing results'));
console.log(chalk.yellow('================='));
}
reporter(resultsForReporter, options.threshold);
driver.quit().then(function () {
done();
});
});
};
var findGlobPatterns = function (urls) {
return urls.map(function (url) {
return isRemoteUrl(url) ? url : glob.sync(url);
});
};
var urls = flatten(findGlobPatterns(options.urls));
if (options.verbose) {
console.log(chalk.yellow('Start reading the urls'));
console.log(chalk.yellow('======================'));
}
Promise.all(urls.map(function (url) {
return new Promise(function (resolve) {
driver
.get(getUrl(url))
.then(function () {
if (options.verbose) {
console.log(chalk.cyan('Analysis start for: ') + url);
}
var startTimestamp = new Date().getTime();
var axeBuilder = new AxeBuilder(driver);
if (options.include) {
axeBuilder.include(options.include);
}
if (options.exclude) {
axeBuilder.exclude(options.exclude);
}
if (tagsAreDefined) {
axeBuilder.withTags(options.tags);
}
if (options.a11yCheckOptions) {
axeBuilder.options(options.a11yCheckOptions);
}
axeBuilder.analyze(function (results) {
results.url = url;
results.timestamp = new Date().getTime();
results.time = results.timestamp - startTimestamp;
if (options.verbose) {
console.log(chalk.cyan('Analyisis finished for: ') + url);
}
resolve(results);
});
});
});
})).then(createResults);
};
|
index.js
|
'use strict';
var path = require('path');
var fs = require('fs-path');
var glob = require('glob');
var AxeBuilder = require('axe-webdriverjs');
var WebDriver = require('selenium-webdriver');
var Promise = require('promise');
var fileUrl = require('file-url');
var reporter = require('./lib/reporter');
var chalk = require('chalk');
var request = require('then-request');
require('chromedriver');
module.exports = function (customOptions, done) {
var defaultOptions = {
folderOutputReport: 'aXeReports',
showOnlyViolations: false,
verbose: false,
headless: false,
saveOutputIn: '',
tags: null,
urls: [],
threshold: 0
};
var options = customOptions ? Object.assign(defaultOptions, customOptions) : defaultOptions;
var chromeCapabilities = WebDriver.Capabilities.chrome();
var chromeOptions = options.headless ? { 'args': ['--headless'] } : {};
chromeCapabilities.set('chromeOptions', chromeOptions);
var driver = new WebDriver.Builder().withCapabilities(chromeCapabilities).build();
driver.manage().timeouts().setScriptTimeout(500);
var tagsAreDefined = (!Array.isArray(options.tags) && options.tags !== null && options.tags !== '') ||
(Array.isArray(options.tags) && options.tags.length > 0);
var isRemoteUrl = function (url) {
return url.indexOf('http://') >= 0 || url.indexOf('https://') >= 0;
};
var flatten = function (arr) {
return [].concat.apply([], arr);
};
var getUrl = function (url) {
return isRemoteUrl(url) ? url : fileUrl(url);
}
var checkNotValidUrls = function (result) {
return new Promise(function (resolve) {
request('GET', result.url, function (error) {
result.status = (error) ? 404 : 200;
resolve(result);
});
});
}
var getRemoteUrls = function (result) {
if (isRemoteUrl(result.url)) {
return result;
}
};
var getLocalUrls = function (result) {
if (!isRemoteUrl(result.url)) {
return result;
}
};
var onlyViolations = function (item) {
return item.violations.length > 0;
};
var removePassesValues = function (item) {
delete item.passes;
return item;
};
var mergeArray = function (coll, item) {
coll.push(item);
return coll;
};
var createResults = function (results) {
var dest = '';
var localUrls = results.filter(getLocalUrls);
var remoteUrls = results.filter(getRemoteUrls);
var promises = remoteUrls.map(checkNotValidUrls);
var resultsForReporter;
Promise.all(promises).then(function (results) {
resultsForReporter = localUrls.reduce(mergeArray, results);
if (options.showOnlyViolations) {
resultsForReporter = resultsForReporter.map(removePassesValues).filter(onlyViolations);
}
if (options.saveOutputIn !== '') {
dest = path.join(options.folderOutputReport, options.saveOutputIn);
fs.writeFileSync(dest, JSON.stringify(resultsForReporter, null, ' '));
}
if (options.verbose) {
console.log(chalk.yellow('Preparing results'));
console.log(chalk.yellow('================='));
}
reporter(resultsForReporter, options.threshold);
driver.quit().then(function () {
done();
});
});
};
var findGlobPatterns = function (urls) {
return urls.map(function (url) {
return isRemoteUrl(url) ? url : glob.sync(url);
});
};
var urls = flatten(findGlobPatterns(options.urls));
if (options.verbose) {
console.log(chalk.yellow('Start reading the urls'));
console.log(chalk.yellow('======================'));
}
Promise.all(urls.map(function (url) {
return new Promise(function (resolve) {
driver
.get(getUrl(url))
.then(function () {
if (options.verbose) {
console.log(chalk.cyan('Analysis start for: ') + url);
}
var startTimestamp = new Date().getTime();
var axeBuilder = new AxeBuilder(driver);
if (options.include) {
axeBuilder.include(options.include);
}
if (options.exclude) {
axeBuilder.exclude(options.exclude);
}
if (tagsAreDefined) {
axeBuilder.withTags(options.tags);
}
if (options.a11yCheckOptions) {
axeBuilder.options(options.a11yCheckOptions);
}
axeBuilder.analyze(function (results) {
results.url = url;
results.timestamp = new Date().getTime();
results.time = results.timestamp - startTimestamp;
if (options.verbose) {
console.log(chalk.cyan('Analyisis finished for: ') + url);
}
resolve(results);
});
});
});
})).then(createResults);
};
|
Increase setScriptTimeout
|
index.js
|
Increase setScriptTimeout
|
<ide><path>ndex.js
<ide> var chromeOptions = options.headless ? { 'args': ['--headless'] } : {};
<ide> chromeCapabilities.set('chromeOptions', chromeOptions);
<ide> var driver = new WebDriver.Builder().withCapabilities(chromeCapabilities).build();
<del> driver.manage().timeouts().setScriptTimeout(500);
<add> driver.manage().timeouts().setScriptTimeout(60000);
<ide>
<ide> var tagsAreDefined = (!Array.isArray(options.tags) && options.tags !== null && options.tags !== '') ||
<ide> (Array.isArray(options.tags) && options.tags.length > 0);
|
|
Java
|
mit
|
error: pathspec 'LeetCodeSolutions/java/src/401_Binary_Watch/Solution.java' did not match any file(s) known to git
|
c797b323d866599e75ba3df18db829cf058ab5df
| 1 |
ChuanleiGuo/AlgorithmsPlayground,ChuanleiGuo/AlgorithmsPlayground,ChuanleiGuo/AlgorithmsPlayground,ChuanleiGuo/AlgorithmsPlayground
|
import java.util.List;
import java.util.ArrayList;
public class Solution {
public List<String> readBinaryWatch(int num) {
List<String> res = new ArrayList<>();
int[] nums1 = new int[]{8, 4, 2, 1}, nums2 = new int[]{32, 16, 8, 4, 2, 1};
for(int i = 0; i <= num; i++) {
List<Integer> list1 = generateDigit(nums1, i);
List<Integer> list2 = generateDigit(nums2, num - i);
for(int num1: list1) {
if(num1 >= 12) continue;
for(int num2: list2) {
if(num2 >= 60) continue;
res.add(num1 + ":" + (num2 < 10 ? "0" + num2 : num2));
}
}
}
return res;
}
private List<Integer> generateDigit(int[] nums, int count) {
List<Integer> res = new ArrayList<>();
generateDigitHelper(nums, count, 0, 0, res);
return res;
}
private void generateDigitHelper(int[] nums, int count, int pos, int sum, List<Integer> res) {
if(count == 0) {
res.add(sum);
return;
}
for(int i = pos; i < nums.length; i++) {
generateDigitHelper(nums, count - 1, i + 1, sum + nums[i], res);
}
}
}
|
LeetCodeSolutions/java/src/401_Binary_Watch/Solution.java
|
401. Binary Watch
|
LeetCodeSolutions/java/src/401_Binary_Watch/Solution.java
|
401. Binary Watch
|
<ide><path>eetCodeSolutions/java/src/401_Binary_Watch/Solution.java
<add>import java.util.List;
<add>import java.util.ArrayList;
<add>
<add>public class Solution {
<add> public List<String> readBinaryWatch(int num) {
<add> List<String> res = new ArrayList<>();
<add> int[] nums1 = new int[]{8, 4, 2, 1}, nums2 = new int[]{32, 16, 8, 4, 2, 1};
<add> for(int i = 0; i <= num; i++) {
<add> List<Integer> list1 = generateDigit(nums1, i);
<add> List<Integer> list2 = generateDigit(nums2, num - i);
<add> for(int num1: list1) {
<add> if(num1 >= 12) continue;
<add> for(int num2: list2) {
<add> if(num2 >= 60) continue;
<add> res.add(num1 + ":" + (num2 < 10 ? "0" + num2 : num2));
<add> }
<add> }
<add> }
<add> return res;
<add> }
<add>
<add> private List<Integer> generateDigit(int[] nums, int count) {
<add> List<Integer> res = new ArrayList<>();
<add> generateDigitHelper(nums, count, 0, 0, res);
<add> return res;
<add> }
<add>
<add> private void generateDigitHelper(int[] nums, int count, int pos, int sum, List<Integer> res) {
<add> if(count == 0) {
<add> res.add(sum);
<add> return;
<add> }
<add>
<add> for(int i = pos; i < nums.length; i++) {
<add> generateDigitHelper(nums, count - 1, i + 1, sum + nums[i], res);
<add> }
<add> }
<add>}
|
|
Java
|
epl-1.0
|
9e56a5f8b50ec16876d0eeca9803605da301cb66
| 0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs,bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs,bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
|
/*******************************************************************************
* Copyright (c) 2011 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* rbarkhouse - 2.1 - initial implementation
******************************************************************************/
package org.eclipse.persistence.testing.jaxb.dynamic;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.UndeclaredThrowableException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import junit.framework.TestCase;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
import org.eclipse.persistence.testing.jaxb.dynamic.util.NoExtensionEntityResolver;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class DynamicJAXBFromXSDTestCases extends TestCase {
DynamicJAXBContext jaxbContext;
static {
try {
// Disable XJC's schema correctness check. XSD imports do not seem to work if this is left on.
System.setProperty("com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.noCorrectnessCheck", "true");
} catch (Exception e) {
// Ignore
}
}
public DynamicJAXBFromXSDTestCases(String name) throws Exception {
super(name);
}
public String getName() {
return "Dynamic JAXB: XSD: " + super.getName();
}
public void testEclipseLinkSchema() throws Exception {
// Bootstrapping from eclipselink_oxm_2_4.xsd will trigger a JAXB 2.2 API (javax.xml.bind.annotation.XmlElementRef.required())
// so only run this test in Java 7
if (System.getProperty("java.version").contains("1.7")) {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(ECLIPSELINK_SCHEMA);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
}
}
// ====================================================================
public void testXmlSchemaQualified() throws Exception {
// <xs:schema targetNamespace="myNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema"
// attributeFormDefault="qualified" elementFormDefault="qualified">
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_QUALIFIED);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 456);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Make sure "targetNamespace" was interpreted properly.
Node node = marshalDoc.getChildNodes().item(0);
assertEquals("Target Namespace was not set as expected.", "myNamespace", node.getNamespaceURI());
// Make sure "elementFormDefault" was interpreted properly.
// elementFormDefault=qualified, so the root node, the
// root node's attribute, and the child node should all have a prefix.
assertNotNull("Root node did not have namespace prefix as expected.", node.getPrefix());
Node attr = node.getAttributes().item(0);
assertNotNull("Attribute did not have namespace prefix as expected.", attr.getPrefix());
Node childNode = node.getChildNodes().item(0);
assertNotNull("Child node did not have namespace prefix as expected.", childNode.getPrefix());
}
public void testXmlSchemaUnqualified() throws Exception {
// <xs:schema targetNamespace="myNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema"
// attributeFormDefault="unqualified" elementFormDefault="unqualified">
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_UNQUALIFIED);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 456);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Make sure "targetNamespace" was interpreted properly.
Node node = marshalDoc.getChildNodes().item(0);
assertEquals("Target Namespace was not set as expected.", "myNamespace", node.getNamespaceURI());
// Make sure "elementFormDefault" was interpreted properly.
// elementFormDefault=unqualified, so the root node should have a prefix
// but the root node's attribute and child node should not.
assertNotNull("Root node did not have namespace prefix as expected.", node.getPrefix());
// Do not test attribute prefix with the Oracle xmlparserv2, it qualifies attributes by default.
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
if (builderFactory.getClass().getPackage().getName().contains("oracle")) {
return;
} else {
Node attr = node.getAttributes().item(0);
assertNull("Attribute should not have namespace prefix (" + attr.getPrefix() + ").", attr.getPrefix());
}
Node childNode = node.getChildNodes().item(0);
assertNull("Child node should not have namespace prefix.", childNode.getPrefix());
}
public void testXmlSchemaDefaults() throws Exception {
// <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_DEFAULTS);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(DEF_PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 456);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// "targetNamespace" should be null by default
Node node = marshalDoc.getChildNodes().item(0);
assertNull("Target Namespace was not null as expected.", node.getNamespaceURI());
// Make sure "elementFormDefault" was interpreted properly.
// When unset, no namespace qualification is done.
assertNull("Root node should not have namespace prefix.", node.getPrefix());
Node attr = node.getAttributes().item(0);
assertNull("Attribute should not have namespace prefix.", attr.getPrefix());
Node childNode = node.getChildNodes().item(0);
assertNull("Child node should not have namespace prefix.", childNode.getPrefix());
}
public void testXmlSchemaImport() throws Exception {
// <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
// <xs:import schemaLocation="xmlschema-currency" namespace="bankNamespace"/>
// Do not run this test if we are not using JDK 1.6
String javaVersion = System.getProperty("java.version");
if (!(javaVersion.startsWith("1.6"))) {
return;
}
// Do not run this test with the Oracle xmlparserv2, it will not properly hit the EntityResolver
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
if (builderFactory.getClass().getPackage().getName().contains("oracle")) {
return;
}
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_IMPORT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, new NoExtensionEntityResolver(), null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
DynamicEntity salary = jaxbContext.newDynamicEntity(BANK_PACKAGE + "." + CDN_CURRENCY);
assertNotNull("Could not create Dynamic Entity.", salary);
salary.set("value", new BigDecimal(75425.75));
person.set("name", "Bob Dobbs");
person.set("salary", salary);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Nothing to really test, if the import failed we couldn't have created the salary.
}
public void testXmlSeeAlso() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSEEALSO);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + EMPLOYEE);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
person.set("employeeId", "CA2472");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Nothing to really test, XmlSeeAlso isn't represented in an instance doc.
}
public void testXmlRootElement() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLROOTELEMENT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + INDIVIDUO);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getChildNodes().item(0);
assertEquals("Root element was not 'individuo' as expected.", "individuo", node.getLocalName());
}
public void testXmlType() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLTYPE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("email", "[email protected]");
person.set("lastName", "Dobbs");
person.set("id", 678);
person.set("phoneNumber", "212-555-8282");
person.set("firstName", "Bob");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Test that XmlType.propOrder was interpreted properly
Node node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "id", node.getLocalName());
node = marshalDoc.getDocumentElement().getChildNodes().item(1);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "first-name", node.getLocalName());
node = marshalDoc.getDocumentElement().getChildNodes().item(2);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "last-name", node.getLocalName());
node = marshalDoc.getDocumentElement().getChildNodes().item(3);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "phone-number", node.getLocalName());
node = marshalDoc.getDocumentElement().getChildNodes().item(4);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "email", node.getLocalName());
}
public void testXmlAttribute() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLATTRIBUTE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 777);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getChildNodes().item(0);
if (node.getAttributes() == null || node.getAttributes().getNamedItem("id") == null) {
fail("Attribute not present.");
}
}
public void testXmlElement() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("type", "O+");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertNotNull("Element not present.", node.getChildNodes());
String elemName = node.getChildNodes().item(0).getNodeName();
assertEquals("Element not present.", "type", elemName);
}
public void testXmlElementCollection() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTCOLLECTION);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList nicknames = new ArrayList();
nicknames.add("Bobby");
nicknames.add("Dobsy");
nicknames.add("Big Kahuna");
person.set("nickname", nicknames);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertNotNull("Element not present.", node.getChildNodes());
assertEquals("Unexpected number of child nodes present.", 3, node.getChildNodes().getLength());
}
public void testXmlElementCustomized() throws Exception {
// Customize the EclipseLink mapping generation by providing an eclipselink-oxm.xml
String metadataFile = RESOURCE_DIR + "eclipselink-oxm.xml";
InputStream iStream = ClassLoader.getSystemResourceAsStream(metadataFile);
HashMap<String, Source> metadataSourceMap = new HashMap<String, Source>();
metadataSourceMap.put(CONTEXT_PATH, new StreamSource(iStream));
Map<String, Object> props = new HashMap<String, Object>();
props.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap);
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, props);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("type", "O+");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertNotNull("Element not present.", node.getChildNodes());
String elemName = node.getChildNodes().item(0).getNodeName();
// 'type' was renamed to 'bloodType' in the OXM bindings file
assertEquals("Element not present.", "bloodType", elemName);
}
public void testXmlList() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLLIST);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList<String> codes = new ArrayList<String>(3);
codes.add("D1182");
codes.add("D1716");
codes.add("G7212");
person.set("name", "Bob Dobbs");
person.set("codes", codes);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertEquals("Unexpected number of nodes in document.", 2, node.getChildNodes().getLength());
String value = node.getChildNodes().item(1).getTextContent();
assertEquals("Unexpected element contents.", "D1182 D1716 G7212", value);
}
public void testXmlValue() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLVALUE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
DynamicEntity salary = jaxbContext.newDynamicEntity(PACKAGE + "." + CDN_CURRENCY);
assertNotNull("Could not create Dynamic Entity.", salary);
salary.set("value", new BigDecimal(75100));
person.set("name", "Bob Dobbs");
person.set("salary", salary);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Nothing to really test, XmlValue isn't represented in an instance doc.
}
public void testXmlAnyElement() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLANYELEMENT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
person.set("any", "StringValue");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertTrue("Any element not found.", node.getChildNodes().item(1).getNodeType() == Node.TEXT_NODE);
}
public void testXmlAnyAttribute() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLANYATTRIBUTE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
Map<QName, Object> otherAttributes = new HashMap<QName, Object>();
otherAttributes.put(new QName("foo"), new BigDecimal(1234));
otherAttributes.put(new QName("bar"), Boolean.FALSE);
person.set("name", "Bob Dobbs");
person.set("otherAttributes", otherAttributes);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
Node otherAttributesNode = node.getAttributes().getNamedItem("foo");
assertNotNull("'foo' attribute not found.", otherAttributesNode);
otherAttributesNode = node.getAttributes().getNamedItem("bar");
assertNotNull("'bar' attribute not found.", otherAttributesNode);
}
public void testXmlMixed() throws Exception {
// Also tests XmlElementRef / XmlElementRefs
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLMIXED);
try {
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
} catch (JAXBException e) {
// If running in a non-JAXB 2.2 environment, we will get this error because the required() method
// on @XmlElementRef is missing. Just ignore this and pass the test.
if (e.getLinkedException() instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
}
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList list = new ArrayList();
list.add("Hello");
list.add(new JAXBElement<String>(new QName("myNamespace", "title"), String.class, person.getClass(), "MR"));
list.add(new JAXBElement<String>(new QName("myNamespace", "name"), String.class, person.getClass(), "Bob Dobbs"));
list.add(", your point balance is");
list.add(new JAXBElement<BigInteger>(new QName("myNamespace", "rewardPoints"), BigInteger.class, person.getClass(), BigInteger.valueOf(175)));
list.add("Visit www.rewards.com!");
person.set("content", list);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertTrue("Unexpected number of elements.", node.getChildNodes().getLength() == 6);
}
public void testXmlId() throws Exception {
// Tests both XmlId and XmlIdRef
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLID);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity data = jaxbContext.newDynamicEntity(PACKAGE + "." + DATA);
assertNotNull("Could not create Dynamic Entity.", data);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
DynamicEntity company = jaxbContext.newDynamicEntity(PACKAGE + "." + COMPANY);
assertNotNull("Could not create Dynamic Entity.", company);
company.set("name", "ACME International");
company.set("address", "165 Main St, Anytown US, 93012");
company.set("id", "882");
person.set("name", "Bob Dobbs");
person.set("company", company);
data.set("person", person);
data.set("company", company);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(data, marshalDoc);
// 'person' node
Node pNode = marshalDoc.getDocumentElement().getChildNodes().item(0);
// 'company' node
Node cNode = pNode.getChildNodes().item(1);
// If IDREF worked properly, the company element should only contain the id of the company object
assertEquals("'company' has unexpected number of child nodes.", 1, cNode.getChildNodes().getLength());
}
public void testXmlElements() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTS);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList list = new ArrayList(1);
list.add("BOB");
person.set("nameOrReferenceNumber", list);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected element name.", "name", node.getNodeName());
person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
list = new ArrayList(1);
list.add(328763);
person.set("nameOrReferenceNumber", list);
marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected element name.", "reference-number", node.getNodeName());
}
public void testXmlElementRef() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTREF);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList list = new ArrayList(1);
list.add("BOB");
person.set("nameOrReferenceNumber", list);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected element name.", "name", node.getNodeName());
person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
list = new ArrayList(1);
list.add(328763);
person.set("nameOrReferenceNumber", list);
marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected element name.", "reference-number", node.getNodeName());
}
public void testXmlSchemaType() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMATYPE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("dateOfBirth", DatatypeFactory.newInstance().newXMLGregorianCalendarDate(1976, 02, 17, DatatypeConstants.FIELD_UNDEFINED));
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected date value.", "1976-02-17", node.getTextContent());
}
public void testXmlEnum() throws Exception {
// Tests XmlEnum and XmlEnumValue
// This test schema contains exactly 6 enum values to test an ASM boundary case
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLENUM);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
Object NORTH = jaxbContext.getEnumConstant(PACKAGE + "." + COMPASS_DIRECTION, NORTH_CONSTANT);
assertNotNull("Could not find enum constant.", NORTH);
person.set("quadrant", NORTH);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testXmlEnumError() throws Exception {
// Tests XmlEnum and XmlEnumValue
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLENUM);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
Exception caughtException = null;
try {
Object NORTHWEST = jaxbContext.getEnumConstant(PACKAGE + "." + COMPASS_DIRECTION, "NORTHWEST");
} catch (Exception e) {
caughtException = e;
}
assertNotNull("Expected exception was not thrown.", caughtException);
}
public void testXmlElementDecl() throws Exception {
// Also tests XmlRegistry
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTDECL);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getChildNodes().item(0);
assertEquals("Root element was not 'individuo' as expected.", "individuo", node.getLocalName());
}
public void testSchemaWithJAXBBindings() throws Exception {
// jaxbcustom.xsd specifies that the generated package name should be "foo.bar" and
// the person type will be named MyPersonType in Java
InputStream inputStream = ClassLoader.getSystemResourceAsStream(JAXBCUSTOM);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity("foo.bar.MyPersonType");
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testSubstitutionGroupsUnmarshal() throws Exception {
try {
InputStream xsdStream = ClassLoader.getSystemResourceAsStream(SUBSTITUTION);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(xsdStream, null, null, null);
InputStream xmlStream = ClassLoader.getSystemResourceAsStream(PERSON_XML);
JAXBElement person = (JAXBElement) jaxbContext.createUnmarshaller().unmarshal(xmlStream);
assertEquals("Element was not substituted properly: ", new QName("myNamespace", "person"), person.getName());
JAXBElement name = (JAXBElement) ((DynamicEntity) person.getValue()).get("name");
assertEquals("Element was not substituted properly: ", new QName("myNamespace", "name"), name.getName());
// ====================================================================
InputStream xmlStream2 = ClassLoader.getSystemResourceAsStream(PERSONNE_XML);
JAXBElement person2 = (JAXBElement) jaxbContext.createUnmarshaller().unmarshal(xmlStream2);
assertEquals("Element was not substituted properly: ", new QName("myNamespace", "personne"), person2.getName());
JAXBElement name2 = (JAXBElement) ((DynamicEntity) person2.getValue()).get("name");
assertEquals("Element was not substituted properly: ", new QName("myNamespace", "nom"), name2.getName());
} catch (JAXBException e) {
// If running in a non-JAXB 2.2 environment, we will get this error because the required() method
// on @XmlElementRef is missing. Just ignore this and pass the test.
if (e.getLinkedException() instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
}
}
public void testSubstitutionGroupsMarshal() throws Exception {
try {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(SUBSTITUTION);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
QName personQName = new QName("myNamespace", "person");
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
JAXBElement<DynamicEntity> personElement = new JAXBElement<DynamicEntity>(personQName, DynamicEntity.class, person);
personElement.setValue(person);
QName nameQName = new QName("myNamespace", "name");
JAXBElement<String> nameElement = new JAXBElement<String>(nameQName, String.class, "Marty Friedman");
person.set("name", nameElement);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(personElement, marshalDoc);
Node node1 = marshalDoc.getDocumentElement();
assertEquals("Incorrect element name: ", "person", node1.getLocalName());
Node node2 = node1.getFirstChild();
assertEquals("Incorrect element name: ", "name", node2.getLocalName());
// ====================================================================
QName personneQName = new QName("myNamespace", "personne");
DynamicEntity personne = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
JAXBElement<DynamicEntity> personneElement = new JAXBElement<DynamicEntity>(personneQName, DynamicEntity.class, personne);
personneElement.setValue(personne);
QName nomQName = new QName("myNamespace", "nom");
JAXBElement<String> nomElement = new JAXBElement<String>(nomQName, String.class, "Marty Friedman");
personne.set("name", nomElement);
Document marshalDoc2 = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(personneElement, marshalDoc2);
Node node3 = marshalDoc2.getDocumentElement();
assertEquals("Incorrect element name: ", "personne", node3.getLocalName());
Node node4 = node3.getFirstChild();
assertEquals("Incorrect element name: ", "nom", node4.getLocalName());
} catch (JAXBException e) {
// If running in a non-JAXB 2.2 environment, we will get this error because the required() method
// on @XmlElementRef is missing. Just ignore this and pass the test.
if (e.getLinkedException() instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
}
}
// ====================================================================
public void testTypePreservation() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_DEFAULTS);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(DEF_PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 456);
person.set("name", "Bob Dobbs");
person.set("salary", 45000.00);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
DynamicEntity readPerson = (DynamicEntity) jaxbContext.createUnmarshaller().unmarshal(marshalDoc);
assertEquals("Property type was not preserved during unmarshal.", Double.class, readPerson.<Object>get("salary").getClass());
assertEquals("Property type was not preserved during unmarshal.", Integer.class, readPerson.<Object>get("id").getClass());
}
public void testNestedInnerClasses() throws Exception {
// Tests multiple levels of inner classes, eg. mynamespace.Person.RelatedResource.Link
InputStream inputStream = ClassLoader.getSystemResourceAsStream(NESTEDINNERCLASSES);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity("mynamespace.Person");
DynamicEntity resource = jaxbContext.newDynamicEntity("mynamespace.Person.RelatedResource");
DynamicEntity link = jaxbContext.newDynamicEntity("mynamespace.Person.RelatedResource.Link");
DynamicEntity link2 = jaxbContext.newDynamicEntity("mynamespace.Person.RelatedResource.Link");
link.set("linkName", "LINKFOO");
link2.set("linkName", "LINKFOO2");
resource.set("resourceName", "RESBAR");
ArrayList<DynamicEntity> links = new ArrayList<DynamicEntity>();
links.add(link);
links.add(link2);
resource.set("link", links);
person.set("name", "Bob Smith");
person.set("relatedResource", resource);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testBinary() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(BINARY);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
byte[] byteArray = new byte[] {30,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4};
DynamicEntity person = jaxbContext.newDynamicEntity("mynamespace.Person");
person.set("name", "B. Nary");
person.set("abyte", (byte) 30);
person.set("base64", byteArray);
person.set("hex", byteArray);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testBinaryGlobalType() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(BINARY2);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
byte[] byteArray = new byte[] {30,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4};
DynamicEntity person = jaxbContext.newDynamicEntity("mynamespace.Person");
person.set("name", "B. Nary");
person.set("abyte", (byte) 30);
person.set("base64", byteArray);
person.set("hex", byteArray);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testXMLSchemaSchema() throws Exception {
try {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMASCHEMA);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity schema = jaxbContext.newDynamicEntity("org.w3._2001.xmlschema.Schema");
schema.set("targetNamespace", "myNamespace");
Object QUALIFIED = jaxbContext.getEnumConstant("org.w3._2001.xmlschema.FormChoice", "QUALIFIED");
schema.set("attributeFormDefault", QUALIFIED);
DynamicEntity complexType = jaxbContext.newDynamicEntity("org.w3._2001.xmlschema.TopLevelComplexType");
complexType.set("name", "myComplexType");
List<DynamicEntity> complexTypes = new ArrayList<DynamicEntity>(1);
complexTypes.add(complexType);
schema.set("simpleTypeOrComplexTypeOrGroup", complexTypes);
List<Object> blocks = new ArrayList<Object>();
blocks.add("FOOBAR");
schema.set("blockDefault", blocks);
File f = new File("myschema.xsd");
jaxbContext.createMarshaller().marshal(schema, f);
} catch (JAXBException e) {
// If running in a non-JAXB 2.2 environment, we will get this error because the required() method
// on @XmlElementRef is missing. Just ignore this and pass the test.
if (e.getLinkedException() instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
}
}
// ====================================================================
private void print(Object o) throws Exception {
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(o, System.err);
}
// ====================================================================
private static final String RESOURCE_DIR = "org/eclipse/persistence/testing/jaxb/dynamic/";
private static final String CONTEXT_PATH = "mynamespace";
// Schema files used to test each annotation
private static final String XMLSCHEMA_QUALIFIED = RESOURCE_DIR + "xmlschema-qualified.xsd";
private static final String XMLSCHEMA_UNQUALIFIED = RESOURCE_DIR + "xmlschema-unqualified.xsd";
private static final String XMLSCHEMA_DEFAULTS = RESOURCE_DIR + "xmlschema-defaults.xsd";
private static final String XMLSCHEMA_IMPORT = RESOURCE_DIR + "xmlschema-import.xsd";
private static final String XMLSCHEMA_CURRENCY = RESOURCE_DIR + "xmlschema-currency.xsd";
private static final String XMLSEEALSO = RESOURCE_DIR + "xmlseealso.xsd";
private static final String XMLROOTELEMENT = RESOURCE_DIR + "xmlrootelement.xsd";
private static final String XMLTYPE = RESOURCE_DIR + "xmltype.xsd";
private static final String XMLATTRIBUTE = RESOURCE_DIR + "xmlattribute.xsd";
private static final String XMLELEMENT = RESOURCE_DIR + "xmlelement.xsd";
private static final String XMLLIST = RESOURCE_DIR + "xmllist.xsd";
private static final String XMLVALUE = RESOURCE_DIR + "xmlvalue.xsd";
private static final String XMLANYELEMENT = RESOURCE_DIR + "xmlanyelement.xsd";
private static final String XMLANYATTRIBUTE = RESOURCE_DIR + "xmlanyattribute.xsd";
private static final String XMLMIXED = RESOURCE_DIR + "xmlmixed.xsd";
private static final String XMLID = RESOURCE_DIR + "xmlid.xsd";
private static final String XMLELEMENTS = RESOURCE_DIR + "xmlelements.xsd";
private static final String XMLELEMENTREF = RESOURCE_DIR + "xmlelementref.xsd";
private static final String XMLSCHEMATYPE = RESOURCE_DIR + "xmlschematype.xsd";
private static final String XMLENUM = RESOURCE_DIR + "xmlenum.xsd";
private static final String XMLELEMENTDECL = RESOURCE_DIR + "xmlelementdecl.xsd";
private static final String XMLELEMENTCOLLECTION = RESOURCE_DIR + "xmlelement-collection.xsd";
private static final String JAXBCUSTOM = RESOURCE_DIR + "jaxbcustom.xsd";
private static final String SUBSTITUTION = RESOURCE_DIR + "substitution.xsd";
private static final String NESTEDINNERCLASSES = RESOURCE_DIR + "nestedinnerclasses.xsd";
private static final String BINARY = RESOURCE_DIR + "binary.xsd";
private static final String BINARY2 = RESOURCE_DIR + "binary2.xsd";
private static final String XMLSCHEMASCHEMA = RESOURCE_DIR + "XMLSchema.xsd";
private static final String ECLIPSELINK_SCHEMA = "org/eclipse/persistence/jaxb/eclipselink_oxm_2_4.xsd";
// Test Instance Docs
private static final String PERSON_XML = RESOURCE_DIR + "sub-person-en.xml";
private static final String PERSONNE_XML = RESOURCE_DIR + "sub-personne-fr.xml";
// Names of types to instantiate
private static final String PACKAGE = "mynamespace";
private static final String DEF_PACKAGE = "generated";
private static final String BANK_PACKAGE = "banknamespace";
private static final String PERSON = "Person";
private static final String EMPLOYEE = "Employee";
private static final String INDIVIDUO = "Individuo";
private static final String CDN_CURRENCY = "CdnCurrency";
private static final String DATA = "Data";
private static final String COMPANY = "Company";
private static final String COMPASS_DIRECTION = "CompassDirection";
private static final String NORTH_CONSTANT = "NORTH";
}
|
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/dynamic/DynamicJAXBFromXSDTestCases.java
|
/*******************************************************************************
* Copyright (c) 2011 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* rbarkhouse - 2.1 - initial implementation
******************************************************************************/
package org.eclipse.persistence.testing.jaxb.dynamic;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.UndeclaredThrowableException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import junit.framework.TestCase;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
import org.eclipse.persistence.testing.jaxb.dynamic.util.NoExtensionEntityResolver;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class DynamicJAXBFromXSDTestCases extends TestCase {
DynamicJAXBContext jaxbContext;
static {
try {
// Disable XJC's schema correctness check. XSD imports do not seem to work if this is left on.
System.setProperty("com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.noCorrectnessCheck", "true");
} catch (Exception e) {
// Ignore
}
}
public DynamicJAXBFromXSDTestCases(String name) throws Exception {
super(name);
}
public String getName() {
return "Dynamic JAXB: XSD: " + super.getName();
}
// ====================================================================
public void testXmlSchemaQualified() throws Exception {
// <xs:schema targetNamespace="myNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema"
// attributeFormDefault="qualified" elementFormDefault="qualified">
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_QUALIFIED);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 456);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Make sure "targetNamespace" was interpreted properly.
Node node = marshalDoc.getChildNodes().item(0);
assertEquals("Target Namespace was not set as expected.", "myNamespace", node.getNamespaceURI());
// Make sure "elementFormDefault" was interpreted properly.
// elementFormDefault=qualified, so the root node, the
// root node's attribute, and the child node should all have a prefix.
assertNotNull("Root node did not have namespace prefix as expected.", node.getPrefix());
Node attr = node.getAttributes().item(0);
assertNotNull("Attribute did not have namespace prefix as expected.", attr.getPrefix());
Node childNode = node.getChildNodes().item(0);
assertNotNull("Child node did not have namespace prefix as expected.", childNode.getPrefix());
}
public void testXmlSchemaUnqualified() throws Exception {
// <xs:schema targetNamespace="myNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema"
// attributeFormDefault="unqualified" elementFormDefault="unqualified">
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_UNQUALIFIED);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 456);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Make sure "targetNamespace" was interpreted properly.
Node node = marshalDoc.getChildNodes().item(0);
assertEquals("Target Namespace was not set as expected.", "myNamespace", node.getNamespaceURI());
// Make sure "elementFormDefault" was interpreted properly.
// elementFormDefault=unqualified, so the root node should have a prefix
// but the root node's attribute and child node should not.
assertNotNull("Root node did not have namespace prefix as expected.", node.getPrefix());
// Do not test attribute prefix with the Oracle xmlparserv2, it qualifies attributes by default.
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
if (builderFactory.getClass().getPackage().getName().contains("oracle")) {
return;
} else {
Node attr = node.getAttributes().item(0);
assertNull("Attribute should not have namespace prefix (" + attr.getPrefix() + ").", attr.getPrefix());
}
Node childNode = node.getChildNodes().item(0);
assertNull("Child node should not have namespace prefix.", childNode.getPrefix());
}
public void testXmlSchemaDefaults() throws Exception {
// <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_DEFAULTS);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(DEF_PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 456);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// "targetNamespace" should be null by default
Node node = marshalDoc.getChildNodes().item(0);
assertNull("Target Namespace was not null as expected.", node.getNamespaceURI());
// Make sure "elementFormDefault" was interpreted properly.
// When unset, no namespace qualification is done.
assertNull("Root node should not have namespace prefix.", node.getPrefix());
Node attr = node.getAttributes().item(0);
assertNull("Attribute should not have namespace prefix.", attr.getPrefix());
Node childNode = node.getChildNodes().item(0);
assertNull("Child node should not have namespace prefix.", childNode.getPrefix());
}
public void testXmlSchemaImport() throws Exception {
// <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
// <xs:import schemaLocation="xmlschema-currency" namespace="bankNamespace"/>
// Do not run this test if we are not using JDK 1.6
String javaVersion = System.getProperty("java.version");
if (!(javaVersion.startsWith("1.6"))) {
return;
}
// Do not run this test with the Oracle xmlparserv2, it will not properly hit the EntityResolver
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
if (builderFactory.getClass().getPackage().getName().contains("oracle")) {
return;
}
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_IMPORT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, new NoExtensionEntityResolver(), null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
DynamicEntity salary = jaxbContext.newDynamicEntity(BANK_PACKAGE + "." + CDN_CURRENCY);
assertNotNull("Could not create Dynamic Entity.", salary);
salary.set("value", new BigDecimal(75425.75));
person.set("name", "Bob Dobbs");
person.set("salary", salary);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Nothing to really test, if the import failed we couldn't have created the salary.
}
public void testXmlSeeAlso() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSEEALSO);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + EMPLOYEE);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
person.set("employeeId", "CA2472");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Nothing to really test, XmlSeeAlso isn't represented in an instance doc.
}
public void testXmlRootElement() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLROOTELEMENT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + INDIVIDUO);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getChildNodes().item(0);
assertEquals("Root element was not 'individuo' as expected.", "individuo", node.getLocalName());
}
public void testXmlType() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLTYPE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("email", "[email protected]");
person.set("lastName", "Dobbs");
person.set("id", 678);
person.set("phoneNumber", "212-555-8282");
person.set("firstName", "Bob");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Test that XmlType.propOrder was interpreted properly
Node node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "id", node.getLocalName());
node = marshalDoc.getDocumentElement().getChildNodes().item(1);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "first-name", node.getLocalName());
node = marshalDoc.getDocumentElement().getChildNodes().item(2);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "last-name", node.getLocalName());
node = marshalDoc.getDocumentElement().getChildNodes().item(3);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "phone-number", node.getLocalName());
node = marshalDoc.getDocumentElement().getChildNodes().item(4);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "email", node.getLocalName());
}
public void testXmlAttribute() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLATTRIBUTE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 777);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getChildNodes().item(0);
if (node.getAttributes() == null || node.getAttributes().getNamedItem("id") == null) {
fail("Attribute not present.");
}
}
public void testXmlElement() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("type", "O+");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertNotNull("Element not present.", node.getChildNodes());
String elemName = node.getChildNodes().item(0).getNodeName();
assertEquals("Element not present.", "type", elemName);
}
public void testXmlElementCollection() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTCOLLECTION);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList nicknames = new ArrayList();
nicknames.add("Bobby");
nicknames.add("Dobsy");
nicknames.add("Big Kahuna");
person.set("nickname", nicknames);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertNotNull("Element not present.", node.getChildNodes());
assertEquals("Unexpected number of child nodes present.", 3, node.getChildNodes().getLength());
}
public void testXmlElementCustomized() throws Exception {
// Customize the EclipseLink mapping generation by providing an eclipselink-oxm.xml
String metadataFile = RESOURCE_DIR + "eclipselink-oxm.xml";
InputStream iStream = ClassLoader.getSystemResourceAsStream(metadataFile);
HashMap<String, Source> metadataSourceMap = new HashMap<String, Source>();
metadataSourceMap.put(CONTEXT_PATH, new StreamSource(iStream));
Map<String, Object> props = new HashMap<String, Object>();
props.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap);
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, props);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("type", "O+");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertNotNull("Element not present.", node.getChildNodes());
String elemName = node.getChildNodes().item(0).getNodeName();
// 'type' was renamed to 'bloodType' in the OXM bindings file
assertEquals("Element not present.", "bloodType", elemName);
}
public void testXmlList() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLLIST);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList<String> codes = new ArrayList<String>(3);
codes.add("D1182");
codes.add("D1716");
codes.add("G7212");
person.set("name", "Bob Dobbs");
person.set("codes", codes);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertEquals("Unexpected number of nodes in document.", 2, node.getChildNodes().getLength());
String value = node.getChildNodes().item(1).getTextContent();
assertEquals("Unexpected element contents.", "D1182 D1716 G7212", value);
}
public void testXmlValue() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLVALUE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
DynamicEntity salary = jaxbContext.newDynamicEntity(PACKAGE + "." + CDN_CURRENCY);
assertNotNull("Could not create Dynamic Entity.", salary);
salary.set("value", new BigDecimal(75100));
person.set("name", "Bob Dobbs");
person.set("salary", salary);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Nothing to really test, XmlValue isn't represented in an instance doc.
}
public void testXmlAnyElement() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLANYELEMENT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
person.set("any", "StringValue");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertTrue("Any element not found.", node.getChildNodes().item(1).getNodeType() == Node.TEXT_NODE);
}
public void testXmlAnyAttribute() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLANYATTRIBUTE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
Map<QName, Object> otherAttributes = new HashMap<QName, Object>();
otherAttributes.put(new QName("foo"), new BigDecimal(1234));
otherAttributes.put(new QName("bar"), Boolean.FALSE);
person.set("name", "Bob Dobbs");
person.set("otherAttributes", otherAttributes);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
Node otherAttributesNode = node.getAttributes().getNamedItem("foo");
assertNotNull("'foo' attribute not found.", otherAttributesNode);
otherAttributesNode = node.getAttributes().getNamedItem("bar");
assertNotNull("'bar' attribute not found.", otherAttributesNode);
}
public void testXmlMixed() throws Exception {
// Also tests XmlElementRef / XmlElementRefs
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLMIXED);
try {
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
} catch (JAXBException e) {
// If running in a non-JAXB 2.2 environment, we will get this error because the required() method
// on @XmlElementRef is missing. Just ignore this and pass the test.
if (e.getLinkedException() instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
}
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList list = new ArrayList();
list.add("Hello");
list.add(new JAXBElement<String>(new QName("myNamespace", "title"), String.class, person.getClass(), "MR"));
list.add(new JAXBElement<String>(new QName("myNamespace", "name"), String.class, person.getClass(), "Bob Dobbs"));
list.add(", your point balance is");
list.add(new JAXBElement<BigInteger>(new QName("myNamespace", "rewardPoints"), BigInteger.class, person.getClass(), BigInteger.valueOf(175)));
list.add("Visit www.rewards.com!");
person.set("content", list);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertTrue("Unexpected number of elements.", node.getChildNodes().getLength() == 6);
}
public void testXmlId() throws Exception {
// Tests both XmlId and XmlIdRef
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLID);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity data = jaxbContext.newDynamicEntity(PACKAGE + "." + DATA);
assertNotNull("Could not create Dynamic Entity.", data);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
DynamicEntity company = jaxbContext.newDynamicEntity(PACKAGE + "." + COMPANY);
assertNotNull("Could not create Dynamic Entity.", company);
company.set("name", "ACME International");
company.set("address", "165 Main St, Anytown US, 93012");
company.set("id", "882");
person.set("name", "Bob Dobbs");
person.set("company", company);
data.set("person", person);
data.set("company", company);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(data, marshalDoc);
// 'person' node
Node pNode = marshalDoc.getDocumentElement().getChildNodes().item(0);
// 'company' node
Node cNode = pNode.getChildNodes().item(1);
// If IDREF worked properly, the company element should only contain the id of the company object
assertEquals("'company' has unexpected number of child nodes.", 1, cNode.getChildNodes().getLength());
}
public void testXmlElements() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTS);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList list = new ArrayList(1);
list.add("BOB");
person.set("nameOrReferenceNumber", list);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected element name.", "name", node.getNodeName());
person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
list = new ArrayList(1);
list.add(328763);
person.set("nameOrReferenceNumber", list);
marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected element name.", "reference-number", node.getNodeName());
}
public void testXmlElementRef() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTREF);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList list = new ArrayList(1);
list.add("BOB");
person.set("nameOrReferenceNumber", list);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected element name.", "name", node.getNodeName());
person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
list = new ArrayList(1);
list.add(328763);
person.set("nameOrReferenceNumber", list);
marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected element name.", "reference-number", node.getNodeName());
}
public void testXmlSchemaType() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMATYPE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("dateOfBirth", DatatypeFactory.newInstance().newXMLGregorianCalendarDate(1976, 02, 17, DatatypeConstants.FIELD_UNDEFINED));
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected date value.", "1976-02-17", node.getTextContent());
}
public void testXmlEnum() throws Exception {
// Tests XmlEnum and XmlEnumValue
// This test schema contains exactly 6 enum values to test an ASM boundary case
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLENUM);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
Object NORTH = jaxbContext.getEnumConstant(PACKAGE + "." + COMPASS_DIRECTION, NORTH_CONSTANT);
assertNotNull("Could not find enum constant.", NORTH);
person.set("quadrant", NORTH);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testXmlEnumError() throws Exception {
// Tests XmlEnum and XmlEnumValue
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLENUM);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
Exception caughtException = null;
try {
Object NORTHWEST = jaxbContext.getEnumConstant(PACKAGE + "." + COMPASS_DIRECTION, "NORTHWEST");
} catch (Exception e) {
caughtException = e;
}
assertNotNull("Expected exception was not thrown.", caughtException);
}
public void testXmlElementDecl() throws Exception {
// Also tests XmlRegistry
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTDECL);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getChildNodes().item(0);
assertEquals("Root element was not 'individuo' as expected.", "individuo", node.getLocalName());
}
public void testSchemaWithJAXBBindings() throws Exception {
// jaxbcustom.xsd specifies that the generated package name should be "foo.bar" and
// the person type will be named MyPersonType in Java
InputStream inputStream = ClassLoader.getSystemResourceAsStream(JAXBCUSTOM);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity("foo.bar.MyPersonType");
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testSubstitutionGroupsUnmarshal() throws Exception {
try {
InputStream xsdStream = ClassLoader.getSystemResourceAsStream(SUBSTITUTION);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(xsdStream, null, null, null);
InputStream xmlStream = ClassLoader.getSystemResourceAsStream(PERSON_XML);
JAXBElement person = (JAXBElement) jaxbContext.createUnmarshaller().unmarshal(xmlStream);
assertEquals("Element was not substituted properly: ", new QName("myNamespace", "person"), person.getName());
JAXBElement name = (JAXBElement) ((DynamicEntity) person.getValue()).get("name");
assertEquals("Element was not substituted properly: ", new QName("myNamespace", "name"), name.getName());
// ====================================================================
InputStream xmlStream2 = ClassLoader.getSystemResourceAsStream(PERSONNE_XML);
JAXBElement person2 = (JAXBElement) jaxbContext.createUnmarshaller().unmarshal(xmlStream2);
assertEquals("Element was not substituted properly: ", new QName("myNamespace", "personne"), person2.getName());
JAXBElement name2 = (JAXBElement) ((DynamicEntity) person2.getValue()).get("name");
assertEquals("Element was not substituted properly: ", new QName("myNamespace", "nom"), name2.getName());
} catch (JAXBException e) {
// If running in a non-JAXB 2.2 environment, we will get this error because the required() method
// on @XmlElementRef is missing. Just ignore this and pass the test.
if (e.getLinkedException() instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
}
}
public void testSubstitutionGroupsMarshal() throws Exception {
try {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(SUBSTITUTION);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
QName personQName = new QName("myNamespace", "person");
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
JAXBElement<DynamicEntity> personElement = new JAXBElement<DynamicEntity>(personQName, DynamicEntity.class, person);
personElement.setValue(person);
QName nameQName = new QName("myNamespace", "name");
JAXBElement<String> nameElement = new JAXBElement<String>(nameQName, String.class, "Marty Friedman");
person.set("name", nameElement);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(personElement, marshalDoc);
Node node1 = marshalDoc.getDocumentElement();
assertEquals("Incorrect element name: ", "person", node1.getLocalName());
Node node2 = node1.getFirstChild();
assertEquals("Incorrect element name: ", "name", node2.getLocalName());
// ====================================================================
QName personneQName = new QName("myNamespace", "personne");
DynamicEntity personne = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
JAXBElement<DynamicEntity> personneElement = new JAXBElement<DynamicEntity>(personneQName, DynamicEntity.class, personne);
personneElement.setValue(personne);
QName nomQName = new QName("myNamespace", "nom");
JAXBElement<String> nomElement = new JAXBElement<String>(nomQName, String.class, "Marty Friedman");
personne.set("name", nomElement);
Document marshalDoc2 = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(personneElement, marshalDoc2);
Node node3 = marshalDoc2.getDocumentElement();
assertEquals("Incorrect element name: ", "personne", node3.getLocalName());
Node node4 = node3.getFirstChild();
assertEquals("Incorrect element name: ", "nom", node4.getLocalName());
} catch (JAXBException e) {
// If running in a non-JAXB 2.2 environment, we will get this error because the required() method
// on @XmlElementRef is missing. Just ignore this and pass the test.
if (e.getLinkedException() instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
}
}
// ====================================================================
public void testTypePreservation() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_DEFAULTS);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(DEF_PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 456);
person.set("name", "Bob Dobbs");
person.set("salary", 45000.00);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
DynamicEntity readPerson = (DynamicEntity) jaxbContext.createUnmarshaller().unmarshal(marshalDoc);
assertEquals("Property type was not preserved during unmarshal.", Double.class, readPerson.<Object>get("salary").getClass());
assertEquals("Property type was not preserved during unmarshal.", Integer.class, readPerson.<Object>get("id").getClass());
}
public void testNestedInnerClasses() throws Exception {
// Tests multiple levels of inner classes, eg. mynamespace.Person.RelatedResource.Link
InputStream inputStream = ClassLoader.getSystemResourceAsStream(NESTEDINNERCLASSES);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity("mynamespace.Person");
DynamicEntity resource = jaxbContext.newDynamicEntity("mynamespace.Person.RelatedResource");
DynamicEntity link = jaxbContext.newDynamicEntity("mynamespace.Person.RelatedResource.Link");
DynamicEntity link2 = jaxbContext.newDynamicEntity("mynamespace.Person.RelatedResource.Link");
link.set("linkName", "LINKFOO");
link2.set("linkName", "LINKFOO2");
resource.set("resourceName", "RESBAR");
ArrayList<DynamicEntity> links = new ArrayList<DynamicEntity>();
links.add(link);
links.add(link2);
resource.set("link", links);
person.set("name", "Bob Smith");
person.set("relatedResource", resource);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testBinary() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(BINARY);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
byte[] byteArray = new byte[] {30,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4};
DynamicEntity person = jaxbContext.newDynamicEntity("mynamespace.Person");
person.set("name", "B. Nary");
person.set("abyte", (byte) 30);
person.set("base64", byteArray);
person.set("hex", byteArray);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testBinaryGlobalType() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(BINARY2);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
byte[] byteArray = new byte[] {30,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4};
DynamicEntity person = jaxbContext.newDynamicEntity("mynamespace.Person");
person.set("name", "B. Nary");
person.set("abyte", (byte) 30);
person.set("base64", byteArray);
person.set("hex", byteArray);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testXMLSchemaSchema() throws Exception {
try {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMASCHEMA);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity schema = jaxbContext.newDynamicEntity("org.w3._2001.xmlschema.Schema");
schema.set("targetNamespace", "myNamespace");
Object QUALIFIED = jaxbContext.getEnumConstant("org.w3._2001.xmlschema.FormChoice", "QUALIFIED");
schema.set("attributeFormDefault", QUALIFIED);
DynamicEntity complexType = jaxbContext.newDynamicEntity("org.w3._2001.xmlschema.TopLevelComplexType");
complexType.set("name", "myComplexType");
List<DynamicEntity> complexTypes = new ArrayList<DynamicEntity>(1);
complexTypes.add(complexType);
schema.set("simpleTypeOrComplexTypeOrGroup", complexTypes);
List<Object> blocks = new ArrayList<Object>();
blocks.add("FOOBAR");
schema.set("blockDefault", blocks);
File f = new File("myschema.xsd");
jaxbContext.createMarshaller().marshal(schema, f);
} catch (JAXBException e) {
// If running in a non-JAXB 2.2 environment, we will get this error because the required() method
// on @XmlElementRef is missing. Just ignore this and pass the test.
if (e.getLinkedException() instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
}
}
// ====================================================================
private void print(Object o) throws Exception {
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(o, System.err);
}
// ====================================================================
private static final String RESOURCE_DIR = "org/eclipse/persistence/testing/jaxb/dynamic/";
private static final String CONTEXT_PATH = "mynamespace";
// Schema files used to test each annotation
private static final String XMLSCHEMA_QUALIFIED = RESOURCE_DIR + "xmlschema-qualified.xsd";
private static final String XMLSCHEMA_UNQUALIFIED = RESOURCE_DIR + "xmlschema-unqualified.xsd";
private static final String XMLSCHEMA_DEFAULTS = RESOURCE_DIR + "xmlschema-defaults.xsd";
private static final String XMLSCHEMA_IMPORT = RESOURCE_DIR + "xmlschema-import.xsd";
private static final String XMLSCHEMA_CURRENCY = RESOURCE_DIR + "xmlschema-currency.xsd";
private static final String XMLSEEALSO = RESOURCE_DIR + "xmlseealso.xsd";
private static final String XMLROOTELEMENT = RESOURCE_DIR + "xmlrootelement.xsd";
private static final String XMLTYPE = RESOURCE_DIR + "xmltype.xsd";
private static final String XMLATTRIBUTE = RESOURCE_DIR + "xmlattribute.xsd";
private static final String XMLELEMENT = RESOURCE_DIR + "xmlelement.xsd";
private static final String XMLLIST = RESOURCE_DIR + "xmllist.xsd";
private static final String XMLVALUE = RESOURCE_DIR + "xmlvalue.xsd";
private static final String XMLANYELEMENT = RESOURCE_DIR + "xmlanyelement.xsd";
private static final String XMLANYATTRIBUTE = RESOURCE_DIR + "xmlanyattribute.xsd";
private static final String XMLMIXED = RESOURCE_DIR + "xmlmixed.xsd";
private static final String XMLID = RESOURCE_DIR + "xmlid.xsd";
private static final String XMLELEMENTS = RESOURCE_DIR + "xmlelements.xsd";
private static final String XMLELEMENTREF = RESOURCE_DIR + "xmlelementref.xsd";
private static final String XMLSCHEMATYPE = RESOURCE_DIR + "xmlschematype.xsd";
private static final String XMLENUM = RESOURCE_DIR + "xmlenum.xsd";
private static final String XMLELEMENTDECL = RESOURCE_DIR + "xmlelementdecl.xsd";
private static final String XMLELEMENTCOLLECTION = RESOURCE_DIR + "xmlelement-collection.xsd";
private static final String JAXBCUSTOM = RESOURCE_DIR + "jaxbcustom.xsd";
private static final String SUBSTITUTION = RESOURCE_DIR + "substitution.xsd";
private static final String NESTEDINNERCLASSES = RESOURCE_DIR + "nestedinnerclasses.xsd";
private static final String BINARY = RESOURCE_DIR + "binary.xsd";
private static final String BINARY2 = RESOURCE_DIR + "binary2.xsd";
private static final String XMLSCHEMASCHEMA = RESOURCE_DIR + "XMLSchema.xsd";
// Test Instance Docs
private static final String PERSON_XML = RESOURCE_DIR + "sub-person-en.xml";
private static final String PERSONNE_XML = RESOURCE_DIR + "sub-personne-fr.xml";
// Names of types to instantiate
private static final String PACKAGE = "mynamespace";
private static final String DEF_PACKAGE = "generated";
private static final String BANK_PACKAGE = "banknamespace";
private static final String PERSON = "Person";
private static final String EMPLOYEE = "Employee";
private static final String INDIVIDUO = "Individuo";
private static final String CDN_CURRENCY = "CdnCurrency";
private static final String DATA = "Data";
private static final String COMPANY = "Company";
private static final String COMPASS_DIRECTION = "CompassDirection";
private static final String NORTH_CONSTANT = "NORTH";
}
|
New test case for bug 361994, no code change required
Former-commit-id: 61ff1d7cb9c8e9a55c663682388e6fa9c8873fd8
|
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/dynamic/DynamicJAXBFromXSDTestCases.java
|
New test case for bug 361994, no code change required
|
<ide><path>oxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/dynamic/DynamicJAXBFromXSDTestCases.java
<ide>
<ide> public String getName() {
<ide> return "Dynamic JAXB: XSD: " + super.getName();
<add> }
<add>
<add> public void testEclipseLinkSchema() throws Exception {
<add> // Bootstrapping from eclipselink_oxm_2_4.xsd will trigger a JAXB 2.2 API (javax.xml.bind.annotation.XmlElementRef.required())
<add> // so only run this test in Java 7
<add> if (System.getProperty("java.version").contains("1.7")) {
<add> InputStream inputStream = ClassLoader.getSystemResourceAsStream(ECLIPSELINK_SCHEMA);
<add> jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
<add> }
<ide> }
<ide>
<ide> // ====================================================================
<ide> private static final String BINARY2 = RESOURCE_DIR + "binary2.xsd";
<ide> private static final String XMLSCHEMASCHEMA = RESOURCE_DIR + "XMLSchema.xsd";
<ide>
<add> private static final String ECLIPSELINK_SCHEMA = "org/eclipse/persistence/jaxb/eclipselink_oxm_2_4.xsd";
<add>
<ide> // Test Instance Docs
<ide> private static final String PERSON_XML = RESOURCE_DIR + "sub-person-en.xml";
<ide> private static final String PERSONNE_XML = RESOURCE_DIR + "sub-personne-fr.xml";
|
|
Java
|
lgpl-2.1
|
39349fa393a7143c5a1b5096a389c132f05f95e1
| 0 |
xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.repository.internal.resources;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.common.SolrDocument;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.extension.Extension;
import org.xwiki.extension.internal.maven.MavenUtils;
import org.xwiki.extension.repository.xwiki.model.jaxb.AbstractExtension;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionAuthor;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionDependency;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionRating;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionScm;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionScmConnection;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionSummary;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionVersion;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionVersionSummary;
import org.xwiki.extension.repository.xwiki.model.jaxb.License;
import org.xwiki.extension.repository.xwiki.model.jaxb.ObjectFactory;
import org.xwiki.extension.repository.xwiki.model.jaxb.Property;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.query.Query;
import org.xwiki.query.QueryException;
import org.xwiki.ratings.AverageRatingApi;
import org.xwiki.ratings.RatingsManager;
import org.xwiki.repository.internal.RepositoryManager;
import org.xwiki.repository.internal.XWikiRepositoryModel;
import org.xwiki.repository.internal.XWikiRepositoryModel.SolrField;
import org.xwiki.rest.XWikiResource;
import org.xwiki.security.authorization.ContextualAuthorizationManager;
import org.xwiki.security.authorization.Right;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.classes.ListClass;
/**
* Base class for the annotation REST services, to implement common functionality to all annotation REST services.
*
* @version $Id$
* @since 3.2M3
*/
public abstract class AbstractExtensionRESTResource extends XWikiResource implements Initializable
{
public static final String[] EPROPERTIES_SUMMARY = new String[] {XWikiRepositoryModel.PROP_EXTENSION_ID,
XWikiRepositoryModel.PROP_EXTENSION_TYPE, XWikiRepositoryModel.PROP_EXTENSION_NAME};
public static final String[] EPROPERTIES_EXTRA = new String[] {XWikiRepositoryModel.PROP_EXTENSION_SUMMARY,
XWikiRepositoryModel.PROP_EXTENSION_DESCRIPTION, XWikiRepositoryModel.PROP_EXTENSION_WEBSITE,
XWikiRepositoryModel.PROP_EXTENSION_AUTHORS, XWikiRepositoryModel.PROP_EXTENSION_FEATURES,
XWikiRepositoryModel.PROP_EXTENSION_LICENSENAME, XWikiRepositoryModel.PROP_EXTENSION_SCMURL,
XWikiRepositoryModel.PROP_EXTENSION_SCMCONNECTION, XWikiRepositoryModel.PROP_EXTENSION_SCMDEVCONNECTION};
protected static final String DEFAULT_BOOST;
protected static final String DEFAULT_FL;
protected static Map<String, Integer> EPROPERTIES_INDEX = new HashMap<String, Integer>();
protected static String SELECT_EXTENSIONSUMMARY;
protected static String SELECT_EXTENSION;
static {
StringBuilder pattern = new StringBuilder();
int j = 0;
pattern.append("doc.name");
EPROPERTIES_INDEX.put("doc.name", j++);
pattern.append(", ");
pattern.append("doc.space");
EPROPERTIES_INDEX.put("doc.space", j++);
// Extension summary
for (int i = 0; i < EPROPERTIES_SUMMARY.length; ++i, ++j) {
String value = EPROPERTIES_SUMMARY[i];
pattern.append(", extension.");
pattern.append(value);
EPROPERTIES_INDEX.put(value, j);
}
SELECT_EXTENSIONSUMMARY = pattern.toString();
// Extension extra
for (int i = 0; i < EPROPERTIES_EXTRA.length; ++i, ++j) {
pattern.append(", extension.");
pattern.append(EPROPERTIES_EXTRA[i]);
EPROPERTIES_INDEX.put(EPROPERTIES_EXTRA[i], j);
}
SELECT_EXTENSION = pattern.toString();
// Solr
StringBuilder boostBuilder = new StringBuilder();
StringBuilder flBuilder = new StringBuilder("wiki,space,name");
for (SolrField field : XWikiRepositoryModel.SOLR_FIELDS.values()) {
// Boost
if (field.boost != null) {
if (boostBuilder.length() > 0) {
boostBuilder.append(' ');
}
boostBuilder.append(field.name);
boostBuilder.append('^');
boostBuilder.append(field.boost);
}
// Fields list
if (flBuilder.length() > 0) {
flBuilder.append(',');
}
flBuilder.append(field.name);
}
DEFAULT_BOOST = boostBuilder.toString();
DEFAULT_FL = flBuilder.toString();
}
@Inject
protected RepositoryManager repositoryManager;
@Inject
protected ContextualAuthorizationManager authorization;
@Inject
@Named("separate")
protected RatingsManager ratingsManager;
/**
* The object factory for model objects to be used when creating representations.
*/
protected ObjectFactory extensionObjectFactory;
@Override
public void initialize() throws InitializationException
{
super.initialize();
this.extensionObjectFactory = new ObjectFactory();
}
public XWikiDocument getExistingExtensionDocumentById(String extensionId) throws QueryException, XWikiException
{
XWikiDocument document = this.repositoryManager.getExistingExtensionDocumentById(extensionId);
if (document == null) {
throw new WebApplicationException(Status.NOT_FOUND);
}
return document;
}
protected Query createExtensionsCountQuery(String from, String where) throws QueryException
{
// select
String select = "count(extension." + XWikiRepositoryModel.PROP_EXTENSION_ID + ")";
return createExtensionsQuery(select, from, where, 0, -1, false);
}
protected long getExtensionsCountResult(Query query) throws QueryException
{
return ((Number) query.execute().get(0)).intValue();
}
protected Query createExtensionsQuery(String from, String where, int offset, int number) throws QueryException
{
// select
String select = SELECT_EXTENSION;
// TODO: add support for real lists: need a HQL or JPQL equivalent to MySQL GROUP_CONCAT
// * dependencies
// Link to last version object
if (where != null) {
where = "(" + where + ") and ";
} else {
where = "";
}
where +=
"extensionVersion." + XWikiRepositoryModel.PROP_VERSION_VERSION + " = extension."
+ XWikiRepositoryModel.PROP_EXTENSION_LASTVERSION;
return createExtensionsQuery(select, from, where, offset, number, true);
}
protected Query createExtensionsSummariesQuery(String from, String where, int offset, int number, boolean versions)
throws QueryException
{
String select = SELECT_EXTENSIONSUMMARY;
return createExtensionsQuery(select, from, where, offset, number, versions);
}
private Query createExtensionsQuery(String select, String from, String where, int offset, int number,
boolean versions) throws QueryException
{
// select
StringBuilder queryStr = new StringBuilder("select ");
queryStr.append(select);
if (versions) {
queryStr.append(", extensionVersion." + XWikiRepositoryModel.PROP_VERSION_VERSION + "");
}
// from
queryStr
.append(" from Document doc, doc.object(" + XWikiRepositoryModel.EXTENSION_CLASSNAME + ") as extension");
if (versions) {
queryStr
.append(", doc.object(" + XWikiRepositoryModel.EXTENSIONVERSION_CLASSNAME + ") as extensionVersion");
}
if (from != null) {
queryStr.append(',');
queryStr.append(from);
}
// where
queryStr.append(" where ");
if (where != null) {
queryStr.append('(');
queryStr.append(where);
queryStr.append(')');
queryStr.append(" and ");
}
queryStr.append("extension." + XWikiRepositoryModel.PROP_EXTENSION_VALIDEXTENSION + " = 1");
Query query = this.queryManager.createQuery(queryStr.toString(), Query.XWQL);
if (offset > 0) {
query.setOffset(offset);
}
if (number > 0) {
query.setLimit(number);
}
return query;
}
protected BaseObject getExtensionObject(XWikiDocument extensionDocument)
{
return extensionDocument.getXObject(XWikiRepositoryModel.EXTENSION_CLASSREFERENCE);
}
protected BaseObject getExtensionObject(String extensionId) throws XWikiException, QueryException
{
return getExtensionObject(getExistingExtensionDocumentById(extensionId));
}
protected BaseObject getExtensionVersionObject(XWikiDocument extensionDocument, String version)
{
if (version == null) {
List<BaseObject> objects =
extensionDocument.getXObjects(XWikiRepositoryModel.EXTENSIONVERSION_CLASSREFERENCE);
if (objects == null || objects.isEmpty()) {
return null;
} else {
return objects.get(objects.size() - 1);
}
}
return extensionDocument.getObject(XWikiRepositoryModel.EXTENSIONVERSION_CLASSNAME, "version", version, false);
}
protected BaseObject getExtensionVersionObject(String extensionId, String version) throws XWikiException,
QueryException
{
return getExtensionVersionObject(getExistingExtensionDocumentById(extensionId), version);
}
protected <E extends AbstractExtension> E createExtension(XWikiDocument extensionDocument, String version)
{
BaseObject extensionObject = getExtensionObject(extensionDocument);
DocumentReference extensionDocumentReference = extensionDocument.getDocumentReference();
if (extensionObject == null) {
throw new WebApplicationException(Status.NOT_FOUND);
}
AbstractExtension extension;
ExtensionVersion extensionVersion;
if (version == null) {
extension = this.extensionObjectFactory.createExtension();
extensionVersion = null;
} else {
BaseObject extensionVersionObject = getExtensionVersionObject(extensionDocument, version);
if (extensionVersionObject == null) {
throw new WebApplicationException(Status.NOT_FOUND);
}
extensionVersion = this.extensionObjectFactory.createExtensionVersion();
extension = extensionVersion;
extensionVersion.setVersion((String) getValue(extensionVersionObject,
XWikiRepositoryModel.PROP_VERSION_VERSION));
}
extension.setId((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_ID));
extension.setType((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_TYPE));
License license = this.extensionObjectFactory.createLicense();
license.setName((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_LICENSENAME));
extension.getLicenses().add(license);
extension.setRating(getExtensionRating(extensionDocumentReference));
extension.setSummary((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_SUMMARY));
extension.setDescription((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_DESCRIPTION));
extension.setName((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_NAME));
extension.setCategory((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_CATEGORY));
extension.setWebsite(StringUtils.defaultIfEmpty(
(String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_WEBSITE),
extensionDocument.getExternalURL("view", getXWikiContext())));
// SCM
ExtensionScm scm = new ExtensionScm();
scm.setUrl((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_SCMURL));
scm.setConnection(toScmConnection((String) getValue(extensionObject,
XWikiRepositoryModel.PROP_EXTENSION_SCMCONNECTION)));
scm.setDeveloperConnection(toScmConnection((String) getValue(extensionObject,
XWikiRepositoryModel.PROP_EXTENSION_SCMDEVCONNECTION)));
extension.setScm(scm);
// Authors
List<String> authors = (List<String>) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_AUTHORS);
if (authors != null) {
for (String authorId : authors) {
extension.getAuthors().add(resolveExtensionAuthor(authorId));
}
}
// Features
List<String> features = (List<String>) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_FEATURES);
if (features != null) {
extension.getFeatures().addAll(features);
}
// Properties
List<String> properties =
(List<String>) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_PROPERTIES);
if (properties != null) {
for (String stringProperty : properties) {
int index = stringProperty.indexOf('=');
if (index > 0) {
Property property = new Property();
property.setKey(stringProperty.substring(0, index));
property.setStringValue((index + 1) < stringProperty.length() ? stringProperty.substring(index + 1)
: "");
extension.getProperties().add(property);
}
}
}
// Dependencies
if (extensionVersion != null) {
List<BaseObject> dependencies =
extensionDocument.getXObjects(XWikiRepositoryModel.EXTENSIONDEPENDENCY_CLASSREFERENCE);
if (dependencies != null) {
for (BaseObject dependencyObject : dependencies) {
if (dependencyObject != null) {
if (StringUtils.equals(
getValue(dependencyObject, XWikiRepositoryModel.PROP_DEPENDENCY_EXTENSIONVERSION,
(String) null), version)) {
ExtensionDependency dependency = extensionObjectFactory.createExtensionDependency();
dependency.setId((String) getValue(dependencyObject,
XWikiRepositoryModel.PROP_DEPENDENCY_ID));
dependency.setConstraint((String) getValue(dependencyObject,
XWikiRepositoryModel.PROP_DEPENDENCY_CONSTRAINT));
extensionVersion.getDependencies().add(dependency);
}
}
}
}
}
return (E) extension;
}
protected ExtensionScmConnection toScmConnection(String connectionString)
{
if (connectionString != null) {
org.xwiki.extension.ExtensionScmConnection connection =
MavenUtils.toExtensionScmConnection(connectionString);
ExtensionScmConnection restConnection = new ExtensionScmConnection();
restConnection.setPath(connection.getPath());
restConnection.setSystem(connection.getSystem());
return restConnection;
}
return null;
}
protected ExtensionAuthor resolveExtensionAuthor(String authorId)
{
ExtensionAuthor author = new ExtensionAuthor();
XWikiContext xcontext = getXWikiContext();
XWikiDocument document;
try {
document = xcontext.getWiki().getDocument(authorId, xcontext);
} catch (XWikiException e) {
document = null;
}
if (document != null && !document.isNew()) {
author.setName(xcontext.getWiki().getPlainUserName(document.getDocumentReference(), xcontext));
author.setUrl(document.getExternalURL("view", xcontext));
} else {
author.setName(authorId);
}
return author;
}
protected void getExtensions(List<ExtensionVersion> extensions, Query query) throws QueryException
{
List<Object[]> entries = query.execute();
for (Object[] entry : entries) {
extensions.add(createExtensionVersionFromQueryResult(entry));
}
}
protected <T> T getSolrValue(SolrDocument document, String property)
{
Object value = document.getFieldValue(XWikiRepositoryModel.toSolrField(property));
if (value instanceof Collection) {
Collection collectionValue = (Collection) value;
value = collectionValue.size() > 0 ? collectionValue.iterator().next() : null;
}
return (T) value;
}
protected <T> Collection<T> getSolrValues(SolrDocument document, String property)
{
return (Collection) document.getFieldValues(XWikiRepositoryModel.toSolrField(property));
}
protected <T> T getQueryValue(Object[] entry, String property)
{
return (T) entry[EPROPERTIES_INDEX.get(property)];
}
protected ExtensionVersion createExtensionVersionFromQueryResult(Object[] entry)
{
XWikiContext xcontext = getXWikiContext();
String documentName = (String) entry[0];
String documentSpace = (String) entry[1];
ExtensionVersion extension = this.extensionObjectFactory.createExtensionVersion();
extension.setId(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_ID));
extension.setType(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_TYPE));
extension.setName(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_NAME));
extension.setSummary(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_SUMMARY));
extension.setDescription(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_DESCRIPTION));
// SCM
ExtensionScm scm = new ExtensionScm();
scm.setUrl(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_SCMURL));
scm.setConnection(toScmConnection(this.<String>getQueryValue(entry,
XWikiRepositoryModel.PROP_EXTENSION_SCMCONNECTION)));
scm.setDeveloperConnection(toScmConnection(this.<String>getQueryValue(entry,
XWikiRepositoryModel.PROP_EXTENSION_SCMDEVCONNECTION)));
extension.setScm(scm);
// Rating
DocumentReference extensionDocumentReference =
new DocumentReference(xcontext.getWikiId(), documentSpace, documentName);
// FIXME: this adds potentially tons of new request to what used to be carefully crafted to produce a single
// request for the whole search... Should be cached in a filed of the document (like the last version is for example).
extension.setRating(getExtensionRating(extensionDocumentReference));
// Website
extension.setWebsite(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_WEBSITE));
if (StringUtils.isBlank(extension.getWebsite())) {
extension.setWebsite(xcontext.getWiki().getURL(
new DocumentReference(xcontext.getWikiId(), documentSpace, documentName), "view", xcontext));
}
// Authors
for (String authorId : ListClass.getListFromString(
this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_AUTHORS), "|", false)) {
extension.getAuthors().add(resolveExtensionAuthor(authorId));
}
// Features
extension.getFeatures().addAll(
ListClass.getListFromString(
this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_FEATURES), "|", false));
// License
License license = this.extensionObjectFactory.createLicense();
license.setName(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_LICENSENAME));
extension.getLicenses().add(license);
// Version
extension.setVersion((String) entry[EPROPERTIES_INDEX.size()]);
// TODO: add support for
// * dependencies
return extension;
}
protected ExtensionVersion createExtensionVersionFromSolrDocument(SolrDocument document)
{
XWikiContext xcontext = getXWikiContext();
String documentName = (String) document.getFieldValue("space");
String documentSpace = (String) document.getFieldValue("name");
ExtensionVersion extension = this.extensionObjectFactory.createExtensionVersion();
extension.setId(this.<String>getSolrValue(document, Extension.FIELD_ID));
extension.setType(this.<String>getSolrValue(document, Extension.FIELD_TYPE));
extension.setName(this.<String>getSolrValue(document, Extension.FIELD_NAME));
extension.setSummary(this.<String>getSolrValue(document, Extension.FIELD_SUMMARY));
extension.setDescription(this.<String>getSolrValue(document, Extension.FIELD_DESCRIPTION));
// SCM
ExtensionScm scm = new ExtensionScm();
scm.setUrl(this.<String>getSolrValue(document, Extension.FIELD_SCM));
scm.setConnection(toScmConnection(this.<String>getSolrValue(document,
XWikiRepositoryModel.PROP_EXTENSION_SCMCONNECTION)));
scm.setDeveloperConnection(toScmConnection(this.<String>getSolrValue(document,
XWikiRepositoryModel.PROP_EXTENSION_SCMDEVCONNECTION)));
extension.setScm(scm);
// Rating
// FIXME: this adds potentially tons of new DB requests to what used to be carefully crafted to produce a single
// request for the whole search... Should be cached in a field of the document (like the last version is for example).
DocumentReference extensionDocumentReference =
new DocumentReference(xcontext.getWikiId(), documentSpace, documentName);
extension.setRating(getExtensionRating(extensionDocumentReference));
// Website
extension.setWebsite(this.<String>getSolrValue(document, Extension.FIELD_WEBSITE));
if (StringUtils.isBlank(extension.getWebsite())) {
extension.setWebsite(xcontext.getWiki().getURL(
new DocumentReference(xcontext.getWikiId(), documentSpace, documentName), "view", xcontext));
}
// Authors
for (String authorId : this.<String>getSolrValues(document, Extension.FIELD_AUTHORS)) {
extension.getAuthors().add(resolveExtensionAuthor(authorId));
}
// Features
extension.getFeatures().addAll(this.<String>getSolrValues(document, Extension.FIELD_FEATURES));
// License
License license = this.extensionObjectFactory.createLicense();
license.setName(this.<String>getSolrValue(document, Extension.FIELD_LICENSE));
extension.getLicenses().add(license);
// Version
extension.setVersion(this.<String>getSolrValue(document, Extension.FIELD_VERSION));
// TODO: add support for
// * dependencies
return extension;
}
protected ExtensionRating getExtensionRating(DocumentReference extensionDocumentReference)
{
ExtensionRating extensionRating = this.extensionObjectFactory.createExtensionRating();
try {
AverageRatingApi averageRating =
new AverageRatingApi(ratingsManager.getAverageRating(extensionDocumentReference));
extensionRating.setTotalVotes(averageRating.getNbVotes());
extensionRating.setAverageVote(averageRating.getAverageVote());
} catch (XWikiException e) {
extensionRating.setTotalVotes(0);
extensionRating.setAverageVote(0);
}
return extensionRating;
}
protected <E extends ExtensionSummary> void getExtensionSummaries(List<E> extensions, Query query)
throws QueryException
{
List<Object[]> entries = query.execute();
for (Object[] entry : entries) {
extensions.add((E) createExtensionSummaryFromQueryResult(entry));
}
}
protected ExtensionSummary createExtensionSummaryFromQueryResult(Object[] entry)
{
ExtensionSummary extension;
ExtensionVersionSummary extensionVersion;
int versionIndex = EPROPERTIES_INDEX.get(EPROPERTIES_SUMMARY[EPROPERTIES_SUMMARY.length - 1]) + 1;
if (entry.length == versionIndex) {
// It's a extension summary without version
extension = this.extensionObjectFactory.createExtensionSummary();
extensionVersion = null;
} else {
extension = extensionVersion = this.extensionObjectFactory.createExtensionVersionSummary();
extensionVersion.setVersion((String) entry[versionIndex]);
}
extension.setId(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_ID));
extension.setType(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_TYPE));
extension.setName(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_NAME));
return extension;
}
protected <T> T getValue(BaseObject object, String field)
{
return getValue(object, field, (T) null);
}
protected <T> T getValue(BaseObject object, String field, T def)
{
BaseProperty<?> property = (BaseProperty<?>) object.safeget(field);
return property != null ? (T) property.getValue() : def;
}
protected ResponseBuilder getAttachmentResponse(XWikiAttachment xwikiAttachment) throws XWikiException
{
if (xwikiAttachment == null) {
throw new WebApplicationException(Status.NOT_FOUND);
}
ResponseBuilder response = Response.ok();
XWikiContext xcontext = getXWikiContext();
response = response.type(xwikiAttachment.getMimeType(xcontext));
response = response.entity(xwikiAttachment.getContent(xcontext));
response =
response.header("content-disposition", "attachment; filename=\"" + xwikiAttachment.getFilename() + "\"");
return response;
}
protected void checkRights(XWikiDocument document) throws XWikiException
{
if (!this.authorization.hasAccess(Right.VIEW, document.getDocumentReference())) {
throw new WebApplicationException(Status.FORBIDDEN);
}
}
}
|
xwiki-platform-core/xwiki-platform-repository/xwiki-platform-repository-server-api/src/main/java/org/xwiki/repository/internal/resources/AbstractExtensionRESTResource.java
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.repository.internal.resources;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.common.SolrDocument;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.extension.Extension;
import org.xwiki.extension.internal.maven.MavenUtils;
import org.xwiki.extension.repository.xwiki.model.jaxb.AbstractExtension;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionAuthor;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionDependency;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionRating;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionScm;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionScmConnection;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionSummary;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionVersion;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionVersionSummary;
import org.xwiki.extension.repository.xwiki.model.jaxb.License;
import org.xwiki.extension.repository.xwiki.model.jaxb.ObjectFactory;
import org.xwiki.extension.repository.xwiki.model.jaxb.Property;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.query.Query;
import org.xwiki.query.QueryException;
import org.xwiki.ratings.AverageRatingApi;
import org.xwiki.ratings.RatingsManager;
import org.xwiki.repository.internal.RepositoryManager;
import org.xwiki.repository.internal.XWikiRepositoryModel;
import org.xwiki.repository.internal.XWikiRepositoryModel.SolrField;
import org.xwiki.rest.XWikiResource;
import org.xwiki.security.authorization.ContextualAuthorizationManager;
import org.xwiki.security.authorization.Right;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.classes.ListClass;
/**
* Base class for the annotation REST services, to implement common functionality to all annotation REST services.
*
* @version $Id$
* @since 3.2M3
*/
public abstract class AbstractExtensionRESTResource extends XWikiResource implements Initializable
{
public static final String[] EPROPERTIES_SUMMARY = new String[] {XWikiRepositoryModel.PROP_EXTENSION_ID,
XWikiRepositoryModel.PROP_EXTENSION_TYPE, XWikiRepositoryModel.PROP_EXTENSION_NAME};
public static final String[] EPROPERTIES_EXTRA = new String[] {XWikiRepositoryModel.PROP_EXTENSION_SUMMARY,
XWikiRepositoryModel.PROP_EXTENSION_DESCRIPTION, XWikiRepositoryModel.PROP_EXTENSION_WEBSITE,
XWikiRepositoryModel.PROP_EXTENSION_AUTHORS, XWikiRepositoryModel.PROP_EXTENSION_FEATURES,
XWikiRepositoryModel.PROP_EXTENSION_LICENSENAME, XWikiRepositoryModel.PROP_EXTENSION_SCMURL,
XWikiRepositoryModel.PROP_EXTENSION_SCMCONNECTION, XWikiRepositoryModel.PROP_EXTENSION_SCMDEVCONNECTION};
protected static final String DEFAULT_BOOST;
protected static final String DEFAULT_FL;
protected static Map<String, Integer> EPROPERTIES_INDEX = new HashMap<String, Integer>();
protected static String SELECT_EXTENSIONSUMMARY;
protected static String SELECT_EXTENSION;
static {
StringBuilder pattern = new StringBuilder();
int j = 0;
pattern.append("doc.name");
EPROPERTIES_INDEX.put("doc.name", j++);
pattern.append(", ");
pattern.append("doc.space");
EPROPERTIES_INDEX.put("doc.space", j++);
// Extension summary
for (int i = 0; i < EPROPERTIES_SUMMARY.length; ++i, ++j) {
String value = EPROPERTIES_SUMMARY[i];
pattern.append(", extension.");
pattern.append(value);
EPROPERTIES_INDEX.put(value, j);
}
SELECT_EXTENSIONSUMMARY = pattern.toString();
// Extension extra
for (int i = 0; i < EPROPERTIES_EXTRA.length; ++i, ++j) {
pattern.append(", extension.");
pattern.append(EPROPERTIES_EXTRA[i]);
EPROPERTIES_INDEX.put(EPROPERTIES_EXTRA[i], j);
}
SELECT_EXTENSION = pattern.toString();
// Solr
StringBuilder boostBuilder = new StringBuilder();
StringBuilder flBuilder = new StringBuilder("wiki,space,name");
for (SolrField field : XWikiRepositoryModel.SOLR_FIELDS.values()) {
// Boost
if (field.boost != null) {
if (boostBuilder.length() > 0) {
boostBuilder.append(' ');
}
boostBuilder.append(field.name);
boostBuilder.append('^');
boostBuilder.append(field.boost);
}
// Fields list
if (flBuilder.length() > 0) {
flBuilder.append(',');
}
flBuilder.append(field.name);
}
DEFAULT_BOOST = boostBuilder.toString();
DEFAULT_FL = flBuilder.toString();
}
@Inject
protected RepositoryManager repositoryManager;
@Inject
protected ContextualAuthorizationManager authorization;
@Inject
@Named("separate")
protected RatingsManager ratingsManager;
/**
* The object factory for model objects to be used when creating representations.
*/
protected ObjectFactory extensionObjectFactory;
@Override
public void initialize() throws InitializationException
{
super.initialize();
this.extensionObjectFactory = new ObjectFactory();
}
public XWikiDocument getExistingExtensionDocumentById(String extensionId) throws QueryException, XWikiException
{
XWikiDocument document = this.repositoryManager.getExistingExtensionDocumentById(extensionId);
if (document == null) {
throw new WebApplicationException(Status.NOT_FOUND);
}
return document;
}
protected Query createExtensionsCountQuery(String from, String where) throws QueryException
{
// select
String select = "count(extension." + XWikiRepositoryModel.PROP_EXTENSION_ID + ")";
return createExtensionsQuery(select, from, where, 0, -1, false);
}
protected long getExtensionsCountResult(Query query) throws QueryException
{
return ((Number) query.execute().get(0)).intValue();
}
protected Query createExtensionsQuery(String from, String where, int offset, int number) throws QueryException
{
// select
String select = SELECT_EXTENSION;
// TODO: add support for real lists: need a HQL or JPQL equivalent to MySQL GROUP_CONCAT
// * dependencies
// Link to last version object
if (where != null) {
where = "(" + where + ") and ";
} else {
where = "";
}
where +=
"extensionVersion." + XWikiRepositoryModel.PROP_VERSION_VERSION + " = extension."
+ XWikiRepositoryModel.PROP_EXTENSION_LASTVERSION;
return createExtensionsQuery(select, from, where, offset, number, true);
}
protected Query createExtensionsSummariesQuery(String from, String where, int offset, int number, boolean versions)
throws QueryException
{
String select = SELECT_EXTENSIONSUMMARY;
return createExtensionsQuery(select, from, where, offset, number, versions);
}
private Query createExtensionsQuery(String select, String from, String where, int offset, int number,
boolean versions) throws QueryException
{
// select
StringBuilder queryStr = new StringBuilder("select ");
queryStr.append(select);
if (versions) {
queryStr.append(", extensionVersion." + XWikiRepositoryModel.PROP_VERSION_VERSION + "");
}
// from
queryStr
.append(" from Document doc, doc.object(" + XWikiRepositoryModel.EXTENSION_CLASSNAME + ") as extension");
if (versions) {
queryStr
.append(", doc.object(" + XWikiRepositoryModel.EXTENSIONVERSION_CLASSNAME + ") as extensionVersion");
}
if (from != null) {
queryStr.append(',');
queryStr.append(from);
}
// where
queryStr.append(" where ");
if (where != null) {
queryStr.append('(');
queryStr.append(where);
queryStr.append(')');
queryStr.append(" and ");
}
queryStr.append("extension." + XWikiRepositoryModel.PROP_EXTENSION_VALIDEXTENSION + " = 1");
Query query = this.queryManager.createQuery(queryStr.toString(), Query.XWQL);
if (offset > 0) {
query.setOffset(offset);
}
if (number > 0) {
query.setLimit(number);
}
return query;
}
protected BaseObject getExtensionObject(XWikiDocument extensionDocument)
{
return extensionDocument.getXObject(XWikiRepositoryModel.EXTENSION_CLASSREFERENCE);
}
protected BaseObject getExtensionObject(String extensionId) throws XWikiException, QueryException
{
return getExtensionObject(getExistingExtensionDocumentById(extensionId));
}
protected BaseObject getExtensionVersionObject(XWikiDocument extensionDocument, String version)
{
if (version == null) {
List<BaseObject> objects =
extensionDocument.getXObjects(XWikiRepositoryModel.EXTENSIONVERSION_CLASSREFERENCE);
if (objects == null || objects.isEmpty()) {
return null;
} else {
return objects.get(objects.size() - 1);
}
}
return extensionDocument.getObject(XWikiRepositoryModel.EXTENSIONVERSION_CLASSNAME, "version", version, false);
}
protected BaseObject getExtensionVersionObject(String extensionId, String version) throws XWikiException,
QueryException
{
return getExtensionVersionObject(getExistingExtensionDocumentById(extensionId), version);
}
protected <E extends AbstractExtension> E createExtension(XWikiDocument extensionDocument, String version)
{
BaseObject extensionObject = getExtensionObject(extensionDocument);
DocumentReference extensionDocumentReference = extensionDocument.getDocumentReference();
if (extensionObject == null) {
throw new WebApplicationException(Status.NOT_FOUND);
}
AbstractExtension extension;
ExtensionVersion extensionVersion;
if (version == null) {
extension = this.extensionObjectFactory.createExtension();
extensionVersion = null;
} else {
BaseObject extensionVersionObject = getExtensionVersionObject(extensionDocument, version);
if (extensionVersionObject == null) {
throw new WebApplicationException(Status.NOT_FOUND);
}
extensionVersion = this.extensionObjectFactory.createExtensionVersion();
extension = extensionVersion;
extensionVersion.setVersion((String) getValue(extensionVersionObject,
XWikiRepositoryModel.PROP_VERSION_VERSION));
}
extension.setId((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_ID));
extension.setType((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_TYPE));
License license = this.extensionObjectFactory.createLicense();
license.setName((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_LICENSENAME));
extension.getLicenses().add(license);
extension.setRating(getExtensionRating(extensionDocumentReference));
extension.setSummary((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_SUMMARY));
extension.setDescription((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_DESCRIPTION));
extension.setName((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_NAME));
extension.setCategory((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_CATEGORY));
extension.setWebsite(StringUtils.defaultIfEmpty(
(String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_WEBSITE),
extensionDocument.getExternalURL("view", getXWikiContext())));
// SCM
ExtensionScm scm = new ExtensionScm();
scm.setUrl((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_SCMURL));
scm.setConnection(toScmConnection((String) getValue(extensionObject,
XWikiRepositoryModel.PROP_EXTENSION_SCMCONNECTION)));
scm.setDeveloperConnection(toScmConnection((String) getValue(extensionObject,
XWikiRepositoryModel.PROP_EXTENSION_SCMDEVCONNECTION)));
extension.setScm(scm);
// Authors
List<String> authors = (List<String>) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_AUTHORS);
if (authors != null) {
for (String authorId : authors) {
extension.getAuthors().add(resolveExtensionAuthor(authorId));
}
}
// Features
List<String> features = (List<String>) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_FEATURES);
if (features != null) {
extension.getFeatures().addAll(features);
}
// Properties
List<String> properties =
(List<String>) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_PROPERTIES);
if (properties != null) {
for (String stringProperty : properties) {
int index = stringProperty.indexOf('=');
if (index > 0) {
Property property = new Property();
property.setKey(stringProperty.substring(0, index));
property.setStringValue((index + 1) < stringProperty.length() ? stringProperty.substring(index + 1)
: "");
extension.getProperties().add(property);
}
}
}
// Dependencies
if (extensionVersion != null) {
List<BaseObject> dependencies =
extensionDocument.getXObjects(XWikiRepositoryModel.EXTENSIONDEPENDENCY_CLASSREFERENCE);
if (dependencies != null) {
for (BaseObject dependencyObject : dependencies) {
if (dependencyObject != null) {
if (StringUtils.equals(
getValue(dependencyObject, XWikiRepositoryModel.PROP_DEPENDENCY_EXTENSIONVERSION,
(String) null), version)) {
ExtensionDependency dependency = extensionObjectFactory.createExtensionDependency();
dependency.setId((String) getValue(dependencyObject,
XWikiRepositoryModel.PROP_DEPENDENCY_ID));
dependency.setConstraint((String) getValue(dependencyObject,
XWikiRepositoryModel.PROP_DEPENDENCY_CONSTRAINT));
extensionVersion.getDependencies().add(dependency);
}
}
}
}
}
return (E) extension;
}
protected ExtensionScmConnection toScmConnection(String connectionString)
{
if (connectionString != null) {
org.xwiki.extension.ExtensionScmConnection connection =
MavenUtils.toExtensionScmConnection(connectionString);
ExtensionScmConnection restConnection = new ExtensionScmConnection();
restConnection.setPath(connection.getPath());
restConnection.setSystem(connection.getSystem());
return restConnection;
}
return null;
}
protected ExtensionAuthor resolveExtensionAuthor(String authorId)
{
ExtensionAuthor author = new ExtensionAuthor();
XWikiContext xcontext = getXWikiContext();
XWikiDocument document;
try {
document = xcontext.getWiki().getDocument(authorId, xcontext);
} catch (XWikiException e) {
document = null;
}
if (document != null && !document.isNew()) {
author.setName(xcontext.getWiki().getPlainUserName(document.getDocumentReference(), xcontext));
author.setUrl(document.getExternalURL("view", xcontext));
} else {
author.setName(authorId);
}
return author;
}
protected void getExtensions(List<ExtensionVersion> extensions, Query query) throws QueryException
{
List<Object[]> entries = query.execute();
for (Object[] entry : entries) {
extensions.add(createExtensionVersionFromQueryResult(entry));
}
}
protected <T> T getSolrValue(SolrDocument document, String property)
{
Object value = document.getFieldValue(XWikiRepositoryModel.toSolrField(property));
if (value instanceof Collection) {
Collection collectionValue = (Collection) value;
value = collectionValue.size() > 0 ? collectionValue.iterator().next() : null;
}
return (T) value;
}
protected <T> Collection<T> getSolrValues(SolrDocument document, String property)
{
return (Collection) document.getFieldValues(XWikiRepositoryModel.toSolrField(property));
}
protected <T> T getQueryValue(Object[] entry, String property)
{
return (T) entry[EPROPERTIES_INDEX.get(property)];
}
protected ExtensionVersion createExtensionVersionFromQueryResult(Object[] entry)
{
XWikiContext xcontext = getXWikiContext();
String documentName = (String) entry[0];
String documentSpace = (String) entry[1];
ExtensionVersion extension = this.extensionObjectFactory.createExtensionVersion();
extension.setId(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_ID));
extension.setType(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_TYPE));
extension.setName(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_NAME));
extension.setSummary(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_SUMMARY));
extension.setDescription(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_DESCRIPTION));
// SCM
ExtensionScm scm = new ExtensionScm();
scm.setUrl(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_SCMURL));
scm.setConnection(toScmConnection(this.<String>getQueryValue(entry,
XWikiRepositoryModel.PROP_EXTENSION_SCMCONNECTION)));
scm.setDeveloperConnection(toScmConnection(this.<String>getQueryValue(entry,
XWikiRepositoryModel.PROP_EXTENSION_SCMDEVCONNECTION)));
extension.setScm(scm);
// Rating
DocumentReference extensionDocumentReference =
new DocumentReference(xcontext.getWikiId(), documentSpace, documentName);
// FIXME: this adds potentially tons of new request to what used to be carefully crafted to produce a single
// request for the whole search... Should be cached in a filed of the document.
extension.setRating(getExtensionRating(extensionDocumentReference));
// Website
extension.setWebsite(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_WEBSITE));
if (StringUtils.isBlank(extension.getWebsite())) {
extension.setWebsite(xcontext.getWiki().getURL(
new DocumentReference(xcontext.getWikiId(), documentSpace, documentName), "view", xcontext));
}
// Authors
for (String authorId : ListClass.getListFromString(
this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_AUTHORS), "|", false)) {
extension.getAuthors().add(resolveExtensionAuthor(authorId));
}
// Features
extension.getFeatures().addAll(
ListClass.getListFromString(
this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_FEATURES), "|", false));
// License
License license = this.extensionObjectFactory.createLicense();
license.setName(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_LICENSENAME));
extension.getLicenses().add(license);
// Version
extension.setVersion((String) entry[EPROPERTIES_INDEX.size()]);
// TODO: add support for
// * dependencies
return extension;
}
protected ExtensionVersion createExtensionVersionFromSolrDocument(SolrDocument document)
{
XWikiContext xcontext = getXWikiContext();
String documentName = (String) document.getFieldValue("space");
String documentSpace = (String) document.getFieldValue("name");
ExtensionVersion extension = this.extensionObjectFactory.createExtensionVersion();
extension.setId(this.<String>getSolrValue(document, Extension.FIELD_ID));
extension.setType(this.<String>getSolrValue(document, Extension.FIELD_TYPE));
extension.setName(this.<String>getSolrValue(document, Extension.FIELD_NAME));
extension.setSummary(this.<String>getSolrValue(document, Extension.FIELD_SUMMARY));
extension.setDescription(this.<String>getSolrValue(document, Extension.FIELD_DESCRIPTION));
// SCM
ExtensionScm scm = new ExtensionScm();
scm.setUrl(this.<String>getSolrValue(document, Extension.FIELD_SCM));
scm.setConnection(toScmConnection(this.<String>getSolrValue(document,
XWikiRepositoryModel.PROP_EXTENSION_SCMCONNECTION)));
scm.setDeveloperConnection(toScmConnection(this.<String>getSolrValue(document,
XWikiRepositoryModel.PROP_EXTENSION_SCMDEVCONNECTION)));
extension.setScm(scm);
// Rating
// FIXME: this adds potentially tons of new DB requests to what used to be carefully crafted to produce a single
// request for the whole search... Should be cached in a filed of the document.
DocumentReference extensionDocumentReference =
new DocumentReference(xcontext.getWikiId(), documentSpace, documentName);
extension.setRating(getExtensionRating(extensionDocumentReference));
// Website
extension.setWebsite(this.<String>getSolrValue(document, Extension.FIELD_WEBSITE));
if (StringUtils.isBlank(extension.getWebsite())) {
extension.setWebsite(xcontext.getWiki().getURL(
new DocumentReference(xcontext.getWikiId(), documentSpace, documentName), "view", xcontext));
}
// Authors
for (String authorId : this.<String>getSolrValues(document, Extension.FIELD_AUTHORS)) {
extension.getAuthors().add(resolveExtensionAuthor(authorId));
}
// Features
extension.getFeatures().addAll(this.<String>getSolrValues(document, Extension.FIELD_FEATURES));
// License
License license = this.extensionObjectFactory.createLicense();
license.setName(this.<String>getSolrValue(document, Extension.FIELD_LICENSE));
extension.getLicenses().add(license);
// Version
extension.setVersion(this.<String>getSolrValue(document, Extension.FIELD_VERSION));
// TODO: add support for
// * dependencies
return extension;
}
protected ExtensionRating getExtensionRating(DocumentReference extensionDocumentReference)
{
ExtensionRating extensionRating = this.extensionObjectFactory.createExtensionRating();
try {
AverageRatingApi averageRating =
new AverageRatingApi(ratingsManager.getAverageRating(extensionDocumentReference));
extensionRating.setTotalVotes(averageRating.getNbVotes());
extensionRating.setAverageVote(averageRating.getAverageVote());
} catch (XWikiException e) {
extensionRating.setTotalVotes(0);
extensionRating.setAverageVote(0);
}
return extensionRating;
}
protected <E extends ExtensionSummary> void getExtensionSummaries(List<E> extensions, Query query)
throws QueryException
{
List<Object[]> entries = query.execute();
for (Object[] entry : entries) {
extensions.add((E) createExtensionSummaryFromQueryResult(entry));
}
}
protected ExtensionSummary createExtensionSummaryFromQueryResult(Object[] entry)
{
ExtensionSummary extension;
ExtensionVersionSummary extensionVersion;
int versionIndex = EPROPERTIES_INDEX.get(EPROPERTIES_SUMMARY[EPROPERTIES_SUMMARY.length - 1]) + 1;
if (entry.length == versionIndex) {
// It's a extension summary without version
extension = this.extensionObjectFactory.createExtensionSummary();
extensionVersion = null;
} else {
extension = extensionVersion = this.extensionObjectFactory.createExtensionVersionSummary();
extensionVersion.setVersion((String) entry[versionIndex]);
}
extension.setId(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_ID));
extension.setType(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_TYPE));
extension.setName(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_NAME));
return extension;
}
protected <T> T getValue(BaseObject object, String field)
{
return getValue(object, field, (T) null);
}
protected <T> T getValue(BaseObject object, String field, T def)
{
BaseProperty<?> property = (BaseProperty<?>) object.safeget(field);
return property != null ? (T) property.getValue() : def;
}
protected ResponseBuilder getAttachmentResponse(XWikiAttachment xwikiAttachment) throws XWikiException
{
if (xwikiAttachment == null) {
throw new WebApplicationException(Status.NOT_FOUND);
}
ResponseBuilder response = Response.ok();
XWikiContext xcontext = getXWikiContext();
response = response.type(xwikiAttachment.getMimeType(xcontext));
response = response.entity(xwikiAttachment.getContent(xcontext));
response =
response.header("content-disposition", "attachment; filename=\"" + xwikiAttachment.getFilename() + "\"");
return response;
}
protected void checkRights(XWikiDocument document) throws XWikiException
{
if (!this.authorization.hasAccess(Right.VIEW, document.getDocumentReference())) {
throw new WebApplicationException(Status.FORBIDDEN);
}
}
}
|
[misc] Improve comment
|
xwiki-platform-core/xwiki-platform-repository/xwiki-platform-repository-server-api/src/main/java/org/xwiki/repository/internal/resources/AbstractExtensionRESTResource.java
|
[misc] Improve comment
|
<ide><path>wiki-platform-core/xwiki-platform-repository/xwiki-platform-repository-server-api/src/main/java/org/xwiki/repository/internal/resources/AbstractExtensionRESTResource.java
<ide> DocumentReference extensionDocumentReference =
<ide> new DocumentReference(xcontext.getWikiId(), documentSpace, documentName);
<ide> // FIXME: this adds potentially tons of new request to what used to be carefully crafted to produce a single
<del> // request for the whole search... Should be cached in a filed of the document.
<add> // request for the whole search... Should be cached in a filed of the document (like the last version is for example).
<ide> extension.setRating(getExtensionRating(extensionDocumentReference));
<ide>
<ide> // Website
<ide>
<ide> // Rating
<ide> // FIXME: this adds potentially tons of new DB requests to what used to be carefully crafted to produce a single
<del> // request for the whole search... Should be cached in a filed of the document.
<add> // request for the whole search... Should be cached in a field of the document (like the last version is for example).
<ide> DocumentReference extensionDocumentReference =
<ide> new DocumentReference(xcontext.getWikiId(), documentSpace, documentName);
<ide> extension.setRating(getExtensionRating(extensionDocumentReference));
|
|
JavaScript
|
mit
|
4b68dbeb903224ef7a0c09ba4c136d9760326ced
| 0 |
rock-doves-2014/onPoint
|
document.addEventListener("DOMContentLoaded", function(event) {
var session = new SessionController();
document.onmouseup = function run(event) {
if (window.getSelection() != "") {
var xCoord = event.pageX;
var yCoord = event.pageY;
var element = session.spawnEchoForm(xCoord, yCoord);
var echoForm = document.getElementById("echo-submit");
var selectedString = window.getSelection().toString();
var userText = document.getElementById("userText").value;
// here for testing Echo object creation
var url = document.URL;
// echoForm.addEventListener("submit", function(){
// var echo = new Echo(selectedString, userText, url);
// console.log(echo);
// debugger in place to see the echo event p to console
// debugger;
// chrome.runtime.sendMessage({message: selectedString}, function(response) {
// });
// });
}
};
});
|
dummyformreader.js
|
document.addEventListener("DOMContentLoaded", function(event) {
var session = new SessionController();
document.onmouseup = function run() {
if (window.getSelection() != "") {
var element = session.spawnEchoForm();
var echoForm = document.getElementById("echo-submit");
var selectedString = window.getSelection().toString();
var userText = document.getElementById("userText").value;
// here for testing Echo object creation
var url = document.URL;
// echoForm.addEventListener("submit", function(){
// var echo = new Echo(selectedString, userText, url);
// console.log(echo);
// debugger in place to see the echo event p to console
// debugger;
// chrome.runtime.sendMessage({message: selectedString}, function(response) {
// });
// });
}
};
});
|
capturing x and y coordinates on mouseup
|
dummyformreader.js
|
capturing x and y coordinates on mouseup
|
<ide><path>ummyformreader.js
<ide>
<ide> var session = new SessionController();
<ide>
<del> document.onmouseup = function run() {
<add> document.onmouseup = function run(event) {
<ide>
<ide> if (window.getSelection() != "") {
<ide>
<del> var element = session.spawnEchoForm();
<add> var xCoord = event.pageX;
<add> var yCoord = event.pageY;
<add>
<add> var element = session.spawnEchoForm(xCoord, yCoord);
<ide>
<ide> var echoForm = document.getElementById("echo-submit");
<ide> var selectedString = window.getSelection().toString();
|
|
Java
|
apache-2.0
|
9551956d376b8423cd9da891f21589845cbf0e4d
| 0 |
spennihana/h2o-3,jangorecki/h2o-3,michalkurka/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,h2oai/h2o-3,mathemage/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,h2oai/h2o-3,spennihana/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,mathemage/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,mathemage/h2o-3,mathemage/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,spennihana/h2o-3,spennihana/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,mathemage/h2o-3,spennihana/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev
|
package hex.deepwater;
import hex.Model;
import hex.ScoreKeeper;
import hex.genmodel.utils.DistributionFamily;
import water.H2O;
import water.exceptions.H2OIllegalArgumentException;
import water.fvec.Vec;
import water.parser.BufferedString;
import water.util.ArrayUtils;
import water.util.Log;
import javax.imageio.ImageIO;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.Arrays;
import static hex.deepwater.DeepWaterParameters.ProblemType.auto;
/**
* Parameters for a Deep Water image classification model
*/
public class DeepWaterParameters extends Model.Parameters {
public String algoName() { return "DeepWater"; }
public String fullName() { return "Deep Water"; }
public String javaName() { return DeepWaterModel.class.getName(); }
@Override protected double defaultStoppingTolerance() { return 0; }
public DeepWaterParameters() {
super();
_stopping_rounds = 5;
_ignore_const_cols = false; //allow String columns with File URIs
}
@Override
public long progressUnits() {
if (train()==null) return 1;
return (long)Math.ceil(_epochs*train().numRows());
}
public float learningRate(double n) { return (float)(_learning_rate / (1 + _learning_rate_annealing * n)); }
final public float momentum(double n) {
double m = _momentum_start;
if( _momentum_ramp > 0 ) {
if( n >= _momentum_ramp)
m = _momentum_stable;
else
m += (_momentum_stable - _momentum_start) * n / _momentum_ramp;
}
return (float)m;
}
public enum Network {
auto, user, lenet, alexnet, vgg, googlenet, inception_bn, resnet,
}
public enum Backend {
unknown,
mxnet, caffe, tensorflow
}
public enum ProblemType {
auto, image_classification, text_classification, h2oframe_classification
}
public double _clip_gradient = 10.0;
public boolean _gpu = true;
public int _device_id=0;
public Network _network = Network.auto;
public Backend _backend = Backend.mxnet;
public String _network_definition_file;
public String _network_parameters_file;
public String _export_native_model_prefix;
public ProblemType _problem_type = auto;
// specific parameters for image_classification
public int[] _image_shape = new int[]{0,0}; //width x height
public int _channels = 3; //either 1 (monochrome) or 3 (RGB)
public String _mean_image_file; //optional file with mean image (backend specific)
/**
* If enabled, store the best model under the destination key of this model at the end of training.
* Only applicable if training is not cancelled.
*/
public boolean _overwrite_with_best_model = true;
public boolean _autoencoder = false;
public boolean _sparse = false;
public boolean _use_all_factor_levels = true;
public enum MissingValuesHandling {
Skip, MeanImputation
}
public MissingValuesHandling _missing_values_handling = MissingValuesHandling.MeanImputation;
/**
* If enabled, automatically standardize the data. If disabled, the user must provide properly scaled input data.
*/
public boolean _standardize = true;
/**
* The number of passes over the training dataset to be carried out.
* It is recommended to start with lower values for initial experiments.
* This value can be modified during checkpoint restarts and allows continuation
* of selected models.
*/
public double _epochs = 10;
/**
* Activation functions
*/
public enum Activation {
Rectifier, Tanh
}
/**
* The activation function (non-linearity) to be used the neurons in the hidden layers.
* Tanh: Hyperbolic tangent function (same as scaled and shifted sigmoid).
* Rectifier: Chooses the maximum of (0, x) where x is the input value.
*/
public Activation _activation = null;
/**
* The number and size of each hidden layer in the model.
* For example, if a user specifies "100,200,100" a model with 3 hidden
* layers will be produced, and the middle hidden layer will have 200
* neurons.
*/
public int[] _hidden = null;
/**
* A fraction of the features for each training row to be omitted from training in order
* to improve generalization (dimension sampling).
*/
public double _input_dropout_ratio = 0.0f;
/**
* A fraction of the inputs for each hidden layer to be omitted from training in order
* to improve generalization. Defaults to 0.5 for each hidden layer if omitted.
*/
public double[] _hidden_dropout_ratios = null;
/**
* The number of training data rows to be processed per iteration. Note that
* independent of this parameter, each row is used immediately to update the model
* with (online) stochastic gradient descent. This parameter controls the
* synchronization period between nodes in a distributed environment and the
* frequency at which scoring and model cancellation can happen. For example, if
* it is set to 10,000 on H2O running on 4 nodes, then each node will
* process 2,500 rows per iteration, sampling randomly from their local data.
* Then, model averaging between the nodes takes place, and scoring can happen
* (dependent on scoring interval and duty factor). Special values are 0 for
* one epoch per iteration, -1 for processing the maximum amount of data
* per iteration (if **replicate training data** is enabled, N epochs
* will be trained per iteration on N nodes, otherwise one epoch). Special value
* of -2 turns on automatic mode (auto-tuning).
*/
public long _train_samples_per_iteration = -2;
public double _target_ratio_comm_to_comp = 0.05;
/*Learning Rate*/
/**
* When adaptive learning rate is disabled, the magnitude of the weight
* updates are determined by the user specified learning rate
* (potentially annealed), and are a function of the difference
* between the predicted value and the target value. That difference,
* generally called delta, is only available at the output layer. To
* correct the output at each hidden layer, back propagation is
* used. Momentum modifies back propagation by allowing prior
* iterations to influence the current update. Using the momentum
* parameter can aid in avoiding local minima and the associated
* instability. Too much momentum can lead to instabilities, that's
* why the momentum is best ramped up slowly.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _learning_rate = .005;
/**
* Learning rate annealing reduces the learning rate to "freeze" into
* local minima in the optimization landscape. The annealing rate is the
* inverse of the number of training samples it takes to cut the learning rate in half
* (e.g., 1e-6 means that it takes 1e6 training samples to halve the learning rate).
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _learning_rate_annealing = 1e-6;
/**
* The momentum_start parameter controls the amount of momentum at the beginning of training.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _momentum_start = 0.9;
/**
* The momentum_ramp parameter controls the amount of learning for which momentum increases
* (assuming momentum_stable is larger than momentum_start). The ramp is measured in the number
* of training samples.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _momentum_ramp = 1e4;
/**
* The momentum_stable parameter controls the final momentum value reached after momentum_ramp training samples.
* The momentum used for training will remain the same for training beyond reaching that point.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _momentum_stable = 0.99;
/**
* The minimum time (in seconds) to elapse between model scoring. The actual
* interval is determined by the number of training samples per iteration and the scoring duty cycle.
*/
public double _score_interval = 5;
/**
* The number of training dataset points to be used for scoring. Will be
* randomly sampled. Use 0 for selecting the entire training dataset.
*/
public long _score_training_samples = 10000l;
/**
* The number of validation dataset points to be used for scoring. Can be
* randomly sampled or stratified (if "balance classes" is set and "score
* validation sampling" is set to stratify). Use 0 for selecting the entire
* training dataset.
*/
public long _score_validation_samples = 0l;
/**
* Maximum fraction of wall clock time spent on model scoring on training and validation samples,
* and on diagnostics such as computation of feature importances (i.e., not on training).
*/
public double _score_duty_cycle = 0.1;
/**
* Enable quiet mode for less output to standard output.
*/
public boolean _quiet_mode = false;
/**
* Replicate the entire training dataset onto every node for faster training on small datasets.
*/
public boolean _replicate_training_data = true;
/**
* Run on a single node for fine-tuning of model parameters. Can be useful for
* checkpoint resumes after training on multiple nodes for fast initial
* convergence.
*/
public boolean _single_node_mode = false;
/**
* Enable shuffling of training data (on each node). This option is
* recommended if training data is replicated on N nodes, and the number of training samples per iteration
* is close to N times the dataset size, where all nodes train with (almost) all
* the data. It is automatically enabled if the number of training samples per iteration is set to -1 (or to N
* times the dataset size or larger).
*/
public boolean _shuffle_training_data = true;
public int _mini_batch_size = 32;
protected boolean _cache_data = true;
/**
* Validate model parameters
* @param dl DL Model Builder (Driver)
* @param expensive (whether or not this is the "final" check)
*/
void validate(DeepWater dl, boolean expensive) {
boolean classification = expensive || dl.nclasses() != 0 ? dl.isClassifier() : _distribution == DistributionFamily.bernoulli || _distribution == DistributionFamily.bernoulli;
if (_mini_batch_size < 1)
dl.error("_mini_batch_size", "Mini-batch size must be >= 1");
if (_weights_column!=null && expensive) {
Vec w = (train().vec(_weights_column));
if (!w.isInt() || w.max() > 1 || w.min() < 0) {
dl.error("_weights_column", "only supporting weights of 0 or 1 right now");
}
}
if (_clip_gradient<=0)
dl.error("_clip_gradient", "Clip gradient must be >= 0");
if (_problem_type == ProblemType.image_classification) {
if (_image_shape.length != 2)
dl.error("_image_shape", "image_shape must have 2 dimensions (width, height)");
if (_image_shape[0] < 0)
dl.error("_image_shape", "image_shape[0] must be >=1 or automatic (0).");
if (_image_shape[1] < 0)
dl.error("_image_shape", "image_shape[1] must be >=1 or automatic (0).");
if (_channels != 1 && _channels != 3)
dl.error("_channels", "channels must be either 1 or 3.");
} else if (_problem_type != auto) {
dl.warn("_image_shape", "image shape is ignored, only used for image_classification");
dl.warn("_channels", "channels shape is ignored, only used for image_classification");
dl.warn("_mean_image_file", "mean_image_file shape is ignored, only used for image_classification");
}
if (_categorical_encoding==CategoricalEncodingScheme.Enum) {
dl.error("_categorical_encoding", "categorical encoding scheme cannot be Enum: the neural network must have numeric columns as input.");
}
if (expensive && !classification)
dl.error("_response_column", "Only classification is supported right now.");
if (_autoencoder)
dl.error("_autoencoder", "Autoencoder is not supported right now.");
if (_network == Network.user) {
if (_network_definition_file == null || _network_definition_file.isEmpty())
dl.error("_network_definition_file", "network_definition_file must be provided if the network is user-specified.");
else if (!new File(_network_definition_file).exists())
dl.error("_network_definition_file", "network_definition_file " + _network_definition_file + " not found.");
} else {
if (_network_definition_file != null && !_network_definition_file.isEmpty() && _network != Network.auto)
dl.error("_network_definition_file", "network_definition_file cannot be provided if a pre-defined network is chosen.");
}
if (_network_parameters_file != null && !_network_parameters_file.isEmpty()) {
if (!new File(_network_parameters_file).exists())
dl.error("_network_parameters_file", "network_parameters_file " + _network_parameters_file + " not found.");
}
if (_backend != Backend.mxnet) {
dl.error("_backend", "only the mxnet backend is supported right now.");
}
if (_checkpoint!=null) {
DeepWaterModel other = (DeepWaterModel) _checkpoint.get();
if (other == null)
dl.error("_width", "Invalid checkpoint provided: width mismatch.");
if (!Arrays.equals(_image_shape, other.get_params()._image_shape))
dl.error("_width", "Invalid checkpoint provided: width mismatch.");
}
if (!_autoencoder) {
if (classification) {
dl.hide("_regression_stop", "regression_stop is used only with regression.");
} else {
dl.hide("_classification_stop", "classification_stop is used only with classification.");
// dl.hide("_max_hit_ratio_k", "max_hit_ratio_k is used only with classification.");
// dl.hide("_balance_classes", "balance_classes is used only with classification.");
}
// if( !classification || !_balance_classes )
// dl.hide("_class_sampling_factors", "class_sampling_factors requires both classification and balance_classes.");
if (!classification && _valid != null || _valid == null)
dl.hide("_score_validation_sampling", "score_validation_sampling requires classification and a validation frame.");
} else {
if (_nfolds > 1) {
dl.error("_nfolds", "N-fold cross-validation is not supported for Autoencoder.");
}
}
if (H2O.CLOUD.size() == 1 && _replicate_training_data)
dl.hide("_replicate_training_data", "replicate_training_data is only valid with cloud size greater than 1.");
if (_single_node_mode && (H2O.CLOUD.size() == 1 || !_replicate_training_data))
dl.hide("_single_node_mode", "single_node_mode is only used with multi-node operation with replicated training data.");
if (H2O.ARGS.client && _single_node_mode)
dl.error("_single_node_mode", "Cannot run on a single node in client mode");
if (_autoencoder)
dl.hide("_use_all_factor_levels", "use_all_factor_levels is mandatory in combination with autoencoder.");
if (_nfolds != 0)
dl.hide("_overwrite_with_best_model", "overwrite_with_best_model is unsupported in combination with n-fold cross-validation.");
if (expensive) dl.checkDistributions();
if (_score_training_samples < 0)
dl.error("_score_training_samples", "Number of training samples for scoring must be >= 0 (0 for all).");
if (_score_validation_samples < 0)
dl.error("_score_validation_samples", "Number of training samples for scoring must be >= 0 (0 for all).");
if (classification && dl.hasOffsetCol())
dl.error("_offset_column", "Offset is only supported for regression.");
// reason for the error message below is that validation might not have the same horizontalized features as the training data (or different order)
if (expensive) {
if (!classification && _balance_classes) {
dl.error("_balance_classes", "balance_classes requires classification.");
}
if (_class_sampling_factors != null && !_balance_classes) {
dl.error("_class_sampling_factors", "class_sampling_factors requires balance_classes to be enabled.");
}
if (_replicate_training_data && null != train() && train().byteSize() > 0.9*H2O.CLOUD.free_mem()/H2O.CLOUD.size() && H2O.CLOUD.size() > 1) {
dl.error("_replicate_training_data", "Compressed training dataset takes more than 90% of avg. free available memory per node (" + 0.9*H2O.CLOUD.free_mem()/H2O.CLOUD.size() + "), cannot run with replicate_training_data.");
}
}
if (_autoencoder && _stopping_metric != ScoreKeeper.StoppingMetric.AUTO && _stopping_metric != ScoreKeeper.StoppingMetric.MSE) {
dl.error("_stopping_metric", "Stopping metric must either be AUTO or MSE for autoencoder.");
}
}
static class Sanity {
// the following parameters can be modified when restarting from a checkpoint
transient static private final String[] cp_modifiable = new String[]{
"_seed",
"_checkpoint",
"_epochs",
"_score_interval",
"_train_samples_per_iteration",
"_target_ratio_comm_to_comp",
"_score_duty_cycle",
"_score_training_samples",
"_score_validation_samples",
"_score_validation_sampling",
"_classification_stop",
"_regression_stop",
"_stopping_rounds",
"_stopping_metric",
"_quiet_mode",
"_max_confusion_matrix_size",
"_max_hit_ratio_k",
"_diagnostics",
"_variable_importances",
"_replicate_training_data",
"_shuffle_training_data",
"_single_node_mode",
"_overwrite_with_best_model",
"_mini_batch_size",
"_network_parameters_file"
};
// the following parameters must not be modified when restarting from a checkpoint
transient static private final String[] cp_not_modifiable = new String[]{
"_drop_na20_cols",
"_response_column",
"_activation",
"_use_all_factor_levels",
"_standardize",
"_autoencoder",
"_network",
"_backend",
"_learn_rate",
"_learn_rate_annealing",
"_rate_decay",
"_momentum_start",
"_momentum_ramp",
"_momentum_stable",
"_ignore_const_cols",
"_max_categorical_features",
"_nfolds",
"_distribution",
"_network_definition_file",
"_mean_image_file"
};
static void checkCompleteness() {
for (Field f : hex.deepwater.DeepWaterParameters.class.getDeclaredFields())
if (!ArrayUtils.contains(cp_not_modifiable, f.getName())
&&
!ArrayUtils.contains(cp_modifiable, f.getName())
) {
if (f.getName().equals("_hidden")) continue;
if (f.getName().equals("_ignored_columns")) continue;
if (f.getName().equals("$jacocoData")) continue; // If code coverage is enabled
throw H2O.unimpl("Please add " + f.getName() + " to either cp_modifiable or cp_not_modifiable");
}
}
/**
* Check that checkpoint continuation is possible
*
* @param oldP old DL parameters (from checkpoint)
* @param newP new DL parameters (user-given, to restart from checkpoint)
*/
static void checkIfParameterChangeAllowed(final hex.deepwater.DeepWaterParameters oldP, final hex.deepwater.DeepWaterParameters newP) {
checkCompleteness();
if (newP._nfolds != 0)
throw new UnsupportedOperationException("nfolds must be 0: Cross-validation is not supported during checkpoint restarts.");
if ((newP._valid == null) != (oldP._valid == null)) {
throw new H2OIllegalArgumentException("Presence of validation dataset must agree with the checkpointed model.");
}
if (!newP._autoencoder && (newP._response_column == null || !newP._response_column.equals(oldP._response_column))) {
throw new H2OIllegalArgumentException("Response column (" + newP._response_column + ") is not the same as for the checkpointed model: " + oldP._response_column);
}
if (!Arrays.equals(newP._ignored_columns, oldP._ignored_columns)) {
throw new H2OIllegalArgumentException("Ignored columns must be the same as for the checkpointed model.");
}
//compare the user-given parameters before and after and check that they are not changed
for (Field fBefore : oldP.getClass().getFields()) {
if (ArrayUtils.contains(cp_not_modifiable, fBefore.getName())) {
for (Field fAfter : newP.getClass().getFields()) {
if (fBefore.equals(fAfter)) {
try {
if (fAfter.get(newP) == null || fBefore.get(oldP) == null || !fBefore.get(oldP).toString().equals(fAfter.get(newP).toString())) { // if either of the two parameters is null, skip the toString()
if (fBefore.get(oldP) == null && fAfter.get(newP) == null)
continue; //if both parameters are null, we don't need to do anything
throw new H2OIllegalArgumentException("Cannot change parameter: '" + fBefore.getName() + "': " + fBefore.get(oldP) + " -> " + fAfter.get(newP));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
}
/**
* Update the parameters from checkpoint to user-specified
*
* @param srcParms source: user-specified parameters
* @param tgtParms target: parameters to be modified
* @param doIt whether to overwrite target parameters (or just print the message)
* @param quiet whether to suppress the notifications about parameter changes
*/
static void updateParametersDuringCheckpointRestart(hex.deepwater.DeepWaterParameters srcParms, hex.deepwater.DeepWaterParameters tgtParms/*actually used during training*/, boolean doIt, boolean quiet) {
for (Field fTarget : tgtParms.getClass().getFields()) {
if (ArrayUtils.contains(cp_modifiable, fTarget.getName())) {
for (Field fSource : srcParms.getClass().getFields()) {
if (fTarget.equals(fSource)) {
try {
if (fSource.get(srcParms) == null || fTarget.get(tgtParms) == null || !fTarget.get(tgtParms).toString().equals(fSource.get(srcParms).toString())) { // if either of the two parameters is null, skip the toString()
if (fTarget.get(tgtParms) == null && fSource.get(srcParms) == null)
continue; //if both parameters are null, we don't need to do anything
if (!tgtParms._quiet_mode && !quiet)
Log.info("Applying user-requested modification of '" + fTarget.getName() + "': " + fTarget.get(tgtParms) + " -> " + fSource.get(srcParms));
if (doIt)
fTarget.set(tgtParms, fSource.get(srcParms));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
}
/**
* Take user-given parameters and turn them into usable, fully populated parameters (e.g., to be used by Neurons during training)
*
* @param fromParms raw user-given parameters from the REST API (READ ONLY)
* @param toParms modified set of parameters, with defaults filled in (WILL BE MODIFIED)
* @param nClasses number of classes (1 for regression or autoencoder)
*/
static void modifyParms(hex.deepwater.DeepWaterParameters fromParms, hex.deepwater.DeepWaterParameters toParms, int nClasses) {
if (H2O.CLOUD.size() == 1 && fromParms._replicate_training_data) {
if (!fromParms._quiet_mode)
Log.info("_replicate_training_data: Disabling replicate_training_data on 1 node.");
toParms._replicate_training_data = false;
}
if (fromParms._single_node_mode && (H2O.CLOUD.size() == 1 || !fromParms._replicate_training_data)) {
if (!fromParms._quiet_mode)
Log.info("_single_node_mode: Disabling single_node_mode (only for multi-node operation with replicated training data).");
toParms._single_node_mode = false;
}
if (fromParms._overwrite_with_best_model && fromParms._nfolds != 0) {
if (!fromParms._quiet_mode)
Log.info("_overwrite_with_best_model: Disabling overwrite_with_best_model in combination with n-fold cross-validation.");
toParms._overwrite_with_best_model = false;
}
// Automatically set the problem_type
if (fromParms._problem_type == auto) {
boolean image=false;
boolean text=false;
if (fromParms.train().vec(0).isString()) {
BufferedString bs = new BufferedString();
String first = fromParms.train().anyVec().atStr(bs, 0).toString();
try {
ImageIO.read(new File(first));
image=true;
} catch(Throwable t) {}
try {
ImageIO.read(new URL(first));
image=true;
} catch(Throwable t) {}
if (!image && (first.endsWith(".jpg") || first.endsWith(".png") || first.endsWith(".tif"))) {
image=true;
Log.warn("Cannot read first image at " + first + " - Check data.");
} else {
text = true;
}
}
if (image) toParms._problem_type = ProblemType.image_classification;
else if (text) toParms._problem_type = ProblemType.text_classification;
else toParms._problem_type = ProblemType.h2oframe_classification;
if (!fromParms._quiet_mode)
Log.info("_problem_type: Automatically selecting problem_type: " + toParms._problem_type.toString());
}
if (fromParms._categorical_encoding==CategoricalEncodingScheme.AUTO) {
if (!fromParms._quiet_mode)
Log.info("_categorical_encoding: Automatically enabling OneHotInternal categorical encoding.");
toParms._categorical_encoding = CategoricalEncodingScheme.OneHotInternal;
}
if (fromParms._nfolds != 0) {
if (fromParms._overwrite_with_best_model) {
if (!fromParms._quiet_mode)
Log.info("_overwrite_with_best_model: Automatically disabling overwrite_with_best_model, since the final model is the only scored model with n-fold cross-validation.");
toParms._overwrite_with_best_model = false;
}
}
if (fromParms._network == Network.auto || fromParms._network==null) {
if (toParms._problem_type==ProblemType.image_classification) toParms._network = Network.inception_bn;
if (toParms._problem_type==ProblemType.text_classification) throw H2O.unimpl();
if (toParms._problem_type==ProblemType.h2oframe_classification) {
toParms._network = null;
if (fromParms._hidden == null) {
toParms._hidden = new int[]{200, 200};
toParms._activation = Activation.Rectifier;
toParms._hidden_dropout_ratios = new double[toParms._hidden.length];
}
}
if (!fromParms._quiet_mode && toParms._network!=null)
Log.info("_network: Using " + toParms._network + " model by default.");
}
if (fromParms._autoencoder && fromParms._stopping_metric == ScoreKeeper.StoppingMetric.AUTO) {
if (!fromParms._quiet_mode)
Log.info("_stopping_metric: Automatically setting stopping_metric to MSE for autoencoder.");
toParms._stopping_metric = ScoreKeeper.StoppingMetric.MSE;
}
if (toParms._hidden!=null) {
if (toParms._hidden_dropout_ratios==null) {
if (!fromParms._quiet_mode)
Log.info("_hidden_dropout_ratios: Automatically setting hidden_dropout_ratios to 0 for all layers.");
toParms._hidden_dropout_ratios = new double[toParms._hidden.length];
}
if (toParms._activation==null) {
toParms._activation = Activation.Rectifier;
if (!fromParms._quiet_mode)
Log.info("_activation: Automatically setting activation to " + toParms._activation + " for all layers.");
}
if (!fromParms._quiet_mode) {
Log.info("Hidden layers: " + Arrays.toString(toParms._hidden));
Log.info("Activation function: " + toParms._activation);
Log.info("Input dropout ratio: " + toParms._input_dropout_ratio);
Log.info("Hidden layer dropout ratio: " + Arrays.toString(toParms._hidden_dropout_ratios));
}
}
// Automatically set the distribution
if (fromParms._distribution == DistributionFamily.AUTO) {
// For classification, allow AUTO/bernoulli/multinomial with losses CrossEntropy/Quadratic/Huber/Absolute
if (nClasses > 1) {
toParms._distribution = nClasses == 2 ? DistributionFamily.bernoulli : DistributionFamily.multinomial;
}
}
}
}
}
|
h2o-algos/src/main/java/hex/deepwater/DeepWaterParameters.java
|
package hex.deepwater;
import hex.Model;
import hex.ScoreKeeper;
import hex.genmodel.utils.DistributionFamily;
import water.H2O;
import water.exceptions.H2OIllegalArgumentException;
import water.fvec.Vec;
import water.parser.BufferedString;
import water.util.ArrayUtils;
import water.util.Log;
import javax.imageio.ImageIO;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.Arrays;
/**
* Parameters for a Deep Water image classification model
*/
public class DeepWaterParameters extends Model.Parameters {
public String algoName() { return "DeepWater"; }
public String fullName() { return "Deep Water"; }
public String javaName() { return DeepWaterModel.class.getName(); }
@Override protected double defaultStoppingTolerance() { return 0; }
public DeepWaterParameters() {
super();
_stopping_rounds = 5;
_ignore_const_cols = false; //allow String columns with File URIs
}
@Override
public long progressUnits() {
if (train()==null) return 1;
return (long)Math.ceil(_epochs*train().numRows());
}
public float learningRate(double n) { return (float)(_learning_rate / (1 + _learning_rate_annealing * n)); }
final public float momentum(double n) {
double m = _momentum_start;
if( _momentum_ramp > 0 ) {
if( n >= _momentum_ramp)
m = _momentum_stable;
else
m += (_momentum_stable - _momentum_start) * n / _momentum_ramp;
}
return (float)m;
}
public enum Network {
auto, user, lenet, alexnet, vgg, googlenet, inception_bn, resnet,
}
public enum Backend {
unknown,
mxnet, caffe, tensorflow
}
public enum ProblemType {
auto, image_classification, text_classification, h2oframe_classification
}
public double _clip_gradient = 10.0;
public boolean _gpu = true;
public int _device_id=0;
public Network _network = Network.auto;
public Backend _backend = Backend.mxnet;
public String _network_definition_file;
public String _network_parameters_file;
public String _export_native_model_prefix;
public ProblemType _problem_type = ProblemType.auto;
// specific parameters for image_classification
public int[] _image_shape = new int[]{0,0}; //width x height
public int _channels = 3; //either 1 (monochrome) or 3 (RGB)
public String _mean_image_file; //optional file with mean image (backend specific)
/**
* If enabled, store the best model under the destination key of this model at the end of training.
* Only applicable if training is not cancelled.
*/
public boolean _overwrite_with_best_model = true;
public boolean _autoencoder = false;
public boolean _sparse = false;
public boolean _use_all_factor_levels = true;
public enum MissingValuesHandling {
Skip, MeanImputation
}
public MissingValuesHandling _missing_values_handling = MissingValuesHandling.MeanImputation;
/**
* If enabled, automatically standardize the data. If disabled, the user must provide properly scaled input data.
*/
public boolean _standardize = true;
/**
* The number of passes over the training dataset to be carried out.
* It is recommended to start with lower values for initial experiments.
* This value can be modified during checkpoint restarts and allows continuation
* of selected models.
*/
public double _epochs = 10;
/**
* Activation functions
*/
public enum Activation {
Rectifier, Tanh
}
/**
* The activation function (non-linearity) to be used the neurons in the hidden layers.
* Tanh: Hyperbolic tangent function (same as scaled and shifted sigmoid).
* Rectifier: Chooses the maximum of (0, x) where x is the input value.
*/
public Activation _activation = null;
/**
* The number and size of each hidden layer in the model.
* For example, if a user specifies "100,200,100" a model with 3 hidden
* layers will be produced, and the middle hidden layer will have 200
* neurons.
*/
public int[] _hidden = null;
/**
* A fraction of the features for each training row to be omitted from training in order
* to improve generalization (dimension sampling).
*/
public double _input_dropout_ratio = 0.0f;
/**
* A fraction of the inputs for each hidden layer to be omitted from training in order
* to improve generalization. Defaults to 0.5 for each hidden layer if omitted.
*/
public double[] _hidden_dropout_ratios = null;
/**
* The number of training data rows to be processed per iteration. Note that
* independent of this parameter, each row is used immediately to update the model
* with (online) stochastic gradient descent. This parameter controls the
* synchronization period between nodes in a distributed environment and the
* frequency at which scoring and model cancellation can happen. For example, if
* it is set to 10,000 on H2O running on 4 nodes, then each node will
* process 2,500 rows per iteration, sampling randomly from their local data.
* Then, model averaging between the nodes takes place, and scoring can happen
* (dependent on scoring interval and duty factor). Special values are 0 for
* one epoch per iteration, -1 for processing the maximum amount of data
* per iteration (if **replicate training data** is enabled, N epochs
* will be trained per iteration on N nodes, otherwise one epoch). Special value
* of -2 turns on automatic mode (auto-tuning).
*/
public long _train_samples_per_iteration = -2;
public double _target_ratio_comm_to_comp = 0.05;
/*Learning Rate*/
/**
* When adaptive learning rate is disabled, the magnitude of the weight
* updates are determined by the user specified learning rate
* (potentially annealed), and are a function of the difference
* between the predicted value and the target value. That difference,
* generally called delta, is only available at the output layer. To
* correct the output at each hidden layer, back propagation is
* used. Momentum modifies back propagation by allowing prior
* iterations to influence the current update. Using the momentum
* parameter can aid in avoiding local minima and the associated
* instability. Too much momentum can lead to instabilities, that's
* why the momentum is best ramped up slowly.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _learning_rate = .005;
/**
* Learning rate annealing reduces the learning rate to "freeze" into
* local minima in the optimization landscape. The annealing rate is the
* inverse of the number of training samples it takes to cut the learning rate in half
* (e.g., 1e-6 means that it takes 1e6 training samples to halve the learning rate).
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _learning_rate_annealing = 1e-6;
/**
* The momentum_start parameter controls the amount of momentum at the beginning of training.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _momentum_start = 0.9;
/**
* The momentum_ramp parameter controls the amount of learning for which momentum increases
* (assuming momentum_stable is larger than momentum_start). The ramp is measured in the number
* of training samples.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _momentum_ramp = 1e4;
/**
* The momentum_stable parameter controls the final momentum value reached after momentum_ramp training samples.
* The momentum used for training will remain the same for training beyond reaching that point.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _momentum_stable = 0.99;
/**
* The minimum time (in seconds) to elapse between model scoring. The actual
* interval is determined by the number of training samples per iteration and the scoring duty cycle.
*/
public double _score_interval = 5;
/**
* The number of training dataset points to be used for scoring. Will be
* randomly sampled. Use 0 for selecting the entire training dataset.
*/
public long _score_training_samples = 10000l;
/**
* The number of validation dataset points to be used for scoring. Can be
* randomly sampled or stratified (if "balance classes" is set and "score
* validation sampling" is set to stratify). Use 0 for selecting the entire
* training dataset.
*/
public long _score_validation_samples = 0l;
/**
* Maximum fraction of wall clock time spent on model scoring on training and validation samples,
* and on diagnostics such as computation of feature importances (i.e., not on training).
*/
public double _score_duty_cycle = 0.1;
/**
* Enable quiet mode for less output to standard output.
*/
public boolean _quiet_mode = false;
/**
* Replicate the entire training dataset onto every node for faster training on small datasets.
*/
public boolean _replicate_training_data = true;
/**
* Run on a single node for fine-tuning of model parameters. Can be useful for
* checkpoint resumes after training on multiple nodes for fast initial
* convergence.
*/
public boolean _single_node_mode = false;
/**
* Enable shuffling of training data (on each node). This option is
* recommended if training data is replicated on N nodes, and the number of training samples per iteration
* is close to N times the dataset size, where all nodes train with (almost) all
* the data. It is automatically enabled if the number of training samples per iteration is set to -1 (or to N
* times the dataset size or larger).
*/
public boolean _shuffle_training_data = true;
public int _mini_batch_size = 32;
protected boolean _cache_data = true;
/**
* Validate model parameters
* @param dl DL Model Builder (Driver)
* @param expensive (whether or not this is the "final" check)
*/
void validate(DeepWater dl, boolean expensive) {
boolean classification = expensive || dl.nclasses() != 0 ? dl.isClassifier() : _distribution == DistributionFamily.bernoulli || _distribution == DistributionFamily.bernoulli;
if (_mini_batch_size < 1)
dl.error("_mini_batch_size", "Mini-batch size must be >= 1");
if (_weights_column!=null && expensive) {
Vec w = (train().vec(_weights_column));
if (!w.isInt() || w.max() > 1 || w.min() < 0) {
dl.error("_weights_column", "only supporting weights of 0 or 1 right now");
}
}
if (_clip_gradient<=0)
dl.error("_clip_gradient", "Clip gradient must be >= 0");
if (_problem_type == ProblemType.image_classification) {
if (_image_shape.length != 2)
dl.error("_image_shape", "image_shape must have 2 dimensions (width, height)");
if (_image_shape[0] < 0)
dl.error("_image_shape", "image_shape[0] must be >=1 or automatic (0).");
if (_image_shape[1] < 0)
dl.error("_image_shape", "image_shape[1] must be >=1 or automatic (0).");
if (_channels != 1 && _channels != 3)
dl.error("_channels", "channels must be either 1 or 3.");
} else {
dl.warn("_image_shape", "image shape is ignored, only used for image_classification");
dl.warn("_channels", "channels shape is ignored, only used for image_classification");
dl.warn("_mean_image_file", "mean_image_file shape is ignored, only used for image_classification");
if (_categorical_encoding==CategoricalEncodingScheme.Enum) {
dl.error("_categorical_encoding", "categorical encoding scheme cannot be Enum: must have numeric columns as input.");
}
}
if (expensive && !classification)
dl.error("_response_column", "Only classification is supported right now.");
if (_autoencoder)
dl.error("_autoencoder", "Autoencoder is not supported right now.");
if (_network == Network.user) {
if (_network_definition_file == null || _network_definition_file.isEmpty())
dl.error("_network_definition_file", "network_definition_file must be provided if the network is user-specified.");
else if (!new File(_network_definition_file).exists())
dl.error("_network_definition_file", "network_definition_file " + _network_definition_file + " not found.");
} else {
if (_network_definition_file != null && !_network_definition_file.isEmpty() && _network != Network.auto)
dl.error("_network_definition_file", "network_definition_file cannot be provided if a pre-defined network is chosen.");
}
if (_network_parameters_file != null && !_network_parameters_file.isEmpty()) {
if (!new File(_network_parameters_file).exists())
dl.error("_network_parameters_file", "network_parameters_file " + _network_parameters_file + " not found.");
}
if (_backend != Backend.mxnet) {
dl.error("_backend", "only the mxnet backend is supported right now.");
}
if (_checkpoint!=null) {
DeepWaterModel other = (DeepWaterModel) _checkpoint.get();
if (other == null)
dl.error("_width", "Invalid checkpoint provided: width mismatch.");
if (!Arrays.equals(_image_shape, other.get_params()._image_shape))
dl.error("_width", "Invalid checkpoint provided: width mismatch.");
}
if (!_autoencoder) {
if (classification) {
dl.hide("_regression_stop", "regression_stop is used only with regression.");
} else {
dl.hide("_classification_stop", "classification_stop is used only with classification.");
// dl.hide("_max_hit_ratio_k", "max_hit_ratio_k is used only with classification.");
// dl.hide("_balance_classes", "balance_classes is used only with classification.");
}
// if( !classification || !_balance_classes )
// dl.hide("_class_sampling_factors", "class_sampling_factors requires both classification and balance_classes.");
if (!classification && _valid != null || _valid == null)
dl.hide("_score_validation_sampling", "score_validation_sampling requires classification and a validation frame.");
} else {
if (_nfolds > 1) {
dl.error("_nfolds", "N-fold cross-validation is not supported for Autoencoder.");
}
}
if (H2O.CLOUD.size() == 1 && _replicate_training_data)
dl.hide("_replicate_training_data", "replicate_training_data is only valid with cloud size greater than 1.");
if (_single_node_mode && (H2O.CLOUD.size() == 1 || !_replicate_training_data))
dl.hide("_single_node_mode", "single_node_mode is only used with multi-node operation with replicated training data.");
if (H2O.ARGS.client && _single_node_mode)
dl.error("_single_node_mode", "Cannot run on a single node in client mode");
if (_autoencoder)
dl.hide("_use_all_factor_levels", "use_all_factor_levels is mandatory in combination with autoencoder.");
if (_nfolds != 0)
dl.hide("_overwrite_with_best_model", "overwrite_with_best_model is unsupported in combination with n-fold cross-validation.");
if (expensive) dl.checkDistributions();
if (_score_training_samples < 0)
dl.error("_score_training_samples", "Number of training samples for scoring must be >= 0 (0 for all).");
if (_score_validation_samples < 0)
dl.error("_score_validation_samples", "Number of training samples for scoring must be >= 0 (0 for all).");
if (classification && dl.hasOffsetCol())
dl.error("_offset_column", "Offset is only supported for regression.");
// reason for the error message below is that validation might not have the same horizontalized features as the training data (or different order)
if (expensive) {
if (!classification && _balance_classes) {
dl.error("_balance_classes", "balance_classes requires classification.");
}
if (_class_sampling_factors != null && !_balance_classes) {
dl.error("_class_sampling_factors", "class_sampling_factors requires balance_classes to be enabled.");
}
if (_replicate_training_data && null != train() && train().byteSize() > 0.9*H2O.CLOUD.free_mem()/H2O.CLOUD.size() && H2O.CLOUD.size() > 1) {
dl.error("_replicate_training_data", "Compressed training dataset takes more than 90% of avg. free available memory per node (" + 0.9*H2O.CLOUD.free_mem()/H2O.CLOUD.size() + "), cannot run with replicate_training_data.");
}
}
if (_autoencoder && _stopping_metric != ScoreKeeper.StoppingMetric.AUTO && _stopping_metric != ScoreKeeper.StoppingMetric.MSE) {
dl.error("_stopping_metric", "Stopping metric must either be AUTO or MSE for autoencoder.");
}
}
static class Sanity {
// the following parameters can be modified when restarting from a checkpoint
transient static private final String[] cp_modifiable = new String[]{
"_seed",
"_checkpoint",
"_epochs",
"_score_interval",
"_train_samples_per_iteration",
"_target_ratio_comm_to_comp",
"_score_duty_cycle",
"_score_training_samples",
"_score_validation_samples",
"_score_validation_sampling",
"_classification_stop",
"_regression_stop",
"_stopping_rounds",
"_stopping_metric",
"_quiet_mode",
"_max_confusion_matrix_size",
"_max_hit_ratio_k",
"_diagnostics",
"_variable_importances",
"_replicate_training_data",
"_shuffle_training_data",
"_single_node_mode",
"_overwrite_with_best_model",
"_mini_batch_size",
"_network_parameters_file"
};
// the following parameters must not be modified when restarting from a checkpoint
transient static private final String[] cp_not_modifiable = new String[]{
"_drop_na20_cols",
"_response_column",
"_activation",
"_use_all_factor_levels",
"_standardize",
"_autoencoder",
"_network",
"_backend",
"_learn_rate",
"_learn_rate_annealing",
"_rate_decay",
"_momentum_start",
"_momentum_ramp",
"_momentum_stable",
"_ignore_const_cols",
"_max_categorical_features",
"_nfolds",
"_distribution",
"_network_definition_file",
"_mean_image_file"
};
static void checkCompleteness() {
for (Field f : hex.deepwater.DeepWaterParameters.class.getDeclaredFields())
if (!ArrayUtils.contains(cp_not_modifiable, f.getName())
&&
!ArrayUtils.contains(cp_modifiable, f.getName())
) {
if (f.getName().equals("_hidden")) continue;
if (f.getName().equals("_ignored_columns")) continue;
if (f.getName().equals("$jacocoData")) continue; // If code coverage is enabled
throw H2O.unimpl("Please add " + f.getName() + " to either cp_modifiable or cp_not_modifiable");
}
}
/**
* Check that checkpoint continuation is possible
*
* @param oldP old DL parameters (from checkpoint)
* @param newP new DL parameters (user-given, to restart from checkpoint)
*/
static void checkIfParameterChangeAllowed(final hex.deepwater.DeepWaterParameters oldP, final hex.deepwater.DeepWaterParameters newP) {
checkCompleteness();
if (newP._nfolds != 0)
throw new UnsupportedOperationException("nfolds must be 0: Cross-validation is not supported during checkpoint restarts.");
if ((newP._valid == null) != (oldP._valid == null)) {
throw new H2OIllegalArgumentException("Presence of validation dataset must agree with the checkpointed model.");
}
if (!newP._autoencoder && (newP._response_column == null || !newP._response_column.equals(oldP._response_column))) {
throw new H2OIllegalArgumentException("Response column (" + newP._response_column + ") is not the same as for the checkpointed model: " + oldP._response_column);
}
if (!Arrays.equals(newP._ignored_columns, oldP._ignored_columns)) {
throw new H2OIllegalArgumentException("Ignored columns must be the same as for the checkpointed model.");
}
//compare the user-given parameters before and after and check that they are not changed
for (Field fBefore : oldP.getClass().getFields()) {
if (ArrayUtils.contains(cp_not_modifiable, fBefore.getName())) {
for (Field fAfter : newP.getClass().getFields()) {
if (fBefore.equals(fAfter)) {
try {
if (fAfter.get(newP) == null || fBefore.get(oldP) == null || !fBefore.get(oldP).toString().equals(fAfter.get(newP).toString())) { // if either of the two parameters is null, skip the toString()
if (fBefore.get(oldP) == null && fAfter.get(newP) == null)
continue; //if both parameters are null, we don't need to do anything
throw new H2OIllegalArgumentException("Cannot change parameter: '" + fBefore.getName() + "': " + fBefore.get(oldP) + " -> " + fAfter.get(newP));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
}
/**
* Update the parameters from checkpoint to user-specified
*
* @param srcParms source: user-specified parameters
* @param tgtParms target: parameters to be modified
* @param doIt whether to overwrite target parameters (or just print the message)
* @param quiet whether to suppress the notifications about parameter changes
*/
static void updateParametersDuringCheckpointRestart(hex.deepwater.DeepWaterParameters srcParms, hex.deepwater.DeepWaterParameters tgtParms/*actually used during training*/, boolean doIt, boolean quiet) {
for (Field fTarget : tgtParms.getClass().getFields()) {
if (ArrayUtils.contains(cp_modifiable, fTarget.getName())) {
for (Field fSource : srcParms.getClass().getFields()) {
if (fTarget.equals(fSource)) {
try {
if (fSource.get(srcParms) == null || fTarget.get(tgtParms) == null || !fTarget.get(tgtParms).toString().equals(fSource.get(srcParms).toString())) { // if either of the two parameters is null, skip the toString()
if (fTarget.get(tgtParms) == null && fSource.get(srcParms) == null)
continue; //if both parameters are null, we don't need to do anything
if (!tgtParms._quiet_mode && !quiet)
Log.info("Applying user-requested modification of '" + fTarget.getName() + "': " + fTarget.get(tgtParms) + " -> " + fSource.get(srcParms));
if (doIt)
fTarget.set(tgtParms, fSource.get(srcParms));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
}
/**
* Take user-given parameters and turn them into usable, fully populated parameters (e.g., to be used by Neurons during training)
*
* @param fromParms raw user-given parameters from the REST API (READ ONLY)
* @param toParms modified set of parameters, with defaults filled in (WILL BE MODIFIED)
* @param nClasses number of classes (1 for regression or autoencoder)
*/
static void modifyParms(hex.deepwater.DeepWaterParameters fromParms, hex.deepwater.DeepWaterParameters toParms, int nClasses) {
if (H2O.CLOUD.size() == 1 && fromParms._replicate_training_data) {
if (!fromParms._quiet_mode)
Log.info("_replicate_training_data: Disabling replicate_training_data on 1 node.");
toParms._replicate_training_data = false;
}
if (fromParms._single_node_mode && (H2O.CLOUD.size() == 1 || !fromParms._replicate_training_data)) {
if (!fromParms._quiet_mode)
Log.info("_single_node_mode: Disabling single_node_mode (only for multi-node operation with replicated training data).");
toParms._single_node_mode = false;
}
if (fromParms._overwrite_with_best_model && fromParms._nfolds != 0) {
if (!fromParms._quiet_mode)
Log.info("_overwrite_with_best_model: Disabling overwrite_with_best_model in combination with n-fold cross-validation.");
toParms._overwrite_with_best_model = false;
}
// Automatically set the problem_type
if (fromParms._problem_type == ProblemType.auto) {
boolean image=false;
boolean text=false;
if (fromParms.train().vec(0).isString()) {
BufferedString bs = new BufferedString();
String first = fromParms.train().anyVec().atStr(bs, 0).toString();
try {
ImageIO.read(new File(first));
image=true;
} catch(Throwable t) {}
try {
ImageIO.read(new URL(first));
image=true;
} catch(Throwable t) {}
if (!image && (first.endsWith(".jpg") || first.endsWith(".png") || first.endsWith(".tif"))) {
image=true;
Log.warn("Cannot read first image at " + first + " - Check data.");
} else {
text = true;
}
}
if (image) toParms._problem_type = ProblemType.image_classification;
else if (text) toParms._problem_type = ProblemType.text_classification;
else toParms._problem_type = ProblemType.h2oframe_classification;
if (!fromParms._quiet_mode)
Log.info("_problem_type: Automatically selecting problem_type: " + toParms._problem_type.toString());
}
if (fromParms._categorical_encoding==CategoricalEncodingScheme.AUTO) {
if (!fromParms._quiet_mode)
Log.info("_categorical_encoding: Automatically enabling OneHotInternal categorical encoding.");
toParms._categorical_encoding = CategoricalEncodingScheme.OneHotInternal;
}
if (fromParms._nfolds != 0) {
if (fromParms._overwrite_with_best_model) {
if (!fromParms._quiet_mode)
Log.info("_overwrite_with_best_model: Automatically disabling overwrite_with_best_model, since the final model is the only scored model with n-fold cross-validation.");
toParms._overwrite_with_best_model = false;
}
}
if (fromParms._network == Network.auto || fromParms._network==null) {
if (toParms._problem_type==ProblemType.image_classification) toParms._network = Network.inception_bn;
if (toParms._problem_type==ProblemType.text_classification) throw H2O.unimpl();
if (toParms._problem_type==ProblemType.h2oframe_classification) {
toParms._network = null;
if (fromParms._hidden == null) {
toParms._hidden = new int[]{200, 200};
toParms._activation = Activation.Rectifier;
toParms._hidden_dropout_ratios = new double[toParms._hidden.length];
}
}
if (!fromParms._quiet_mode && toParms._network!=null)
Log.info("_network: Using " + toParms._network + " model by default.");
}
if (fromParms._autoencoder && fromParms._stopping_metric == ScoreKeeper.StoppingMetric.AUTO) {
if (!fromParms._quiet_mode)
Log.info("_stopping_metric: Automatically setting stopping_metric to MSE for autoencoder.");
toParms._stopping_metric = ScoreKeeper.StoppingMetric.MSE;
}
if (toParms._hidden!=null) {
if (toParms._hidden_dropout_ratios==null) {
if (!fromParms._quiet_mode)
Log.info("_hidden_dropout_ratios: Automatically setting hidden_dropout_ratios to 0 for all layers.");
toParms._hidden_dropout_ratios = new double[toParms._hidden.length];
}
if (toParms._activation==null) {
toParms._activation = Activation.Rectifier;
if (!fromParms._quiet_mode)
Log.info("_activation: Automatically setting activation to " + toParms._activation + " for all layers.");
}
if (!fromParms._quiet_mode) {
Log.info("Hidden layers: " + Arrays.toString(toParms._hidden));
Log.info("Activation function: " + toParms._activation);
Log.info("Input dropout ratio: " + toParms._input_dropout_ratio);
Log.info("Hidden layer dropout ratio: " + Arrays.toString(toParms._hidden_dropout_ratios));
}
}
// Automatically set the distribution
if (fromParms._distribution == DistributionFamily.AUTO) {
// For classification, allow AUTO/bernoulli/multinomial with losses CrossEntropy/Quadratic/Huber/Absolute
if (nClasses > 1) {
toParms._distribution = nClasses == 2 ? DistributionFamily.bernoulli : DistributionFamily.multinomial;
}
}
}
}
}
|
Cleanup error handling to not hve WARN messages during startup.
|
h2o-algos/src/main/java/hex/deepwater/DeepWaterParameters.java
|
Cleanup error handling to not hve WARN messages during startup.
|
<ide><path>2o-algos/src/main/java/hex/deepwater/DeepWaterParameters.java
<ide> import java.lang.reflect.Field;
<ide> import java.net.URL;
<ide> import java.util.Arrays;
<add>
<add>import static hex.deepwater.DeepWaterParameters.ProblemType.auto;
<ide>
<ide> /**
<ide> * Parameters for a Deep Water image classification model
<ide> public String _network_parameters_file;
<ide> public String _export_native_model_prefix;
<ide>
<del> public ProblemType _problem_type = ProblemType.auto;
<add> public ProblemType _problem_type = auto;
<ide>
<ide> // specific parameters for image_classification
<ide> public int[] _image_shape = new int[]{0,0}; //width x height
<ide> dl.error("_image_shape", "image_shape[1] must be >=1 or automatic (0).");
<ide> if (_channels != 1 && _channels != 3)
<ide> dl.error("_channels", "channels must be either 1 or 3.");
<del> } else {
<add> } else if (_problem_type != auto) {
<ide> dl.warn("_image_shape", "image shape is ignored, only used for image_classification");
<ide> dl.warn("_channels", "channels shape is ignored, only used for image_classification");
<ide> dl.warn("_mean_image_file", "mean_image_file shape is ignored, only used for image_classification");
<del> if (_categorical_encoding==CategoricalEncodingScheme.Enum) {
<del> dl.error("_categorical_encoding", "categorical encoding scheme cannot be Enum: must have numeric columns as input.");
<del> }
<add> }
<add> if (_categorical_encoding==CategoricalEncodingScheme.Enum) {
<add> dl.error("_categorical_encoding", "categorical encoding scheme cannot be Enum: the neural network must have numeric columns as input.");
<ide> }
<ide>
<ide> if (expensive && !classification)
<ide> toParms._overwrite_with_best_model = false;
<ide> }
<ide> // Automatically set the problem_type
<del> if (fromParms._problem_type == ProblemType.auto) {
<add> if (fromParms._problem_type == auto) {
<ide> boolean image=false;
<ide> boolean text=false;
<ide> if (fromParms.train().vec(0).isString()) {
|
|
Java
|
epl-1.0
|
620a9f8589179dbcca0739c9a424f68c3e8838b8
| 0 |
ingridcoda/jantarDosFilosofos
|
jantarDosFilosofos_versaoCorreta/jantarDosFilosofos/jantarDosFilosofos_OK/Jantar.java
|
package jantarDosFilosofos_OK;
public class Jantar {
/* Classe principal do programa */
public static void main(String[] args){
Mesa mesa = new Mesa();
Thread filosofo1 = new Filosofo(0, mesa);
Thread filosofo2 = new Filosofo(1, mesa);
Thread filosofo3 = new Filosofo(2, mesa);
Thread filosofo4 = new Filosofo(3, mesa);
Thread filosofo5 = new Filosofo(4, mesa);
filosofo1.start();
filosofo2.start();
filosofo3.start();
filosofo4.start();
filosofo5.start();
}
}
|
Delete Jantar.java
|
jantarDosFilosofos_versaoCorreta/jantarDosFilosofos/jantarDosFilosofos_OK/Jantar.java
|
Delete Jantar.java
|
<ide><path>antarDosFilosofos_versaoCorreta/jantarDosFilosofos/jantarDosFilosofos_OK/Jantar.java
<del>package jantarDosFilosofos_OK;
<del>
<del>public class Jantar {
<del>
<del> /* Classe principal do programa */
<del> public static void main(String[] args){
<del>
<del> Mesa mesa = new Mesa();
<del>
<del> Thread filosofo1 = new Filosofo(0, mesa);
<del> Thread filosofo2 = new Filosofo(1, mesa);
<del> Thread filosofo3 = new Filosofo(2, mesa);
<del> Thread filosofo4 = new Filosofo(3, mesa);
<del> Thread filosofo5 = new Filosofo(4, mesa);
<del>
<del> filosofo1.start();
<del> filosofo2.start();
<del> filosofo3.start();
<del> filosofo4.start();
<del> filosofo5.start();
<del>
<del> }
<del>
<del>}
|
||
JavaScript
|
mit
|
0e1bb3431e516441cc52a0b3604462ccde7336ac
| 0 |
WordPress-Coding-Standards/eslint-plugin-wordpress,ntwb/eslint-plugin-wordpress
|
module.exports = {
extends: 'plugin:wordpress/recommended',
env: {
browser: true,
qunit: true
},
plugins: [
'qunit'
],
rules: require('./rules/qunit')
};
|
lib/configs/qunit.js
|
module.exports = {
extends: 'plugin:wordpress/recommended',
env: {
browser: true
},
plugins: [
'qunit'
],
rules: require('./rules/qunit')
};
|
fix: Add qunit environment to qunit shared config (#22)
|
lib/configs/qunit.js
|
fix: Add qunit environment to qunit shared config (#22)
|
<ide><path>ib/configs/qunit.js
<ide> extends: 'plugin:wordpress/recommended',
<ide>
<ide> env: {
<del> browser: true
<add> browser: true,
<add> qunit: true
<ide> },
<ide>
<ide> plugins: [
|
|
JavaScript
|
apache-2.0
|
2fbea2efe282e60a7140a0f3272bbb1c3ca57c0d
| 0 |
interglobalvision/fruitmilk-net,interglobalvision/fruitmilk-net,interglobalvision/fruitmilk-net
|
//(function() {
/*
* NAV / MATTER.JS
*/
// Matter module aliases
var Engine = Matter.Engine,
Events = Matter.Events,
World = Matter.World,
Body = Matter.Body,
Bodies = Matter.Bodies,
Vertices = Matter.Vertices,
Common = Matter.Common,
Composite = Matter.Composite,
Composites = Matter.Composites,
MouseConstraint = Matter.MouseConstraint,
Mouse = Matter.Mouse;
var Nav = {};
Nav.options = {
maxForce: 0.15,
minForce: -0.15,
loopTimer: 8000
};
var _engine,
_sceneWidth,
_sceneHeight;
Nav.init = function() {
Nav.container = document.getElementById('nav');
// create a Matter.js engine
_engine = Engine.create(Nav.container, {
timing: {
timeScale: 1,
},
render: {
options: {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
background: 'rgba(0,0,0,0)',
wireframes: false,
showAngleIndicator: true,
showBounds: true,
showDebug: true,
showCollisions: true,
showAxis: true,
showAngleIndicator: true
}
},
world: {
gravity: {
y: 0
},
}
});
// run the engine
Engine.run(_engine);
// Create main composites: blobs & walls
Nav.walls = Composite.create();
Nav.blobs = Composite.create();
Nav.staticBlobs = Composite.create();
Composite.add(_engine.world, [Nav.walls, Nav.blobs, Nav.staticBlobs]);
Nav.main();
Nav.updateScene();
Nav.loop();
};
Nav.main = function() {
var _world = _engine.world;
// add a mouse controlled constraint
World.add(_world, MouseConstraint.create(_engine));
// Blobs options
var blobsOptions = {
frictionAir: 0,
friction: 0,
restitution: 1,
render: {
strokeStyle: '#000000',
fillStyle: '#000000'
}
};
// Blobls
var aboutBlob = Body.create( Common.extend({
label: 'About',
position: {
x: Nav.random(0, _engine.render.options.width),
y: Nav.random(0, _engine.render.options.height),
},
force: {
x: Nav.random(Nav.options.minForce, Nav.options.maxForce),
y: Nav.random(Nav.options.minForce, Nav.options.maxForce)
},
vertices: Vertices.fromPath('245.3919982910 322.7799987793 L 247.6749982834 327.6749987602 L 250.0369982719 331.8439989090 L 252.9509983063 334.9599988461 L 262.4539985657 344.0589988232 L 269.0579986572 354.5759990215 L 273.4019985199 366.1589992046 L 276.1269984245 378.4549996853 L 281.4239983559 405.1380002499 L 289.6849980354 430.1669995785 L 303.2799983025 452.4190003872 L 324.5799975395 470.7720010281 L 331.1249976158 474.2220010757 L 336.9639978409 475.6590011120 L 342.8069977760 474.9310011268 L 349.3639979362 471.8890010715 L 354.5889978409 468.9950010180 L 360.0419979095 466.4360010028 L 365.6589980125 464.3200010657 L 371.3759980202 462.7550010085 L 379.2149982452 461.4740009904 L 387.1659984589 460.7060009837 L 395.1319985390 459.9880009890 L 403.0179986954 458.8580009937 L 411.0219984055 457.2530009747 L 418.9949984550 455.3780009747 L 426.8209986687 453.0790009499 L 434.3849987984 450.2020008564 L 443.4169983864 443.9660007954 L 448.2549986839 435.4540007114 L 448.8439986706 425.4630005360 L 445.1269986629 414.7920010090 L 439.5449988842 402.0750010014 L 436.8219988346 389.1400005817 L 437.2399988174 375.9500010014 L 441.0829987526 362.4670011997 L 443.2019987106 357.2330009937 L 445.2119987011 351.9500010014 L 447.0629987717 346.6150009632 L 448.7059988976 341.2230007648 L 453.3579988480 323.8120014668 L 456.5999989510 306.3050014973 L 457.0259989798 288.5800011158 L 453.2299989760 270.5160019398 L 446.0489987433 253.8640015125 L 436.2709988654 240.0790016651 L 422.9419983923 230.1050016880 L 405.1089982092 224.8860018253 L 391.9009980261 224.4030018151 L 378.9919976294 225.9410018027 L 366.3269976676 229.0040017664 L 353.8499974310 233.1000019610 L 345.6059969962 237.1590019763 L 339.0479969084 242.8060022891 L 334.2379969656 250.0080024302 L 331.2379969656 258.7320024073 L 328.3679970801 266.6320025027 L 323.7269972861 272.5200025141 L 317.3789972365 276.5530025065 L 309.3879970610 278.8860024512 L 295.1069969237 282.2170025408 L 281.4339965880 287.0730024874 L 268.3919967711 293.3860026896 L 256.0029968321 301.0860024989 L 252.3119968474 304.3930024207 L 249.0849968493 308.4720024168 L 245.9949969351 312.9590024054 L 245.3919982910 322.7799987793')
}, blobsOptions));
var blogBlob = Body.create( Common.extend({
label: 'Blog',
position: {
x: Nav.random(0, _engine.render.options.width),
y: Nav.random(0, _engine.render.options.height),
},
force: {
x: Nav.random(Nav.options.minForce, Nav.options.maxForce),
y: Nav.random(Nav.options.minForce, Nav.options.maxForce)
},
vertices: Vertices.fromPath('520.4160156250 431.0119934082 L 520.4540156275 427.4269933701 L 520.5130156316 424.2079932690 L 520.5070156315 421.2399933338 L 520.3520156303 418.4089932442 L 519.3880155841 414.8549933434 L 517.4950155774 412.9609932899 L 514.9700154820 412.8649932891 L 512.1090154210 414.7069932967 L 506.0370153943 418.8279931098 L 499.6190151731 420.3749931604 L 493.0380153218 420.1959931403 L 486.4790153066 419.1369931251 L 467.9170150319 414.9019929916 L 450.2690143147 408.6729929000 L 433.9760150472 399.5569927245 L 419.4780149022 386.6569931060 L 415.9330148259 383.3029930145 L 411.9910149137 380.3069929630 L 407.9740147153 377.3659929782 L 404.2040147344 374.1779930145 L 395.5960149327 366.3699929267 L 386.9790153066 358.5669929534 L 379.1160153905 350.0339929610 L 372.7720155278 340.0349933654 L 370.5200154344 333.6939932853 L 370.8020154396 328.7749931365 L 373.7710155407 324.9949931651 L 379.5790156284 322.0679931194 L 383.8110155025 320.2959931642 L 387.9240154186 318.1889930516 L 391.9890154758 315.9449930936 L 396.0790156284 313.7639930993 L 398.3420156399 312.6159930974 L 400.6140157143 311.4829930812 L 402.9090157906 310.4039930850 L 405.2410158077 309.4179930836 L 410.2390159527 307.5079929978 L 415.2590159336 305.6559929997 L 420.2800158421 303.8029929549 L 425.2770160595 301.8909930140 L 428.7200161377 300.4339929968 L 432.1260162750 298.8829929978 L 435.5410162369 297.3579930216 L 439.0080162445 295.9779930264 L 449.7790161530 292.1499929577 L 460.5710159699 288.3829929978 L 471.3590160767 284.6039929539 L 482.1150156418 280.7389929444 L 486.5680157105 278.3479929119 L 489.5130158821 274.9999928623 L 490.7000159184 270.8029928356 L 489.8780159513 265.8639927059 L 486.7810158292 257.3239927441 L 483.5310158292 248.8249931484 L 479.9400157491 240.4999933392 L 475.8170156041 232.4829931408 L 470.8970155278 226.2019930035 L 465.0320157567 222.9149930626 L 458.0420159856 222.2139930874 L 449.7470159093 223.6889931113 L 435.4320163289 228.2459932715 L 421.7650165120 234.0529934317 L 408.6860160390 241.1609932333 L 396.1360158483 249.6199928671 L 385.0570153752 257.2439929396 L 373.5490150014 264.2929927260 L 361.8570146123 271.0939928442 L 350.2220143834 277.9729930311 L 349.2490143338 278.6529930383 L 348.3040142814 279.3899930865 L 347.3410142222 280.0649930984 L 346.3160142461 280.5599931031 L 342.8090142766 281.9679930955 L 339.2380141774 283.4649930745 L 335.7810141603 284.4689930230 L 332.6180140534 284.3989930153 L 324.7710139314 282.2389929295 L 316.9460141221 279.7409930229 L 309.5010139504 276.5949931145 L 302.7960140267 272.4909930229 L 284.8100139657 258.5909934044 L 267.1120140115 244.3059935570 L 249.6560146371 229.7169938087 L 232.3970138589 214.9039940834 L 224.4050137559 209.6669940948 L 216.2190138856 207.3409941196 L 207.8080136338 207.4279941246 L 199.1400134126 209.4299942181 L 196.2930132905 210.7069941685 L 193.5590133229 212.6239942238 L 191.2340132752 214.9749942943 L 189.6150133172 217.5539942905 L 187.0490133325 224.0599943325 L 184.8520133058 230.7279945537 L 182.7430133382 237.4409943745 L 180.4410132924 244.0789943859 L 179.3460132638 249.1129943058 L 180.0970132509 253.3289943859 L 182.4850132624 256.8919943497 L 186.3020131746 259.9659944698 L 192.8180129686 264.1719943210 L 199.3280131975 268.3849941418 L 205.8210132280 272.6239939854 L 212.2830131212 276.9079939052 L 225.5670135180 285.7659937069 L 238.8470132509 294.6319938824 L 252.0690133730 303.5809942409 L 265.1790130297 312.6869941875 L 275.6980130831 320.1389943287 L 286.1300132433 327.7269941494 L 296.3340137163 335.5889941379 L 306.1680133501 343.8629943058 L 317.5060136477 354.3629943058 L 328.5200135866 365.2289944813 L 339.3630139986 376.2839947864 L 350.1870143572 387.3509951755 L 357.9090144793 394.9829951450 L 365.6470143953 402.6209951565 L 373.0730145136 410.4959951565 L 379.8620145479 418.8369947597 L 395.4480149904 437.5719953701 L 412.6720159212 454.4809957668 L 431.0150163332 470.1779962704 L 449.9580171267 485.2759958431 L 459.6360175768 490.7759958431 L 469.5740173021 492.8269959614 L 479.6910169283 492.2089959309 L 489.9050166765 489.7019959614 L 494.4480168978 487.9999960586 L 498.9330170313 485.6669961140 L 502.8350169817 482.7509962246 L 505.6290168921 479.3019963428 L 511.7780170599 467.7439967319 L 516.8810172239 455.8879967853 L 520.0550172487 443.6669970676 L 520.4160156250 431.0119934082')
}, blobsOptions));
var collabsBlob = Body.create( Common.extend({
label: 'Collabs',
position: {
x: Nav.random(0, _engine.render.options.width),
y: Nav.random(0, _engine.render.options.height),
},
force: {
x: Nav.random(Nav.options.minForce, Nav.options.maxForce),
y: Nav.random(Nav.options.minForce, Nav.options.maxForce)
},
vertices: Vertices.fromPath('245.3919982910 322.7799987793 L 247.6749982834 327.6749987602 L 250.0369982719 331.8439989090 L 252.9509983063 334.9599988461 L 262.4539985657 344.0589988232 L 269.0579986572 354.5759990215 L 273.4019985199 366.1589992046 L 276.1269984245 378.4549996853 L 281.4239983559 405.1380002499 L 289.6849980354 430.1669995785 L 303.2799983025 452.4190003872 L 324.5799975395 470.7720010281 L 331.1249976158 474.2220010757 L 336.9639978409 475.6590011120 L 342.8069977760 474.9310011268 L 349.3639979362 471.8890010715 L 354.5889978409 468.9950010180 L 360.0419979095 466.4360010028 L 365.6589980125 464.3200010657 L 371.3759980202 462.7550010085 L 379.2149982452 461.4740009904 L 387.1659984589 460.7060009837 L 395.1319985390 459.9880009890 L 403.0179986954 458.8580009937 L 411.0219984055 457.2530009747 L 418.9949984550 455.3780009747 L 426.8209986687 453.0790009499 L 434.3849987984 450.2020008564 L 443.4169983864 443.9660007954 L 448.2549986839 435.4540007114 L 448.8439986706 425.4630005360 L 445.1269986629 414.7920010090 L 439.5449988842 402.0750010014 L 436.8219988346 389.1400005817 L 437.2399988174 375.9500010014 L 441.0829987526 362.4670011997 L 443.2019987106 357.2330009937 L 445.2119987011 351.9500010014 L 447.0629987717 346.6150009632 L 448.7059988976 341.2230007648 L 453.3579988480 323.8120014668 L 456.5999989510 306.3050014973 L 457.0259989798 288.5800011158 L 453.2299989760 270.5160019398 L 446.0489987433 253.8640015125 L 436.2709988654 240.0790016651 L 422.9419983923 230.1050016880 L 405.1089982092 224.8860018253 L 391.9009980261 224.4030018151 L 378.9919976294 225.9410018027 L 366.3269976676 229.0040017664 L 353.8499974310 233.1000019610 L 345.6059969962 237.1590019763 L 339.0479969084 242.8060022891 L 334.2379969656 250.0080024302 L 331.2379969656 258.7320024073 L 328.3679970801 266.6320025027 L 323.7269972861 272.5200025141 L 317.3789972365 276.5530025065 L 309.3879970610 278.8860024512 L 295.1069969237 282.2170025408 L 281.4339965880 287.0730024874 L 268.3919967711 293.3860026896 L 256.0029968321 301.0860024989 L 252.3119968474 304.3930024207 L 249.0849968493 308.4720024168 L 245.9949969351 312.9590024054 L 245.3919982910 322.7799987793')
}, blobsOptions));
var installationsBlob = Body.create( Common.extend({}, {
label: 'Installations',
position: {
x: Nav.random(0, _engine.render.options.width),
y: Nav.random(0, _engine.render.options.height),
},
force: {
x: Nav.random(Nav.options.minForce, Nav.options.maxForce),
y: Nav.random(Nav.options.minForce, Nav.options.maxForce)
},
vertices: Vertices.fromPath('337.1380004883 334.5559997559 L 343.0400004387 339.7289996147 L 345.0880005360 345.4679994583 L 344.6180005074 351.5139994621 L 342.9640004635 357.6089992523 L 338.3730003834 381.8759994507 L 338.9400004148 405.5459995270 L 344.1560004950 428.6679992676 L 353.5090001822 451.2899990082 L 356.1060003042 455.9799990654 L 359.0610002279 460.5039992332 L 362.3110002279 464.8309993744 L 365.7890001535 468.9279994965 L 371.7760001421 473.9199995995 L 378.3979998827 476.4229996204 L 385.5749999285 476.5439996272 L 393.2279998064 474.3889996558 L 405.8589993715 467.0849997550 L 414.4469996691 457.1449992210 L 419.3039995432 444.1949994117 L 420.7419995070 427.8629986793 L 420.1419994831 403.2749993354 L 420.0259994864 378.7099988014 L 422.2439994216 354.3269993812 L 428.6469992995 330.2849995643 L 428.9889993072 329.1759995967 L 429.2099993080 328.0129996091 L 429.3299993128 326.8279996663 L 429.3689993136 325.6509996206 L 429.5109993182 305.2269998342 L 429.6519993208 284.8020005971 L 429.7209993266 264.3780008107 L 429.6479993202 243.9550004750 L 428.0889993049 233.8100000173 L 423.6429992057 226.9020000249 L 416.3749990799 223.5219999105 L 406.3509989120 223.9609999210 L 396.8159990646 226.6189999133 L 387.4699993469 230.1579999477 L 378.2359991409 234.1509999782 L 369.0379991867 238.1739997417 L 367.5069992878 239.2199997455 L 366.1639993526 240.8249997646 L 365.0779993869 242.7219998389 L 364.3169994093 244.6449999362 L 361.2849993445 252.3969997913 L 357.5949992873 256.3759998828 L 352.2279991843 257.0699999481 L 344.1669993140 254.9659998566 L 339.2999992110 253.2289998680 L 334.4389991499 251.4649999291 L 329.5489992835 249.8259999901 L 324.5939993598 248.4649999291 L 320.2879991271 248.0609999150 L 317.1209990717 249.2079998702 L 315.4529990889 252.0929998606 L 315.6399990954 256.9039997309 L 316.4319990315 260.5809997767 L 317.2079989947 264.2629996985 L 317.9039990343 267.9559997767 L 318.4569990672 271.6649998873 L 318.6309990771 277.4899996966 L 317.1769990809 280.7709995955 L 313.8009991534 281.8079995364 L 308.2099990733 280.8989994973 L 298.6069993861 279.6799995154 L 290.1569995768 281.3619994372 L 282.9589996226 285.9659995288 L 277.1119995005 293.5169996470 L 271.3829994090 306.6589998454 L 270.4929994233 317.9450000972 L 273.9439993985 329.0040001124 L 281.2379995473 341.4660000056 L 292.5949998982 353.1369995326 L 305.6909996159 357.5459994525 L 318.9799991734 354.0919994563 L 330.9149995930 342.1759990901 L 332.2609995492 340.3129990548 L 333.7689995654 338.4839990586 L 335.4059996493 336.5959990472 L 337.1380004883 334.5559997559')
}, blobsOptions));
var pressBlob = Body.create( Common.extend({
label: 'Press',
position: {
x: Nav.random(0, _engine.render.options.width),
y: Nav.random(0, _engine.render.options.height),
},
force: {
x: Nav.random(Nav.options.minForce, Nav.options.maxForce),
y: Nav.random(Nav.options.minForce, Nav.options.maxForce)
},
vertices: Vertices.fromPath('181.0469970703 467.5660095215 L 180.6409970522 468.1870095134 L 180.2349970341 468.8090094924 L 179.8279970288 469.4310094714 L 179.4209970236 470.0530094504 L 184.0009969473 479.0390095115 L 188.3979967833 488.2370094657 L 193.3369969130 496.8030094504 L 199.5419968367 503.8950094581 L 218.6149967909 516.8320097327 L 239.5629967451 525.4140095115 L 261.7119969130 530.4170092940 L 284.3899964094 532.6180092692 L 298.2799967527 531.8770092726 L 312.2689970732 529.0770093203 L 326.2739971876 525.2750092745 L 340.2119969130 521.5290092230 L 343.9969967604 520.3230092525 L 347.7519968748 518.5280092955 L 351.0629967451 516.2090092897 L 353.5119966269 513.4320093393 L 363.9159969091 496.9350095987 L 374.1799968481 480.3390089273 L 384.0359967947 463.5240083933 L 393.2189964056 446.3700090647 L 402.6659959555 426.4130083323 L 411.4689964056 406.1320081949 L 420.1419967413 385.7810083628 L 429.1999963522 365.6140085459 L 438.5809959173 348.7510076761 L 450.1079963446 333.7710081339 L 463.9859966040 320.7640081644 L 480.4189971685 309.8200079203 L 493.4709972143 300.4840074778 L 504.0679973364 288.7670074701 L 512.4279969931 275.1730076075 L 518.7709969282 260.2040077448 L 520.5669969320 250.3760076761 L 518.3109968901 243.5270076990 L 512.2289971113 240.1290076971 L 502.5489968061 240.6500076652 L 486.6389969587 244.5830077529 L 470.8449972868 249.0920075774 L 455.2919968367 254.2980074286 L 440.1069964170 260.3190073371 L 431.2189959288 265.0170072913 L 422.8249958754 270.9890074134 L 415.0299957991 277.8560075164 L 407.9389957190 285.2380074859 L 401.8459957838 291.6680073142 L 395.4279955626 297.3840073943 L 388.4589956999 302.2160071731 L 380.7129958868 305.9930071235 L 368.1009963751 308.5140070319 L 357.3919967413 305.9170069098 L 349.2539972067 298.5220069289 L 344.3599971533 286.6490067840 L 342.1909972429 270.8330067992 L 342.8369972706 255.3710069060 L 346.6079971790 240.3850068450 L 353.8169972897 225.9970063567 L 358.6189973354 218.7670063376 L 363.5959975719 211.6470064521 L 368.6789977551 204.5980066657 L 373.8029978275 197.5810064673 L 378.3939979076 190.8300065398 L 382.2159979343 183.7070063949 L 384.9089980125 175.9550065398 L 386.1119980812 167.3170060515 L 383.5009980202 167.3910060599 L 381.2589979172 167.4190060608 L 379.2859978676 167.5140060671 L 377.4809978008 167.7890060730 L 366.2849977016 170.3330062218 L 355.0939977169 172.9010063000 L 343.9339978695 175.5840063877 L 332.8299977779 178.4710064717 L 327.5089976788 180.1800064631 L 322.2869975567 182.2560064383 L 317.1219975948 184.5240063258 L 311.9729974270 186.8070063181 L 307.6089975834 189.3950063772 L 304.4259974957 192.8330063410 L 302.3699975014 197.0920061655 L 301.3859974742 202.1440062113 L 300.1549975276 214.7640060969 L 298.8099974990 227.3770060129 L 297.6229974627 239.9940056391 L 296.8649974465 252.6270060129 L 296.6039974689 286.8000063486 L 298.7229974270 320.7250055857 L 303.8989975452 354.2790064402 L 312.8099977970 387.3390078135 L 316.6449978352 400.4860081263 L 319.4639978409 413.7530083247 L 321.4279978275 427.1460079737 L 322.6949977875 440.6730084009 L 321.8189978004 455.2560085841 L 317.4849976897 468.6980089732 L 310.2799977660 479.5490088053 L 300.7919978499 486.3590087481 L 293.3869976401 489.1320087500 L 285.8219975829 491.5190088339 L 278.1669973731 493.6610087939 L 270.4919971824 495.7020086832 L 268.0329970717 496.1150086708 L 265.4579970241 496.1580086723 L 262.8559970260 495.9250086620 L 260.3159970641 495.5110086575 L 244.0829972625 491.7380086556 L 228.3609971404 486.6220084801 L 213.1609973311 480.0740086213 L 198.4949969649 472.0040089265 L 194.5369967818 470.2400089875 L 190.1419968009 469.1830089465 L 185.5609969497 468.4270089641 L 181.0469970703 467.5660095215')
}, blobsOptions));
var shopBlob = Body.create( Common.extend({}, {
label: 'Shop',
position: {
x: Nav.random(0, _engine.render.options.width),
y: Nav.random(0, _engine.render.options.height),
},
force: {
x: Nav.random(Nav.options.minForce, Nav.options.maxForce),
y: Nav.random(Nav.options.minForce, Nav.options.maxForce)
},
vertices: Vertices.fromPath('245.0310058594 384.2950134277 L 245.7280059457 393.7280130386 L 246.2510059476 403.2260131836 L 247.3130059838 412.5220136642 L 249.6270061135 421.3510141373 L 256.0860062242 437.0640144348 L 263.6210060716 452.2830142975 L 272.3440056443 466.9820146561 L 282.3680058122 481.1350145340 L 292.4060059190 488.8750143051 L 304.1920061707 490.8470143080 L 315.3630066514 487.7230142355 L 323.5590067506 480.1770142317 L 328.8740068078 473.1600140333 L 335.1690068841 467.5510138273 L 342.4530068040 463.1970137358 L 350.7340069413 459.9460138083 L 361.1420069337 455.1930135489 L 369.4470072389 448.2160133123 L 375.2900071740 439.2820132971 L 378.3110070825 428.6560128927 L 379.3270071149 415.6440128088 L 379.3880071156 402.5090125799 L 379.0940070860 389.3210128546 L 379.0460070819 376.1500123739 L 379.0960070863 369.1170123816 L 379.2340070829 362.0400122404 L 379.8800071105 355.1050122976 L 381.4540071115 348.4980124235 L 390.6280068979 330.1660116911 L 403.7080068216 317.3020113707 L 420.6560067758 309.7660115957 L 441.4320058450 307.4180115461 L 446.8490056619 306.9590115249 L 450.9630055055 305.1900114715 L 453.6480054483 301.6790115535 L 454.7760054693 295.9940116107 L 455.1670054719 281.3890120685 L 453.9760054871 267.2600123584 L 449.6320056245 253.9220120609 L 440.5670060441 241.6900117099 L 435.9570059106 236.7260114849 L 431.7070059106 231.3900115192 L 427.6110057160 225.8940117061 L 423.4630059525 220.4530117214 L 414.6900061890 213.2170116603 L 403.6780061051 209.5760116279 L 391.8810061738 209.5410116278 L 380.7530059144 213.1230116449 L 366.8340062425 220.1270118318 L 352.7360066697 226.7900119387 L 338.5380067155 233.2560120188 L 324.3190068528 239.6680121981 L 315.2010068223 243.5410123430 L 306.2440070435 247.5590124689 L 297.7880067155 252.6640124880 L 290.1730069444 259.7990127169 L 270.0200070664 287.7730136476 L 255.3810071275 317.6260142885 L 246.8520068452 349.6890140139 L 245.0310058594 384.2950134277')
}, blobsOptions));
// create semi-static blobs
var staticBlobsOptios = {
frictionAir: 1,
friction: 0,
restitution: 1,
render: {
strokeStyle: '#000000',
fillStyle: 'red'
}
};
var boxA = Bodies.rectangle(Nav.random(0, _engine.render.options.width), Nav.random(0, _engine.render.options.height), 80, 80, staticBlobsOptios);
var boxB = Bodies.rectangle(Nav.random(0, _engine.render.options.width), Nav.random(0, _engine.render.options.height), 80, 80, staticBlobsOptios);
// add all of the bodies to the world
Composite.add(Nav.blobs, [aboutBlob, blogBlob, collabsBlob, installationsBlob, pressBlob, shopBlob]);
Composite.add(Nav.staticBlobs, [boxA, boxB]);
};
Nav.updateScene = function() {
if (!_engine)
return;
_sceneWidth = document.documentElement.clientWidth;
_sceneHeight = document.documentElement.clientHeight;
var boundsMax = _engine.world.bounds.max,
renderOptions = _engine.render.options,
canvas = _engine.render.canvas;
boundsMax.x = _sceneWidth;
boundsMax.y = _sceneHeight;
canvas.width = renderOptions.width = _sceneWidth;
canvas.height = renderOptions.height = _sceneHeight;
Nav.updateWalls();
};
Nav.updateWalls = function() {
if (!_engine)
return;
if(this.walls.bodies.length != 0)
Composite.clear(Nav.walls);
wallOptions = {
isStatic: true,
restitution: 1,
render: {
visible: true,
strokeStyle: 'red'
}
};
Composite.add( Nav.walls, [
Bodies.rectangle(window.innerWidth/2, 1, window.innerWidth, 2, wallOptions),
Bodies.rectangle(window.innerWidth/2, window.innerHeight - 1, window.innerWidth, 2, wallOptions),
Bodies.rectangle(0, window.innerHeight/2, 2, window.innerHeight, wallOptions),
Bodies.rectangle(window.innerWidth-1, window.innerHeight/2, 2, window.innerHeight, wallOptions)
]);
};
Nav.loop = function() {
setTimeout(function () {
Nav.loop();
}, Nav.options.loopTimer);
};
Nav.random = function(min, max) {
return Math.random() * (max - min) + min;
}
window.addEventListener('load', Nav.init);
window.addEventListener('resize', Nav.updateScene);
//})();
|
js/nav.js
|
//(function() {
/*
* NAV / MATTER.JS
*/
// Matter module aliases
var Engine = Matter.Engine,
World = Matter.World,
Body = Matter.Body,
Bodies = Matter.Bodies,
Vertices = Matter.Vertices,
Common = Matter.Common,
Composite = Matter.Composite,
Composites = Matter.Composites,
MouseConstraint = Matter.MouseConstraint,
Mouse = Matter.Mouse;
var Nav = {};
Nav.options = {
maxForce: 0.15,
minForce: -0.15,
loopTimer: 8000
};
var _engine,
_sceneWidth,
_sceneHeight;
Nav.init = function() {
Nav.container = document.getElementById('nav');
// create a Matter.js engine
_engine = Engine.create(Nav.container, {
timing: {
timeScale: 1,
},
render: {
options: {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
background: 'rgba(0,0,0,0)',
wireframes: false,
showAngleIndicator: true,
showBounds: true,
showDebug: true,
showCollisions: true,
showAxis: true,
showAngleIndicator: true
}
},
world: {
gravity: {
y: 0
},
}
});
// run the engine
Engine.run(_engine);
// Create main composites: blobs & walls
Nav.walls = Composite.create();
Nav.blobs = Composite.create();
Nav.staticBlobs = Composite.create();
Composite.add(_engine.world, [Nav.walls, Nav.blobs, Nav.staticBlobs]);
Nav.main();
Nav.updateScene();
Nav.loop();
};
Nav.main = function() {
var _world = _engine.world;
// add a mouse controlled constraint
World.add(_world, MouseConstraint.create(_engine));
// Blobs options
var blobsOptions = {
frictionAir: 0,
friction: 0,
restitution: 1,
render: {
strokeStyle: '#000000',
fillStyle: '#000000'
}
};
// Blobls
var aboutBlob = Body.create( Common.extend({
label: 'About',
position: {
x: Nav.random(0, _engine.render.options.width),
y: Nav.random(0, _engine.render.options.height),
},
force: {
x: Nav.random(Nav.options.minForce, Nav.options.maxForce),
y: Nav.random(Nav.options.minForce, Nav.options.maxForce)
},
vertices: Vertices.fromPath('245.3919982910 322.7799987793 L 247.6749982834 327.6749987602 L 250.0369982719 331.8439989090 L 252.9509983063 334.9599988461 L 262.4539985657 344.0589988232 L 269.0579986572 354.5759990215 L 273.4019985199 366.1589992046 L 276.1269984245 378.4549996853 L 281.4239983559 405.1380002499 L 289.6849980354 430.1669995785 L 303.2799983025 452.4190003872 L 324.5799975395 470.7720010281 L 331.1249976158 474.2220010757 L 336.9639978409 475.6590011120 L 342.8069977760 474.9310011268 L 349.3639979362 471.8890010715 L 354.5889978409 468.9950010180 L 360.0419979095 466.4360010028 L 365.6589980125 464.3200010657 L 371.3759980202 462.7550010085 L 379.2149982452 461.4740009904 L 387.1659984589 460.7060009837 L 395.1319985390 459.9880009890 L 403.0179986954 458.8580009937 L 411.0219984055 457.2530009747 L 418.9949984550 455.3780009747 L 426.8209986687 453.0790009499 L 434.3849987984 450.2020008564 L 443.4169983864 443.9660007954 L 448.2549986839 435.4540007114 L 448.8439986706 425.4630005360 L 445.1269986629 414.7920010090 L 439.5449988842 402.0750010014 L 436.8219988346 389.1400005817 L 437.2399988174 375.9500010014 L 441.0829987526 362.4670011997 L 443.2019987106 357.2330009937 L 445.2119987011 351.9500010014 L 447.0629987717 346.6150009632 L 448.7059988976 341.2230007648 L 453.3579988480 323.8120014668 L 456.5999989510 306.3050014973 L 457.0259989798 288.5800011158 L 453.2299989760 270.5160019398 L 446.0489987433 253.8640015125 L 436.2709988654 240.0790016651 L 422.9419983923 230.1050016880 L 405.1089982092 224.8860018253 L 391.9009980261 224.4030018151 L 378.9919976294 225.9410018027 L 366.3269976676 229.0040017664 L 353.8499974310 233.1000019610 L 345.6059969962 237.1590019763 L 339.0479969084 242.8060022891 L 334.2379969656 250.0080024302 L 331.2379969656 258.7320024073 L 328.3679970801 266.6320025027 L 323.7269972861 272.5200025141 L 317.3789972365 276.5530025065 L 309.3879970610 278.8860024512 L 295.1069969237 282.2170025408 L 281.4339965880 287.0730024874 L 268.3919967711 293.3860026896 L 256.0029968321 301.0860024989 L 252.3119968474 304.3930024207 L 249.0849968493 308.4720024168 L 245.9949969351 312.9590024054 L 245.3919982910 322.7799987793')
}, blobsOptions));
var blogBlob = Body.create( Common.extend({
label: 'Blog',
position: {
x: Nav.random(0, _engine.render.options.width),
y: Nav.random(0, _engine.render.options.height),
},
force: {
x: Nav.random(Nav.options.minForce, Nav.options.maxForce),
y: Nav.random(Nav.options.minForce, Nav.options.maxForce)
},
vertices: Vertices.fromPath('520.4160156250 431.0119934082 L 520.4540156275 427.4269933701 L 520.5130156316 424.2079932690 L 520.5070156315 421.2399933338 L 520.3520156303 418.4089932442 L 519.3880155841 414.8549933434 L 517.4950155774 412.9609932899 L 514.9700154820 412.8649932891 L 512.1090154210 414.7069932967 L 506.0370153943 418.8279931098 L 499.6190151731 420.3749931604 L 493.0380153218 420.1959931403 L 486.4790153066 419.1369931251 L 467.9170150319 414.9019929916 L 450.2690143147 408.6729929000 L 433.9760150472 399.5569927245 L 419.4780149022 386.6569931060 L 415.9330148259 383.3029930145 L 411.9910149137 380.3069929630 L 407.9740147153 377.3659929782 L 404.2040147344 374.1779930145 L 395.5960149327 366.3699929267 L 386.9790153066 358.5669929534 L 379.1160153905 350.0339929610 L 372.7720155278 340.0349933654 L 370.5200154344 333.6939932853 L 370.8020154396 328.7749931365 L 373.7710155407 324.9949931651 L 379.5790156284 322.0679931194 L 383.8110155025 320.2959931642 L 387.9240154186 318.1889930516 L 391.9890154758 315.9449930936 L 396.0790156284 313.7639930993 L 398.3420156399 312.6159930974 L 400.6140157143 311.4829930812 L 402.9090157906 310.4039930850 L 405.2410158077 309.4179930836 L 410.2390159527 307.5079929978 L 415.2590159336 305.6559929997 L 420.2800158421 303.8029929549 L 425.2770160595 301.8909930140 L 428.7200161377 300.4339929968 L 432.1260162750 298.8829929978 L 435.5410162369 297.3579930216 L 439.0080162445 295.9779930264 L 449.7790161530 292.1499929577 L 460.5710159699 288.3829929978 L 471.3590160767 284.6039929539 L 482.1150156418 280.7389929444 L 486.5680157105 278.3479929119 L 489.5130158821 274.9999928623 L 490.7000159184 270.8029928356 L 489.8780159513 265.8639927059 L 486.7810158292 257.3239927441 L 483.5310158292 248.8249931484 L 479.9400157491 240.4999933392 L 475.8170156041 232.4829931408 L 470.8970155278 226.2019930035 L 465.0320157567 222.9149930626 L 458.0420159856 222.2139930874 L 449.7470159093 223.6889931113 L 435.4320163289 228.2459932715 L 421.7650165120 234.0529934317 L 408.6860160390 241.1609932333 L 396.1360158483 249.6199928671 L 385.0570153752 257.2439929396 L 373.5490150014 264.2929927260 L 361.8570146123 271.0939928442 L 350.2220143834 277.9729930311 L 349.2490143338 278.6529930383 L 348.3040142814 279.3899930865 L 347.3410142222 280.0649930984 L 346.3160142461 280.5599931031 L 342.8090142766 281.9679930955 L 339.2380141774 283.4649930745 L 335.7810141603 284.4689930230 L 332.6180140534 284.3989930153 L 324.7710139314 282.2389929295 L 316.9460141221 279.7409930229 L 309.5010139504 276.5949931145 L 302.7960140267 272.4909930229 L 284.8100139657 258.5909934044 L 267.1120140115 244.3059935570 L 249.6560146371 229.7169938087 L 232.3970138589 214.9039940834 L 224.4050137559 209.6669940948 L 216.2190138856 207.3409941196 L 207.8080136338 207.4279941246 L 199.1400134126 209.4299942181 L 196.2930132905 210.7069941685 L 193.5590133229 212.6239942238 L 191.2340132752 214.9749942943 L 189.6150133172 217.5539942905 L 187.0490133325 224.0599943325 L 184.8520133058 230.7279945537 L 182.7430133382 237.4409943745 L 180.4410132924 244.0789943859 L 179.3460132638 249.1129943058 L 180.0970132509 253.3289943859 L 182.4850132624 256.8919943497 L 186.3020131746 259.9659944698 L 192.8180129686 264.1719943210 L 199.3280131975 268.3849941418 L 205.8210132280 272.6239939854 L 212.2830131212 276.9079939052 L 225.5670135180 285.7659937069 L 238.8470132509 294.6319938824 L 252.0690133730 303.5809942409 L 265.1790130297 312.6869941875 L 275.6980130831 320.1389943287 L 286.1300132433 327.7269941494 L 296.3340137163 335.5889941379 L 306.1680133501 343.8629943058 L 317.5060136477 354.3629943058 L 328.5200135866 365.2289944813 L 339.3630139986 376.2839947864 L 350.1870143572 387.3509951755 L 357.9090144793 394.9829951450 L 365.6470143953 402.6209951565 L 373.0730145136 410.4959951565 L 379.8620145479 418.8369947597 L 395.4480149904 437.5719953701 L 412.6720159212 454.4809957668 L 431.0150163332 470.1779962704 L 449.9580171267 485.2759958431 L 459.6360175768 490.7759958431 L 469.5740173021 492.8269959614 L 479.6910169283 492.2089959309 L 489.9050166765 489.7019959614 L 494.4480168978 487.9999960586 L 498.9330170313 485.6669961140 L 502.8350169817 482.7509962246 L 505.6290168921 479.3019963428 L 511.7780170599 467.7439967319 L 516.8810172239 455.8879967853 L 520.0550172487 443.6669970676 L 520.4160156250 431.0119934082')
}, blobsOptions));
var collabsBlob = Body.create( Common.extend({
label: 'Collabs',
position: {
x: Nav.random(0, _engine.render.options.width),
y: Nav.random(0, _engine.render.options.height),
},
force: {
x: Nav.random(Nav.options.minForce, Nav.options.maxForce),
y: Nav.random(Nav.options.minForce, Nav.options.maxForce)
},
vertices: Vertices.fromPath('245.3919982910 322.7799987793 L 247.6749982834 327.6749987602 L 250.0369982719 331.8439989090 L 252.9509983063 334.9599988461 L 262.4539985657 344.0589988232 L 269.0579986572 354.5759990215 L 273.4019985199 366.1589992046 L 276.1269984245 378.4549996853 L 281.4239983559 405.1380002499 L 289.6849980354 430.1669995785 L 303.2799983025 452.4190003872 L 324.5799975395 470.7720010281 L 331.1249976158 474.2220010757 L 336.9639978409 475.6590011120 L 342.8069977760 474.9310011268 L 349.3639979362 471.8890010715 L 354.5889978409 468.9950010180 L 360.0419979095 466.4360010028 L 365.6589980125 464.3200010657 L 371.3759980202 462.7550010085 L 379.2149982452 461.4740009904 L 387.1659984589 460.7060009837 L 395.1319985390 459.9880009890 L 403.0179986954 458.8580009937 L 411.0219984055 457.2530009747 L 418.9949984550 455.3780009747 L 426.8209986687 453.0790009499 L 434.3849987984 450.2020008564 L 443.4169983864 443.9660007954 L 448.2549986839 435.4540007114 L 448.8439986706 425.4630005360 L 445.1269986629 414.7920010090 L 439.5449988842 402.0750010014 L 436.8219988346 389.1400005817 L 437.2399988174 375.9500010014 L 441.0829987526 362.4670011997 L 443.2019987106 357.2330009937 L 445.2119987011 351.9500010014 L 447.0629987717 346.6150009632 L 448.7059988976 341.2230007648 L 453.3579988480 323.8120014668 L 456.5999989510 306.3050014973 L 457.0259989798 288.5800011158 L 453.2299989760 270.5160019398 L 446.0489987433 253.8640015125 L 436.2709988654 240.0790016651 L 422.9419983923 230.1050016880 L 405.1089982092 224.8860018253 L 391.9009980261 224.4030018151 L 378.9919976294 225.9410018027 L 366.3269976676 229.0040017664 L 353.8499974310 233.1000019610 L 345.6059969962 237.1590019763 L 339.0479969084 242.8060022891 L 334.2379969656 250.0080024302 L 331.2379969656 258.7320024073 L 328.3679970801 266.6320025027 L 323.7269972861 272.5200025141 L 317.3789972365 276.5530025065 L 309.3879970610 278.8860024512 L 295.1069969237 282.2170025408 L 281.4339965880 287.0730024874 L 268.3919967711 293.3860026896 L 256.0029968321 301.0860024989 L 252.3119968474 304.3930024207 L 249.0849968493 308.4720024168 L 245.9949969351 312.9590024054 L 245.3919982910 322.7799987793')
}, blobsOptions));
var installationsBlob = Body.create( Common.extend({}, {
label: 'Installations',
position: {
x: Nav.random(0, _engine.render.options.width),
y: Nav.random(0, _engine.render.options.height),
},
force: {
x: Nav.random(Nav.options.minForce, Nav.options.maxForce),
y: Nav.random(Nav.options.minForce, Nav.options.maxForce)
},
vertices: Vertices.fromPath('337.1380004883 334.5559997559 L 343.0400004387 339.7289996147 L 345.0880005360 345.4679994583 L 344.6180005074 351.5139994621 L 342.9640004635 357.6089992523 L 338.3730003834 381.8759994507 L 338.9400004148 405.5459995270 L 344.1560004950 428.6679992676 L 353.5090001822 451.2899990082 L 356.1060003042 455.9799990654 L 359.0610002279 460.5039992332 L 362.3110002279 464.8309993744 L 365.7890001535 468.9279994965 L 371.7760001421 473.9199995995 L 378.3979998827 476.4229996204 L 385.5749999285 476.5439996272 L 393.2279998064 474.3889996558 L 405.8589993715 467.0849997550 L 414.4469996691 457.1449992210 L 419.3039995432 444.1949994117 L 420.7419995070 427.8629986793 L 420.1419994831 403.2749993354 L 420.0259994864 378.7099988014 L 422.2439994216 354.3269993812 L 428.6469992995 330.2849995643 L 428.9889993072 329.1759995967 L 429.2099993080 328.0129996091 L 429.3299993128 326.8279996663 L 429.3689993136 325.6509996206 L 429.5109993182 305.2269998342 L 429.6519993208 284.8020005971 L 429.7209993266 264.3780008107 L 429.6479993202 243.9550004750 L 428.0889993049 233.8100000173 L 423.6429992057 226.9020000249 L 416.3749990799 223.5219999105 L 406.3509989120 223.9609999210 L 396.8159990646 226.6189999133 L 387.4699993469 230.1579999477 L 378.2359991409 234.1509999782 L 369.0379991867 238.1739997417 L 367.5069992878 239.2199997455 L 366.1639993526 240.8249997646 L 365.0779993869 242.7219998389 L 364.3169994093 244.6449999362 L 361.2849993445 252.3969997913 L 357.5949992873 256.3759998828 L 352.2279991843 257.0699999481 L 344.1669993140 254.9659998566 L 339.2999992110 253.2289998680 L 334.4389991499 251.4649999291 L 329.5489992835 249.8259999901 L 324.5939993598 248.4649999291 L 320.2879991271 248.0609999150 L 317.1209990717 249.2079998702 L 315.4529990889 252.0929998606 L 315.6399990954 256.9039997309 L 316.4319990315 260.5809997767 L 317.2079989947 264.2629996985 L 317.9039990343 267.9559997767 L 318.4569990672 271.6649998873 L 318.6309990771 277.4899996966 L 317.1769990809 280.7709995955 L 313.8009991534 281.8079995364 L 308.2099990733 280.8989994973 L 298.6069993861 279.6799995154 L 290.1569995768 281.3619994372 L 282.9589996226 285.9659995288 L 277.1119995005 293.5169996470 L 271.3829994090 306.6589998454 L 270.4929994233 317.9450000972 L 273.9439993985 329.0040001124 L 281.2379995473 341.4660000056 L 292.5949998982 353.1369995326 L 305.6909996159 357.5459994525 L 318.9799991734 354.0919994563 L 330.9149995930 342.1759990901 L 332.2609995492 340.3129990548 L 333.7689995654 338.4839990586 L 335.4059996493 336.5959990472 L 337.1380004883 334.5559997559')
}, blobsOptions));
var pressBlob = Body.create( Common.extend({
label: 'Press',
position: {
x: Nav.random(0, _engine.render.options.width),
y: Nav.random(0, _engine.render.options.height),
},
force: {
x: Nav.random(Nav.options.minForce, Nav.options.maxForce),
y: Nav.random(Nav.options.minForce, Nav.options.maxForce)
},
vertices: Vertices.fromPath('181.0469970703 467.5660095215 L 180.6409970522 468.1870095134 L 180.2349970341 468.8090094924 L 179.8279970288 469.4310094714 L 179.4209970236 470.0530094504 L 184.0009969473 479.0390095115 L 188.3979967833 488.2370094657 L 193.3369969130 496.8030094504 L 199.5419968367 503.8950094581 L 218.6149967909 516.8320097327 L 239.5629967451 525.4140095115 L 261.7119969130 530.4170092940 L 284.3899964094 532.6180092692 L 298.2799967527 531.8770092726 L 312.2689970732 529.0770093203 L 326.2739971876 525.2750092745 L 340.2119969130 521.5290092230 L 343.9969967604 520.3230092525 L 347.7519968748 518.5280092955 L 351.0629967451 516.2090092897 L 353.5119966269 513.4320093393 L 363.9159969091 496.9350095987 L 374.1799968481 480.3390089273 L 384.0359967947 463.5240083933 L 393.2189964056 446.3700090647 L 402.6659959555 426.4130083323 L 411.4689964056 406.1320081949 L 420.1419967413 385.7810083628 L 429.1999963522 365.6140085459 L 438.5809959173 348.7510076761 L 450.1079963446 333.7710081339 L 463.9859966040 320.7640081644 L 480.4189971685 309.8200079203 L 493.4709972143 300.4840074778 L 504.0679973364 288.7670074701 L 512.4279969931 275.1730076075 L 518.7709969282 260.2040077448 L 520.5669969320 250.3760076761 L 518.3109968901 243.5270076990 L 512.2289971113 240.1290076971 L 502.5489968061 240.6500076652 L 486.6389969587 244.5830077529 L 470.8449972868 249.0920075774 L 455.2919968367 254.2980074286 L 440.1069964170 260.3190073371 L 431.2189959288 265.0170072913 L 422.8249958754 270.9890074134 L 415.0299957991 277.8560075164 L 407.9389957190 285.2380074859 L 401.8459957838 291.6680073142 L 395.4279955626 297.3840073943 L 388.4589956999 302.2160071731 L 380.7129958868 305.9930071235 L 368.1009963751 308.5140070319 L 357.3919967413 305.9170069098 L 349.2539972067 298.5220069289 L 344.3599971533 286.6490067840 L 342.1909972429 270.8330067992 L 342.8369972706 255.3710069060 L 346.6079971790 240.3850068450 L 353.8169972897 225.9970063567 L 358.6189973354 218.7670063376 L 363.5959975719 211.6470064521 L 368.6789977551 204.5980066657 L 373.8029978275 197.5810064673 L 378.3939979076 190.8300065398 L 382.2159979343 183.7070063949 L 384.9089980125 175.9550065398 L 386.1119980812 167.3170060515 L 383.5009980202 167.3910060599 L 381.2589979172 167.4190060608 L 379.2859978676 167.5140060671 L 377.4809978008 167.7890060730 L 366.2849977016 170.3330062218 L 355.0939977169 172.9010063000 L 343.9339978695 175.5840063877 L 332.8299977779 178.4710064717 L 327.5089976788 180.1800064631 L 322.2869975567 182.2560064383 L 317.1219975948 184.5240063258 L 311.9729974270 186.8070063181 L 307.6089975834 189.3950063772 L 304.4259974957 192.8330063410 L 302.3699975014 197.0920061655 L 301.3859974742 202.1440062113 L 300.1549975276 214.7640060969 L 298.8099974990 227.3770060129 L 297.6229974627 239.9940056391 L 296.8649974465 252.6270060129 L 296.6039974689 286.8000063486 L 298.7229974270 320.7250055857 L 303.8989975452 354.2790064402 L 312.8099977970 387.3390078135 L 316.6449978352 400.4860081263 L 319.4639978409 413.7530083247 L 321.4279978275 427.1460079737 L 322.6949977875 440.6730084009 L 321.8189978004 455.2560085841 L 317.4849976897 468.6980089732 L 310.2799977660 479.5490088053 L 300.7919978499 486.3590087481 L 293.3869976401 489.1320087500 L 285.8219975829 491.5190088339 L 278.1669973731 493.6610087939 L 270.4919971824 495.7020086832 L 268.0329970717 496.1150086708 L 265.4579970241 496.1580086723 L 262.8559970260 495.9250086620 L 260.3159970641 495.5110086575 L 244.0829972625 491.7380086556 L 228.3609971404 486.6220084801 L 213.1609973311 480.0740086213 L 198.4949969649 472.0040089265 L 194.5369967818 470.2400089875 L 190.1419968009 469.1830089465 L 185.5609969497 468.4270089641 L 181.0469970703 467.5660095215')
}, blobsOptions));
var shopBlob = Body.create( Common.extend({}, {
label: 'Shop',
position: {
x: Nav.random(0, _engine.render.options.width),
y: Nav.random(0, _engine.render.options.height),
},
force: {
x: Nav.random(Nav.options.minForce, Nav.options.maxForce),
y: Nav.random(Nav.options.minForce, Nav.options.maxForce)
},
vertices: Vertices.fromPath('245.0310058594 384.2950134277 L 245.7280059457 393.7280130386 L 246.2510059476 403.2260131836 L 247.3130059838 412.5220136642 L 249.6270061135 421.3510141373 L 256.0860062242 437.0640144348 L 263.6210060716 452.2830142975 L 272.3440056443 466.9820146561 L 282.3680058122 481.1350145340 L 292.4060059190 488.8750143051 L 304.1920061707 490.8470143080 L 315.3630066514 487.7230142355 L 323.5590067506 480.1770142317 L 328.8740068078 473.1600140333 L 335.1690068841 467.5510138273 L 342.4530068040 463.1970137358 L 350.7340069413 459.9460138083 L 361.1420069337 455.1930135489 L 369.4470072389 448.2160133123 L 375.2900071740 439.2820132971 L 378.3110070825 428.6560128927 L 379.3270071149 415.6440128088 L 379.3880071156 402.5090125799 L 379.0940070860 389.3210128546 L 379.0460070819 376.1500123739 L 379.0960070863 369.1170123816 L 379.2340070829 362.0400122404 L 379.8800071105 355.1050122976 L 381.4540071115 348.4980124235 L 390.6280068979 330.1660116911 L 403.7080068216 317.3020113707 L 420.6560067758 309.7660115957 L 441.4320058450 307.4180115461 L 446.8490056619 306.9590115249 L 450.9630055055 305.1900114715 L 453.6480054483 301.6790115535 L 454.7760054693 295.9940116107 L 455.1670054719 281.3890120685 L 453.9760054871 267.2600123584 L 449.6320056245 253.9220120609 L 440.5670060441 241.6900117099 L 435.9570059106 236.7260114849 L 431.7070059106 231.3900115192 L 427.6110057160 225.8940117061 L 423.4630059525 220.4530117214 L 414.6900061890 213.2170116603 L 403.6780061051 209.5760116279 L 391.8810061738 209.5410116278 L 380.7530059144 213.1230116449 L 366.8340062425 220.1270118318 L 352.7360066697 226.7900119387 L 338.5380067155 233.2560120188 L 324.3190068528 239.6680121981 L 315.2010068223 243.5410123430 L 306.2440070435 247.5590124689 L 297.7880067155 252.6640124880 L 290.1730069444 259.7990127169 L 270.0200070664 287.7730136476 L 255.3810071275 317.6260142885 L 246.8520068452 349.6890140139 L 245.0310058594 384.2950134277')
}, blobsOptions));
// create semi-static blobs
var staticBlobsOptios = {
frictionAir: 1,
friction: 1,
restitution: 1,
render: {
strokeStyle: '#000000',
fillStyle: 'red'
}
};
var boxA = Bodies.rectangle(Nav.random(0, _engine.render.options.width), Nav.random(0, _engine.render.options.height), 80, 80, staticBlobsOptios);
var boxB = Bodies.rectangle(Nav.random(0, _engine.render.options.width), Nav.random(0, _engine.render.options.height), 80, 80, staticBlobsOptios);
// add all of the bodies to the world
Composite.add(Nav.blobs, [aboutBlob, blogBlob, collabsBlob, installationsBlob, pressBlob, shopBlob]);
Composite.add(Nav.blobs, [boxA, boxB]);
};
Nav.updateScene = function() {
if (!_engine)
return;
debugger;
_sceneWidth = document.documentElement.clientWidth;
_sceneHeight = document.documentElement.clientHeight;
var boundsMax = _engine.world.bounds.max,
renderOptions = _engine.render.options,
canvas = _engine.render.canvas;
boundsMax.x = _sceneWidth;
boundsMax.y = _sceneHeight;
canvas.width = renderOptions.width = _sceneWidth;
canvas.height = renderOptions.height = _sceneHeight;
Nav.updateWalls();
};
Nav.updateWalls = function() {
if (!_engine)
return;
if(this.walls.bodies.length != 0)
Composite.clear(Nav.walls);
wallOptions = {
isStatic: true,
restitution: 1,
render: {
visible: true,
strokeStyle: 'red'
}
};
Composite.add( Nav.walls, [
Bodies.rectangle(window.innerWidth/2, 1, window.innerWidth, 2, wallOptions),
Bodies.rectangle(window.innerWidth/2, window.innerHeight - 1, window.innerWidth, 2, wallOptions),
Bodies.rectangle(0, window.innerHeight/2, 2, window.innerHeight, wallOptions),
Bodies.rectangle(window.innerWidth-1, window.innerHeight/2, 2, window.innerHeight, wallOptions)
]);
};
Nav.loop = function() {
setTimeout(function () {
Nav.loop();
}, Nav.options.loopTimer);
};
Nav.random = function(min, max) {
return Math.random() * (max - min) + min;
}
window.addEventListener('load', Nav.init);
window.addEventListener('resize', Nav.updateScene);
//})();
|
fix - static blobs composite
|
js/nav.js
|
fix - static blobs composite
|
<ide><path>s/nav.js
<ide>
<ide> // Matter module aliases
<ide> var Engine = Matter.Engine,
<add> Events = Matter.Events,
<ide> World = Matter.World,
<ide> Body = Matter.Body,
<ide> Bodies = Matter.Bodies,
<ide> // create semi-static blobs
<ide> var staticBlobsOptios = {
<ide> frictionAir: 1,
<del> friction: 1,
<add> friction: 0,
<ide> restitution: 1,
<ide> render: {
<ide> strokeStyle: '#000000',
<ide>
<ide> // add all of the bodies to the world
<ide> Composite.add(Nav.blobs, [aboutBlob, blogBlob, collabsBlob, installationsBlob, pressBlob, shopBlob]);
<del> Composite.add(Nav.blobs, [boxA, boxB]);
<add> Composite.add(Nav.staticBlobs, [boxA, boxB]);
<ide>
<ide> };
<ide>
<ide> if (!_engine)
<ide> return;
<ide>
<del> debugger;
<ide> _sceneWidth = document.documentElement.clientWidth;
<ide> _sceneHeight = document.documentElement.clientHeight;
<ide>
|
|
JavaScript
|
mit
|
2c14d2bf6e1888e97000d22d7c6af7f21dc64766
| 0 |
ahmedkotb/sfg.js
|
DEFAULT_RADIUS = 12
DEFAULT_COLOR = "#228b22"
DEFAULT_EDGE_COLOR = "#000000"
DEFAULT_SELECTED_COLOR = "#0000FF"
STATES = {NORMAL : 0, ADD_NODE: 1, NODE_MOVE: 2,
EDGE_WAIT_NODE1: 3,EDGE_WAIT_NODE2: 4,
PAN: 5
};
//helper functions
function debug(str){
document.getElementById("debug").innerHTML += str + "<br/>";
}
function debugClear(){
document.getElementById("debug").innerHTML = "";
}
function toRadians(angle){
return angle * Math.PI / 360;
}
function setPixelColor(data,x,y,color){
var index = (x + y * 400) * 4;
data[index+0] = color.r;
data[index+1] = color.g;
data[index+2] = color.b;
data[index+3] = 0xff;
}
function solveCubic(c) {
//Code ported from c version available here
//http://tog.acm.org/resources/GraphicsGems/gems/Roots3And4.c
M_PI = 3.14159265358979323846;
function isZero(x){
var EQN_EPS = 1e-9;
return Math.abs(x) < EQN_EPS;
}
function cbrt(x){
return (x > 0.0 ? Math.pow(x, 1/3) : (x < 0.0 ? - Math.pow(-x, 1/3) : 0.0));
}
var s = null;
var i, num;
var sub;
var A, B, C;
var sq_A, p, q;
var cb_p, D;
/* normal form: x^3 + Ax^2 + Bx + C = 0 */
A = c[ 2 ] / c[ 3 ];
B = c[ 1 ] / c[ 3 ];
C = c[ 0 ] / c[ 3 ];
/* substitute x = y - A/3 to eliminate quadric term:
x^3 +px + q = 0 */
sq_A = A * A;
p = 1.0/3 * (- 1.0/3 * sq_A + B);
q = 1.0/2 * (2.0/27 * A * sq_A - 1.0/3 * A * B + C);
/* use Cardano's formula */
cb_p = p * p * p;
D = q * q + cb_p;
if (isZero(D)) {
if (isZero(q)) {
/* one triple solution */
s = [0.0];
s[ 0 ] = 0;
num = 1;
} else {
/* one single and one double solution */
s = [0.0,0.0];
var u = cbrt(-q);
s[ 0 ] = 2 * u;
s[ 1 ] = - u;
num = 2;
}
}
else if (D < 0){
/* Casus irreducibilis: three real solutions */
var phi = 1.0/3 * Math.acos(-q / Math.sqrt(-cb_p));
var t = 2 * Math.sqrt(-p);
s = [0.0,0.0,0.0];
s[ 0 ] = t * Math.cos(phi);
s[ 1 ] = - t * Math.cos(phi + M_PI / 3);
s[ 2 ] = - t * Math.cos(phi - M_PI / 3);
num = 3;
}
else{
/* one real solution */
var sqrt_D = Math.sqrt(D);
var u = cbrt(sqrt_D - q);
var v = - cbrt(sqrt_D + q);
s = [0.0];
s[ 0 ] = u + v;
num = 1;
}
/* resubstitute */
sub = 1.0/3 * A;
for (i = 0; i < num; ++i)
s[ i ] -= sub;
return s;
}
//--------------------------------------------
function SFG(canvas){
if (canvas.getContext){
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.canvas.sfg = this;
this.canvas.ctx = this.ctx;
this.scale = 1.5;
this.transX = -30;
this.transY = -30;
this.graph = {};
this.nodeCounter = 0;
this.nodes = [];
this.edges = [];
this.state = STATES.NORMAL;
this.selectedNode = null;
this.selected = null;
this.newNode = null;
this.newEdge = null;
this.controlNode = null;
canvas.addEventListener('mousedown',this.mousedown,false);
canvas.addEventListener('mouseup',this.mouseup,false);
canvas.addEventListener('mousemove',this.mousemove,false);
//Demo example for testing
this.addNode(100,150);
this.addNode(250,150);
this.addNode(100,250);
e = new ArcEdge(this.nodes[0],this.nodes[1]);
this.addEdge(e);
this.redraw();
}else{
alert("canvas not supported!");
}
}
SFG.prototype.mousedown = function(e){
e = e || window.e;
e.preventDefault();
e.stopPropagation();
var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;
var state = this.sfg.state;
var sfg = this.sfg;
//scale and translate factors
x -= sfg.transX; y -= sfg.transY;
x /= sfg.scale; y /= sfg.scale;
if (state == STATES.ADD_NODE){
sfg.newNode = null;
sfg.state = STATES.NORMAL;
sfg.addNode(x,y);
}else if (state == STATES.NORMAL){
var selected = sfg.find(x,y);
if (selected instanceof Node){
sfg.state = STATES.NODE_MOVE;
sfg.controlNode = null;
}else if (selected instanceof LineEdge){
sfg.controlNode = null;
}else if (selected instanceof ControlNode){
sfg.state = STATES.NODE_MOVE;
}else if (selected instanceof ArcEdge){
sfg.controlNode = new ControlNode(selected);
}else{
sfg.controlNode = null;
}
if (selected == null){
this.startX = x;
this.startY = y;
sfg.state = STATES.PAN;
this.style.cursor = "move";
}
sfg.selectItem(selected);
}else if (state == STATES.EDGE_WAIT_NODE1){
//sfg.newEdge must be initialized to empty edge
//either by startAddingLineEdge or arc edge methods
var selected = sfg.findNode(x,y);
sfg.selectItem(selected);
if (selected){
sfg.state = STATES.EDGE_WAIT_NODE2;
sfg.newEdge.setStartNode(selected);
}
}else if (state == STATES.EDGE_WAIT_NODE2){
var selected = sfg.findNode(x,y);
sfg.state = STATES.NORMAL;
if (selected == null){
sfg.newEdge = null;
return;
}
var edge = sfg.newEdge;
edge.setEndNode(selected);
sfg.addEdge(edge);
sfg.selectItem(null);
}
}
SFG.prototype.mouseup = function(e){
e = e || window.e;
e.preventDefault();
e.stopPropagation();
var state = this.sfg.state;
if (state == STATES.NODE_MOVE || state == STATES.PAN){
this.sfg.state = STATES.NORMAL;
this.style.cursor = "auto";
}
}
SFG.prototype.mousemove = function(e){
e = e || window.e;
var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;
var state = this.sfg.state;
var sfg = this.sfg;
var node = null;
//scale and translate factors
x -= sfg.transX; y -= sfg.transY;
x /= sfg.scale; y /= sfg.scale;
if (sfg.selected instanceof Node || sfg.selected instanceof ControlNode)
node = sfg.selected;
if (state == STATES.NODE_MOVE && node != null){
node.setX(x);
node.setY(y);
sfg.redraw();
}else if (state == STATES.ADD_NODE){
sfg.newNode.setX(x);
sfg.newNode.setY(y);
sfg.redraw();
sfg.newNode.draw(sfg.ctx);
}else if (state == STATES.EDGE_WAIT_NODE2){
sfg.redraw();
sfg.newEdge.drawToPoint(sfg.ctx,x,y);
}else if (state == STATES.PAN){
var dx = x - this.startX;
var dy = y - this.startY;
sfg.transX += dx;
sfg.transY += dy;
sfg.redraw();
}
}
SFG.prototype.startAddingNode = function(){
this.newNode = new Node(-1);
this.newNode.name = "new";
this.state = STATES.ADD_NODE;
if (this.selected != null){
this.selected.setUnselected();
this.selected = null;
}
}
SFG.prototype.startAddingLineEdge = function(){
if (this.selected instanceof Node){
this.newEdge = new LineEdge(this.selected,null);
this.state = STATES.EDGE_WAIT_NODE2;
}else{
this.newEdge = new LineEdge(null,null);
this.state = STATES.EDGE_WAIT_NODE1;
}
}
SFG.prototype.startAddingArcEdge = function(){
if (this.selected instanceof Node){
this.newEdge = new ArcEdge(this.selected,null);
this.state = STATES.EDGE_WAIT_NODE2;
}else{
this.newEdge = new ArcEdge(null,null);
this.state = STATES.EDGE_WAIT_NODE1;
}
}
SFG.prototype.selectItem = function(item){
var oldItem = this.selected;
var needRedraw = false;
if (oldItem != null){
oldItem.setUnselected();
needRedraw = true;
}
if (item != null){
item.setSelected();
needRedraw = true;
}
this.selected = item;
if (needRedraw)
this.redraw();
}
SFG.prototype.findNode = function(x,y){
var nodes = this.nodes;
var selected = null;
for (var i=0;i<nodes.length;i++){
var node = nodes[i];
if (node.pointInside(x,y)){
selected = node;
break;
}
}
return selected;
}
SFG.prototype.findEdge = function(x,y){
var edges = this.edges;
var selected = null;
for (var i=0;i<edges.length;i++){
var edge = this.edges[i];
if (edge.nearPoint(x,y)){
selected = edge;
break;
}
}
return selected;
}
SFG.prototype.find = function(x,y){
// first check for control point selection
if (this.controlNode != null && this.controlNode.pointInside(x,y))
return this.controlNode;
// second check for any node selection
var node = this.findNode(x,y);
if (node != null)
return node;
// third check for any edge selection
return this.findEdge(x,y);
}
SFG.prototype.addNode = function(x,y){
var node = new Node(this.nodeCounter);
this.nodeCounter++;
this.graph[node.id] = {};
node.setX(x);
node.setY(y);
this.nodes.push(node);
this.redraw();
}
SFG.prototype.addEdge = function(edge){
if (this.graph[edge.startNode.id][edge.endNode.id] == undefined){
//TODO:check for self edges
this.edges.push(edge);
this.graph[edge.startNode.id][edge.endNode.id] = edge;
}
//debug("no of edges = " + this.edges.length);
}
SFG.prototype.deleteSelected = function(){
if (this.selected instanceof Node){
var id = this.selected.id;
var nodes = this.nodes;
var index = -1;
for (var i=0;i<nodes.length;i++){
if (nodes[i].id == id)
index = i;
var e = this.graph[nodes[i].id][id];
if (e != undefined)
this.deleteEdge(e);
e = this.graph[id][nodes[i].id];
if (e != undefined)
this.deleteEdge(e);
}
this.nodes.splice(index,1);
}else if (this.selected instanceof LineEdge
|| this.selected instanceof ArcEdge){
this.controlNode = null;
this.deleteEdge(this.selected);
}else if (this.selected instanceof ControlNode){
this.deleteEdge(this.controlNode.arcEdge);
this.controlNode = null;
}
this.selectItem(null);
}
SFG.prototype.deleteEdge = function(edge){
var from = edge.startNode;
var to = edge.endNode;
var index = -1;
for (var i=0;i<this.edges.length;i++){
var e = this.edges[i];
if (e.startNode.id == from.id && e.endNode.id == to.id){
index = i;
break;
}
}
if (index != -1)
this.edges.splice(index,1);
delete this.graph[from.id][to.id];
}
SFG.prototype.redraw = function(){
this.ctx.setTransform(this.scale,0,0,this.scale,this.transX,this.transY);
this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
var nodes = this.nodes;
var edges = this.edges;
//draw control node if exists
if (this.controlNode)
this.controlNode.draw(this.ctx);
//draw edges
for (var i=0;i<edges.length;i++)
edges[i].draw(this.ctx);
//draw nodes
for (var i=0;i<nodes.length;i++)
nodes[i].draw(this.ctx);
}
//--------------------------------------------
function Node(id){
this.id = id;
this.name = "node " + this.id;
this.x = 0;
this.y = 0;
this.radius = DEFAULT_RADIUS;
this.color = DEFAULT_COLOR;
}
Node.prototype.setX = function(x){
this.x = x;
}
Node.prototype.setY = function(y){
this.y = y;
}
Node.prototype.draw = function(ctx){
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0,2*Math.PI,false);
ctx.fillStyle = this.color;
ctx.strokeStyle = this.color;
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#000000";
var width = ctx.measureText(this.name).width;
ctx.fillText(this.name,this.x-width/2.0,this.y+this.radius+10);
}
Node.prototype.setSelected = function(){
this.color = DEFAULT_SELECTED_COLOR;
}
Node.prototype.setUnselected = function(){
this.color = DEFAULT_COLOR;
}
Node.prototype.pointInside = function(x,y){
return Math.abs(this.x-x) < this.radius && Math.abs(this.y-y) < this.radius;
}
//--------------------------------------------
function ControlNode(arcEdge){
this.arcEdge = arcEdge;
this.x = arcEdge.controlPoint.x;
this.y = arcEdge.controlPoint.y;
this.name = "";
this.radius = DEFAULT_RADIUS/1.5;
this.color = "#FF0000";
}
ControlNode.prototype.setX = function(x){
this.arcEdge.controlPoint.x = x;
this.x = x;
}
ControlNode.prototype.setY = function(y){
this.arcEdge.controlPoint.y = y;
this.y = y;
}
//same draw method as Node object
ControlNode.prototype.draw = Node.prototype.draw;
ControlNode.prototype.setSelected = function(){
this.color = DEFAULT_SELECTED_COLOR;
this.arcEdge.setSelected();
}
ControlNode.prototype.setUnselected = function(){
this.color = "#FF0000";
this.arcEdge.setUnselected();
}
//same pointInside method as Node Object
ControlNode.prototype.pointInside = Node.prototype.pointInside;
//---------------------------
function LineEdge(startNode,endNode){
this.startNode = startNode;
this.endNode = endNode;
this.color = "#000000";
this.arrowColor = "#800000";
this.label = "a";
}
LineEdge.prototype.setStartNode = function(startNode){
this.startNode = startNode;
}
LineEdge.prototype.setEndNode = function(endNode){
this.endNode = endNode;
}
LineEdge.prototype.draw = function(ctx){
//drawing the edge
ctx.beginPath();
ctx.moveTo(this.startNode.x,this.startNode.y);
ctx.lineTo(this.endNode.x,this.endNode.y);
ctx.strokeStyle = this.color;
ctx.stroke();
//drawing the arrow
var r = 10;
var arrowAng = 45;
var midX = (this.startNode.x+this.endNode.x)/2.0;
var midY = (this.startNode.y+this.endNode.y)/2.0;
var x1,x2,y1,y2;
if (this.startNode.x == this.endNode.x){
x1 = midX - r * Math.sin(toRadians(arrowAng));
x2 = midX + r * Math.sin(toRadians(arrowAng));
var sign = 0;
if (this.startNode.y - this.endNode.y < 0) sign = -1;
else sign = 1;
y1 = midY + sign * r * Math.cos(toRadians(arrowAng));
y2 = y1;
}else{
var ang = Math.atan2(this.startNode.y-this.endNode.y
,this.startNode.x-this.endNode.x);
var ang1 = ang + Math.tan(toRadians(arrowAng));
var ang2 = ang - Math.tan(toRadians(arrowAng));
x1 = midX + r * Math.cos(ang1);
x2 = midX + r * Math.cos(ang2);
y1 = midY + r * Math.sin(ang1);
y2 = midY + r * Math.sin(ang2);
}
ctx.beginPath();
ctx.strokeStyle = this.arrowColor;
ctx.moveTo(x1,y1);
ctx.lineTo(midX,midY);
ctx.moveTo(x2,y2);
ctx.lineTo(midX,midY);
ctx.stroke();
//drawing the label
var width = ctx.measureText(this.label).width;
ctx.fillText(this.label,midX-width/2.0,midY+10);
}
LineEdge.prototype.nearPoint = function(x,y){
var threshold = 8;
var x1 = this.startNode.x;
var y1 = this.startNode.y;
var x2 = this.endNode.x;
var y2 = this.endNode.y;
var mag = ((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
var u = ((x-x1)*(x2-x1) + (y-y1)*(y2-y1))/mag;
var xp = x1 + u*(x2-x1);
var yp = y1 + u*(y2-y1);
var dist = Math.sqrt((xp-x)*(xp-x) + (yp-y)*(yp-y));
return dist < threshold;
}
LineEdge.prototype.drawToPoint = function(ctx,x,y){
ctx.beginPath();
ctx.moveTo(this.startNode.x,this.startNode.y);
ctx.lineTo(x,y);
ctx.stroke();
}
LineEdge.prototype.setSelected = function(){
this.color = "#0000FF";
}
LineEdge.prototype.setUnselected = function(){
this.color = DEFAULT_EDGE_COLOR;
}
//---------------------------
function ArcEdge(startNode,endNode){
this.startNode = startNode;
this.endNode = endNode;
this.controlPoint = {x:0,y:0};
this.drawControlLines = false;
if (this.startNode != null && this.endNode != null){
this.controlPoint.x = (this.startNode.x + this.endNode.x)/2;
this.controlPoint.y = (this.startNode.y + this.endNode.y)/2;
}
this.color = "#000000";
this.arrowColor = "#800000";
this.label = "a";
}
ArcEdge.prototype.setStartNode = function(startNode){
this.startNode = startNode;
//re-estimate control point location
if (this.startNode != null && this.endNode != null){
this.controlPoint.x = (this.startNode.x + this.endNode.x)/2;
this.controlPoint.y = (this.startNode.y + this.endNode.y)/2;
}
}
ArcEdge.prototype.setEndNode = function(endNode){
this.endNode = endNode;
//re-estimate control point location
if (this.startNode != null && this.endNode != null){
this.controlPoint.x = (this.startNode.x + this.endNode.x)/2;
this.controlPoint.y = (this.startNode.y + this.endNode.y)/2;
}
}
ArcEdge.prototype.draw = function(ctx){
//drawing the edge
ctx.beginPath();
ctx.moveTo(this.startNode.x,this.startNode.y);
ctx.quadraticCurveTo(this.controlPoint.x,this.controlPoint.y,
this.endNode.x,this.endNode.y);
ctx.strokeStyle = this.color;
ctx.stroke();
//draw control lines
if (this.drawControlLines){
ctx.beginPath();
ctx.moveTo(this.startNode.x,this.startNode.y);
ctx.lineTo(this.controlPoint.x,this.controlPoint.y);
ctx.lineTo(this.endNode.x,this.endNode.y);
ctx.strokeStyle = "#C0C0C0";
ctx.stroke();
}
//drawing the arrow
//first get the midpoint on the curve (t=0.5)
var t = 0.5;
var x = 0,y = 0;
var p0x = this.startNode.x, p0y = this.startNode.y;
var p1x = this.controlPoint.x, p1y = this.controlPoint.y;
var p2x = this.endNode.x, p2y = this.endNode.y;
x = (1-t)*(1-t)*p0x + 2*(1-t)*t*p1x + t*t*p2x;
y = (1-t)*(1-t)*p0y + 2*(1-t)*t*p1y + t*t*p2y;
//second draw the arrow
var r = 10;
var arrowAng = 45;
var midX = x;
var midY = y;
var x1,x2,y1,y2;
if (this.startNode.x == this.endNode.x){
x1 = midX - r * Math.sin(toRadians(arrowAng));
x2 = midX + r * Math.sin(toRadians(arrowAng));
var sign = 0;
if (this.startNode.y - this.endNode.y < 0) sign = -1;
else sign = 1;
y1 = midY + sign * r * Math.cos(toRadians(arrowAng));
y2 = y1;
}else{
var ang = Math.atan2(this.startNode.y-this.endNode.y
,this.startNode.x-this.endNode.x);
var ang1 = ang + Math.tan(toRadians(arrowAng));
var ang2 = ang - Math.tan(toRadians(arrowAng));
x1 = midX + r * Math.cos(ang1);
x2 = midX + r * Math.cos(ang2);
y1 = midY + r * Math.sin(ang1);
y2 = midY + r * Math.sin(ang2);
}
ctx.beginPath();
ctx.strokeStyle = this.arrowColor;
ctx.moveTo(x1,y1);
ctx.lineTo(midX,midY);
ctx.moveTo(x2,y2);
ctx.lineTo(midX,midY);
ctx.stroke();
//drawing the label
var width = ctx.measureText(this.label).width;
ctx.fillText(this.label,x-width/2.0,y+10);
}
ArcEdge.prototype.nearPoint = function(x,y){
var threshold = 8;
if ((this.startNode.x == this.endNode.x
&& this.startNode.x == this.controlPoint.x) ||
this.startNode.y == this.endNode.y
&& this.startNode.y == this.controlPoint.y){
//vertical or horizontal case
var x1 = this.startNode.x;
var y1 = this.startNode.y;
var x2 = this.endNode.x;
var y2 = this.endNode.y;
var mag = ((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
var u = ((x-x1)*(x2-x1) + (y-y1)*(y2-y1))/mag;
var xp = x1 + u*(x2-x1);
var yp = y1 + u*(y2-y1);
var dist = Math.sqrt((xp-x)*(xp-x) + (yp-y)*(yp-y));
return dist < threshold;
}
//solving cubic equation to get closest point
var A = {x:this.controlPoint.x - this.startNode.x,
y:this.controlPoint.y - this.startNode.y}
var B = {x:this.endNode.x - this.controlPoint.x - A.x,
y:this.endNode.y - this.controlPoint.y - A.y}
var M = {x:x,
y:y}
var Mp = {x:this.startNode.x - M.x,
y:this.startNode.y - M.y}
var a = B.x*B.x + B.y*B.y;
var b = 3 *(A.x*B.x + A.y*B.y);
var c = 2 *(A.x*A.x + A.y*A.y) + (Mp.x*B.x + Mp.y*B.y);
var d = Mp.x*A.x + Mp.y*A.y;
result = solveCubic([d,c,b,a]);
/*
debugClear();
debug(a + " " + b + " " + c + " " + d);
debug(result);
*/
//to always check for endpoints (for corner cases)
result.push(2);
result.push(-2);
var minDist = Infinity;
var px = 0,py = 0;
for (var i=0;i<result.length;i++){
var t = result[i];
if (t > 0 && t < 1){
var p0x = this.startNode.x, p0y = this.startNode.y;
var p1x = this.controlPoint.x, p1y = this.controlPoint.y;
var p2x = this.endNode.x, p2y = this.endNode.y;
px = (1-t)*(1-t)*p0x + 2*(1-t)*t*p1x + t*t*p2x;
py = (1-t)*(1-t)*p0y + 2*(1-t)*t*p1y + t*t*p2y;
var dist = Math.sqrt((x-px)*(x-px) + (y-py)*(y-py));
minDist = dist < minDist ? dist : minDist;
}else if (t > 1){
px = this.endNode.x;
py = this.endNode.y;
var dist = Math.sqrt((x-px)*(x-px) + (y-py)*(y-py));
minDist = dist < minDist ? dist : minDist;
}else{
px = this.startNode.x;
py = this.startNode.y;
var dist = Math.sqrt((x-px)*(x-px) + (y-py)*(y-py));
minDist = dist < minDist ? dist : minDist;
}
}
return minDist < threshold;
}
ArcEdge.prototype.drawToPoint = function(ctx,x,y){
ctx.beginPath();
ctx.moveTo(this.startNode.x,this.startNode.y);
ctx.lineTo(x,y);
ctx.stroke();
}
ArcEdge.prototype.setSelected = function(){
this.color = "#0000FF";
this.drawControlLines = true;
}
ArcEdge.prototype.setUnselected = function(){
this.color = DEFAULT_EDGE_COLOR;
this.drawControlLines = false;
}
|
sfg.js
|
DEFAULT_RADIUS = 12
DEFAULT_COLOR = "#228b22"
DEFAULT_EDGE_COLOR = "#000000"
DEFAULT_SELECTED_COLOR = "#0000FF"
STATES = {NORMAL : 0, ADD_NODE: 1, NODE_MOVE: 2,
EDGE_WAIT_NODE1: 3,EDGE_WAIT_NODE2: 4
};
//helper functions
function debug(str){
document.getElementById("debug").innerHTML += str + "<br/>";
}
function debugClear(){
document.getElementById("debug").innerHTML = "";
}
function toRadians(angle){
return angle * Math.PI / 360;
}
function setPixelColor(data,x,y,color){
var index = (x + y * 400) * 4;
data[index+0] = color.r;
data[index+1] = color.g;
data[index+2] = color.b;
data[index+3] = 0xff;
}
function solveCubic(c) {
//Code ported from c version available here
//http://tog.acm.org/resources/GraphicsGems/gems/Roots3And4.c
M_PI = 3.14159265358979323846;
function isZero(x){
var EQN_EPS = 1e-9;
return Math.abs(x) < EQN_EPS;
}
function cbrt(x){
return (x > 0.0 ? Math.pow(x, 1/3) : (x < 0.0 ? - Math.pow(-x, 1/3) : 0.0));
}
var s = null;
var i, num;
var sub;
var A, B, C;
var sq_A, p, q;
var cb_p, D;
/* normal form: x^3 + Ax^2 + Bx + C = 0 */
A = c[ 2 ] / c[ 3 ];
B = c[ 1 ] / c[ 3 ];
C = c[ 0 ] / c[ 3 ];
/* substitute x = y - A/3 to eliminate quadric term:
x^3 +px + q = 0 */
sq_A = A * A;
p = 1.0/3 * (- 1.0/3 * sq_A + B);
q = 1.0/2 * (2.0/27 * A * sq_A - 1.0/3 * A * B + C);
/* use Cardano's formula */
cb_p = p * p * p;
D = q * q + cb_p;
if (isZero(D)) {
if (isZero(q)) {
/* one triple solution */
s = [0.0];
s[ 0 ] = 0;
num = 1;
} else {
/* one single and one double solution */
s = [0.0,0.0];
var u = cbrt(-q);
s[ 0 ] = 2 * u;
s[ 1 ] = - u;
num = 2;
}
}
else if (D < 0){
/* Casus irreducibilis: three real solutions */
var phi = 1.0/3 * Math.acos(-q / Math.sqrt(-cb_p));
var t = 2 * Math.sqrt(-p);
s = [0.0,0.0,0.0];
s[ 0 ] = t * Math.cos(phi);
s[ 1 ] = - t * Math.cos(phi + M_PI / 3);
s[ 2 ] = - t * Math.cos(phi - M_PI / 3);
num = 3;
}
else{
/* one real solution */
var sqrt_D = Math.sqrt(D);
var u = cbrt(sqrt_D - q);
var v = - cbrt(sqrt_D + q);
s = [0.0];
s[ 0 ] = u + v;
num = 1;
}
/* resubstitute */
sub = 1.0/3 * A;
for (i = 0; i < num; ++i)
s[ i ] -= sub;
return s;
}
//--------------------------------------------
function SFG(canvas){
if (canvas.getContext){
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.canvas.sfg = this;
this.canvas.ctx = this.ctx;
this.scale = 1.5;
this.transX = -30;
this.transY = -30;
this.graph = {};
this.nodeCounter = 0;
this.nodes = [];
this.edges = [];
this.state = STATES.NORMAL;
this.selectedNode = null;
this.selected = null;
this.newNode = null;
this.newEdge = null;
this.controlNode = null;
canvas.addEventListener('mousedown',this.mousedown,false);
canvas.addEventListener('mouseup',this.mouseup,false);
canvas.addEventListener('mousemove',this.mousemove,false);
//Demo example for testing
this.addNode(100,150);
this.addNode(250,150);
this.addNode(100,250);
e = new ArcEdge(this.nodes[0],this.nodes[1]);
this.addEdge(e);
this.ctx.setTransform(this.scale,0,0,this.scale,this.transX,this.transY);
this.redraw();
}else{
alert("canvas not supported!");
}
}
SFG.prototype.mousedown = function(e){
e = e || window.e;
var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;
var state = this.sfg.state;
var sfg = this.sfg;
//scale and translate factors
x -= sfg.transX; y -= sfg.transY;
x /= sfg.scale; y /= sfg.scale;
if (state == STATES.ADD_NODE){
sfg.newNode = null;
sfg.state = STATES.NORMAL;
sfg.addNode(x,y);
}else if (state == STATES.NORMAL){
var selected = sfg.find(x,y);
if (selected instanceof Node){
sfg.state = STATES.NODE_MOVE;
sfg.controlNode = null;
}else if (selected instanceof LineEdge){
sfg.controlNode = null;
}else if (selected instanceof ControlNode){
sfg.state = STATES.NODE_MOVE;
}else if (selected instanceof ArcEdge){
sfg.controlNode = new ControlNode(selected);
}else{
sfg.controlNode = null;
}
sfg.selectItem(selected);
}else if (state == STATES.EDGE_WAIT_NODE1){
//sfg.newEdge must be initialized to empty edge
//either by startAddingLineEdge or arc edge methods
var selected = sfg.findNode(x,y);
sfg.selectItem(selected);
if (selected){
sfg.state = STATES.EDGE_WAIT_NODE2;
sfg.newEdge.setStartNode(selected);
}
}else if (state == STATES.EDGE_WAIT_NODE2){
var selected = sfg.findNode(x,y);
sfg.state = STATES.NORMAL;
if (selected == null){
sfg.newEdge = null;
return;
}
var edge = sfg.newEdge;
edge.setEndNode(selected);
sfg.addEdge(edge);
sfg.selectItem(null);
}
}
SFG.prototype.mouseup = function(e){
e = e || window.e;
var state = this.sfg.state;
if (state == STATES.NODE_MOVE)
this.sfg.state = STATES.NORMAL;
}
SFG.prototype.mousemove = function(e){
e = e || window.e;
var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;
var state = this.sfg.state;
var sfg = this.sfg;
var node = null;
//scale and translate factors
x -= sfg.transX; y -= sfg.transY;
x /= sfg.scale; y /= sfg.scale;
if (sfg.selected instanceof Node || sfg.selected instanceof ControlNode)
node = sfg.selected;
if (state == STATES.NODE_MOVE && node != null){
node.setX(x);
node.setY(y);
sfg.redraw();
}else if (state == STATES.ADD_NODE){
sfg.newNode.setX(x);
sfg.newNode.setY(y);
sfg.redraw();
sfg.newNode.draw(sfg.ctx);
}else if (state == STATES.EDGE_WAIT_NODE2){
sfg.redraw();
sfg.newEdge.drawToPoint(sfg.ctx,x,y);
}
}
SFG.prototype.startAddingNode = function(){
this.newNode = new Node(-1);
this.newNode.name = "new";
this.state = STATES.ADD_NODE;
if (this.selected != null){
this.selected.setUnselected();
this.selected = null;
}
}
SFG.prototype.startAddingLineEdge = function(){
if (this.selected instanceof Node){
this.newEdge = new LineEdge(this.selected,null);
this.state = STATES.EDGE_WAIT_NODE2;
}else{
this.newEdge = new LineEdge(null,null);
this.state = STATES.EDGE_WAIT_NODE1;
}
}
SFG.prototype.startAddingArcEdge = function(){
if (this.selected instanceof Node){
this.newEdge = new ArcEdge(this.selected,null);
this.state = STATES.EDGE_WAIT_NODE2;
}else{
this.newEdge = new ArcEdge(null,null);
this.state = STATES.EDGE_WAIT_NODE1;
}
}
SFG.prototype.selectItem = function(item){
var oldItem = this.selected;
var needRedraw = false;
if (oldItem != null){
oldItem.setUnselected();
needRedraw = true;
}
if (item != null){
item.setSelected();
needRedraw = true;
}
this.selected = item;
if (needRedraw)
this.redraw();
}
SFG.prototype.findNode = function(x,y){
var nodes = this.nodes;
var selected = null;
for (var i=0;i<nodes.length;i++){
var node = nodes[i];
if (node.pointInside(x,y)){
selected = node;
break;
}
}
return selected;
}
SFG.prototype.findEdge = function(x,y){
var edges = this.edges;
var selected = null;
for (var i=0;i<edges.length;i++){
var edge = this.edges[i];
if (edge.nearPoint(x,y)){
selected = edge;
break;
}
}
return selected;
}
SFG.prototype.find = function(x,y){
// first check for control point selection
if (this.controlNode != null && this.controlNode.pointInside(x,y))
return this.controlNode;
// second check for any node selection
var node = this.findNode(x,y);
if (node != null)
return node;
// third check for any edge selection
return this.findEdge(x,y);
}
SFG.prototype.addNode = function(x,y){
var node = new Node(this.nodeCounter);
this.nodeCounter++;
this.graph[node.id] = {};
node.setX(x);
node.setY(y);
this.nodes.push(node);
this.redraw();
}
SFG.prototype.addEdge = function(edge){
if (this.graph[edge.startNode.id][edge.endNode.id] == undefined){
//TODO:check for self edges
this.edges.push(edge);
this.graph[edge.startNode.id][edge.endNode.id] = edge;
}
//debug("no of edges = " + this.edges.length);
}
SFG.prototype.deleteSelected = function(){
if (this.selected instanceof Node){
var id = this.selected.id;
var nodes = this.nodes;
var index = -1;
for (var i=0;i<nodes.length;i++){
if (nodes[i].id == id)
index = i;
var e = this.graph[nodes[i].id][id];
if (e != undefined)
this.deleteEdge(e);
e = this.graph[id][nodes[i].id];
if (e != undefined)
this.deleteEdge(e);
}
this.nodes.splice(index,1);
}else if (this.selected instanceof LineEdge
|| this.selected instanceof ArcEdge){
this.controlNode = null;
this.deleteEdge(this.selected);
}else if (this.selected instanceof ControlNode){
this.deleteEdge(this.controlNode.arcEdge);
this.controlNode = null;
}
this.selectItem(null);
}
SFG.prototype.deleteEdge = function(edge){
var from = edge.startNode;
var to = edge.endNode;
var index = -1;
for (var i=0;i<this.edges.length;i++){
var e = this.edges[i];
if (e.startNode.id == from.id && e.endNode.id == to.id){
index = i;
break;
}
}
if (index != -1)
this.edges.splice(index,1);
delete this.graph[from.id][to.id];
}
SFG.prototype.redraw = function(){
this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
var nodes = this.nodes;
var edges = this.edges;
//draw control node if exists
if (this.controlNode)
this.controlNode.draw(this.ctx);
//draw edges
for (var i=0;i<edges.length;i++)
edges[i].draw(this.ctx);
//draw nodes
for (var i=0;i<nodes.length;i++)
nodes[i].draw(this.ctx);
}
//--------------------------------------------
function Node(id){
this.id = id;
this.name = "node " + this.id;
this.x = 0;
this.y = 0;
this.radius = DEFAULT_RADIUS;
this.color = DEFAULT_COLOR;
}
Node.prototype.setX = function(x){
this.x = x;
}
Node.prototype.setY = function(y){
this.y = y;
}
Node.prototype.draw = function(ctx){
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0,2*Math.PI,false);
ctx.fillStyle = this.color;
ctx.strokeStyle = this.color;
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#000000";
var width = ctx.measureText(this.name).width;
ctx.fillText(this.name,this.x-width/2.0,this.y+this.radius+10);
}
Node.prototype.setSelected = function(){
this.color = DEFAULT_SELECTED_COLOR;
}
Node.prototype.setUnselected = function(){
this.color = DEFAULT_COLOR;
}
Node.prototype.pointInside = function(x,y){
return Math.abs(this.x-x) < this.radius && Math.abs(this.y-y) < this.radius;
}
//--------------------------------------------
function ControlNode(arcEdge){
this.arcEdge = arcEdge;
this.x = arcEdge.controlPoint.x;
this.y = arcEdge.controlPoint.y;
this.name = "";
this.radius = DEFAULT_RADIUS/1.5;
this.color = "#FF0000";
}
ControlNode.prototype.setX = function(x){
this.arcEdge.controlPoint.x = x;
this.x = x;
}
ControlNode.prototype.setY = function(y){
this.arcEdge.controlPoint.y = y;
this.y = y;
}
//same draw method as Node object
ControlNode.prototype.draw = Node.prototype.draw;
ControlNode.prototype.setSelected = function(){
this.color = DEFAULT_SELECTED_COLOR;
this.arcEdge.setSelected();
}
ControlNode.prototype.setUnselected = function(){
this.color = "#FF0000";
this.arcEdge.setUnselected();
}
//same pointInside method as Node Object
ControlNode.prototype.pointInside = Node.prototype.pointInside;
//---------------------------
function LineEdge(startNode,endNode){
this.startNode = startNode;
this.endNode = endNode;
this.color = "#000000";
this.arrowColor = "#800000";
this.label = "a";
}
LineEdge.prototype.setStartNode = function(startNode){
this.startNode = startNode;
}
LineEdge.prototype.setEndNode = function(endNode){
this.endNode = endNode;
}
LineEdge.prototype.draw = function(ctx){
//drawing the edge
ctx.beginPath();
ctx.moveTo(this.startNode.x,this.startNode.y);
ctx.lineTo(this.endNode.x,this.endNode.y);
ctx.strokeStyle = this.color;
ctx.stroke();
//drawing the arrow
var r = 10;
var arrowAng = 45;
var midX = (this.startNode.x+this.endNode.x)/2.0;
var midY = (this.startNode.y+this.endNode.y)/2.0;
var x1,x2,y1,y2;
if (this.startNode.x == this.endNode.x){
x1 = midX - r * Math.sin(toRadians(arrowAng));
x2 = midX + r * Math.sin(toRadians(arrowAng));
var sign = 0;
if (this.startNode.y - this.endNode.y < 0) sign = -1;
else sign = 1;
y1 = midY + sign * r * Math.cos(toRadians(arrowAng));
y2 = y1;
}else{
var ang = Math.atan2(this.startNode.y-this.endNode.y
,this.startNode.x-this.endNode.x);
var ang1 = ang + Math.tan(toRadians(arrowAng));
var ang2 = ang - Math.tan(toRadians(arrowAng));
x1 = midX + r * Math.cos(ang1);
x2 = midX + r * Math.cos(ang2);
y1 = midY + r * Math.sin(ang1);
y2 = midY + r * Math.sin(ang2);
}
ctx.beginPath();
ctx.strokeStyle = this.arrowColor;
ctx.moveTo(x1,y1);
ctx.lineTo(midX,midY);
ctx.moveTo(x2,y2);
ctx.lineTo(midX,midY);
ctx.stroke();
//drawing the label
var width = ctx.measureText(this.label).width;
ctx.fillText(this.label,midX-width/2.0,midY+10);
}
LineEdge.prototype.nearPoint = function(x,y){
var threshold = 8;
var x1 = this.startNode.x;
var y1 = this.startNode.y;
var x2 = this.endNode.x;
var y2 = this.endNode.y;
var mag = ((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
var u = ((x-x1)*(x2-x1) + (y-y1)*(y2-y1))/mag;
var xp = x1 + u*(x2-x1);
var yp = y1 + u*(y2-y1);
var dist = Math.sqrt((xp-x)*(xp-x) + (yp-y)*(yp-y));
return dist < threshold;
}
LineEdge.prototype.drawToPoint = function(ctx,x,y){
ctx.beginPath();
ctx.moveTo(this.startNode.x,this.startNode.y);
ctx.lineTo(x,y);
ctx.stroke();
}
LineEdge.prototype.setSelected = function(){
this.color = "#0000FF";
}
LineEdge.prototype.setUnselected = function(){
this.color = DEFAULT_EDGE_COLOR;
}
//---------------------------
function ArcEdge(startNode,endNode){
this.startNode = startNode;
this.endNode = endNode;
this.controlPoint = {x:0,y:0};
this.drawControlLines = false;
if (this.startNode != null && this.endNode != null){
this.controlPoint.x = (this.startNode.x + this.endNode.x)/2;
this.controlPoint.y = (this.startNode.y + this.endNode.y)/2;
}
this.color = "#000000";
this.arrowColor = "#800000";
this.label = "a";
}
ArcEdge.prototype.setStartNode = function(startNode){
this.startNode = startNode;
//re-estimate control point location
if (this.startNode != null && this.endNode != null){
this.controlPoint.x = (this.startNode.x + this.endNode.x)/2;
this.controlPoint.y = (this.startNode.y + this.endNode.y)/2;
}
}
ArcEdge.prototype.setEndNode = function(endNode){
this.endNode = endNode;
//re-estimate control point location
if (this.startNode != null && this.endNode != null){
this.controlPoint.x = (this.startNode.x + this.endNode.x)/2;
this.controlPoint.y = (this.startNode.y + this.endNode.y)/2;
}
}
ArcEdge.prototype.draw = function(ctx){
//drawing the edge
ctx.beginPath();
ctx.moveTo(this.startNode.x,this.startNode.y);
ctx.quadraticCurveTo(this.controlPoint.x,this.controlPoint.y,
this.endNode.x,this.endNode.y);
ctx.strokeStyle = this.color;
ctx.stroke();
//draw control lines
if (this.drawControlLines){
ctx.beginPath();
ctx.moveTo(this.startNode.x,this.startNode.y);
ctx.lineTo(this.controlPoint.x,this.controlPoint.y);
ctx.lineTo(this.endNode.x,this.endNode.y);
ctx.strokeStyle = "#C0C0C0";
ctx.stroke();
}
//drawing the arrow
//first get the midpoint on the curve (t=0.5)
var t = 0.5;
var x = 0,y = 0;
var p0x = this.startNode.x, p0y = this.startNode.y;
var p1x = this.controlPoint.x, p1y = this.controlPoint.y;
var p2x = this.endNode.x, p2y = this.endNode.y;
x = (1-t)*(1-t)*p0x + 2*(1-t)*t*p1x + t*t*p2x;
y = (1-t)*(1-t)*p0y + 2*(1-t)*t*p1y + t*t*p2y;
//second draw the arrow
var r = 10;
var arrowAng = 45;
var midX = x;
var midY = y;
var x1,x2,y1,y2;
if (this.startNode.x == this.endNode.x){
x1 = midX - r * Math.sin(toRadians(arrowAng));
x2 = midX + r * Math.sin(toRadians(arrowAng));
var sign = 0;
if (this.startNode.y - this.endNode.y < 0) sign = -1;
else sign = 1;
y1 = midY + sign * r * Math.cos(toRadians(arrowAng));
y2 = y1;
}else{
var ang = Math.atan2(this.startNode.y-this.endNode.y
,this.startNode.x-this.endNode.x);
var ang1 = ang + Math.tan(toRadians(arrowAng));
var ang2 = ang - Math.tan(toRadians(arrowAng));
x1 = midX + r * Math.cos(ang1);
x2 = midX + r * Math.cos(ang2);
y1 = midY + r * Math.sin(ang1);
y2 = midY + r * Math.sin(ang2);
}
ctx.beginPath();
ctx.strokeStyle = this.arrowColor;
ctx.moveTo(x1,y1);
ctx.lineTo(midX,midY);
ctx.moveTo(x2,y2);
ctx.lineTo(midX,midY);
ctx.stroke();
//drawing the label
var width = ctx.measureText(this.label).width;
ctx.fillText(this.label,x-width/2.0,y+10);
}
ArcEdge.prototype.nearPoint = function(x,y){
var threshold = 8;
if ((this.startNode.x == this.endNode.x
&& this.startNode.x == this.controlPoint.x) ||
this.startNode.y == this.endNode.y
&& this.startNode.y == this.controlPoint.y){
//vertical or horizontal case
var x1 = this.startNode.x;
var y1 = this.startNode.y;
var x2 = this.endNode.x;
var y2 = this.endNode.y;
var mag = ((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
var u = ((x-x1)*(x2-x1) + (y-y1)*(y2-y1))/mag;
var xp = x1 + u*(x2-x1);
var yp = y1 + u*(y2-y1);
var dist = Math.sqrt((xp-x)*(xp-x) + (yp-y)*(yp-y));
return dist < threshold;
}
//solving cubic equation to get closest point
var A = {x:this.controlPoint.x - this.startNode.x,
y:this.controlPoint.y - this.startNode.y}
var B = {x:this.endNode.x - this.controlPoint.x - A.x,
y:this.endNode.y - this.controlPoint.y - A.y}
var M = {x:x,
y:y}
var Mp = {x:this.startNode.x - M.x,
y:this.startNode.y - M.y}
var a = B.x*B.x + B.y*B.y;
var b = 3 *(A.x*B.x + A.y*B.y);
var c = 2 *(A.x*A.x + A.y*A.y) + (Mp.x*B.x + Mp.y*B.y);
var d = Mp.x*A.x + Mp.y*A.y;
result = solveCubic([d,c,b,a]);
/*
debugClear();
debug(a + " " + b + " " + c + " " + d);
debug(result);
*/
//to always check for endpoints (for corner cases)
result.push(2);
result.push(-2);
var minDist = Infinity;
var px = 0,py = 0;
for (var i=0;i<result.length;i++){
var t = result[i];
if (t > 0 && t < 1){
var p0x = this.startNode.x, p0y = this.startNode.y;
var p1x = this.controlPoint.x, p1y = this.controlPoint.y;
var p2x = this.endNode.x, p2y = this.endNode.y;
px = (1-t)*(1-t)*p0x + 2*(1-t)*t*p1x + t*t*p2x;
py = (1-t)*(1-t)*p0y + 2*(1-t)*t*p1y + t*t*p2y;
var dist = Math.sqrt((x-px)*(x-px) + (y-py)*(y-py));
minDist = dist < minDist ? dist : minDist;
}else if (t > 1){
px = this.endNode.x;
py = this.endNode.y;
var dist = Math.sqrt((x-px)*(x-px) + (y-py)*(y-py));
minDist = dist < minDist ? dist : minDist;
}else{
px = this.startNode.x;
py = this.startNode.y;
var dist = Math.sqrt((x-px)*(x-px) + (y-py)*(y-py));
minDist = dist < minDist ? dist : minDist;
}
}
return minDist < threshold;
}
ArcEdge.prototype.drawToPoint = function(ctx,x,y){
ctx.beginPath();
ctx.moveTo(this.startNode.x,this.startNode.y);
ctx.lineTo(x,y);
ctx.stroke();
}
ArcEdge.prototype.setSelected = function(){
this.color = "#0000FF";
this.drawControlLines = true;
}
ArcEdge.prototype.setUnselected = function(){
this.color = DEFAULT_EDGE_COLOR;
this.drawControlLines = false;
}
|
added pan action to canvas
|
sfg.js
|
added pan action to canvas
|
<ide><path>fg.js
<ide> DEFAULT_SELECTED_COLOR = "#0000FF"
<ide>
<ide> STATES = {NORMAL : 0, ADD_NODE: 1, NODE_MOVE: 2,
<del> EDGE_WAIT_NODE1: 3,EDGE_WAIT_NODE2: 4
<add> EDGE_WAIT_NODE1: 3,EDGE_WAIT_NODE2: 4,
<add> PAN: 5
<ide> };
<ide>
<ide> //helper functions
<ide> this.addNode(100,250);
<ide> e = new ArcEdge(this.nodes[0],this.nodes[1]);
<ide> this.addEdge(e);
<del> this.ctx.setTransform(this.scale,0,0,this.scale,this.transX,this.transY);
<ide> this.redraw();
<ide> }else{
<ide> alert("canvas not supported!");
<ide>
<ide> SFG.prototype.mousedown = function(e){
<ide> e = e || window.e;
<add> e.preventDefault();
<add> e.stopPropagation();
<add>
<ide> var x = e.pageX - canvas.offsetLeft;
<ide> var y = e.pageY - canvas.offsetTop;
<ide> var state = this.sfg.state;
<ide> }else{
<ide> sfg.controlNode = null;
<ide> }
<add> if (selected == null){
<add> this.startX = x;
<add> this.startY = y;
<add> sfg.state = STATES.PAN;
<add> this.style.cursor = "move";
<add> }
<ide> sfg.selectItem(selected);
<ide> }else if (state == STATES.EDGE_WAIT_NODE1){
<ide> //sfg.newEdge must be initialized to empty edge
<ide>
<ide> SFG.prototype.mouseup = function(e){
<ide> e = e || window.e;
<add> e.preventDefault();
<add> e.stopPropagation();
<ide> var state = this.sfg.state;
<del> if (state == STATES.NODE_MOVE)
<add> if (state == STATES.NODE_MOVE || state == STATES.PAN){
<ide> this.sfg.state = STATES.NORMAL;
<add> this.style.cursor = "auto";
<add> }
<ide> }
<ide>
<ide> SFG.prototype.mousemove = function(e){
<ide> }else if (state == STATES.EDGE_WAIT_NODE2){
<ide> sfg.redraw();
<ide> sfg.newEdge.drawToPoint(sfg.ctx,x,y);
<add> }else if (state == STATES.PAN){
<add> var dx = x - this.startX;
<add> var dy = y - this.startY;
<add> sfg.transX += dx;
<add> sfg.transY += dy;
<add> sfg.redraw();
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> SFG.prototype.redraw = function(){
<add> this.ctx.setTransform(this.scale,0,0,this.scale,this.transX,this.transY);
<ide> this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
<ide> var nodes = this.nodes;
<ide> var edges = this.edges;
|
|
Java
|
bsd-3-clause
|
19ffde752ed12bbfaecef5165134496b8f1cea82
| 0 |
knopflerfish/knopflerfish.org,knopflerfish/knopflerfish.org,knopflerfish/knopflerfish.org
|
/*
* Copyright (c) 2003-2006, KNOPFLERFISH project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the KNOPFLERFISH project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.knopflerfish.framework.bundlestorage.file;
import org.knopflerfish.framework.*;
import org.osgi.framework.*;
import java.io.*;
import java.net.*;
//import java.security.*;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Iterator;
import java.util.Vector;
import java.util.jar.*;
import java.util.zip.*;
import java.util.Hashtable;
/**
* JAR file handling.
*
* @author Jan Stein
* @author Philippe Laporte
* @author Mats-Ola Persson
*/
class Archive {
/**
* Base for filename used to store copy of archive.
*/
final private static String ARCHIVE = "jar";
/**
* Directory base name to use for sub-archives.
*/
final private static String SUBDIR = "sub";
// Directory where optional bundle files are stored
// these need not be unpacked locally
final private static String OSGI_OPT_DIR = "OSGI-OPT/";
/**
* Controls if we should try to unpack bundles with sub-jars and
* native code.
*/
final private static boolean unpack = new Boolean(System.getProperty("org.knopflerfish.framework.bundlestorage.file.unpack", "true")).booleanValue();
/**
* Controls if we should try to unpack bundles with sub-jars and
* native code.
*/
final private static boolean alwaysUnpack = new Boolean(System.getProperty("org.knopflerfish.framework.bundlestorage.file.always_unpack", "false")).booleanValue();
/**
* Controls if file: URLs should be referenced only, not copied
* to bundle storage dir
*/
boolean bReference = new Boolean(System.getProperty("org.knopflerfish.framework.bundlestorage.file.reference", "false")).booleanValue();
/**
* File handle for file that contains current archive.
*/
private FileTree file;
/**
* JAR file handle for file that contains current archive.
*/
private ZipFile jar;
private String location;
/**
* Archive's manifest
*/
AutoManifest manifest /*= null*/;
/**
* JAR Entry handle for file that contains current archive.
* If not null, it is a sub jar instead.
*/
private ZipEntry subJar /*= null*/;
/**
* Create an Archive based on contents of an InputStream,
* the archive is saved as local copy in the specified
* directory.
*
* @param dir Directory to save data in.
* @param rev Revision of bundle content (used for updates).
* @param is Jar file data in an InputStream.
* @param url URL to use to CodeSource.
*/
Archive(File dir, int rev, InputStream is, String location) throws IOException {
this(dir, rev, is, null, location);
}
FileTree refFile = null;
Archive(File dir, int rev, InputStream is, URL source, String location) throws IOException {
this.location = location;
BufferedInputStream bis;
//Dodge Skelmir-specific problem. Not a great solution, since problem not well understood at this time. Passes KF test suite
if(System.getProperty("java.vendor").startsWith("Skelmir")){
bis = new BufferedInputStream(is, is.available());
}
else{
bis = new BufferedInputStream(is, 8192);
}
ZipInputStream zi = null;
// Handle reference: URLs by overriding global flag
if(source != null && "reference".equals(source.getProtocol())) {
bReference = true;
}
if (alwaysUnpack) {
zi = new ZipInputStream(bis);
} else if (unpack) {
//Dodge Skelmir-specific problem. Not a great solution, since problem not well understood at this time. Passes KF test suite
if(System.getProperty("java.vendor").startsWith("Skelmir")){
bis.mark(98304);
}
else{
//Is 16000 enough?
bis.mark(16000);
}
JarInputStream ji = new JarInputStream(bis);
manifest = new AutoManifest(ji.getManifest(), location);
if (manifest != null) {
if (checkManifest()) {
zi = ji;
} else {
bis.reset();
}
} else {
// Manifest probably not first in JAR, should we complain?
// Now, try to use the jar anyway. Maybe the manifest is there.
bis.reset();
}
}
file = new FileTree(dir, ARCHIVE + rev);
if (zi != null) {
File f;
file.mkdirs();
if (manifest != null) {
f = new File(file, "META-INF");
f.mkdir();
BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(new File(f, "MANIFEST.MF")));
try {
manifest.write(o);
} finally {
o.close();
}
}
ZipEntry ze;
while ((ze = zi.getNextEntry()) != null) {
if (!ze.isDirectory()) {
if (isSkipped(ze.getName())) {
// Optional files are not copied to disk
} else {
StringTokenizer st = new StringTokenizer(ze.getName(), "/");
f = new File(file, st.nextToken());
while (st.hasMoreTokens()) {
f.mkdir();
f = new File(f, st.nextToken());
}
loadFile(f, zi, true);
}
}
}
jar = null;
} else {
// Only copy to storage when applicable, otherwise
// use reference
if (source != null && bReference && "file".equals(source.getProtocol())) {
refFile = new FileTree(source.getFile());
jar = new ZipFile(refFile);
} else {
loadFile(file, bis, true);
jar = new ZipFile(file);
}
}
if (manifest == null) {
manifest = getManifest();
checkManifest();
}
handleAutoManifest();
}
/**
* Return true if the specified path name should be
* skipped when unpacking.
*/
boolean isSkipped(String pathName) {
return pathName.startsWith(OSGI_OPT_DIR);
}
/**
* Create an Archive based on contents of a saved
* archive in the specified directory.
* Take lowest versioned archive and remove rest.
*
*/
Archive(File dir, int rev, String location) throws IOException {
this.location = location;
String [] f = dir.list();
file = null;
if (rev != -1) {
file = new FileTree(dir, ARCHIVE + rev);
} else {
rev = Integer.MAX_VALUE;
for (int i = 0; i < f.length; i++) {
if (f[i].startsWith(ARCHIVE)) {
try {
int c = Integer.parseInt(f[i].substring(ARCHIVE.length()));
if (c < rev) {
rev = c;
file = new FileTree(dir, f[i]);
}
} catch (NumberFormatException ignore) { }
}
}
}
for (int i = 0; i < f.length; i++) {
if (f[i].startsWith(ARCHIVE)) {
try {
int c = Integer.parseInt(f[i].substring(ARCHIVE.length()));
if (c != rev) {
(new FileTree(dir, f[i])).delete();
}
} catch (NumberFormatException ignore) { }
}
if (f[i].startsWith(SUBDIR)) {
try {
int c = Integer.parseInt(f[i].substring(SUBDIR.length()));
if (c != rev) {
(new FileTree(dir, f[i])).delete();
}
} catch (NumberFormatException ignore) { }
}
}
if (file == null || !file.exists()) {
if(bReference && (location != null)) {
try {
URL source = new URL(location);
if("file".equals(source.getProtocol())) {
refFile = file = new FileTree(source.getFile());
}
} catch (Exception e) {
throw new IOException("Bad file URL stored in referenced jar in: " +
dir.getAbsolutePath() +
", location=" + location);
}
}
if(file == null || !file.exists()) {
throw new IOException("No saved jar file found in: " + dir.getAbsolutePath() + ", old location=" + location);
}
}
if (file.isDirectory()) {
jar = null;
} else {
jar = new ZipFile(file);
}
manifest = getManifest();
handleAutoManifest();
}
// handle automanifest stuff
void handleAutoManifest() throws IOException {
if(manifest != null && manifest.isAuto()) {
if(jar != null) {
manifest.addZipFile(jar);
} else {
if(file != null && file.isDirectory()) {
manifest.addFile(file.getAbsolutePath(), file);
}
}
}
}
/**
* Create a Sub-Archive based on a path to in an already
* existing Archive. The new archive is saved in a subdirectory
* below local copy of the existing Archive.
*
* @param a Parent Archive.
* @param path Path of new Archive inside old Archive.
* @exception FileNotFoundException if no such Jar file in archive.
* @exception IOException if failed to read Jar file.
*/
Archive(Archive a, String path) throws IOException {
this.location = a.location;
if (a.jar != null) {
jar = a.jar;
subJar = jar.getEntry(path);
if (subJar == null) {
throw new IOException("No such JAR component: " + path);
}
// If directory make sure that it ends with "/"
if (subJar.isDirectory() && !path.endsWith("/")) {
subJar = jar.getEntry(path + "/");
}
file = a.file;
} else {
file = findFile(a.file, path);
if (file.isDirectory()) {
jar = null;
} else {
jar = new ZipFile(file);
}
}
}
/**
* Show file name for archive, if zip show if it is sub archive.
*
* @return A string with result.
*/
public String toString() {
if (subJar != null) {
return file.getAbsolutePath() + "(" + subJar.getName() + ")";
} else {
return file.getAbsolutePath();
}
}
/**
* Get revision number this archive.
*
* @return Archive revision number
*/
int getRevision() {
try {
return Integer.parseInt(file.getName().substring(ARCHIVE.length()));
} catch (NumberFormatException ignore) {
// assert?
return -1;
}
}
/**
* Get an attribute from the manifest of the archive.
*
* @param key Name of attribute to get.
* @return A string with result or null if the entry doesn't exists.
*/
String getAttribute(String key) {
Attributes a = manifest.getMainAttributes();
if (a != null) {
return a.getValue(key);
}
return null;
}
/**
* Get a byte array containg the contents of named class file from
* the archive.
*
* @param Class File to get.
* @return Byte array with contents of class file or null if file doesn't exist.
* @exception IOException if failed to read jar entry.
*/
byte[] getClassBytes(String classFile) throws IOException {
if(bClosed) {
return null;
}
InputFlow cif = getInputFlow(classFile);
if (cif != null) {
byte[] bytes;
if (cif.length >= 0) {
bytes = new byte[(int)cif.length];
DataInputStream dis = new DataInputStream(cif.is);
dis.readFully(bytes);
} else {
bytes = new byte[0];
byte[] tmp = new byte[8192];
try {
int len;
while ((len = cif.is.read(tmp)) > 0) {
byte[] oldbytes = bytes;
bytes = new byte[oldbytes.length + len];
System.arraycopy(oldbytes, 0, bytes, 0, oldbytes.length);
System.arraycopy(tmp, 0, bytes, oldbytes.length, len);
}
}
catch (EOFException ignore) {
// On Pjava we somtimes get a mysterious EOF excpetion,
// but everything seems okey. (SUN Bug 4040920)
}
}
cif.is.close();
return bytes;
} else {
return null;
}
}
/**
* Get an InputFlow to named entry inside an Archive.
*
* @param component Entry to get reference to.
* @return InputFlow to entry or null if it doesn't exist.
*/
InputFlow getInputFlow(String component) {
if(bClosed) {
return null;
}
if (component.startsWith("/")) {
throw new RuntimeException("Assert! Path should never start with / here");
}
ZipEntry ze;
try {
if (jar != null) {
if (subJar != null) {
if (component.equals("")) {
// Return a stream to the entire Jar.
return new InputFlow(jar.getInputStream(subJar), subJar.getSize());
} else {
if (subJar.isDirectory()) {
ze = jar.getEntry(subJar.getName() + component);
} else {
JarInputStream ji = new JarInputStream(jar.getInputStream(subJar));
do {
ze = ji.getNextJarEntry();
if (ze == null) {
ji.close();
return null;
}
} while (!component.equals(ze.getName()));
return new InputFlow((InputStream)ji, ze.getSize());
}
}
} else {
if (component.equals("")) {
// Return a stream to the entire Jar.
File f = new File(jar.getName());
return new InputFlow(new FileInputStream(f), f.length() );
} else {
ze = jar.getEntry(component);
}
}
return ze != null ? new InputFlow(jar.getInputStream(ze), ze.getSize()) : null;
} else {
File f = findFile(file, component);
return f.exists() ? new InputFlow(new FileInputStream(f), f.length()) : null;
}
} catch (IOException ignore) {
return null;
}
}
//TODO not extensively tested
Enumeration findResourcesPath(String path) {
Vector answer = new Vector();
if (jar != null) {
ZipEntry entry;
//"normalize" + erroneous path check: be generous
path.replace('\\', '/');
if (path.startsWith("/")){
path = path.substring(1);
}
if (!path.endsWith("/")/*in case bad argument*/){
if (path.length() > 1){
path += "/";
}
}
Enumeration entries = jar.entries();
while (entries.hasMoreElements()){
entry = (ZipEntry) entries.nextElement();
String name = entry.getName();
if (name.startsWith(path)){
int idx = name.lastIndexOf('/');
if (entry.isDirectory()){
idx = name.substring(0, idx).lastIndexOf('/');
}
if (idx > 0){
if (name.substring(0, idx + 1).equals(path)){
answer.add(name);
}
} else if (path.equals("")){
answer.add(name);
}
}
}
} else {
File f = findFile(file, path);
if (!f.exists()) {
return null;
}
if (!f.isDirectory()) {
return null;
}
File[] files = f.listFiles();
int length = files.length;
for(int i = 0; i < length; i++){
String filePath = files[i].getPath();
filePath = filePath.substring(file.getPath().length() + 1);
filePath.replace(File.separatorChar, '/');
if(files[i].isDirectory()){
filePath += "/";
}
answer.add(filePath);
}
}
if(answer.size() == 0){
return null;
}
return answer.elements();
}
/**
* Get an Archive handle to a named Jar file within this archive.
*
* @param path Name of Jar file to get.
* @return An Archive object representing new archive.
* @exception FileNotFoundException if no such Jar file in archive.
* @exception IOException if failed to read Jar file.
*/
Archive getSubArchive(String path) throws IOException {
if(bClosed) {
return null;
}
return new Archive(this, path);
}
/**
* Extract native library from JAR.
*
* @param key Name of Jar file to get.
* @return A string with path to native library.
*/
String getNativeLibrary(String path) throws IOException {
if(bClosed) {
throw new IOException("Archive is closed");
}
if (path.startsWith("/")) {
path = path.substring(1);
}
File lib;
if (jar != null) {
lib = getSubFile(this, path);
if (!lib.exists()) {
(new File(lib.getParent())).mkdirs();
ZipEntry ze = jar.getEntry(path);
if (ze != null) {
InputStream is = jar.getInputStream(ze);
try {
loadFile(lib, is, false);
} finally {
is.close();
}
} else {
throw new FileNotFoundException("No such sub-archive: " + path);
}
}
} else {
lib = findFile(file, path);
//XXX - start L-3 modification
if (!lib.exists() && (lib.getParent() != null)) {
final String libname = lib.getName();
File[] list = lib.getParentFile().listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
int pos = name.lastIndexOf(libname);
return ((pos > 1) && (name.charAt(pos - 1) == '_'));
}
});
if (list.length > 0) {
list[0].renameTo(lib);
}
}
//XXX - end L-3 modification
}
return lib.getAbsolutePath();
}
/**
* Remove archive and any unpacked sub-archives.
*/
void purge() {
close();
// Remove archive
file.delete();
// Remove any cached sub files
getSubFileTree(this).delete();
}
boolean bClosed = false;
/**
* Close archive and all open sub-archives.
* If close fails it is silently ignored.
*/
void close() {
bClosed = true; // Mark as closed to safely handle referenced files
if (subJar == null && jar != null) {
try {
jar.close();
} catch (IOException ignore) {}
}
}
//
// Private methods
//
/**
* Check that we have a valid manifest for the bundle
* and if we need to unpack bundle for fast performance,
* i.e has native code file or subjars.
*
* @return true if bundle needs to be unpacked.
* @exception IllegalArgumentException if we have a broken manifest.
*/
private boolean checkManifest() {
Attributes a = manifest.getMainAttributes();
Util.parseEntries(Constants.EXPORT_PACKAGE, a.getValue(Constants.EXPORT_PACKAGE),
false, true, false);
Util.parseEntries(Constants.IMPORT_PACKAGE, a.getValue(Constants.IMPORT_PACKAGE),
false, true, false);
Iterator nc = Util.parseEntries(Constants.BUNDLE_NATIVECODE,
a.getValue(Constants.BUNDLE_NATIVECODE),
false, false, false);
String bc = a.getValue(Constants.BUNDLE_CLASSPATH);
return (bc != null && !bc.trim().equals(".")) || nc.hasNext();
}
/**
* Get file handle for file inside a directory structure.
* The path for the file is always specified with a '/'
* separated path.
*
* @param root Directory structure to search.
* @param path Path to file to find.
* @return The File object for file <code>path</code>.
*/
private FileTree findFile(File root, String path) {
return new FileTree(root, path.replace('/', File.separatorChar));
}
/**
* Get the manifest for this archive.
*
* @return The manifest for this Archive
*/
private AutoManifest getManifest() throws IOException {
// TBD: Should recognize entry with lower case?
InputFlow mif = getInputFlow("META-INF/MANIFEST.MF");
if (mif != null) {
return new AutoManifest(new Manifest(mif.is), location);
} else {
throw new IOException("Manifest is missing");
}
}
/**
* Get dir for unpacked components.
*
* @param archive Archive which contains the components.
* @return FileTree for archives component cache directory.
*/
private FileTree getSubFileTree(Archive archive) {
return new FileTree(archive.file.getParent(),
SUBDIR + archive.file.getName().substring(ARCHIVE.length()));
}
/**
* Get file for an unpacked component.
*
* @param archive Archive which contains the component.
* @param path Name of the component to get.
* @return File for components cache file.
*/
private File getSubFile(Archive archive, String path) {
return new File(getSubFileTree(archive), path.replace('/', '-'));
}
/**
* Loads a file from an InputStream and stores it in a file.
*
* @param output File to save data in.
* @param is InputStream to read from.
*/
private void loadFile(File output, InputStream is, boolean verify) throws IOException {
OutputStream os = null;
// NYI! Verify
try {
os = new FileOutputStream(output);
byte[] buf = new byte[8192];
int n;
try {
while ((n = is.read(buf)) > 0) {
os.write(buf, 0, n);
}
} catch (EOFException ignore) {
// On Pjava we sometimes get a mysterious EOF exception,
// but everything seems okey. (SUN Bug 4040920)
}
} catch (IOException e) {
output.delete();
throw e;
} finally {
if (os != null) {
os.close();
}
}
}
/**
* Returns the path to this bundle.
*/
String getPath() {
return file.getAbsolutePath();
}
/**
* InputFlow represents an InputStream with a known length
*/
class InputFlow {
final InputStream is;
final long length;
InputFlow(InputStream is, long length) {
this.is = is;
this.length = length;
}
}
}
|
osgi/framework/src/org/knopflerfish/framework/bundlestorage/file/Archive.java
|
/*
* Copyright (c) 2003-2006, KNOPFLERFISH project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the KNOPFLERFISH project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.knopflerfish.framework.bundlestorage.file;
import org.knopflerfish.framework.*;
import org.osgi.framework.*;
import java.io.*;
import java.net.*;
//import java.security.*;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Iterator;
import java.util.Vector;
import java.util.jar.*;
import java.util.zip.*;
import java.util.Hashtable;
/**
* JAR file handling.
*
* @author Jan Stein
* @author Philippe Laporte
* @author Mats-Ola Persson
*/
class Archive {
/**
* Base for filename used to store copy of archive.
*/
final private static String ARCHIVE = "jar";
/**
* Directory base name to use for sub-archives.
*/
final private static String SUBDIR = "sub";
// Directory where optional bundle files are stored
// these need not be unpacked locally
final private static String OSGI_OPT_DIR = "OSGI-OPT/";
/**
* Controls if we should try to unpack bundles with sub-jars and
* native code.
*/
final private static boolean unpack = new Boolean(System.getProperty("org.knopflerfish.framework.bundlestorage.file.unpack", "true")).booleanValue();
/**
* Controls if we should try to unpack bundles with sub-jars and
* native code.
*/
final private static boolean alwaysUnpack = new Boolean(System.getProperty("org.knopflerfish.framework.bundlestorage.file.always_unpack", "false")).booleanValue();
/**
* Controls if file: URLs should be referenced only, not copied
* to bundle storage dir
*/
boolean bReference = new Boolean(System.getProperty("org.knopflerfish.framework.bundlestorage.file.reference", "false")).booleanValue();
/**
* File handle for file that contains current archive.
*/
private FileTree file;
/**
* JAR file handle for file that contains current archive.
*/
private ZipFile jar;
private String location;
/**
* Archive's manifest
*/
AutoManifest manifest /*= null*/;
/**
* JAR Entry handle for file that contains current archive.
* If not null, it is a sub jar instead.
*/
private ZipEntry subJar /*= null*/;
/**
* Create an Archive based on contents of an InputStream,
* the archive is saved as local copy in the specified
* directory.
*
* @param dir Directory to save data in.
* @param rev Revision of bundle content (used for updates).
* @param is Jar file data in an InputStream.
* @param url URL to use to CodeSource.
*/
Archive(File dir, int rev, InputStream is, String location) throws IOException {
this(dir, rev, is, null, location);
}
FileTree refFile = null;
Archive(File dir, int rev, InputStream is, URL source, String location) throws IOException {
this.location = location;
BufferedInputStream bis;
//Dodge Skelmir-specific problem. Not a great solution, since problem not well understood at this time. Passes KF test suite
if(System.getProperty("java.vendor").startsWith("Skelmir")){
bis = new BufferedInputStream(is, is.available());
}
else{
bis = new BufferedInputStream(is, 8192);
}
ZipInputStream zi = null;
// Handle reference: URLs by overriding global flag
if(source != null && "reference".equals(source.getProtocol())) {
bReference = true;
}
if (alwaysUnpack) {
zi = new ZipInputStream(bis);
} else if (unpack) {
//Dodge Skelmir-specific problem. Not a great solution, since problem not well understood at this time. Passes KF test suite
if(System.getProperty("java.vendor").startsWith("Skelmir")){
bis.mark(98304);
}
else{
//Is 16000 enough?
bis.mark(16000);
}
JarInputStream ji = new JarInputStream(bis);
manifest = new AutoManifest(ji.getManifest(), location);
if (manifest != null) {
if (checkManifest()) {
zi = ji;
} else {
bis.reset();
}
} else {
// Manifest probably not first in JAR, should we complain?
// Now, try to use the jar anyway. Maybe the manifest is there.
bis.reset();
}
}
file = new FileTree(dir, ARCHIVE + rev);
if (zi != null) {
File f;
file.mkdirs();
if (manifest != null) {
f = new File(file, "META-INF");
f.mkdir();
BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(new File(f, "MANIFEST.MF")));
try {
manifest.write(o);
} finally {
o.close();
}
}
ZipEntry ze;
while ((ze = zi.getNextEntry()) != null) {
if (!ze.isDirectory()) {
if (isSkipped(ze.getName())) {
// Optional files are not copied to disk
} else {
StringTokenizer st = new StringTokenizer(ze.getName(), "/");
f = new File(file, st.nextToken());
while (st.hasMoreTokens()) {
f.mkdir();
f = new File(f, st.nextToken());
}
loadFile(f, zi, true);
}
}
}
jar = null;
} else {
// Only copy to storage when applicable, otherwise
// use reference
if (source != null && bReference && "file".equals(source.getProtocol())) {
refFile = new FileTree(source.getFile());
jar = new ZipFile(refFile);
} else {
loadFile(file, bis, true);
jar = new ZipFile(file);
}
}
if (manifest == null) {
manifest = getManifest();
checkManifest();
}
handleAutoManifest();
}
/**
* Return true if the specified path name should be
* skipped when unpacking.
*/
boolean isSkipped(String pathName) {
return pathName.startsWith(OSGI_OPT_DIR);
}
/**
* Create an Archive based on contents of a saved
* archive in the specified directory.
* Take lowest versioned archive and remove rest.
*
*/
Archive(File dir, int rev, String location) throws IOException {
this.location = location;
String [] f = dir.list();
file = null;
if (rev != -1) {
file = new FileTree(dir, ARCHIVE + rev);
} else {
rev = Integer.MAX_VALUE;
for (int i = 0; i < f.length; i++) {
if (f[i].startsWith(ARCHIVE)) {
try {
int c = Integer.parseInt(f[i].substring(ARCHIVE.length()));
if (c < rev) {
rev = c;
file = new FileTree(dir, f[i]);
}
} catch (NumberFormatException ignore) { }
}
}
}
for (int i = 0; i < f.length; i++) {
if (f[i].startsWith(ARCHIVE)) {
try {
int c = Integer.parseInt(f[i].substring(ARCHIVE.length()));
if (c != rev) {
(new FileTree(dir, f[i])).delete();
}
} catch (NumberFormatException ignore) { }
}
if (f[i].startsWith(SUBDIR)) {
try {
int c = Integer.parseInt(f[i].substring(SUBDIR.length()));
if (c != rev) {
(new FileTree(dir, f[i])).delete();
}
} catch (NumberFormatException ignore) { }
}
}
if (file == null || !file.exists()) {
if(bReference && (location != null)) {
try {
URL source = new URL(location);
if("file".equals(source.getProtocol())) {
refFile = file = new FileTree(source.getFile());
}
} catch (Exception e) {
throw new IOException("Bad file URL stored in referenced jar in: " +
dir.getAbsolutePath() +
", location=" + location);
}
}
if(file == null || !file.exists()) {
throw new IOException("No saved jar file found in: " + dir.getAbsolutePath() + ", old location=" + location);
}
}
if (file.isDirectory()) {
jar = null;
} else {
jar = new ZipFile(file);
}
manifest = getManifest();
handleAutoManifest();
}
// handle automanifest stuff
void handleAutoManifest() throws IOException {
if(manifest != null && manifest.isAuto()) {
if(jar != null) {
manifest.addZipFile(jar);
} else {
if(file != null && file.isDirectory()) {
manifest.addFile(file.getAbsolutePath(), file);
}
}
}
}
/**
* Create a Sub-Archive based on a path to in an already
* existing Archive. The new archive is saved in a subdirectory
* below local copy of the existing Archive.
*
* @param a Parent Archive.
* @param path Path of new Archive inside old Archive.
* @exception FileNotFoundException if no such Jar file in archive.
* @exception IOException if failed to read Jar file.
*/
Archive(Archive a, String path) throws IOException {
this.location = a.location;
if (a.jar != null) {
jar = a.jar;
subJar = jar.getEntry(path);
if (subJar == null) {
throw new IOException("No such JAR component: " + path);
}
// If directory make sure that it ends with "/"
if (subJar.isDirectory() && !path.endsWith("/")) {
subJar = jar.getEntry(path + "/");
}
file = a.file;
} else {
file = findFile(a.file, path);
if (file.isDirectory()) {
jar = null;
} else {
jar = new ZipFile(file);
}
}
}
/**
* Show file name for archive, if zip show if it is sub archive.
*
* @return A string with result.
*/
public String toString() {
if (subJar != null) {
return file.getAbsolutePath() + "(" + subJar.getName() + ")";
} else {
return file.getAbsolutePath();
}
}
/**
* Get revision number this archive.
*
* @return Archive revision number
*/
int getRevision() {
try {
return Integer.parseInt(file.getName().substring(ARCHIVE.length()));
} catch (NumberFormatException ignore) {
// assert?
return -1;
}
}
/**
* Get an attribute from the manifest of the archive.
*
* @param key Name of attribute to get.
* @return A string with result or null if the entry doesn't exists.
*/
String getAttribute(String key) {
Attributes a = manifest.getMainAttributes();
if (a != null) {
return a.getValue(key);
}
return null;
}
/**
* Get a byte array containg the contents of named class file from
* the archive.
*
* @param Class File to get.
* @return Byte array with contents of class file or null if file doesn't exist.
* @exception IOException if failed to read jar entry.
*/
byte[] getClassBytes(String classFile) throws IOException {
if(bClosed) {
return null;
}
InputFlow cif = getInputFlow(classFile);
if (cif != null) {
byte[] bytes;
if (cif.length >= 0) {
bytes = new byte[(int)cif.length];
DataInputStream dis = new DataInputStream(cif.is);
dis.readFully(bytes);
} else {
bytes = new byte[0];
byte[] tmp = new byte[8192];
try {
int len;
while ((len = cif.is.read(tmp)) > 0) {
byte[] oldbytes = bytes;
bytes = new byte[oldbytes.length + len];
System.arraycopy(oldbytes, 0, bytes, 0, oldbytes.length);
System.arraycopy(tmp, 0, bytes, oldbytes.length, len);
}
}
catch (EOFException ignore) {
// On Pjava we somtimes get a mysterious EOF excpetion,
// but everything seems okey. (SUN Bug 4040920)
}
}
cif.is.close();
return bytes;
} else {
return null;
}
}
/**
* Get an InputFlow to named entry inside an Archive.
*
* @param component Entry to get reference to.
* @return InputFlow to entry or null if it doesn't exist.
*/
InputFlow getInputFlow(String component) {
if(bClosed) {
return null;
}
if (component.startsWith("/")) {
throw new RuntimeException("Assert! Path should never start with / here");
}
ZipEntry ze;
try {
if (jar != null) {
if (subJar != null) {
if (subJar.isDirectory()) {
ze = jar.getEntry(subJar.getName() + component);
} else {
JarInputStream ji = new JarInputStream(jar.getInputStream(subJar));
do {
ze = ji.getNextJarEntry();
if (ze == null) {
ji.close();
return null;
}
} while (!component.equals(ze.getName()));
return new InputFlow((InputStream)ji, ze.getSize());
}
} else {
ze = jar.getEntry(component);
}
return ze != null ? new InputFlow(jar.getInputStream(ze), ze.getSize()) : null;
} else {
File f = findFile(file, component);
return f.exists() ? new InputFlow(new FileInputStream(f), f.length()) : null;
}
} catch (IOException ignore) {
return null;
}
}
//TODO not extensively tested
Enumeration findResourcesPath(String path) {
Vector answer = new Vector();
if (jar != null) {
ZipEntry entry;
//"normalize" + erroneous path check: be generous
path.replace('\\', '/');
if (path.startsWith("/")){
path = path.substring(1);
}
if (!path.endsWith("/")/*in case bad argument*/){
if (path.length() > 1){
path += "/";
}
}
Enumeration entries = jar.entries();
while (entries.hasMoreElements()){
entry = (ZipEntry) entries.nextElement();
String name = entry.getName();
if (name.startsWith(path)){
int idx = name.lastIndexOf('/');
if (entry.isDirectory()){
idx = name.substring(0, idx).lastIndexOf('/');
}
if (idx > 0){
if (name.substring(0, idx + 1).equals(path)){
answer.add(name);
}
} else if (path.equals("")){
answer.add(name);
}
}
}
} else {
File f = findFile(file, path);
if (!f.exists()) {
return null;
}
if (!f.isDirectory()) {
return null;
}
File[] files = f.listFiles();
int length = files.length;
for(int i = 0; i < length; i++){
String filePath = files[i].getPath();
filePath = filePath.substring(file.getPath().length() + 1);
filePath.replace(File.separatorChar, '/');
if(files[i].isDirectory()){
filePath += "/";
}
answer.add(filePath);
}
}
if(answer.size() == 0){
return null;
}
return answer.elements();
}
/**
* Get an Archive handle to a named Jar file within this archive.
*
* @param path Name of Jar file to get.
* @return An Archive object representing new archive.
* @exception FileNotFoundException if no such Jar file in archive.
* @exception IOException if failed to read Jar file.
*/
Archive getSubArchive(String path) throws IOException {
if(bClosed) {
return null;
}
return new Archive(this, path);
}
/**
* Extract native library from JAR.
*
* @param key Name of Jar file to get.
* @return A string with path to native library.
*/
String getNativeLibrary(String path) throws IOException {
if(bClosed) {
throw new IOException("Archive is closed");
}
if (path.startsWith("/")) {
path = path.substring(1);
}
File lib;
if (jar != null) {
lib = getSubFile(this, path);
if (!lib.exists()) {
(new File(lib.getParent())).mkdirs();
ZipEntry ze = jar.getEntry(path);
if (ze != null) {
InputStream is = jar.getInputStream(ze);
try {
loadFile(lib, is, false);
} finally {
is.close();
}
} else {
throw new FileNotFoundException("No such sub-archive: " + path);
}
}
} else {
lib = findFile(file, path);
//XXX - start L-3 modification
if (!lib.exists() && (lib.getParent() != null)) {
final String libname = lib.getName();
File[] list = lib.getParentFile().listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
int pos = name.lastIndexOf(libname);
return ((pos > 1) && (name.charAt(pos - 1) == '_'));
}
});
if (list.length > 0) {
list[0].renameTo(lib);
}
}
//XXX - end L-3 modification
}
return lib.getAbsolutePath();
}
/**
* Remove archive and any unpacked sub-archives.
*/
void purge() {
close();
// Remove archive
file.delete();
// Remove any cached sub files
getSubFileTree(this).delete();
}
boolean bClosed = false;
/**
* Close archive and all open sub-archives.
* If close fails it is silently ignored.
*/
void close() {
bClosed = true; // Mark as closed to safely handle referenced files
if (subJar == null && jar != null) {
try {
jar.close();
} catch (IOException ignore) {}
}
}
//
// Private methods
//
/**
* Check that we have a valid manifest for the bundle
* and if we need to unpack bundle for fast performance,
* i.e has native code file or subjars.
*
* @return true if bundle needs to be unpacked.
* @exception IllegalArgumentException if we have a broken manifest.
*/
private boolean checkManifest() {
Attributes a = manifest.getMainAttributes();
Util.parseEntries(Constants.EXPORT_PACKAGE, a.getValue(Constants.EXPORT_PACKAGE),
false, true, false);
Util.parseEntries(Constants.IMPORT_PACKAGE, a.getValue(Constants.IMPORT_PACKAGE),
false, true, false);
Iterator nc = Util.parseEntries(Constants.BUNDLE_NATIVECODE,
a.getValue(Constants.BUNDLE_NATIVECODE),
false, false, false);
String bc = a.getValue(Constants.BUNDLE_CLASSPATH);
return (bc != null && !bc.trim().equals(".")) || nc.hasNext();
}
/**
* Get file handle for file inside a directory structure.
* The path for the file is always specified with a '/'
* separated path.
*
* @param root Directory structure to search.
* @param path Path to file to find.
* @return The File object for file <code>path</code>.
*/
private FileTree findFile(File root, String path) {
return new FileTree(root, path.replace('/', File.separatorChar));
}
/**
* Get the manifest for this archive.
*
* @return The manifest for this Archive
*/
private AutoManifest getManifest() throws IOException {
// TBD: Should recognize entry with lower case?
InputFlow mif = getInputFlow("META-INF/MANIFEST.MF");
if (mif != null) {
return new AutoManifest(new Manifest(mif.is), location);
} else {
throw new IOException("Manifest is missing");
}
}
/**
* Get dir for unpacked components.
*
* @param archive Archive which contains the components.
* @return FileTree for archives component cache directory.
*/
private FileTree getSubFileTree(Archive archive) {
return new FileTree(archive.file.getParent(),
SUBDIR + archive.file.getName().substring(ARCHIVE.length()));
}
/**
* Get file for an unpacked component.
*
* @param archive Archive which contains the component.
* @param path Name of the component to get.
* @return File for components cache file.
*/
private File getSubFile(Archive archive, String path) {
return new File(getSubFileTree(archive), path.replace('/', '-'));
}
/**
* Loads a file from an InputStream and stores it in a file.
*
* @param output File to save data in.
* @param is InputStream to read from.
*/
private void loadFile(File output, InputStream is, boolean verify) throws IOException {
OutputStream os = null;
// NYI! Verify
try {
os = new FileOutputStream(output);
byte[] buf = new byte[8192];
int n;
try {
while ((n = is.read(buf)) > 0) {
os.write(buf, 0, n);
}
} catch (EOFException ignore) {
// On Pjava we sometimes get a mysterious EOF exception,
// but everything seems okey. (SUN Bug 4040920)
}
} catch (IOException e) {
output.delete();
throw e;
} finally {
if (os != null) {
os.close();
}
}
}
/**
* Returns the path to this bundle.
*/
String getPath() {
return file.getAbsolutePath();
}
/**
* InputFlow represents an InputStream with a known length
*/
class InputFlow {
final InputStream is;
final long length;
InputFlow(InputStream is, long length) {
this.is = is;
this.length = length;
}
}
}
|
Archive.getInputStream() now returns a steram to the entire jar file holding the archive contents. This solves issue [1516267] in tracker on SourceForge.
|
osgi/framework/src/org/knopflerfish/framework/bundlestorage/file/Archive.java
|
Archive.getInputStream() now returns a steram to the entire jar file holding the archive contents. This solves issue [1516267] in tracker on SourceForge.
|
<ide><path>sgi/framework/src/org/knopflerfish/framework/bundlestorage/file/Archive.java
<ide> try {
<ide> if (jar != null) {
<ide> if (subJar != null) {
<del> if (subJar.isDirectory()) {
<del> ze = jar.getEntry(subJar.getName() + component);
<add> if (component.equals("")) {
<add> // Return a stream to the entire Jar.
<add> return new InputFlow(jar.getInputStream(subJar), subJar.getSize());
<ide> } else {
<del> JarInputStream ji = new JarInputStream(jar.getInputStream(subJar));
<del> do {
<del> ze = ji.getNextJarEntry();
<del> if (ze == null) {
<del> ji.close();
<del> return null;
<del> }
<del> } while (!component.equals(ze.getName()));
<del> return new InputFlow((InputStream)ji, ze.getSize());
<add> if (subJar.isDirectory()) {
<add> ze = jar.getEntry(subJar.getName() + component);
<add> } else {
<add> JarInputStream ji = new JarInputStream(jar.getInputStream(subJar));
<add> do {
<add> ze = ji.getNextJarEntry();
<add> if (ze == null) {
<add> ji.close();
<add> return null;
<add> }
<add> } while (!component.equals(ze.getName()));
<add> return new InputFlow((InputStream)ji, ze.getSize());
<add> }
<ide> }
<ide> } else {
<del> ze = jar.getEntry(component);
<add> if (component.equals("")) {
<add> // Return a stream to the entire Jar.
<add> File f = new File(jar.getName());
<add> return new InputFlow(new FileInputStream(f), f.length() );
<add> } else {
<add> ze = jar.getEntry(component);
<add> }
<ide> }
<ide> return ze != null ? new InputFlow(jar.getInputStream(ze), ze.getSize()) : null;
<ide> } else {
|
|
Java
|
apache-2.0
|
8d2d6421fa1e717fd41130a23c940c910547c00b
| 0 |
wso2/product-apim,wso2/product-apim,wso2/product-apim,chamilaadhi/product-apim,wso2/product-apim,wso2/product-apim,chamilaadhi/product-apim,chamilaadhi/product-apim,chamilaadhi/product-apim,chamilaadhi/product-apim
|
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.wso2.am.integration.tests.restapi.admin.throttlingpolicy;
import org.apache.http.HttpStatus;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.am.integration.clients.admin.ApiException;
import org.wso2.am.integration.clients.admin.ApiResponse;
import org.wso2.am.integration.clients.admin.api.dto.BandwidthLimitDTO;
import org.wso2.am.integration.clients.admin.api.dto.CustomAttributeDTO;
import org.wso2.am.integration.clients.admin.api.dto.RequestCountLimitDTO;
import org.wso2.am.integration.clients.admin.api.dto.SubscriptionThrottlePolicyDTO;
import org.wso2.am.integration.clients.admin.api.dto.SubscriptionThrottlePolicyPermissionDTO;
import org.wso2.am.integration.clients.admin.api.dto.ThrottleLimitDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.SubscriptionDTO;
import org.wso2.am.integration.test.Constants;
import org.wso2.am.integration.test.helpers.AdminApiTestHelper;
import org.wso2.am.integration.test.impl.DtoFactory;
import org.wso2.am.integration.test.impl.RestAPIStoreImpl;
import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.test.utils.bean.APIRequest;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.admin.client.UserManagementClient;
import javax.ws.rs.core.Response;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class SubscriptionThrottlingPolicyTestCase extends APIMIntegrationBaseTest {
private String displayName = "Test Policy";
private String description = "This is a test subscription throttle policy";
private String timeUnit = "min";
private Integer unitTime = 1;
private Integer graphQLMaxComplexity = 400;
private Integer graphQLMaxDepth = 10;
private Integer rateLimitCount = -1;
private String rateLimitTimeUnit = "NA";
private boolean stopQuotaOnReach = false;
private String billingPlan = "COMMERCIAL";
private Integer subscriberCount = 0;
private List<CustomAttributeDTO> customAttributes = null;
private SubscriptionThrottlePolicyDTO requestCountPolicyDTO;
private SubscriptionThrottlePolicyDTO bandwidthPolicyDTO;
private SubscriptionThrottlePolicyPermissionDTO permissions;
private AdminApiTestHelper adminApiTestHelper;
UserManagementClient userManagementClient1 = null;
private String CREATOR_USER = "testUserCreator";
private String SUBSCRIBER_USER = "testUserSubscriber";
private final String USER_PASSWORD = "123123";
private final String INTERNAL_CREATOR = "Internal/creator";
private final String INTERNAL_PUBLISHER = "Internal/publisher";
private final String INTERNAL_SUBSCRIBER = "Internal/subscriber";
private final String INTERNAL_EVERYONE= "Internal/everyone";
private final String API_END_POINT_METHOD = "/customers/123";
private final String API_NAME = "TestAPI";
private final String API_CONTEXT = "testapi";
private final String API_VERSION = "1.0.0";
private String apiId;
private String app1Id;
private String app2Id;
private String providerName;
private SubscriptionThrottlePolicyDTO sampleSubscriptionThrottlePolicyDTO1;
private SubscriptionThrottlePolicyDTO sampleSubscriptionThrottlePolicyDTO2;
private ArrayList grantTypes;
private List<String> roleList;
@Factory(dataProvider = "userModeDataProvider")
public SubscriptionThrottlingPolicyTestCase(TestUserMode userMode) {
this.userMode = userMode;
}
@DataProvider
public static Object[][] userModeDataProvider() {
return new Object[][]{new Object[]{TestUserMode.SUPER_TENANT_ADMIN},
new Object[]{TestUserMode.TENANT_ADMIN}};
}
@BeforeClass(alwaysRun = true)
public void setEnvironment() throws Exception {
super.init(userMode);
userManagementClient1 = new UserManagementClient(keyManagerContext.getContextUrls().getBackEndUrl(),
createSession(keyManagerContext));
userManagementClient1
.addUser(CREATOR_USER, USER_PASSWORD, new String[] { INTERNAL_CREATOR, INTERNAL_PUBLISHER }, CREATOR_USER);
userManagementClient1
.addUser(SUBSCRIBER_USER, USER_PASSWORD, new String[] { INTERNAL_SUBSCRIBER }, SUBSCRIBER_USER);
providerName = user.getUserName();
adminApiTestHelper = new AdminApiTestHelper();
customAttributes = new ArrayList<>();
CustomAttributeDTO attribute = new CustomAttributeDTO();
attribute.setName("testAttribute");
attribute.setValue("testValue");
customAttributes.add(attribute);
grantTypes = new ArrayList();
grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL);
}
@Test(groups = {"wso2.am"}, description = "Test add subscription throttling policy with request count limit")
public void testAddPolicyWithRequestCountLimit() throws Exception {
//Create the subscription throttling policy DTO with request count limit
String policyName = "TestPolicyOne";
Long requestCount = 50L;
roleList = new ArrayList<>();
roleList.add(INTERNAL_CREATOR);
RequestCountLimitDTO requestCountLimit =
DtoFactory.createRequestCountLimitDTO(timeUnit, unitTime, requestCount);
ThrottleLimitDTO defaultLimit =
DtoFactory.createThrottleLimitDTO(ThrottleLimitDTO.TypeEnum.REQUESTCOUNTLIMIT, requestCountLimit, null);
permissions = DtoFactory.
createSubscriptionThrottlePolicyPermissionDTO(SubscriptionThrottlePolicyPermissionDTO.
PermissionTypeEnum.ALLOW, roleList);
requestCountPolicyDTO = DtoFactory
.createSubscriptionThrottlePolicyDTO(policyName, displayName, description, false, defaultLimit,
graphQLMaxComplexity, graphQLMaxDepth, rateLimitCount, rateLimitTimeUnit, customAttributes,
stopQuotaOnReach, billingPlan, subscriberCount, permissions);
//Add the subscription throttling policy
ApiResponse<SubscriptionThrottlePolicyDTO> addedPolicy =
restAPIAdmin.addSubscriptionThrottlingPolicy(requestCountPolicyDTO);
//Assert the status code and policy ID
Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED);
SubscriptionThrottlePolicyDTO addedPolicyDTO = addedPolicy.getData();
String policyId = addedPolicyDTO.getPolicyId();
Assert.assertNotNull(policyId, "The policy ID cannot be null or empty");
requestCountPolicyDTO.setPolicyId(policyId);
requestCountPolicyDTO.setIsDeployed(true);
//Verify the created subscription throttling policy DTO
adminApiTestHelper.verifySubscriptionThrottlePolicyDTO(requestCountPolicyDTO, addedPolicyDTO);
}
@Test(groups = {"wso2.am"}, description = "Test add subscription throttling policy with bandwidth limit",
dependsOnMethods = "testAddPolicyWithRequestCountLimit")
public void testAddPolicyWithBandwidthLimit() throws Exception {
//Create the subscription throttling policy DTO with bandwidth limit
String policyName = "TestPolicyTwo";
Long dataAmount = 2L;
String dataUnit = "KB";
roleList = new ArrayList<>();
roleList.add(INTERNAL_EVERYONE);
roleList.add(INTERNAL_SUBSCRIBER);
BandwidthLimitDTO bandwidthLimit = DtoFactory.createBandwidthLimitDTO(timeUnit, unitTime, dataAmount, dataUnit);
ThrottleLimitDTO defaultLimit =
DtoFactory.createThrottleLimitDTO(ThrottleLimitDTO.TypeEnum.BANDWIDTHLIMIT, null, bandwidthLimit);
bandwidthPolicyDTO = DtoFactory
.createSubscriptionThrottlePolicyDTO(policyName, displayName, description, false, defaultLimit,
graphQLMaxComplexity, graphQLMaxDepth, rateLimitCount, rateLimitTimeUnit, customAttributes,
stopQuotaOnReach, billingPlan, subscriberCount, permissions);
//Add the subscription throttling policy
ApiResponse<SubscriptionThrottlePolicyDTO> addedPolicy =
restAPIAdmin.addSubscriptionThrottlingPolicy(bandwidthPolicyDTO);
//Assert the status code and policy ID
Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED);
SubscriptionThrottlePolicyDTO addedPolicyDTO = addedPolicy.getData();
String policyId = addedPolicyDTO.getPolicyId();
Assert.assertNotNull(policyId, "The policy ID cannot be null or empty");
bandwidthPolicyDTO.setPolicyId(policyId);
bandwidthPolicyDTO.setIsDeployed(true);
//Verify the created subscription throttling policy DTO
adminApiTestHelper.verifySubscriptionThrottlePolicyDTO(bandwidthPolicyDTO, addedPolicyDTO);
}
@Test(groups = {"wso2.am"}, description = "Test check whether subscription throttling policy works",
dependsOnMethods = "testAddPolicyWithBandwidthLimit")
public void testSubscriptionLevelThrottling() throws Exception {
// Add the subscription throttle policy (10per1hour)
String policyName1 = "SubscriptionThrottlePolicy10per1hour";
RequestCountLimitDTO requestCountLimit1 = DtoFactory.createRequestCountLimitDTO("hour", 1, 10L);
ThrottleLimitDTO defaultLimit1 = DtoFactory.createThrottleLimitDTO(ThrottleLimitDTO.TypeEnum.REQUESTCOUNTLIMIT,
requestCountLimit1, null);
SubscriptionThrottlePolicyPermissionDTO permissions1 = DtoFactory
.createSubscriptionThrottlePolicyPermissionDTO(
SubscriptionThrottlePolicyPermissionDTO.PermissionTypeEnum.ALLOW, roleList);
sampleSubscriptionThrottlePolicyDTO1 = DtoFactory
.createSubscriptionThrottlePolicyDTO(policyName1, policyName1, description, false, defaultLimit1,
graphQLMaxComplexity, graphQLMaxDepth, rateLimitCount, rateLimitTimeUnit, customAttributes,
stopQuotaOnReach, billingPlan, subscriberCount, permissions1);
ApiResponse<SubscriptionThrottlePolicyDTO> addedPolicy1 =
restAPIAdmin.addSubscriptionThrottlingPolicy(sampleSubscriptionThrottlePolicyDTO1);
Assert.assertEquals(addedPolicy1.getStatusCode(), HttpStatus.SC_CREATED);
// Add the subscription throttle policy (20per1hour)
String policyName2 = "SubscriptionThrottlePolicy20per1hour";
RequestCountLimitDTO requestCountLimit2 = DtoFactory.createRequestCountLimitDTO("hour", 1, 20L);
ThrottleLimitDTO defaultLimit2 = DtoFactory.createThrottleLimitDTO(ThrottleLimitDTO.TypeEnum.REQUESTCOUNTLIMIT,
requestCountLimit2, null);
SubscriptionThrottlePolicyPermissionDTO permissions2 = DtoFactory
.createSubscriptionThrottlePolicyPermissionDTO(
SubscriptionThrottlePolicyPermissionDTO.PermissionTypeEnum.ALLOW, roleList);
sampleSubscriptionThrottlePolicyDTO2 = DtoFactory
.createSubscriptionThrottlePolicyDTO(policyName2, policyName2, description, false, defaultLimit2,
graphQLMaxComplexity, graphQLMaxDepth, rateLimitCount, rateLimitTimeUnit, customAttributes,
stopQuotaOnReach, billingPlan, subscriberCount, permissions2);
ApiResponse<SubscriptionThrottlePolicyDTO> addedPolicy2 =
restAPIAdmin.addSubscriptionThrottlingPolicy(sampleSubscriptionThrottlePolicyDTO2);
Assert.assertEquals(addedPolicy2.getStatusCode(), HttpStatus.SC_CREATED);
// Create and publish an API
APIRequest apiRequest;
apiRequest = new APIRequest(API_NAME, API_CONTEXT, new URL(getGatewayURLNhttp() + "response"));
apiRequest.setVersion(API_VERSION);
apiRequest.setTiersCollection(policyName1 + "," + policyName2 + "," + APIMIntegrationConstants.API_TIER.BRONZE
+ "," + "TestPolicyOne");
apiRequest.setProvider(providerName);
HttpResponse apiResponse = restAPIPublisher.addAPI(apiRequest);
Assert.assertEquals(apiResponse.getResponseCode(), Response.Status.CREATED.getStatusCode(),
"Response Code miss matched when creating the API");
apiId = apiResponse.getData();
createAPIRevisionAndDeployUsingRest(apiId, restAPIPublisher);
restAPIPublisher.changeAPILifeCycleStatus(apiId, Constants.PUBLISHED);
waitForAPIDeployment();
// Create an application
ApplicationDTO applicationDTO = restAPIStore.addApplication("App1",
APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "", "TestApp Description");
app1Id = applicationDTO.getApplicationId();
// Subscribe to throttling policy and generate access token
SubscriptionDTO subscriptionDTO = restAPIStore.subscribeToAPI(apiId, app1Id, policyName1);
Assert.assertNotNull(subscriptionDTO);
ApplicationKeyDTO applicationKeyDTO = restAPIStore.generateKeys(app1Id,
APIMIntegrationConstants.DEFAULT_TOKEN_VALIDITY_TIME, "",
ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
Assert.assertNotNull(applicationKeyDTO);
String accessToken1 = applicationKeyDTO.getToken().getAccessToken();
// Invoke API until throttling out
Map<String, String> requestHeaders1 = new HashMap<>();
requestHeaders1.put("Authorization", "Bearer " + accessToken1);
requestHeaders1.put("accept", "text/xml");
requestHeaders1.put("content-type", "application/json");
HttpResponse response1;
boolean isThrottled1 = false;
for (int i = 0; i < 15; i++) {
response1 = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION) + API_END_POINT_METHOD,
requestHeaders1);
if (response1.getResponseCode() == 429) {
Assert.assertTrue(i >= 10);
isThrottled1 = true;
break;
}
Thread.sleep(1000);
}
Assert.assertTrue(isThrottled1, "Request not throttled by " + policyName1);
restAPIStore.removeSubscription(subscriptionDTO);
// Subscribe to throttling policy and generate access token
subscriptionDTO = restAPIStore.subscribeToAPI(apiId, app1Id, policyName2);
Assert.assertNotNull(subscriptionDTO);
String accessToken2 = applicationKeyDTO.getToken().getAccessToken();
// Invoke API until throttling out
Map<String, String> requestHeaders2 = new HashMap<>();
requestHeaders2.put("Authorization", "Bearer " + accessToken2);
requestHeaders2.put("accept", "text/xml");
requestHeaders2.put("content-type", "application/json");
HttpResponse response2;
boolean isThrottled2 = false;
for (int i = 0; i < 25; i++) {
response2 = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION) + API_END_POINT_METHOD,
requestHeaders2);
if (response2.getResponseCode() == 429) {
Assert.assertTrue(i >= 20);
isThrottled2 = true;
break;
}
Thread.sleep(1000);
}
Assert.assertTrue(isThrottled2, "Request not throttled by " + policyName2);
restAPIStore.removeSubscription(subscriptionDTO);
}
@Test(groups = {"wso2.am"}, description = "Test check whether restricted policies can be viewed",
dependsOnMethods = "testSubscriptionLevelThrottling")
public void testCheckPolicyPermission() throws Exception {
restAPIStore = new RestAPIStoreImpl(SUBSCRIBER_USER, USER_PASSWORD,
keyManagerContext.getContextTenant().getDomain(), storeURLHttps);
//Create an application
ApplicationDTO applicationDTO = restAPIStore.addApplication("App2",
APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "", "Applications");
app2Id = applicationDTO.getApplicationId();
ApplicationKeyDTO appDTO = restAPIStore.generateKeys(app2Id,
APIMIntegrationConstants.DEFAULT_TOKEN_VALIDITY_TIME, "",
ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
Assert.assertNotNull(appDTO);
//Subscribe with policy with permission
SubscriptionDTO subscriptionDTO = restAPIStore.subscribeToAPI(apiId, app2Id,
APIMIntegrationConstants.API_TIER.BRONZE);
Assert.assertNotNull(subscriptionDTO);
//Subscribe with policy without permission
try {
restAPIStore.subscribeToAPI(apiId, app2Id, "TestPolicyOne");
} catch (org.wso2.am.integration.clients.store.api.ApiException e) {
Assert.assertEquals(e.getCode(), 403);
Assert.assertTrue(e.getResponseBody().contains("Tier TestPolicyOne is not allowed"));
}
}
@Test(groups = {"wso2.am"}, description = "Test get and update subscription throttling policy",
dependsOnMethods = "testCheckPolicyPermission")
public void testGetAndUpdatePolicy() throws Exception {
//Get the added subscription throttling policy with request count limit
String policyId = requestCountPolicyDTO.getPolicyId();
ApiResponse<SubscriptionThrottlePolicyDTO> retrievedPolicy =
restAPIAdmin.getSubscriptionThrottlingPolicy(policyId);
SubscriptionThrottlePolicyDTO retrievedPolicyDTO = retrievedPolicy.getData();
Assert.assertEquals(retrievedPolicy.getStatusCode(), HttpStatus.SC_OK);
//Verify the retrieved subscription throttling policy DTO
adminApiTestHelper.verifySubscriptionThrottlePolicyDTO(requestCountPolicyDTO, retrievedPolicyDTO);
//Update the subscription throttling policy
String updatedDescription = "This is a updated test subscription throttle policy";
requestCountPolicyDTO.setDescription(updatedDescription);
ApiResponse<SubscriptionThrottlePolicyDTO> updatedPolicy =
restAPIAdmin.updateSubscriptionThrottlingPolicy(policyId, requestCountPolicyDTO);
SubscriptionThrottlePolicyDTO updatedPolicyDTO = updatedPolicy.getData();
Assert.assertEquals(updatedPolicy.getStatusCode(), HttpStatus.SC_OK);
//Verify the updated subscription throttling policy DTO
adminApiTestHelper.verifySubscriptionThrottlePolicyDTO(requestCountPolicyDTO, updatedPolicyDTO);
}
@Test(groups = {"wso2.am"}, description = "Test delete subscription throttling policy",
dependsOnMethods = "testGetAndUpdatePolicy")
public void testDeletePolicy() throws Exception {
ApiResponse<Void> apiResponse =
restAPIAdmin.deleteSubscriptionThrottlingPolicy(requestCountPolicyDTO.getPolicyId());
Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK);
}
@Test(groups = {"wso2.am"}, description = "Test add subscription throttling policy with existing policy name",
dependsOnMethods = "testDeletePolicy")
public void testAddPolicyWithExistingPolicyName() {
//Exception occurs when adding an subscription throttling policy with an existing policy name. The status code
//in the Exception object is used to assert this scenario
try {
restAPIAdmin.addSubscriptionThrottlingPolicy(bandwidthPolicyDTO);
} catch (ApiException e) {
Assert.assertEquals(e.getCode(), HttpStatus.SC_CONFLICT);
}
}
@Test(groups = {"wso2.am"}, description = "Test delete subscription throttling policy with non existing policy ID",
dependsOnMethods = "testAddPolicyWithExistingPolicyName")
public void testDeletePolicyWithNonExistingPolicyId() {
//Exception occurs when deleting an subscription throttling policy with a non existing policy ID. The
//status code in the Exception object is used to assert this scenario
try {
//The policy ID is created by combining two generated UUIDs
restAPIAdmin
.deleteSubscriptionThrottlingPolicy(UUID.randomUUID().toString() + UUID.randomUUID().toString());
} catch (ApiException e) {
Assert.assertEquals(e.getCode(), HttpStatus.SC_NOT_FOUND);
}
}
@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
restAPIAdmin.deleteSubscriptionThrottlingPolicy(bandwidthPolicyDTO.getPolicyId());
restAPIStore.deleteApplication(app1Id);
restAPIStore.deleteApplication(app2Id);
restAPIPublisher.deleteAPI(apiId);
}
}
|
modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/restapi/admin/throttlingpolicy/SubscriptionThrottlingPolicyTestCase.java
|
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.wso2.am.integration.tests.restapi.admin.throttlingpolicy;
import org.apache.http.HttpStatus;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.am.integration.clients.admin.ApiException;
import org.wso2.am.integration.clients.admin.ApiResponse;
import org.wso2.am.integration.clients.admin.api.dto.BandwidthLimitDTO;
import org.wso2.am.integration.clients.admin.api.dto.CustomAttributeDTO;
import org.wso2.am.integration.clients.admin.api.dto.RequestCountLimitDTO;
import org.wso2.am.integration.clients.admin.api.dto.SubscriptionThrottlePolicyDTO;
import org.wso2.am.integration.clients.admin.api.dto.SubscriptionThrottlePolicyPermissionDTO;
import org.wso2.am.integration.clients.admin.api.dto.ThrottleLimitDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.SubscriptionDTO;
import org.wso2.am.integration.test.Constants;
import org.wso2.am.integration.test.helpers.AdminApiTestHelper;
import org.wso2.am.integration.test.impl.DtoFactory;
import org.wso2.am.integration.test.impl.RestAPIStoreImpl;
import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.test.utils.bean.APIRequest;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.admin.client.UserManagementClient;
import javax.ws.rs.core.Response;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class SubscriptionThrottlingPolicyTestCase extends APIMIntegrationBaseTest {
private String displayName = "Test Policy";
private String description = "This is a test subscription throttle policy";
private String timeUnit = "min";
private Integer unitTime = 1;
private Integer graphQLMaxComplexity = 400;
private Integer graphQLMaxDepth = 10;
private Integer rateLimitCount = -1;
private String rateLimitTimeUnit = "NA";
private boolean stopQuotaOnReach = false;
private String billingPlan = "COMMERCIAL";
private Integer subscriberCount = 0;
private List<CustomAttributeDTO> customAttributes = null;
private SubscriptionThrottlePolicyDTO requestCountPolicyDTO;
private SubscriptionThrottlePolicyDTO bandwidthPolicyDTO;
private SubscriptionThrottlePolicyPermissionDTO permissions;
private AdminApiTestHelper adminApiTestHelper;
UserManagementClient userManagementClient1 = null;
private String CREATOR_USER = "testUserCreator";
private String SUBSCRIBER_USER = "testUserSubscriber";
private final String USER_PASSWORD = "123123";
private final String INTERNAL_CREATOR = "Internal/creator";
private final String INTERNAL_PUBLISHER = "Internal/publisher";
private final String INTERNAL_SUBSCRIBER = "Internal/subscriber";
private final String INTERNAL_EVERYONE= "Internal/everyone";
private final String API_END_POINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/";
private String apiEndPointUrl;
private String apiId;
private String appId;
private String tierCollection;
private String providerName;
@Factory(dataProvider = "userModeDataProvider")
public SubscriptionThrottlingPolicyTestCase(TestUserMode userMode) {
this.userMode = userMode;
}
@DataProvider
public static Object[][] userModeDataProvider() {
return new Object[][]{new Object[]{TestUserMode.SUPER_TENANT_ADMIN},
new Object[]{TestUserMode.TENANT_ADMIN}};
}
@BeforeClass(alwaysRun = true)
public void setEnvironment() throws Exception {
super.init(userMode);
userManagementClient1 = new UserManagementClient(keyManagerContext.getContextUrls().getBackEndUrl(),
createSession(keyManagerContext));
userManagementClient1
.addUser(CREATOR_USER, USER_PASSWORD, new String[] { INTERNAL_CREATOR, INTERNAL_PUBLISHER }, CREATOR_USER);
userManagementClient1
.addUser(SUBSCRIBER_USER, USER_PASSWORD, new String[] { INTERNAL_SUBSCRIBER }, SUBSCRIBER_USER);
apiEndPointUrl = backEndServerUrl.getWebAppURLHttp() + API_END_POINT_POSTFIX_URL;
providerName = user.getUserName();
adminApiTestHelper = new AdminApiTestHelper();
customAttributes = new ArrayList<>();
CustomAttributeDTO attribute = new CustomAttributeDTO();
attribute.setName("testAttribute");
attribute.setValue("testValue");
customAttributes.add(attribute);
}
@Test(groups = {"wso2.am"}, description = "Test add subscription throttling policy with request count limit")
public void testAddPolicyWithRequestCountLimit() throws Exception {
//Create the subscription throttling policy DTO with request count limit
String policyName = "TestPolicyOne";
Long requestCount = 50L;
List<String> roleList = new ArrayList<>();
roleList.add(INTERNAL_CREATOR);
RequestCountLimitDTO requestCountLimit =
DtoFactory.createRequestCountLimitDTO(timeUnit, unitTime, requestCount);
ThrottleLimitDTO defaultLimit =
DtoFactory.createThrottleLimitDTO(ThrottleLimitDTO.TypeEnum.REQUESTCOUNTLIMIT, requestCountLimit, null);
permissions = DtoFactory.
createSubscriptionThrottlePolicyPermissionDTO(SubscriptionThrottlePolicyPermissionDTO.
PermissionTypeEnum.ALLOW, roleList);
requestCountPolicyDTO = DtoFactory
.createSubscriptionThrottlePolicyDTO(policyName, displayName, description, false, defaultLimit,
graphQLMaxComplexity, graphQLMaxDepth, rateLimitCount, rateLimitTimeUnit, customAttributes,
stopQuotaOnReach, billingPlan, subscriberCount, permissions);
//Add the subscription throttling policy
ApiResponse<SubscriptionThrottlePolicyDTO> addedPolicy =
restAPIAdmin.addSubscriptionThrottlingPolicy(requestCountPolicyDTO);
//Assert the status code and policy ID
Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED);
SubscriptionThrottlePolicyDTO addedPolicyDTO = addedPolicy.getData();
String policyId = addedPolicyDTO.getPolicyId();
Assert.assertNotNull(policyId, "The policy ID cannot be null or empty");
requestCountPolicyDTO.setPolicyId(policyId);
requestCountPolicyDTO.setIsDeployed(true);
//Verify the created subscription throttling policy DTO
adminApiTestHelper.verifySubscriptionThrottlePolicyDTO(requestCountPolicyDTO, addedPolicyDTO);
}
@Test(groups = {"wso2.am"}, description = "Test add subscription throttling policy with bandwidth limit",
dependsOnMethods = "testAddPolicyWithRequestCountLimit")
public void testAddPolicyWithBandwidthLimit() throws Exception {
//Create the subscription throttling policy DTO with bandwidth limit
String policyName = "TestPolicyTwo";
Long dataAmount = 2L;
String dataUnit = "KB";
List<String> roleList = new ArrayList<>();
roleList.add(INTERNAL_EVERYONE);
roleList.add(INTERNAL_SUBSCRIBER);
BandwidthLimitDTO bandwidthLimit = DtoFactory.createBandwidthLimitDTO(timeUnit, unitTime, dataAmount, dataUnit);
ThrottleLimitDTO defaultLimit =
DtoFactory.createThrottleLimitDTO(ThrottleLimitDTO.TypeEnum.BANDWIDTHLIMIT, null, bandwidthLimit);
bandwidthPolicyDTO = DtoFactory
.createSubscriptionThrottlePolicyDTO(policyName, displayName, description, false, defaultLimit,
graphQLMaxComplexity, graphQLMaxDepth, rateLimitCount, rateLimitTimeUnit, customAttributes,
stopQuotaOnReach, billingPlan, subscriberCount, permissions);
//Add the subscription throttling policy
ApiResponse<SubscriptionThrottlePolicyDTO> addedPolicy =
restAPIAdmin.addSubscriptionThrottlingPolicy(bandwidthPolicyDTO);
//Assert the status code and policy ID
Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED);
SubscriptionThrottlePolicyDTO addedPolicyDTO = addedPolicy.getData();
String policyId = addedPolicyDTO.getPolicyId();
Assert.assertNotNull(policyId, "The policy ID cannot be null or empty");
bandwidthPolicyDTO.setPolicyId(policyId);
bandwidthPolicyDTO.setIsDeployed(true);
//Verify the created subscription throttling policy DTO
adminApiTestHelper.verifySubscriptionThrottlePolicyDTO(bandwidthPolicyDTO, addedPolicyDTO);
}
@Test(groups = {"wso2.am"}, description = "Test get and update subscription throttling policy",
dependsOnMethods = "testAddPolicyWithBandwidthLimit")
public void testGetAndUpdatePolicy() throws Exception {
//Get the added subscription throttling policy with request count limit
String policyId = requestCountPolicyDTO.getPolicyId();
ApiResponse<SubscriptionThrottlePolicyDTO> retrievedPolicy =
restAPIAdmin.getSubscriptionThrottlingPolicy(policyId);
SubscriptionThrottlePolicyDTO retrievedPolicyDTO = retrievedPolicy.getData();
Assert.assertEquals(retrievedPolicy.getStatusCode(), HttpStatus.SC_OK);
//Verify the retrieved subscription throttling policy DTO
adminApiTestHelper.verifySubscriptionThrottlePolicyDTO(requestCountPolicyDTO, retrievedPolicyDTO);
//Update the subscription throttling policy
String updatedDescription = "This is a updated test subscription throttle policy";
requestCountPolicyDTO.setDescription(updatedDescription);
ApiResponse<SubscriptionThrottlePolicyDTO> updatedPolicy =
restAPIAdmin.updateSubscriptionThrottlingPolicy(policyId, requestCountPolicyDTO);
SubscriptionThrottlePolicyDTO updatedPolicyDTO = updatedPolicy.getData();
Assert.assertEquals(updatedPolicy.getStatusCode(), HttpStatus.SC_OK);
//Verify the updated subscription throttling policy DTO
adminApiTestHelper.verifySubscriptionThrottlePolicyDTO(requestCountPolicyDTO, updatedPolicyDTO);
}
@Test(groups = {"wso2.am"}, description = "Test delete subscription throttling policy",
dependsOnMethods = "testGetAndUpdatePolicy")
public void testDeletePolicy() throws Exception {
ApiResponse<Void> apiResponse =
restAPIAdmin.deleteSubscriptionThrottlingPolicy(requestCountPolicyDTO.getPolicyId());
Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK);
}
@Test(groups = {"wso2.am"}, description = "Test add subscription throttling policy with existing policy name",
dependsOnMethods = "testDeletePolicy")
public void testAddPolicyWithExistingPolicyName() {
//Exception occurs when adding an subscription throttling policy with an existing policy name. The status code
//in the Exception object is used to assert this scenario
try {
restAPIAdmin.addSubscriptionThrottlingPolicy(bandwidthPolicyDTO);
} catch (ApiException e) {
Assert.assertEquals(e.getCode(), HttpStatus.SC_CONFLICT);
}
}
@Test(groups = {"wso2.am"}, description = "Test delete subscription throttling policy with non existing policy ID",
dependsOnMethods = "testAddPolicyWithExistingPolicyName")
public void testDeletePolicyWithNonExistingPolicyId() {
//Exception occurs when deleting an subscription throttling policy with a non existing policy ID. The
//status code in the Exception object is used to assert this scenario
try {
//The policy ID is created by combining two generated UUIDs
restAPIAdmin
.deleteSubscriptionThrottlingPolicy(UUID.randomUUID().toString() + UUID.randomUUID().toString());
} catch (ApiException e) {
Assert.assertEquals(e.getCode(), HttpStatus.SC_NOT_FOUND);
}
}
@Test(groups = {"wso2.am"}, description = "Test check whether restricted policies can be viewed",
dependsOnMethods = "testAddPolicyWithRequestCountLimit")
public void testCheckPolicyPermission() throws Exception {
// Create an API
tierCollection = APIMIntegrationConstants.API_TIER.BRONZE + "," + "TestPolicyOne";
APIRequest apiRequest;
apiRequest = new APIRequest("SubscriptionThrottlingAPI", "SubscriptionThrottlingPolicy",
new URL(apiEndPointUrl));
apiRequest.setVersion("1.0.0");
apiRequest.setTiersCollection(tierCollection);
apiRequest.setProvider(providerName);
HttpResponse apiResponse = restAPIPublisher.addAPI(apiRequest);
apiId = apiResponse.getData();
Assert.assertEquals(apiResponse.getResponseCode(), Response.Status.CREATED.getStatusCode(),
"Response Code miss matched when creating the API");
restAPIPublisher.changeAPILifeCycleStatus(apiId, Constants.PUBLISHED);
restAPIStore = new RestAPIStoreImpl(SUBSCRIBER_USER, USER_PASSWORD,
keyManagerContext.getContextTenant().getDomain(), storeURLHttps);
//Create an application
ArrayList grantTypes = new ArrayList();
grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL);
ApplicationDTO applicationDTO = restAPIStore.addApplication("App1",
APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "", "Applications");
appId = applicationDTO.getApplicationId();
ApplicationKeyDTO appDTO = restAPIStore.generateKeys(appId,
APIMIntegrationConstants.DEFAULT_TOKEN_VALIDITY_TIME, "",
ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
Assert.assertNotNull(appDTO);
//Subscribe with policy with permission
SubscriptionDTO subscriptionDTO = restAPIStore.subscribeToAPI(apiId, appId,
APIMIntegrationConstants.API_TIER.BRONZE);
Assert.assertNotNull(subscriptionDTO);
//Subscribe with policy without permission
try {
restAPIStore.subscribeToAPI(apiId, appId, "TestPolicyOne");
} catch (org.wso2.am.integration.clients.store.api.ApiException e) {
Assert.assertEquals(e.getCode(), 403);
Assert.assertTrue(e.getResponseBody().contains("Tier TestPolicyOne is not allowed for" +
" user testUserSubscribe"));
}
}
@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
restAPIAdmin.deleteSubscriptionThrottlingPolicy(bandwidthPolicyDTO.getPolicyId());
restAPIStore.deleteApplication(appId);
restAPIPublisher.deleteAPI(apiId);
}
}
|
Add integration tests for subscription throttle policy update
|
modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/restapi/admin/throttlingpolicy/SubscriptionThrottlingPolicyTestCase.java
|
Add integration tests for subscription throttle policy update
|
<ide><path>odules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/restapi/admin/throttlingpolicy/SubscriptionThrottlingPolicyTestCase.java
<ide> import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
<ide> import org.wso2.am.integration.test.utils.bean.APIRequest;
<ide> import org.wso2.carbon.automation.engine.context.TestUserMode;
<add>import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
<ide> import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
<ide> import org.wso2.carbon.integration.common.admin.client.UserManagementClient;
<ide>
<ide> import javax.ws.rs.core.Response;
<ide> import java.net.URL;
<ide> import java.util.ArrayList;
<add>import java.util.HashMap;
<ide> import java.util.List;
<add>import java.util.Map;
<ide> import java.util.UUID;
<ide>
<ide> public class SubscriptionThrottlingPolicyTestCase extends APIMIntegrationBaseTest {
<ide> private final String INTERNAL_PUBLISHER = "Internal/publisher";
<ide> private final String INTERNAL_SUBSCRIBER = "Internal/subscriber";
<ide> private final String INTERNAL_EVERYONE= "Internal/everyone";
<del> private final String API_END_POINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/";
<del> private String apiEndPointUrl;
<add> private final String API_END_POINT_METHOD = "/customers/123";
<add> private final String API_NAME = "TestAPI";
<add> private final String API_CONTEXT = "testapi";
<add> private final String API_VERSION = "1.0.0";
<ide> private String apiId;
<del> private String appId;
<del> private String tierCollection;
<add> private String app1Id;
<add> private String app2Id;
<ide> private String providerName;
<add> private SubscriptionThrottlePolicyDTO sampleSubscriptionThrottlePolicyDTO1;
<add> private SubscriptionThrottlePolicyDTO sampleSubscriptionThrottlePolicyDTO2;
<add> private ArrayList grantTypes;
<add> private List<String> roleList;
<ide>
<ide> @Factory(dataProvider = "userModeDataProvider")
<ide> public SubscriptionThrottlingPolicyTestCase(TestUserMode userMode) {
<ide> .addUser(CREATOR_USER, USER_PASSWORD, new String[] { INTERNAL_CREATOR, INTERNAL_PUBLISHER }, CREATOR_USER);
<ide> userManagementClient1
<ide> .addUser(SUBSCRIBER_USER, USER_PASSWORD, new String[] { INTERNAL_SUBSCRIBER }, SUBSCRIBER_USER);
<del> apiEndPointUrl = backEndServerUrl.getWebAppURLHttp() + API_END_POINT_POSTFIX_URL;
<ide> providerName = user.getUserName();
<ide> adminApiTestHelper = new AdminApiTestHelper();
<ide> customAttributes = new ArrayList<>();
<ide> attribute.setName("testAttribute");
<ide> attribute.setValue("testValue");
<ide> customAttributes.add(attribute);
<add> grantTypes = new ArrayList();
<add> grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL);
<ide> }
<ide>
<ide> @Test(groups = {"wso2.am"}, description = "Test add subscription throttling policy with request count limit")
<ide> //Create the subscription throttling policy DTO with request count limit
<ide> String policyName = "TestPolicyOne";
<ide> Long requestCount = 50L;
<del> List<String> roleList = new ArrayList<>();
<add> roleList = new ArrayList<>();
<ide> roleList.add(INTERNAL_CREATOR);
<ide> RequestCountLimitDTO requestCountLimit =
<ide> DtoFactory.createRequestCountLimitDTO(timeUnit, unitTime, requestCount);
<ide> String policyName = "TestPolicyTwo";
<ide> Long dataAmount = 2L;
<ide> String dataUnit = "KB";
<del> List<String> roleList = new ArrayList<>();
<add> roleList = new ArrayList<>();
<ide> roleList.add(INTERNAL_EVERYONE);
<ide> roleList.add(INTERNAL_SUBSCRIBER);
<ide>
<ide> adminApiTestHelper.verifySubscriptionThrottlePolicyDTO(bandwidthPolicyDTO, addedPolicyDTO);
<ide> }
<ide>
<add> @Test(groups = {"wso2.am"}, description = "Test check whether subscription throttling policy works",
<add> dependsOnMethods = "testAddPolicyWithBandwidthLimit")
<add> public void testSubscriptionLevelThrottling() throws Exception {
<add>
<add> // Add the subscription throttle policy (10per1hour)
<add> String policyName1 = "SubscriptionThrottlePolicy10per1hour";
<add> RequestCountLimitDTO requestCountLimit1 = DtoFactory.createRequestCountLimitDTO("hour", 1, 10L);
<add> ThrottleLimitDTO defaultLimit1 = DtoFactory.createThrottleLimitDTO(ThrottleLimitDTO.TypeEnum.REQUESTCOUNTLIMIT,
<add> requestCountLimit1, null);
<add> SubscriptionThrottlePolicyPermissionDTO permissions1 = DtoFactory
<add> .createSubscriptionThrottlePolicyPermissionDTO(
<add> SubscriptionThrottlePolicyPermissionDTO.PermissionTypeEnum.ALLOW, roleList);
<add> sampleSubscriptionThrottlePolicyDTO1 = DtoFactory
<add> .createSubscriptionThrottlePolicyDTO(policyName1, policyName1, description, false, defaultLimit1,
<add> graphQLMaxComplexity, graphQLMaxDepth, rateLimitCount, rateLimitTimeUnit, customAttributes,
<add> stopQuotaOnReach, billingPlan, subscriberCount, permissions1);
<add> ApiResponse<SubscriptionThrottlePolicyDTO> addedPolicy1 =
<add> restAPIAdmin.addSubscriptionThrottlingPolicy(sampleSubscriptionThrottlePolicyDTO1);
<add> Assert.assertEquals(addedPolicy1.getStatusCode(), HttpStatus.SC_CREATED);
<add>
<add> // Add the subscription throttle policy (20per1hour)
<add> String policyName2 = "SubscriptionThrottlePolicy20per1hour";
<add> RequestCountLimitDTO requestCountLimit2 = DtoFactory.createRequestCountLimitDTO("hour", 1, 20L);
<add> ThrottleLimitDTO defaultLimit2 = DtoFactory.createThrottleLimitDTO(ThrottleLimitDTO.TypeEnum.REQUESTCOUNTLIMIT,
<add> requestCountLimit2, null);
<add> SubscriptionThrottlePolicyPermissionDTO permissions2 = DtoFactory
<add> .createSubscriptionThrottlePolicyPermissionDTO(
<add> SubscriptionThrottlePolicyPermissionDTO.PermissionTypeEnum.ALLOW, roleList);
<add> sampleSubscriptionThrottlePolicyDTO2 = DtoFactory
<add> .createSubscriptionThrottlePolicyDTO(policyName2, policyName2, description, false, defaultLimit2,
<add> graphQLMaxComplexity, graphQLMaxDepth, rateLimitCount, rateLimitTimeUnit, customAttributes,
<add> stopQuotaOnReach, billingPlan, subscriberCount, permissions2);
<add> ApiResponse<SubscriptionThrottlePolicyDTO> addedPolicy2 =
<add> restAPIAdmin.addSubscriptionThrottlingPolicy(sampleSubscriptionThrottlePolicyDTO2);
<add> Assert.assertEquals(addedPolicy2.getStatusCode(), HttpStatus.SC_CREATED);
<add>
<add> // Create and publish an API
<add> APIRequest apiRequest;
<add> apiRequest = new APIRequest(API_NAME, API_CONTEXT, new URL(getGatewayURLNhttp() + "response"));
<add> apiRequest.setVersion(API_VERSION);
<add> apiRequest.setTiersCollection(policyName1 + "," + policyName2 + "," + APIMIntegrationConstants.API_TIER.BRONZE
<add> + "," + "TestPolicyOne");
<add> apiRequest.setProvider(providerName);
<add> HttpResponse apiResponse = restAPIPublisher.addAPI(apiRequest);
<add> Assert.assertEquals(apiResponse.getResponseCode(), Response.Status.CREATED.getStatusCode(),
<add> "Response Code miss matched when creating the API");
<add> apiId = apiResponse.getData();
<add> createAPIRevisionAndDeployUsingRest(apiId, restAPIPublisher);
<add> restAPIPublisher.changeAPILifeCycleStatus(apiId, Constants.PUBLISHED);
<add> waitForAPIDeployment();
<add>
<add> // Create an application
<add> ApplicationDTO applicationDTO = restAPIStore.addApplication("App1",
<add> APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "", "TestApp Description");
<add> app1Id = applicationDTO.getApplicationId();
<add>
<add> // Subscribe to throttling policy and generate access token
<add> SubscriptionDTO subscriptionDTO = restAPIStore.subscribeToAPI(apiId, app1Id, policyName1);
<add> Assert.assertNotNull(subscriptionDTO);
<add> ApplicationKeyDTO applicationKeyDTO = restAPIStore.generateKeys(app1Id,
<add> APIMIntegrationConstants.DEFAULT_TOKEN_VALIDITY_TIME, "",
<add> ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
<add> Assert.assertNotNull(applicationKeyDTO);
<add> String accessToken1 = applicationKeyDTO.getToken().getAccessToken();
<add>
<add> // Invoke API until throttling out
<add> Map<String, String> requestHeaders1 = new HashMap<>();
<add> requestHeaders1.put("Authorization", "Bearer " + accessToken1);
<add> requestHeaders1.put("accept", "text/xml");
<add> requestHeaders1.put("content-type", "application/json");
<add> HttpResponse response1;
<add> boolean isThrottled1 = false;
<add> for (int i = 0; i < 15; i++) {
<add> response1 = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION) + API_END_POINT_METHOD,
<add> requestHeaders1);
<add> if (response1.getResponseCode() == 429) {
<add> Assert.assertTrue(i >= 10);
<add> isThrottled1 = true;
<add> break;
<add> }
<add> Thread.sleep(1000);
<add> }
<add> Assert.assertTrue(isThrottled1, "Request not throttled by " + policyName1);
<add> restAPIStore.removeSubscription(subscriptionDTO);
<add>
<add> // Subscribe to throttling policy and generate access token
<add> subscriptionDTO = restAPIStore.subscribeToAPI(apiId, app1Id, policyName2);
<add> Assert.assertNotNull(subscriptionDTO);
<add> String accessToken2 = applicationKeyDTO.getToken().getAccessToken();
<add>
<add> // Invoke API until throttling out
<add> Map<String, String> requestHeaders2 = new HashMap<>();
<add> requestHeaders2.put("Authorization", "Bearer " + accessToken2);
<add> requestHeaders2.put("accept", "text/xml");
<add> requestHeaders2.put("content-type", "application/json");
<add> HttpResponse response2;
<add> boolean isThrottled2 = false;
<add> for (int i = 0; i < 25; i++) {
<add> response2 = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION) + API_END_POINT_METHOD,
<add> requestHeaders2);
<add> if (response2.getResponseCode() == 429) {
<add> Assert.assertTrue(i >= 20);
<add> isThrottled2 = true;
<add> break;
<add> }
<add> Thread.sleep(1000);
<add> }
<add> Assert.assertTrue(isThrottled2, "Request not throttled by " + policyName2);
<add> restAPIStore.removeSubscription(subscriptionDTO);
<add> }
<add>
<add> @Test(groups = {"wso2.am"}, description = "Test check whether restricted policies can be viewed",
<add> dependsOnMethods = "testSubscriptionLevelThrottling")
<add> public void testCheckPolicyPermission() throws Exception {
<add>
<add> restAPIStore = new RestAPIStoreImpl(SUBSCRIBER_USER, USER_PASSWORD,
<add> keyManagerContext.getContextTenant().getDomain(), storeURLHttps);
<add> //Create an application
<add> ApplicationDTO applicationDTO = restAPIStore.addApplication("App2",
<add> APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "", "Applications");
<add> app2Id = applicationDTO.getApplicationId();
<add> ApplicationKeyDTO appDTO = restAPIStore.generateKeys(app2Id,
<add> APIMIntegrationConstants.DEFAULT_TOKEN_VALIDITY_TIME, "",
<add> ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
<add> Assert.assertNotNull(appDTO);
<add>
<add> //Subscribe with policy with permission
<add> SubscriptionDTO subscriptionDTO = restAPIStore.subscribeToAPI(apiId, app2Id,
<add> APIMIntegrationConstants.API_TIER.BRONZE);
<add> Assert.assertNotNull(subscriptionDTO);
<add>
<add> //Subscribe with policy without permission
<add> try {
<add> restAPIStore.subscribeToAPI(apiId, app2Id, "TestPolicyOne");
<add> } catch (org.wso2.am.integration.clients.store.api.ApiException e) {
<add> Assert.assertEquals(e.getCode(), 403);
<add> Assert.assertTrue(e.getResponseBody().contains("Tier TestPolicyOne is not allowed"));
<add> }
<add> }
<add>
<ide> @Test(groups = {"wso2.am"}, description = "Test get and update subscription throttling policy",
<del> dependsOnMethods = "testAddPolicyWithBandwidthLimit")
<add> dependsOnMethods = "testCheckPolicyPermission")
<ide> public void testGetAndUpdatePolicy() throws Exception {
<ide>
<ide> //Get the added subscription throttling policy with request count limit
<ide> }
<ide> }
<ide>
<del> @Test(groups = {"wso2.am"}, description = "Test check whether restricted policies can be viewed",
<del> dependsOnMethods = "testAddPolicyWithRequestCountLimit")
<del> public void testCheckPolicyPermission() throws Exception {
<del> // Create an API
<del> tierCollection = APIMIntegrationConstants.API_TIER.BRONZE + "," + "TestPolicyOne";
<del> APIRequest apiRequest;
<del> apiRequest = new APIRequest("SubscriptionThrottlingAPI", "SubscriptionThrottlingPolicy",
<del> new URL(apiEndPointUrl));
<del> apiRequest.setVersion("1.0.0");
<del> apiRequest.setTiersCollection(tierCollection);
<del> apiRequest.setProvider(providerName);
<del>
<del> HttpResponse apiResponse = restAPIPublisher.addAPI(apiRequest);
<del> apiId = apiResponse.getData();
<del> Assert.assertEquals(apiResponse.getResponseCode(), Response.Status.CREATED.getStatusCode(),
<del> "Response Code miss matched when creating the API");
<del>
<del> restAPIPublisher.changeAPILifeCycleStatus(apiId, Constants.PUBLISHED);
<del>
<del> restAPIStore = new RestAPIStoreImpl(SUBSCRIBER_USER, USER_PASSWORD,
<del> keyManagerContext.getContextTenant().getDomain(), storeURLHttps);
<del> //Create an application
<del> ArrayList grantTypes = new ArrayList();
<del> grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL);
<del> ApplicationDTO applicationDTO = restAPIStore.addApplication("App1",
<del> APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "", "Applications");
<del> appId = applicationDTO.getApplicationId();
<del> ApplicationKeyDTO appDTO = restAPIStore.generateKeys(appId,
<del> APIMIntegrationConstants.DEFAULT_TOKEN_VALIDITY_TIME, "",
<del> ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
<del> Assert.assertNotNull(appDTO);
<del>
<del> //Subscribe with policy with permission
<del> SubscriptionDTO subscriptionDTO = restAPIStore.subscribeToAPI(apiId, appId,
<del> APIMIntegrationConstants.API_TIER.BRONZE);
<del> Assert.assertNotNull(subscriptionDTO);
<del>
<del> //Subscribe with policy without permission
<del> try {
<del> restAPIStore.subscribeToAPI(apiId, appId, "TestPolicyOne");
<del> } catch (org.wso2.am.integration.clients.store.api.ApiException e) {
<del> Assert.assertEquals(e.getCode(), 403);
<del> Assert.assertTrue(e.getResponseBody().contains("Tier TestPolicyOne is not allowed for" +
<del> " user testUserSubscribe"));
<del> }
<del> }
<del>
<del>
<ide> @AfterClass(alwaysRun = true)
<ide> public void destroy() throws Exception {
<ide> restAPIAdmin.deleteSubscriptionThrottlingPolicy(bandwidthPolicyDTO.getPolicyId());
<del> restAPIStore.deleteApplication(appId);
<add> restAPIStore.deleteApplication(app1Id);
<add> restAPIStore.deleteApplication(app2Id);
<ide> restAPIPublisher.deleteAPI(apiId);
<ide> }
<ide> }
|
|
JavaScript
|
epl-1.0
|
97b9e6697ce579c2dac31a50a6548b01f03711d5
| 0 |
cscheid/lux,cscheid/lux,cscheid/lux
|
Facet.DrawingMode.additive = {
set_caps: function()
{
var ctx = Facet.ctx;
ctx.enable(ctx.BLEND);
ctx.blendFunc(ctx.SRC_ALPHA, ctx.ONE);
}
};
|
src/facet/drawing_mode/additive.js
|
Facet.DrawingMode.additive = {
set_caps: function()
{
var ctx = Facet.ctx;
ctx.enable(ctx.BLEND);
ctx.blendFunc(ctx.ONE, ctx.ONE);
}
};
|
reverted additive blending
|
src/facet/drawing_mode/additive.js
|
reverted additive blending
|
<ide><path>rc/facet/drawing_mode/additive.js
<ide> {
<ide> var ctx = Facet.ctx;
<ide> ctx.enable(ctx.BLEND);
<del> ctx.blendFunc(ctx.ONE, ctx.ONE);
<add> ctx.blendFunc(ctx.SRC_ALPHA, ctx.ONE);
<ide> }
<ide> };
|
|
Java
|
mit
|
d332aad6bf37011c8c9d4a131ca2c3b20578754c
| 0 |
RedTroop/Cubes_2,RedTroop/Cubes_2,ictrobot/Cubes,ictrobot/Cubes
|
package ethanjones.cubes.world.generator.smooth;
import ethanjones.cubes.core.logging.Log;
import ethanjones.cubes.side.common.Cubes;
import ethanjones.cubes.world.reference.AreaReference;
import ethanjones.cubes.world.reference.BlockReference;
import ethanjones.cubes.world.server.WorldServer;
import ethanjones.cubes.world.storage.Area;
import com.badlogic.gdx.math.RandomXS128;
import com.badlogic.gdx.utils.IntArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static ethanjones.cubes.world.generator.smooth.SmoothWorld.minSurfaceHeight;
import static ethanjones.cubes.world.generator.smooth.SmoothWorld.murmurHash3;
public class CaveGenerator {
public static final int roomNodesMin = 25;
public static final int roomNodesMax = 100;
public static final int roomChangeXZConstant = 10;
public static final int roomChangeXZRandom = 15;
public static final int roomChangeY = 10;
public static final int roomConnectDistanceMin = 5;
public static final int roomConnectDistanceMax = 75;
public final int caveStartX;
public final int caveStartY;
public final int caveStartZ;
private final SmoothWorld smoothWorld;
private final RandomXS128 numbers;
private final HashMap<AreaReference, IntArray> blocks = new HashMap<AreaReference, IntArray>();
private final ArrayList<RoomNode> rooms = new ArrayList<RoomNode>();
private final ArrayList<TunnelNode> tunnels = new ArrayList<TunnelNode>();
public CaveGenerator(int x, int z, SmoothWorld smoothWorld) {
this.caveStartX = x;
this.caveStartY = smoothWorld.getSurfaceHeight(x, z);
this.caveStartZ = z;
this.smoothWorld = smoothWorld;
long l = x + z + (x * (x - 1)) + (z * (z + 1)) + (long) Math.pow(x, z > 0 ? z : (z < 0 ? -z : 1));
this.numbers = new RandomXS128(smoothWorld.baseSeed, murmurHash3(smoothWorld.baseSeed + murmurHash3(l)));
}
public Cave generate() {
int spawnDist = (int) distanceFromSpawn(caveStartX, caveStartZ);
Log.debug("Generating new cave at " + caveStartX + "," + caveStartZ + " (" + spawnDist + " blocks from spawn)");
generateNodes();
calculateBlocks();
Cave cave = new Cave(caveStartX, caveStartY, caveStartZ, new HashMap<AreaReference, int[]>() {{
for (Map.Entry<AreaReference, IntArray> entry : blocks.entrySet()) {
this.put(entry.getKey(), entry.getValue().toArray());
}
}});
return cave;
}
private void clear(int blockX, int blockY, int blockZ) {
if (blockY <= 0) return;
AreaReference areaReference = new AreaReference().setFromBlockCoordinates(blockX, blockZ);
IntArray array = blocks.get(areaReference);
if (array == null) {
array = new IntArray();
blocks.put(areaReference, array);
}
array.add(Area.getRef(blockX - areaReference.minBlockX(), blockY, blockZ - areaReference.minBlockZ()));
}
public void generateNodes() {
// make rooms
rooms.add(new RoomNode(caveStartX, caveStartY, caveStartZ, 0, null));
int num = 0;
while (num <= roomNodesMax) {
RoomNode randomNode = rooms.get(numbers.nextInt(rooms.size()));
boolean allowSurface = num <= (roomNodesMin / 4);
int finalX = randomNode.location.blockX + getRoomChangeXZ();
int finalZ = randomNode.location.blockZ + getRoomChangeXZ();
if (inRange(finalX, finalZ)) {
int offsetY = numbers.nextInt((roomChangeY * 2) + 1) - roomChangeY;
int finalY = undergroundY(finalX, finalZ, randomNode.location.blockY, offsetY, allowSurface);
rooms.add(new RoomNode(finalX, finalY, finalZ, 1 + numbers.nextInt(2), randomNode));
}
if (num >= roomNodesMin && numbers.nextInt((roomNodesMax - roomNodesMin) - num) == 0) break;
num++;
}
// make tunnels
ArrayList<TunnelNode> straightTunnels = new ArrayList<TunnelNode>();
for (int i = 0; i < rooms.size(); i++) {
RoomNode roomNode = rooms.get(i);
if (roomNode.connect != null) straightTunnels.add(new TunnelNode(roomNode.location, roomNode.connect.location));
int roomConnections = 0;
for (int j = 0; j < 25; j++) {
RoomNode other = rooms.get(numbers.nextInt(rooms.size()));
if (other == roomNode || other == roomNode.connect) continue;
float roomDistance = distance(roomNode.location, other.location);
if (roomDistance < roomConnectDistanceMin || roomDistance > roomConnectDistanceMax) continue;
straightTunnels.add(new TunnelNode(roomNode.location, other.location));
roomConnections++;
if (roomConnections == 2) break;
}
}
// make bends in tunnels
ArrayList<BlockReference> tunnelSections = new ArrayList<BlockReference>();
for (TunnelNode tunnelNode : straightTunnels) {
BlockReference a = tunnelNode.start;
BlockReference b = tunnelNode.end;
int dX = a.blockX - b.blockX;
int dY = a.blockY - b.blockY;
int dZ = a.blockZ - b.blockZ;
int dist = (int) Math.sqrt(dX * dX + dY * dX + dZ * dZ);
int numTurns = 1 + (dist / 10) + (dist / 5 == 0 ? 0 : numbers.nextInt(dist / 5));
float turnXZChange = (float) Math.sqrt(dX * dX + dZ * dZ) / (float) numTurns;
tunnelSections.clear();
tunnelSections.add(a);
for (int i = 1; i <= numTurns; i++) {
float f = (float) i / ((float) numTurns + 1f);
int x = b.blockX + (int) (dX * f);
int y = b.blockY + (int) (dY * f);
int z = b.blockZ + (int) (dZ * f);
int randomX = (int) (((4 * numbers.nextFloat()) - 2f) * turnXZChange);
int randomY = numbers.nextInt(3) - 1;
int randomZ = (int) (((4 * numbers.nextFloat()) - 2f) * turnXZChange);
int finalX = x + randomX;
int finalY = y + randomY;
int finalZ = z + randomZ;
tunnelSections.add(new BlockReference().setFromBlockCoordinates(finalX, finalY, finalZ));
}
tunnelSections.add(b);
for (int i = 0; i + 1 < tunnelSections.size(); i++) {
tunnels.add(new TunnelNode(tunnelSections.get(i), tunnelSections.get(i + 1)));
}
}
}
private void calculateBlocks() {
for (RoomNode room : rooms) {
int roomX = room.location.blockX;
int roomY = room.location.blockY;
int roomZ = room.location.blockZ;
int r = room.size;
int r2 = r * r;
for (int x = roomX - r; x <= roomX + r; x++) {
for (int y = roomY - r; y <= roomY + r; y++) {
for (int z = roomZ - r; z <= roomZ + r; z++) {
int dX = roomX - x;
int dY = roomY - y;
int dZ = roomZ - z;
if (dX * dX + dY * dY + dZ * dZ <= r2) {
clear(x, y, z);
}
}
}
}
}
for (TunnelNode tunnel : tunnels) {
int r = 2;
int cX = tunnel.end.blockX - tunnel.start.blockX >= 0 ? 1 : -1;
int cY = tunnel.end.blockY - tunnel.start.blockY >= 0 ? 1 : -1;
int cZ = tunnel.end.blockZ - tunnel.start.blockZ >= 0 ? 1 : -1;
int startX = tunnel.start.blockX - (cX * r);
int startY = tunnel.start.blockY - (cY * r);
int startZ = tunnel.start.blockZ - (cZ * r);
int endX = tunnel.end.blockX + (cX * r);
int endY = tunnel.end.blockY + (cY * r);
int endZ = tunnel.end.blockZ + (cZ * r);
BlockReference temp = new BlockReference();
for (int x = startX; x <= endX; x += cX) {
for (int y = startY; y <= endY; y += cY) {
for (int z = startZ; z <= endZ; z += cZ) {
temp.setFromBlockCoordinates(x, y, z);
float radius;
if (distance(tunnel.start, temp) < distance(tunnel.end, temp)) {
radius = tunnel.startRadius;
} else {
radius = tunnel.endRadius;
}
if (distanceFromLine(tunnel.start, tunnel.end, temp.setFromBlockCoordinates(x, y, z)) <= radius) {
clear(x, y, z);
}
}
}
}
}
}
private int getRoomChangeXZ() {
int rand = numbers.nextInt((roomChangeXZRandom * 2) + 1) - roomChangeXZRandom;
return rand + (rand < 0 ? -roomChangeXZConstant : roomChangeXZConstant);
}
private int undergroundY(int x, int z, int prevY, int changeY, boolean allowSurface) {
int y = prevY + changeY;
if (y < 10) return 10;
if (y < minSurfaceHeight) return y;
int height = smoothWorld.getSurfaceHeight(x, z);
while (y > height - (allowSurface ? -1 : 8) && y >= 10)
y--;
return y;
}
private boolean inRange(int x, int z) {
int dX = Math.abs(caveStartX - x);
int dZ = Math.abs(caveStartZ - z);
return dX < CaveManager.caveSafeBlockRadius && dZ < CaveManager.caveSafeBlockRadius;
}
private static float distanceFromLine(BlockReference start, BlockReference end, BlockReference location) {
float a = distance(start, location);
float b = distance(end, location);
float c = distance(start, end);
float s = (a + b + c) / 2f;
float area = (float) Math.sqrt(s * (s - a) * (s - b) * (s - c));
return (area * 2) / c;
}
public float distanceFromSpawn(int x, int z) {
BlockReference spawnPoint = smoothWorld.spawnPoint(((WorldServer) Cubes.getServer().world));
int dX = x - spawnPoint.blockX;
int dZ = z - spawnPoint.blockZ;
return (float) Math.sqrt(dX * dX + dZ * dZ);
}
private static float distance(BlockReference a, BlockReference b) {
int dX = a.blockX - b.blockX;
int dY = a.blockY - b.blockY;
int dZ = a.blockZ - b.blockZ;
return (float) Math.sqrt(dX * dX + dY * dY + dZ * dZ);
}
private class TunnelNode {
BlockReference start;
BlockReference end;
float startRadius = (float) (1.5f + (numbers.nextFloat() * 1.5));
float endRadius = (float) (1.5f + (numbers.nextFloat() * 1.5));
private TunnelNode(BlockReference start, BlockReference end) {
this.start = start;
this.end = end;
}
}
private class RoomNode {
BlockReference location;
RoomNode connect;
int size;
private RoomNode(int blockX, int blockY, int blockZ, int size, RoomNode connect) {
this.location = new BlockReference().setFromBlockCoordinates(blockX, blockY, blockZ);
this.connect = connect;
this.size = size;
}
}
}
|
core/src/ethanjones/cubes/world/generator/smooth/CaveGenerator.java
|
package ethanjones.cubes.world.generator.smooth;
import ethanjones.cubes.core.logging.Log;
import ethanjones.cubes.side.common.Cubes;
import ethanjones.cubes.world.reference.AreaReference;
import ethanjones.cubes.world.reference.BlockReference;
import ethanjones.cubes.world.server.WorldServer;
import ethanjones.cubes.world.storage.Area;
import com.badlogic.gdx.math.RandomXS128;
import com.badlogic.gdx.utils.IntArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static ethanjones.cubes.world.generator.smooth.SmoothWorld.minSurfaceHeight;
import static ethanjones.cubes.world.generator.smooth.SmoothWorld.murmurHash3;
public class CaveGenerator {
public static final int roomNodesMin = 25;
public static final int roomNodesMax = 100;
public static final int roomChangeXZConstant = 10;
public static final int roomChangeXZRandom = 15;
public static final int roomChangeY = 10;
public static final int roomConnectDistanceMin = 5;
public static final int roomConnectDistanceMax = 75;
public final int caveStartX;
public final int caveStartY;
public final int caveStartZ;
private final SmoothWorld smoothWorld;
private final RandomXS128 numbers;
private final HashMap<AreaReference, IntArray> blocks = new HashMap<AreaReference, IntArray>();
private final ArrayList<RoomNode> rooms = new ArrayList<RoomNode>();
private final ArrayList<TunnelNode> tunnels = new ArrayList<TunnelNode>();
public CaveGenerator(int x, int z, SmoothWorld smoothWorld) {
this.caveStartX = x;
this.caveStartY = smoothWorld.getSurfaceHeight(x, z);
this.caveStartZ = z;
this.smoothWorld = smoothWorld;
long l = x + z + (x * (x - 1)) + (z * (z + 1)) + (long) Math.pow(x, z > 0 ? z : (z < 0 ? -z : 1));
this.numbers = new RandomXS128(smoothWorld.baseSeed, murmurHash3(smoothWorld.baseSeed + murmurHash3(l)));
}
public Cave generate() {
int spawnDist = (int) distanceFromSpawn(caveStartX, caveStartZ);
Log.debug("Generating new cave at " + caveStartX + "," + caveStartZ + " (" + spawnDist + " blocks from spawn)");
generateNodes();
calculateBlocks();
Cave cave = new Cave(caveStartX, caveStartY, caveStartZ, new HashMap<AreaReference, int[]>() {{
for (Map.Entry<AreaReference, IntArray> entry : blocks.entrySet()) {
this.put(entry.getKey(), entry.getValue().toArray());
}
}});
blocks.clear();
rooms.clear();
tunnels.clear();
return cave;
}
private void clear(int blockX, int blockY, int blockZ) {
if (blockY <= 0) return;
AreaReference areaReference = new AreaReference().setFromBlockCoordinates(blockX, blockZ);
IntArray array = blocks.get(areaReference);
if (array == null) {
array = new IntArray();
blocks.put(areaReference, array);
}
array.add(Area.getRef(blockX - areaReference.minBlockX(), blockY, blockZ - areaReference.minBlockZ()));
}
public void generateNodes() {
// make rooms
rooms.add(new RoomNode(caveStartX, caveStartY, caveStartZ, 0, null));
int num = 0;
while (num <= roomNodesMax) {
RoomNode randomNode = rooms.get(numbers.nextInt(rooms.size()));
boolean allowSurface = num <= (roomNodesMin / 4);
int finalX = randomNode.location.blockX + getRoomChangeXZ();
int finalZ = randomNode.location.blockZ + getRoomChangeXZ();
if (inRange(finalX, finalZ)) {
int offsetY = numbers.nextInt((roomChangeY * 2) + 1) - roomChangeY;
int finalY = undergroundY(finalX, finalZ, randomNode.location.blockY, offsetY, allowSurface);
rooms.add(new RoomNode(finalX, finalY, finalZ, 1 + numbers.nextInt(2), randomNode));
}
if (num >= roomNodesMin && numbers.nextInt((roomNodesMax - roomNodesMin) - num) == 0) break;
num++;
}
// make tunnels
ArrayList<TunnelNode> straightTunnels = new ArrayList<TunnelNode>();
for (int i = 0; i < rooms.size(); i++) {
RoomNode roomNode = rooms.get(i);
if (roomNode.connect != null) straightTunnels.add(new TunnelNode(roomNode.location, roomNode.connect.location));
int roomConnections = 0;
for (int j = 0; j < 25; j++) {
RoomNode other = rooms.get(numbers.nextInt(rooms.size()));
if (other == roomNode || other == roomNode.connect) continue;
float roomDistance = distance(roomNode.location, other.location);
if (roomDistance < roomConnectDistanceMin || roomDistance > roomConnectDistanceMax) continue;
straightTunnels.add(new TunnelNode(roomNode.location, other.location));
roomConnections++;
if (roomConnections == 2) break;
}
}
// make bends in tunnels
ArrayList<BlockReference> tunnelSections = new ArrayList<BlockReference>();
for (TunnelNode tunnelNode : straightTunnels) {
BlockReference a = tunnelNode.start;
BlockReference b = tunnelNode.end;
int dX = a.blockX - b.blockX;
int dY = a.blockY - b.blockY;
int dZ = a.blockZ - b.blockZ;
int dist = (int) Math.sqrt(dX * dX + dY * dX + dZ * dZ);
int numTurns = 1 + (dist / 10) + (dist / 5 == 0 ? 0 : numbers.nextInt(dist / 5));
float turnXZChange = (float) Math.sqrt(dX * dX + dZ * dZ) / (float) numTurns;
tunnelSections.clear();
tunnelSections.add(a);
for (int i = 1; i <= numTurns; i++) {
float f = (float) i / ((float) numTurns + 1f);
int x = b.blockX + (int) (dX * f);
int y = b.blockY + (int) (dY * f);
int z = b.blockZ + (int) (dZ * f);
int randomX = (int) (((4 * numbers.nextFloat()) - 2f) * turnXZChange);
int randomY = numbers.nextInt(3) - 1;
int randomZ = (int) (((4 * numbers.nextFloat()) - 2f) * turnXZChange);
int finalX = x + randomX;
int finalY = y + randomY;
int finalZ = z + randomZ;
tunnelSections.add(new BlockReference().setFromBlockCoordinates(finalX, finalY, finalZ));
}
tunnelSections.add(b);
for (int i = 0; i + 1 < tunnelSections.size(); i++) {
tunnels.add(new TunnelNode(tunnelSections.get(i), tunnelSections.get(i + 1)));
}
}
}
private void calculateBlocks() {
for (RoomNode room : rooms) {
int roomX = room.location.blockX;
int roomY = room.location.blockY;
int roomZ = room.location.blockZ;
int r = room.size;
int r2 = r * r;
for (int x = roomX - r; x <= roomX + r; x++) {
for (int y = roomY - r; y <= roomY + r; y++) {
for (int z = roomZ - r; z <= roomZ + r; z++) {
int dX = roomX - x;
int dY = roomY - y;
int dZ = roomZ - z;
if (dX * dX + dY * dY + dZ * dZ <= r2) {
clear(x, y, z);
}
}
}
}
}
for (TunnelNode tunnel : tunnels) {
int r = 2;
int cX = tunnel.end.blockX - tunnel.start.blockX >= 0 ? 1 : -1;
int cY = tunnel.end.blockY - tunnel.start.blockY >= 0 ? 1 : -1;
int cZ = tunnel.end.blockZ - tunnel.start.blockZ >= 0 ? 1 : -1;
int startX = tunnel.start.blockX - (cX * r);
int startY = tunnel.start.blockY - (cY * r);
int startZ = tunnel.start.blockZ - (cZ * r);
int endX = tunnel.end.blockX + (cX * r);
int endY = tunnel.end.blockY + (cY * r);
int endZ = tunnel.end.blockZ + (cZ * r);
BlockReference temp = new BlockReference();
for (int x = startX; x <= endX; x += cX) {
for (int y = startY; y <= endY; y += cY) {
for (int z = startZ; z <= endZ; z += cZ) {
temp.setFromBlockCoordinates(x, y, z);
float radius;
if (distance(tunnel.start, temp) < distance(tunnel.end, temp)) {
radius = tunnel.startRadius;
} else {
radius = tunnel.endRadius;
}
if (distanceFromLine(tunnel.start, tunnel.end, temp.setFromBlockCoordinates(x, y, z)) <= radius) {
clear(x, y, z);
}
}
}
}
}
}
private int getRoomChangeXZ() {
int rand = numbers.nextInt((roomChangeXZRandom * 2) + 1) - roomChangeXZRandom;
return rand + (rand < 0 ? -roomChangeXZConstant : roomChangeXZConstant);
}
private int undergroundY(int x, int z, int prevY, int changeY, boolean allowSurface) {
int y = prevY + changeY;
if (y < 10) return 10;
if (y < minSurfaceHeight) return y;
int height = smoothWorld.getSurfaceHeight(x, z);
while (y > height - (allowSurface ? -1 : 8) && y >= 10)
y--;
return y;
}
private boolean inRange(int x, int z) {
int dX = Math.abs(caveStartX - x);
int dZ = Math.abs(caveStartZ - z);
return dX < CaveManager.caveSafeBlockRadius && dZ < CaveManager.caveSafeBlockRadius;
}
private static float distanceFromLine(BlockReference start, BlockReference end, BlockReference location) {
float a = distance(start, location);
float b = distance(end, location);
float c = distance(start, end);
float s = (a + b + c) / 2f;
float area = (float) Math.sqrt(s * (s - a) * (s - b) * (s - c));
return (area * 2) / c;
}
public float distanceFromSpawn(int x, int z) {
BlockReference spawnPoint = smoothWorld.spawnPoint(((WorldServer) Cubes.getServer().world));
int dX = x - spawnPoint.blockX;
int dZ = z - spawnPoint.blockZ;
return (float) Math.sqrt(dX * dX + dZ * dZ);
}
private static float distance(BlockReference a, BlockReference b) {
int dX = a.blockX - b.blockX;
int dY = a.blockY - b.blockY;
int dZ = a.blockZ - b.blockZ;
return (float) Math.sqrt(dX * dX + dY * dY + dZ * dZ);
}
private class TunnelNode {
BlockReference start;
BlockReference end;
float startRadius = (float) (1.5f + (numbers.nextFloat() * 1.5));
float endRadius = (float) (1.5f + (numbers.nextFloat() * 1.5));
private TunnelNode(BlockReference start, BlockReference end) {
this.start = start;
this.end = end;
}
}
private class RoomNode {
BlockReference location;
RoomNode connect;
int size;
private RoomNode(int blockX, int blockY, int blockZ, int size, RoomNode connect) {
this.location = new BlockReference().setFromBlockCoordinates(blockX, blockY, blockZ);
this.connect = connect;
this.size = size;
}
}
}
|
Don't bother .clear() before gc
|
core/src/ethanjones/cubes/world/generator/smooth/CaveGenerator.java
|
Don't bother .clear() before gc
|
<ide><path>ore/src/ethanjones/cubes/world/generator/smooth/CaveGenerator.java
<ide> }
<ide> }});
<ide>
<del> blocks.clear();
<del> rooms.clear();
<del> tunnels.clear();
<ide> return cave;
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
5ec306e582ff0d7db54959f78d668b1ffdf6b0e3
| 0 |
filodb/FiloDB,velvia/FiloDB,tuplejump/FiloDB,velvia/FiloDB,tuplejump/FiloDB,filodb/FiloDB
|
package filodb.standalone;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Method;
import java.time.Instant;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigException;
/**
* Simple profiler which samples threads and periodically logs a report to a file. When the
* process is cleanly shutdown, the profiler stops and reports what it has immediately. This
* makes it possible to use a very long report interval without data loss.
*/
public class SimpleProfiler {
/**
* Launches a global profiler, based on config. Typically, these are nested under the
* "filodb.profiler" path:
*
* sample-rate = 10ms
* report-interval = 60s
* top-count = 50
* out-file = "filodb.prof"
*
* In order for profiling to be enabled, all of the above properies must be set except for
* the file. If no file is provided, then a temporary file is created, whose name is logged.
*
* @return false if not configured
* @throws IOException if file cannot be opened
*/
public static boolean launch(Config config) throws IOException {
try {
long sampleRateMillis = config.getDuration("sample-rate", TimeUnit.MILLISECONDS);
long reportIntervalSeconds = config.getDuration("report-interval", TimeUnit.SECONDS);
int topCount = config.getInt("top-count");
File outFile = selectProfilerFile(config.getString("out-file"));
FileOutputStream out = new FileOutputStream(outFile);
new SimpleProfiler(sampleRateMillis, reportIntervalSeconds, topCount, out).start();
return true;
} catch (ConfigException e) {
LoggerFactory.getLogger(SimpleProfiler.class).debug("Not profiling: " + e);
return false;
}
}
/**
* @param fileName candidate file name; if null, a temp file is created
*/
private static File selectProfilerFile(String fileName) throws IOException {
if (fileName != null) {
return new File(fileName);
}
File file = File.createTempFile("filodb.SimpleProfiler", ".txt");
LoggerFactory.getLogger(SimpleProfiler.class).info
("Created temp file for profile reporting: " + file);
return file;
}
private final long mSampleRateMillis;
private final long mReportIntervalMillis;
private final int mTopCount;
private final OutputStream mOut;
private Sampler mSampler;
private Thread mShutdownHook;
private long mNextReportAtMillis;
/**
* Reports to System.out.
*/
public SimpleProfiler(long sampleRateMillis, long reportIntervalSeconds, int topCount) {
this(sampleRateMillis, reportIntervalSeconds, topCount, System.out);
}
/**
* @param sampleRateMillis how often to perform a thread dump (10 millis is good)
* @param reportIntervalSeconds how often to write a report to the output stream
* @param topCount number of methods to report
* @param out where to write the report
*/
public SimpleProfiler(long sampleRateMillis, long reportIntervalSeconds, int topCount,
OutputStream out)
{
mSampleRateMillis = sampleRateMillis;
mReportIntervalMillis = reportIntervalSeconds * 1000;
mTopCount = topCount;
mOut = out;
}
/**
* Start the profiler. Calling a second time does nothing unless stopped.
*/
public synchronized void start() {
if (mSampler == null) {
Sampler s = new Sampler();
s.start();
mSampler = s;
mNextReportAtMillis = System.currentTimeMillis() + mReportIntervalMillis;
try {
mShutdownHook = new Thread(this::shutdown);
Runtime.getRuntime().addShutdownHook(mShutdownHook);
} catch (Throwable e) {
// Ignore.
mShutdownHook = null;
}
}
}
/**
* Stop the profiler. Calling a second time does nothing unless started again.
*/
public void stop() {
Sampler s;
synchronized (this) {
s = mSampler;
if (s != null) {
s.mShouldStop = true;
s.interrupt();
if (mShutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(mShutdownHook);
} catch (Throwable e) {
// Ignore.
} finally {
mShutdownHook = null;
}
}
}
}
if (s != null) {
while (true) {
try {
s.join();
break;
} catch (InterruptedException e) {
// Ignore.
}
}
synchronized (this) {
if (mSampler == s) {
mSampler = null;
}
}
}
}
private void analyze(Map<StackTraceElement, Counter> samples, ThreadInfo[] infos)
throws IOException
{
for (ThreadInfo info : infos) {
StackTraceElement[] trace = examine(info);
if (trace != null) {
StackTraceElement elem = trace[0];
Counter c = samples.get(elem);
if (c == null) {
c = new Counter(elem);
samples.put(elem, c);
}
c.mValue++;
}
}
synchronized (this) {
long now = System.currentTimeMillis();
if (now >= mNextReportAtMillis && mSampler == Thread.currentThread()) {
mNextReportAtMillis = Math.max(now, mNextReportAtMillis + mReportIntervalMillis);
report(samples);
}
}
}
private void report(Map<StackTraceElement, Counter> samples) throws IOException {
int size = samples.size();
if (size == 0) {
return;
}
Counter[] top = new Counter[size];
samples.values().toArray(top);
Arrays.sort(top);
double sum = 0;
for (Counter c : top) {
sum += c.mValue;
}
int limit = Math.min(mTopCount, size);
StringBuilder b = new StringBuilder(limit * 80);
b.append(Instant.now()).append(' ').append(getClass().getName()).append('\n');
for (int i=0; i<limit; i++) {
Counter c = top[i];
if (c.mValue == 0) {
// No more to report.
break;
}
String percentStr = String.format("%1$7.3f%%", 100.0 * (c.mValue / sum));
b.append(percentStr);
StackTraceElement elem = c.mElem;
b.append(' ').append(elem.getClassName()).append('.').append(elem.getMethodName());
String fileName = elem.getFileName();
int lineNumber = elem.getLineNumber();
if (fileName == null) {
if (lineNumber >= 0) {
b.append("(:").append(lineNumber).append(')');
}
} else {
b.append('(').append(fileName);
if (lineNumber >= 0) {
b.append(':').append(lineNumber);
}
b.append(')');
}
b.append('\n');
// Reset for next report.
c.mValue = 0;
}
report(b.toString());
}
/**
* Override this method to report somewhere else.
*/
protected void report(String s) throws IOException {
mOut.write(s.getBytes(StandardCharsets.UTF_8));
mOut.flush();
}
/**
* @return null if rejected
*/
private StackTraceElement[] examine(ThreadInfo info) {
// Reject the sampler thread itself.
if (info.getThreadId() == Thread.currentThread().getId()) {
return null;
}
// Reject threads which aren't doing any real work.
if (!info.getThreadState().equals(Thread.State.RUNNABLE)) {
return null;
}
StackTraceElement[] trace = info.getStackTrace();
// Reject internal threads which have no trace at all.
if (trace == null || trace.length == 0) {
return null;
}
// Reject some special internal native methods which aren't actually running.
StackTraceElement elem = trace[0];
if (elem.isNativeMethod()) {
String className = elem.getClassName();
// Reject threads which appeared as doing work only because they unparked another
// thread, effectively yielding due to priority boosting.
if (className.endsWith("misc.Unsafe")) {
if (elem.getMethodName().equals("unpark")) {
return null;
}
// Sometimes the thread state is runnable for this method. Filter it out.
if (elem.getMethodName().equals("park")) {
return null;
}
}
switch (className) {
case "java.lang.Object":
// Reject threads which appeared as doing work only because they notified
// another thread, effectively yielding due to priority boosting.
if (elem.getMethodName().startsWith("notify")) {
return null;
}
break;
case "java.lang.ref.Reference":
// Reject threads waiting for GC'd objects to clean up.
return null;
case "java.lang.Thread":
/* Track yield, since it's used by the ChunkMap lock.
// Reject threads which appeared as doing work only because they yielded.
if (elem.getMethodName().equals("yield")) {
return null;
}
*/
// Sometimes the thread state is runnable for this method. Filter it out.
if (elem.getMethodName().equals("sleep")) {
return null;
}
break;
case "java.net.PlainSocketImpl":
// Reject threads blocked while accepting sockets.
if (elem.getMethodName().startsWith("accept") ||
elem.getMethodName().startsWith("socketAccept"))
{
return null;
}
break;
case "sun.nio.ch.ServerSocketChannelImpl":
// Reject threads blocked while accepting sockets.
if (elem.getMethodName().startsWith("accept")) {
return null;
}
break;
case "java.net.SocketInputStream":
// Reject threads blocked while reading sockets. This also rejects threads
// which are actually reading, but it's more common for threads to block.
if (elem.getMethodName().startsWith("socketRead")) {
return null;
}
break;
case "sun.nio.ch.SocketDispatcher":
// Reject threads blocked while reading sockets. This also rejects threads
// which are actually reading, but it's more common for threads to block.
if (elem.getMethodName().startsWith("read")) {
return null;
}
break;
case "sun.nio.ch.EPoll":
// Reject threads blocked while selecting sockets.
if (elem.getMethodName().startsWith("wait")) {
return null;
}
break;
case "sun.nio.ch.KQueue":
// Reject threads blocked while selecting sockets.
if (elem.getMethodName().startsWith("poll")) {
return null;
}
break;
case "sun.nio.ch.KQueueArrayWrapper":
// Reject threads blocked while selecting sockets.
if (elem.getMethodName().startsWith("kevent")) {
return null;
}
break;
case "sun.nio.ch.WindowsSelectorImpl$SubSelector":
// Reject threads blocked while selecting sockets.
if (elem.getMethodName().startsWith("poll")) {
return null;
}
break;
}
// Reject threads blocked while selecting sockets. Match just on method name here,
// to capture multiple epoll library implementations.
if (elem.getMethodName().startsWith("epollWait")) {
return null;
}
}
return trace;
}
private void shutdown() {
synchronized (this) {
mShutdownHook = null;
mNextReportAtMillis = Long.MIN_VALUE;
}
stop();
}
private static class Counter implements Comparable<Counter> {
final StackTraceElement mElem;
long mValue;
Counter(StackTraceElement elem) {
mElem = elem;
}
@Override
public int compareTo(Counter other) {
// Descending order.
return Long.compare(other.mValue, mValue);
}
}
private class Sampler extends Thread {
private final Map<StackTraceElement, Counter> mSamples;
volatile boolean mShouldStop;
Sampler() {
super(SimpleProfiler.class.getName());
try {
setDaemon(true);
setPriority(Thread.MAX_PRIORITY);
} catch (SecurityException e) {
// Ignore.
}
mSamples = new HashMap<>();
}
@Override
public void run() {
ThreadMXBean tb = ManagementFactory.getThreadMXBean();
/*
The method we want to call is:
dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers, int maxDepth)
...but it's only available in Java 10. When running an older version of Java,
we're forced to capture full stack traces, which is much more expensive.
*/
Method dumpMethod = null;
try {
dumpMethod = ThreadMXBean.class.getMethod
("dumpAllThreads", boolean.class, boolean.class, int.class);
} catch (NoSuchMethodException e) {
// Oh well, we tried.
}
while (!mShouldStop) {
try {
try {
Thread.sleep(mSampleRateMillis);
} catch (InterruptedException e) {
// Probably should report upon JVM shutdown and then stop.
}
ThreadInfo[] infos;
if (dumpMethod == null) {
// Use the slow version.
// lockMonitors=false, lockedSynchronizers=false
infos = tb.dumpAllThreads(false, false);
} else {
// Use the fast version.
// lockMonitors=false, lockedSynchronizers=false, maxDepth=1
infos = (ThreadInfo[]) dumpMethod.invoke(tb, false, false, 1);
}
analyze(mSamples, infos);
} catch (InterruptedIOException e) {
// Probably should stop.
} catch (Throwable e) {
Thread t = Thread.currentThread();
t.getThreadGroup().uncaughtException(t, e);
}
}
}
}
}
|
standalone/src/main/java/filodb/standalone/SimpleProfiler.java
|
package filodb.standalone;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Method;
import java.time.Instant;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigException;
/**
* Simple profiler which samples threads and periodically logs a report to a file. When the
* process is cleanly shutdown, the profiler stops and reports what it has immediately. This
* makes it possible to use a very long report interval without data loss.
*/
public class SimpleProfiler {
/**
* Launches a global profiler, based on config. Typically, these are nested under the
* "filodb.profiler" path:
*
* sample-rate = 10ms
* report-interval = 60s
* top-count = 50
* out-file = "filodb.prof"
*
* In order for profiling to be enabled, all of the above properies must be set except for
* the file. If no file is provided, then a temporary file is created, whose name is logged.
*
* @return false if not configured
* @throws IOException if file cannot be opened
*/
public static boolean launch(Config config) throws IOException {
try {
long sampleRateMillis = config.getDuration("sample-rate", TimeUnit.MILLISECONDS);
long reportIntervalSeconds = config.getDuration("report-interval", TimeUnit.SECONDS);
int topCount = config.getInt("top-count");
File outFile = selectProfilerFile(config.getString("out-file"));
FileOutputStream out = new FileOutputStream(outFile);
new SimpleProfiler(sampleRateMillis, reportIntervalSeconds, topCount, out).start();
return true;
} catch (ConfigException e) {
LoggerFactory.getLogger(SimpleProfiler.class).debug("Not profiling: " + e);
return false;
}
}
/**
* @param fileName candidate file name; if null, a temp file is created
*/
private static File selectProfilerFile(String fileName) throws IOException {
if (fileName != null) {
return new File(fileName);
}
File file = File.createTempFile("filodb.SimpleProfiler", ".txt");
LoggerFactory.getLogger(SimpleProfiler.class).info
("Created temp file for profile reporting: " + file);
return file;
}
private final long mSampleRateMillis;
private final long mReportIntervalMillis;
private final int mTopCount;
private final OutputStream mOut;
private Sampler mSampler;
private Thread mShutdownHook;
private long mNextReportAtMillis;
/**
* Reports to System.out.
*/
public SimpleProfiler(long sampleRateMillis, long reportIntervalSeconds, int topCount) {
this(sampleRateMillis, reportIntervalSeconds, topCount, System.out);
}
/**
* @param sampleRateMillis how often to perform a thread dump (10 millis is good)
* @param reportIntervalSeconds how often to write a report to the output stream
* @param topCount number of methods to report
* @param out where to write the report
*/
public SimpleProfiler(long sampleRateMillis, long reportIntervalSeconds, int topCount,
OutputStream out)
{
mSampleRateMillis = sampleRateMillis;
mReportIntervalMillis = reportIntervalSeconds * 1000;
mTopCount = topCount;
mOut = out;
}
/**
* Start the profiler. Calling a second time does nothing unless stopped.
*/
public synchronized void start() {
if (mSampler == null) {
Sampler s = new Sampler();
s.start();
mSampler = s;
mNextReportAtMillis = System.currentTimeMillis() + mReportIntervalMillis;
try {
mShutdownHook = new Thread(this::shutdown);
Runtime.getRuntime().addShutdownHook(mShutdownHook);
} catch (Throwable e) {
// Ignore.
mShutdownHook = null;
}
}
}
/**
* Stop the profiler. Calling a second time does nothing unless started again.
*/
public void stop() {
Sampler s;
synchronized (this) {
s = mSampler;
if (s != null) {
s.mShouldStop = true;
s.interrupt();
if (mShutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(mShutdownHook);
} catch (Throwable e) {
// Ignore.
} finally {
mShutdownHook = null;
}
}
}
}
if (s != null) {
while (true) {
try {
s.join();
break;
} catch (InterruptedException e) {
// Ignore.
}
}
synchronized (this) {
if (mSampler == s) {
mSampler = null;
}
}
}
}
private void analyze(Map<StackTraceElement, Counter> samples, ThreadInfo[] infos)
throws IOException
{
for (ThreadInfo info : infos) {
StackTraceElement[] trace = examine(info);
if (trace != null) {
StackTraceElement elem = trace[0];
Counter c = samples.get(elem);
if (c == null) {
c = new Counter(elem);
samples.put(elem, c);
}
c.mValue++;
}
}
synchronized (this) {
long now = System.currentTimeMillis();
if (now >= mNextReportAtMillis && mSampler == Thread.currentThread()) {
mNextReportAtMillis = Math.max(now, mNextReportAtMillis + mReportIntervalMillis);
report(samples);
}
}
}
private void report(Map<StackTraceElement, Counter> samples) throws IOException {
int size = samples.size();
if (size == 0) {
return;
}
Counter[] top = new Counter[size];
samples.values().toArray(top);
Arrays.sort(top);
double sum = 0;
for (Counter c : top) {
sum += c.mValue;
}
int limit = Math.min(mTopCount, size);
StringBuilder b = new StringBuilder(limit * 80);
b.append(Instant.now()).append(' ').append(getClass().getName()).append('\n');
for (int i=0; i<limit; i++) {
Counter c = top[i];
if (c.mValue == 0) {
// No more to report.
break;
}
String percentStr = String.format("%1$7.3f%%", 100.0 * (c.mValue / sum));
b.append(percentStr);
StackTraceElement elem = c.mElem;
b.append(' ').append(elem.getClassName()).append('.').append(elem.getMethodName());
String fileName = elem.getFileName();
int lineNumber = elem.getLineNumber();
if (fileName == null) {
if (lineNumber >= 0) {
b.append("(:").append(lineNumber).append(')');
}
} else {
b.append('(').append(fileName);
if (lineNumber >= 0) {
b.append(':').append(lineNumber);
}
b.append(')');
}
b.append('\n');
// Reset for next report.
c.mValue = 0;
}
report(b.toString());
}
/**
* Override this method to report somewhere else.
*/
protected void report(String s) throws IOException {
mOut.write(s.getBytes(StandardCharsets.UTF_8));
mOut.flush();
}
/**
* @return null if rejected
*/
private StackTraceElement[] examine(ThreadInfo info) {
// Reject the sampler thread itself.
if (info.getThreadId() == Thread.currentThread().getId()) {
return null;
}
// Reject threads which aren't doing any real work.
if (!info.getThreadState().equals(Thread.State.RUNNABLE)) {
return null;
}
StackTraceElement[] trace = info.getStackTrace();
// Reject internal threads which have no trace at all.
if (trace == null || trace.length == 0) {
return null;
}
// Reject some special internal native methods which aren't actually running.
StackTraceElement elem = trace[0];
if (elem.isNativeMethod()) {
String className = elem.getClassName();
// Reject threads which appeared as doing work only because they unparked another
// thread, effectively yielding due to priority boosting.
if (className.endsWith("misc.Unsafe")) {
if (elem.getMethodName().equals("unpark")) {
return null;
}
// Sometimes the thread state is runnable for this method. Filter it out.
if (elem.getMethodName().equals("park")) {
return null;
}
}
switch (className) {
case "java.lang.Object":
// Reject threads which appeared as doing work only because they notified
// another thread, effectively yielding due to priority boosting.
if (elem.getMethodName().startsWith("notify")) {
return null;
}
break;
case "java.lang.ref.Reference":
// Reject threads waiting for GC'd objects to clean up.
return null;
case "java.lang.Thread":
// Reject threads which appeared as doing work only because they yielded.
if (elem.getMethodName().equals("yield")) {
return null;
}
// Sometimes the thread state is runnable for this method. Filter it out.
if (elem.getMethodName().equals("sleep")) {
return null;
}
break;
case "java.net.PlainSocketImpl":
// Reject threads blocked while accepting sockets.
if (elem.getMethodName().startsWith("accept") ||
elem.getMethodName().startsWith("socketAccept"))
{
return null;
}
break;
case "sun.nio.ch.ServerSocketChannelImpl":
// Reject threads blocked while accepting sockets.
if (elem.getMethodName().startsWith("accept")) {
return null;
}
break;
case "java.net.SocketInputStream":
// Reject threads blocked while reading sockets. This also rejects threads
// which are actually reading, but it's more common for threads to block.
if (elem.getMethodName().startsWith("socketRead")) {
return null;
}
break;
case "sun.nio.ch.SocketDispatcher":
// Reject threads blocked while reading sockets. This also rejects threads
// which are actually reading, but it's more common for threads to block.
if (elem.getMethodName().startsWith("read")) {
return null;
}
break;
case "sun.nio.ch.EPoll":
// Reject threads blocked while selecting sockets.
if (elem.getMethodName().startsWith("wait")) {
return null;
}
break;
case "sun.nio.ch.KQueue":
// Reject threads blocked while selecting sockets.
if (elem.getMethodName().startsWith("poll")) {
return null;
}
break;
case "sun.nio.ch.KQueueArrayWrapper":
// Reject threads blocked while selecting sockets.
if (elem.getMethodName().startsWith("kevent")) {
return null;
}
break;
case "sun.nio.ch.WindowsSelectorImpl$SubSelector":
// Reject threads blocked while selecting sockets.
if (elem.getMethodName().startsWith("poll")) {
return null;
}
break;
}
// Reject threads blocked while selecting sockets. Match just on method name here,
// to capture multiple epoll library implementations.
if (elem.getMethodName().startsWith("epollWait")) {
return null;
}
}
return trace;
}
private void shutdown() {
synchronized (this) {
mShutdownHook = null;
mNextReportAtMillis = Long.MIN_VALUE;
}
stop();
}
private static class Counter implements Comparable<Counter> {
final StackTraceElement mElem;
long mValue;
Counter(StackTraceElement elem) {
mElem = elem;
}
@Override
public int compareTo(Counter other) {
// Descending order.
return Long.compare(other.mValue, mValue);
}
}
private class Sampler extends Thread {
private final Map<StackTraceElement, Counter> mSamples;
volatile boolean mShouldStop;
Sampler() {
super(SimpleProfiler.class.getName());
try {
setDaemon(true);
setPriority(Thread.MAX_PRIORITY);
} catch (SecurityException e) {
// Ignore.
}
mSamples = new HashMap<>();
}
@Override
public void run() {
ThreadMXBean tb = ManagementFactory.getThreadMXBean();
/*
The method we want to call is:
dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers, int maxDepth)
...but it's only available in Java 10. When running an older version of Java,
we're forced to capture full stack traces, which is much more expensive.
*/
Method dumpMethod = null;
try {
dumpMethod = ThreadMXBean.class.getMethod
("dumpAllThreads", boolean.class, boolean.class, int.class);
} catch (NoSuchMethodException e) {
// Oh well, we tried.
}
while (!mShouldStop) {
try {
try {
Thread.sleep(mSampleRateMillis);
} catch (InterruptedException e) {
// Probably should report upon JVM shutdown and then stop.
}
ThreadInfo[] infos;
if (dumpMethod == null) {
// Use the slow version.
// lockMonitors=false, lockedSynchronizers=false
infos = tb.dumpAllThreads(false, false);
} else {
// Use the fast version.
// lockMonitors=false, lockedSynchronizers=false, maxDepth=1
infos = (ThreadInfo[]) dumpMethod.invoke(tb, false, false, 1);
}
analyze(mSamples, infos);
} catch (InterruptedIOException e) {
// Probably should stop.
} catch (Throwable e) {
Thread t = Thread.currentThread();
t.getThreadGroup().uncaughtException(t, e);
}
}
}
}
}
|
feat(standalone): Profiler tracks calls to Thread.yield, to indicate how much time is spent contended for ChunkMap locks. (#250)
|
standalone/src/main/java/filodb/standalone/SimpleProfiler.java
|
feat(standalone): Profiler tracks calls to Thread.yield, to indicate how much time is spent contended for ChunkMap locks. (#250)
|
<ide><path>tandalone/src/main/java/filodb/standalone/SimpleProfiler.java
<ide> return null;
<ide>
<ide> case "java.lang.Thread":
<add> /* Track yield, since it's used by the ChunkMap lock.
<ide> // Reject threads which appeared as doing work only because they yielded.
<ide> if (elem.getMethodName().equals("yield")) {
<ide> return null;
<ide> }
<add> */
<ide> // Sometimes the thread state is runnable for this method. Filter it out.
<ide> if (elem.getMethodName().equals("sleep")) {
<ide> return null;
|
|
Java
|
apache-2.0
|
d8552eac084ef92af5eb030eb1e3b66bc17cee13
| 0 |
roboguy/pentaho-kettle,ddiroma/pentaho-kettle,dkincade/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,HiromuHota/pentaho-kettle,emartin-pentaho/pentaho-kettle,DFieldFL/pentaho-kettle,e-cuellar/pentaho-kettle,mkambol/pentaho-kettle,stepanovdg/pentaho-kettle,aminmkhan/pentaho-kettle,stepanovdg/pentaho-kettle,ddiroma/pentaho-kettle,lgrill-pentaho/pentaho-kettle,pminutillo/pentaho-kettle,graimundo/pentaho-kettle,tmcsantos/pentaho-kettle,rmansoor/pentaho-kettle,mbatchelor/pentaho-kettle,roboguy/pentaho-kettle,matthewtckr/pentaho-kettle,pedrofvteixeira/pentaho-kettle,aminmkhan/pentaho-kettle,roboguy/pentaho-kettle,emartin-pentaho/pentaho-kettle,kurtwalker/pentaho-kettle,SergeyTravin/pentaho-kettle,rmansoor/pentaho-kettle,DFieldFL/pentaho-kettle,mkambol/pentaho-kettle,ccaspanello/pentaho-kettle,emartin-pentaho/pentaho-kettle,flbrino/pentaho-kettle,Advent51/pentaho-kettle,skofra0/pentaho-kettle,ccaspanello/pentaho-kettle,e-cuellar/pentaho-kettle,pavel-sakun/pentaho-kettle,graimundo/pentaho-kettle,tkafalas/pentaho-kettle,ddiroma/pentaho-kettle,bmorrise/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,wseyler/pentaho-kettle,pavel-sakun/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,aminmkhan/pentaho-kettle,flbrino/pentaho-kettle,e-cuellar/pentaho-kettle,DFieldFL/pentaho-kettle,Advent51/pentaho-kettle,tkafalas/pentaho-kettle,DFieldFL/pentaho-kettle,bmorrise/pentaho-kettle,matthewtckr/pentaho-kettle,mdamour1976/pentaho-kettle,pminutillo/pentaho-kettle,tmcsantos/pentaho-kettle,pentaho/pentaho-kettle,kurtwalker/pentaho-kettle,mkambol/pentaho-kettle,flbrino/pentaho-kettle,skofra0/pentaho-kettle,tmcsantos/pentaho-kettle,rmansoor/pentaho-kettle,Advent51/pentaho-kettle,bmorrise/pentaho-kettle,e-cuellar/pentaho-kettle,Advent51/pentaho-kettle,pentaho/pentaho-kettle,marcoslarsen/pentaho-kettle,SergeyTravin/pentaho-kettle,stepanovdg/pentaho-kettle,ddiroma/pentaho-kettle,kurtwalker/pentaho-kettle,dkincade/pentaho-kettle,pminutillo/pentaho-kettle,pentaho/pentaho-kettle,mdamour1976/pentaho-kettle,HiromuHota/pentaho-kettle,graimundo/pentaho-kettle,lgrill-pentaho/pentaho-kettle,mkambol/pentaho-kettle,mdamour1976/pentaho-kettle,marcoslarsen/pentaho-kettle,HiromuHota/pentaho-kettle,wseyler/pentaho-kettle,rmansoor/pentaho-kettle,pavel-sakun/pentaho-kettle,roboguy/pentaho-kettle,graimundo/pentaho-kettle,kurtwalker/pentaho-kettle,SergeyTravin/pentaho-kettle,pedrofvteixeira/pentaho-kettle,tmcsantos/pentaho-kettle,dkincade/pentaho-kettle,skofra0/pentaho-kettle,matthewtckr/pentaho-kettle,dkincade/pentaho-kettle,pentaho/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,marcoslarsen/pentaho-kettle,bmorrise/pentaho-kettle,pedrofvteixeira/pentaho-kettle,lgrill-pentaho/pentaho-kettle,mdamour1976/pentaho-kettle,tkafalas/pentaho-kettle,pminutillo/pentaho-kettle,HiromuHota/pentaho-kettle,marcoslarsen/pentaho-kettle,ccaspanello/pentaho-kettle,mbatchelor/pentaho-kettle,matthewtckr/pentaho-kettle,pedrofvteixeira/pentaho-kettle,mbatchelor/pentaho-kettle,emartin-pentaho/pentaho-kettle,SergeyTravin/pentaho-kettle,ccaspanello/pentaho-kettle,flbrino/pentaho-kettle,aminmkhan/pentaho-kettle,wseyler/pentaho-kettle,stepanovdg/pentaho-kettle,lgrill-pentaho/pentaho-kettle,pavel-sakun/pentaho-kettle,wseyler/pentaho-kettle,skofra0/pentaho-kettle,tkafalas/pentaho-kettle,mbatchelor/pentaho-kettle
|
/*
* ! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Pentaho : http://www.pentaho.com
*
* ******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* *****************************************************************************
*/
package org.pentaho.di.trans.ael.websocket;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.engine.api.events.PDIEvent;
import org.pentaho.di.engine.api.model.Operation;
import org.pentaho.di.engine.api.model.Transformation;
import org.pentaho.di.engine.api.remote.ExecutionRequest;
import org.pentaho.di.engine.api.remote.Message;
import org.pentaho.di.engine.api.remote.RemoteSource;
import org.pentaho.di.engine.api.remote.StopMessage;
import org.pentaho.di.engine.api.reporting.LogEntry;
import org.pentaho.di.engine.api.reporting.LogLevel;
import org.pentaho.di.engine.api.reporting.Status;
import org.pentaho.di.engine.model.ActingPrincipal;
import org.pentaho.di.trans.RowProducer;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.ael.adapters.TransMetaConverter;
import org.pentaho.di.trans.ael.websocket.exception.HandlerRegistrationException;
import org.pentaho.di.trans.ael.websocket.exception.MessageEventHandlerExecutionException;
import org.pentaho.di.trans.ael.websocket.handler.MessageEventHandler;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaDataCombi;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.Collection;
import static java.util.stream.Collectors.toMap;
/**
* Created by fcamara on 8/17/17.
*/
public class TransWebSocketEngineAdapter extends Trans {
private static final String OPERATION_LOG = "OPERATION_LOG_TRANS_WEBSOCK_";
private static final String TRANSFORMATION_LOG = "TRANSFORMATION_LOG_TRANS_WEBSOCK";
private static final String TRANSFORMATION_STATUS = "TRANSFORMATION_STATUS_TRANS_WEBSOCK";
private static final String TRANSFORMATION_ERROR = "TRANSFORMATION_ERROR_TRANS_WEBSOCK";
private static final String TRANSFORMATION_STOP = "TRANSFORMATION_STOP_TRANS_WEBSOCK";
private static final String SPARK_SESSION_KILLED_MSG = "Spark session was killed";
//session monitor properties
private static final int SLEEP_TIME_MS = 10000;
private static final int MAX_TEST_FAILED = 3;
private ExecutorService sessionMonitor = null;
private final Transformation transformation;
private ExecutionRequest executionRequest;
private DaemonMessagesClientEndpoint daemonMessagesClientEndpoint = null;
private final MessageEventService messageEventService;
private LogLevel logLevel = null;
private final String host;
private final String port;
private final boolean ssl;
//completion signal used to wait until Transformation is finished
private CountDownLatch transFinishedSignal = new CountDownLatch( 1 );
private AtomicInteger errors = new AtomicInteger();
private static final Map<org.pentaho.di.core.logging.LogLevel, LogLevel> LEVEL_MAP = new HashMap<>();
static {
LEVEL_MAP.put( org.pentaho.di.core.logging.LogLevel.BASIC, LogLevel.BASIC );
LEVEL_MAP.put( org.pentaho.di.core.logging.LogLevel.DEBUG, LogLevel.DEBUG );
LEVEL_MAP.put( org.pentaho.di.core.logging.LogLevel.DETAILED, LogLevel.DETAILED );
LEVEL_MAP.put( org.pentaho.di.core.logging.LogLevel.ERROR, LogLevel.ERROR );
LEVEL_MAP.put( org.pentaho.di.core.logging.LogLevel.MINIMAL, LogLevel.MINIMAL );
LEVEL_MAP.put( org.pentaho.di.core.logging.LogLevel.ROWLEVEL, LogLevel.TRACE );
}
public TransWebSocketEngineAdapter( TransMeta transMeta, String host, String port, boolean ssl ) {
transformation = TransMetaConverter.convert( transMeta );
this.transMeta = transMeta;
this.messageEventService = new MessageEventService();
this.host = host;
this.port = port;
this.ssl = ssl;
}
private DaemonMessagesClientEndpoint getDaemonEndpoint() throws KettleException {
try {
if ( daemonMessagesClientEndpoint == null ) {
daemonMessagesClientEndpoint = new DaemonMessagesClientEndpoint( host, port, ssl, messageEventService );
}
return daemonMessagesClientEndpoint;
} catch ( KettleException e ) {
finishProcess( true );
transFinishedSignal.countDown();
throw e;
}
}
@Override public void setLogLevel( org.pentaho.di.core.logging.LogLevel logLogLevel ) {
this.logLevel = LEVEL_MAP.getOrDefault( logLogLevel, LogLevel.MINIMAL );
}
@Override public void killAll() {
throw new UnsupportedOperationException( "Not yet implemented" );
}
@Override public void stopAll() {
try {
getDaemonEndpoint().sendMessage( new StopMessage( getErrors() == 0 ? "User Request" : "Error reported" ) );
if ( getErrors() == 0 ) {
waitUntilFinished();
}
} catch ( KettleException e ) {
getLogChannel().logDebug( e.getMessage() );
}
}
@Override public void prepareExecution( String[] arguments ) throws KettleException {
activateParameters();
transMeta.activateParameters();
transMeta.setInternalKettleVariables();
Map<String, Object> env = Arrays.stream( transMeta.listVariables() )
.collect( toMap( Function.identity(), transMeta::getVariable ) );
this.executionRequest = new ExecutionRequest( new HashMap<>(), env, transformation, new HashMap<>(), logLevel,
getActingPrincipal( transMeta ) );
setSteps( new ArrayList<>( opsToSteps() ) );
wireStatusToTransListeners();
subscribeToOpLogging();
subscribeToTransLogging();
setReadyToStart( true );
}
private void logToChannel( LogChannelInterface logChannel, LogEntry data ) {
LogLevel logLogLevel = data.getLogLogLevel();
switch ( logLogLevel ) {
case ERROR:
if ( data.getThrowable() != null ) {
logChannel.logError( data.getMessage(), data.getThrowable() );
} else {
logChannel.logError( data.getMessage() );
}
break;
case MINIMAL:
logChannel.logMinimal( data.getMessage() );
break;
case BASIC:
logChannel.logBasic( data.getMessage() );
break;
case DETAILED:
logChannel.logDetailed( data.getMessage() );
break;
case DEBUG:
logChannel.logDebug( data.getMessage() );
break;
case TRACE:
logChannel.logRowlevel( data.getMessage() );
break;
}
}
private void subscribeToOpLogging() throws KettleException {
transformation.getOperations().stream().forEach( operation -> {
try {
messageEventService.addHandler( Util.getOperationLogEvent( operation.getId() ),
new MessageEventHandler() {
@Override
public void execute( Message message ) throws MessageEventHandlerExecutionException {
PDIEvent<RemoteSource, LogEntry> event = (PDIEvent<RemoteSource, LogEntry>) message;
LogEntry logEntry = event.getData();
StepInterface stepInterface = findStepInterface( operation.getId(), 0 );
if ( stepInterface != null ) {
LogChannelInterface logChannel = stepInterface.getLogChannel();
logToChannel( logChannel, logEntry );
} else {
// Could not find step, log at transformation level instead
logToChannel( getLogChannel(), logEntry );
}
}
@Override
public String getIdentifier() {
return OPERATION_LOG + operation.getId();
}
} );
} catch ( HandlerRegistrationException e ) {
getLogChannel().logError( "Error registering message handlers", e );
}
} );
}
private void subscribeToTransLogging() throws KettleException {
messageEventService.addHandler( Util.getTransformationLogEvent(),
new MessageEventHandler() {
@Override
public void execute( Message message ) throws MessageEventHandlerExecutionException {
PDIEvent<RemoteSource, LogEntry> event = (PDIEvent<RemoteSource, LogEntry>) message;
LogEntry data = event.getData();
logToChannel( getLogChannel(), data );
}
@Override
public String getIdentifier() {
return TRANSFORMATION_LOG;
}
} );
}
private void wireStatusToTransListeners() throws KettleException {
messageEventService.addHandler( Util.getTransformationStatusEvent(),
new MessageEventHandler() {
@Override
public void execute( Message message ) throws MessageEventHandlerExecutionException {
PDIEvent<RemoteSource, Status> transStatusEvent = (PDIEvent<RemoteSource, Status>) message;
addStepPerformanceSnapShot();
getTransListeners().forEach( l -> {
try {
switch ( transStatusEvent.getData() ) {
case RUNNING:
l.transStarted( TransWebSocketEngineAdapter.this );
l.transActive( TransWebSocketEngineAdapter.this );
break;
case PAUSED:
break;
case STOPPED:
break;
case FAILED:
case FINISHED:
l.transFinished( TransWebSocketEngineAdapter.this );
setFinished( true );
break;
}
} catch ( KettleException e ) {
throw new RuntimeException( e );
}
} );
}
@Override
public String getIdentifier() {
return TRANSFORMATION_STATUS;
}
} );
messageEventService
.addHandler( Util.getTransformationErrorEvent(), new MessageEventHandler() {
@Override
public void execute( Message message ) throws MessageEventHandlerExecutionException {
Throwable throwable = ( (PDIEvent<RemoteSource, LogEntry>) message ).getData().getThrowable();
getLogChannel().logError( "Error Executing Transformation", throwable );
errors.incrementAndGet();
finishProcess( true );
}
@Override
public String getIdentifier() {
return TRANSFORMATION_ERROR;
}
} );
messageEventService
.addHandler( Util.getStopMessage(), new MessageEventHandler() {
@Override
public void execute( Message message ) throws MessageEventHandlerExecutionException {
String stopMessage = ((StopMessage) message ).getReasonPhrase();
if ( SPARK_SESSION_KILLED_MSG.equals( stopMessage ) ) {
errors.incrementAndGet();
getLogChannel().logError( "Finalizing execution: " + stopMessage );
} else {
getLogChannel().logBasic( "Finalizing execution: " + stopMessage );
}
finishProcess( false );
try {
getDaemonEndpoint().close( stopMessage );
} catch ( KettleException e ) {
getLogChannel().logError( "Error finalizing", e );
}
//let's shutdown the session monitor thread
closeSessionMonitor();
// Signal for the the waitUntilFinished blocker...
transFinishedSignal.countDown();
}
@Override
public String getIdentifier() {
return TRANSFORMATION_STOP;
}
} );
}
private Collection<StepMetaDataCombi> opsToSteps() {
Map<Operation, StepMetaDataCombi> operationToCombi = transformation.getOperations().stream()
.collect( toMap( Function.identity(),
op -> {
StepMetaDataCombi combi = new StepMetaDataCombi();
combi.stepMeta = StepMeta.fromXml( (String) op.getConfig().get( TransMetaConverter.STEP_META_CONF_KEY ) );
try {
combi.data = new StepDataInterfaceWebSocketEngineAdapter( op, messageEventService );
combi.step = new StepInterfaceWebSocketEngineAdapter( op, messageEventService, combi.stepMeta, transMeta,
combi.data, this );
} catch ( KettleException e ) {
//TODO: treat the exception
e.printStackTrace();
}
combi.meta = combi.stepMeta.getStepMetaInterface();
combi.stepname = combi.stepMeta.getName();
return combi;
} ) );
return operationToCombi.values();
}
@Override public void startThreads() throws KettleException {
getDaemonEndpoint().sendMessage( executionRequest );
//let's start the session monitor
startSessionMonitor();
}
private void startSessionMonitor() {
getLogChannel().logDebug( "Starting Session Monitor." );
sessionMonitor = Executors.newSingleThreadExecutor();
sessionMonitor.submit( () -> {
int failedTests = 0;
while ( !isFinished() ) {
try {
if ( failedTests > MAX_TEST_FAILED ) {
// Too many tests missed let's close
errors.incrementAndGet();
getLogChannel().logError(
"Session Monitor detected that communication with the server was lost. Finalizing execution." );
finishProcess( false );
// Signal for the the waitUntilFinished blocker...
transFinishedSignal.countDown();
} else {
TimeUnit.MILLISECONDS.sleep( SLEEP_TIME_MS );
getDaemonEndpoint().sessionValid();
if ( failedTests > 0 ) {
getLogChannel()
.logDebug( "Session Monitor - Server Communication restored." );
}
failedTests = 0;
}
} catch ( KettleException e ) {
failedTests++;
getLogChannel()
.logDebug(
"Session Monitor detected communication problem with the server. Retry (" + failedTests + "/"
+ MAX_TEST_FAILED + ")." );
} catch ( InterruptedException e ) {
getLogChannel().logDebug( "Session Monitor was interrupted." );
}
}
closeSessionMonitor();
} );
}
private void closeSessionMonitor() {
if ( sessionMonitor != null && !sessionMonitor.isShutdown() ) {
try {
getLogChannel().logDebug( "Shutting down the Session Monitor." );
sessionMonitor.shutdown();
} finally {
if ( !sessionMonitor.isTerminated() ) {
sessionMonitor.shutdownNow();
}
getLogChannel().logDebug( "Session Monitor shutdown." );
}
}
}
@Override public void waitUntilFinished() {
try {
transFinishedSignal.await();
} catch ( InterruptedException e ) {
throw new RuntimeException( "Waiting for transformation to be finished interrupted!", e );
}
}
@Override
public int getErrors() {
int nrErrors = errors.get();
if ( getSteps() != null ) {
for ( int i = 0; i < getSteps().size(); i++ ) {
nrErrors += getSteps().get( i ).step.getErrors();
}
}
return nrErrors;
}
@Override
public Result getResult() {
Result toRet = new Result();
toRet.setNrErrors( getErrors() );
return toRet;
}
private void finishProcess( boolean emitToAllSteps ) {
setFinished( true );
if ( emitToAllSteps ) {
// emit error on all steps
getSteps().stream().map( stepMetaDataCombi -> stepMetaDataCombi.step ).forEach( step -> {
step.setStopped( true );
step.setRunning( false );
} );
}
getTransListeners().forEach( l -> {
try {
l.transFinished( TransWebSocketEngineAdapter.this );
} catch ( KettleException e1 ) {
getLogChannel().logError( "Error notifying trans listener", e1 );
}
} );
}
// ======================== May want to implement ================================= //
@Override public RowProducer addRowProducer( String stepname, int copynr ) throws KettleException {
throw new UnsupportedOperationException( "Not yet implemented" );
}
private Principal getActingPrincipal( TransMeta transMeta ) {
if ( transMeta.getRepository() == null || transMeta.getRepository().getUserInfo() == null ) {
return ActingPrincipal.ANONYMOUS;
}
return new ActingPrincipal( transMeta.getRepository().getUserInfo().getName() );
}
}
|
engine/src/main/java/org/pentaho/di/trans/ael/websocket/TransWebSocketEngineAdapter.java
|
/*
* ! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Pentaho : http://www.pentaho.com
*
* ******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* *****************************************************************************
*/
package org.pentaho.di.trans.ael.websocket;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.engine.api.events.PDIEvent;
import org.pentaho.di.engine.api.model.Operation;
import org.pentaho.di.engine.api.model.Transformation;
import org.pentaho.di.engine.api.remote.ExecutionRequest;
import org.pentaho.di.engine.api.remote.Message;
import org.pentaho.di.engine.api.remote.RemoteSource;
import org.pentaho.di.engine.api.remote.StopMessage;
import org.pentaho.di.engine.api.reporting.LogEntry;
import org.pentaho.di.engine.api.reporting.LogLevel;
import org.pentaho.di.engine.api.reporting.Status;
import org.pentaho.di.engine.model.ActingPrincipal;
import org.pentaho.di.trans.RowProducer;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.ael.adapters.TransMetaConverter;
import org.pentaho.di.trans.ael.websocket.exception.HandlerRegistrationException;
import org.pentaho.di.trans.ael.websocket.exception.MessageEventHandlerExecutionException;
import org.pentaho.di.trans.ael.websocket.handler.MessageEventHandler;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaDataCombi;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.Collection;
import static java.util.stream.Collectors.toMap;
/**
* Created by fcamara on 8/17/17.
*/
public class TransWebSocketEngineAdapter extends Trans {
private static final String OPERATION_LOG = "OPERATION_LOG_TRANS_WEBSOCK_";
private static final String TRANSFORMATION_LOG = "TRANSFORMATION_LOG_TRANS_WEBSOCK";
private static final String TRANSFORMATION_STATUS = "TRANSFORMATION_STATUS_TRANS_WEBSOCK";
private static final String TRANSFORMATION_ERROR = "TRANSFORMATION_ERROR_TRANS_WEBSOCK";
private static final String TRANSFORMATION_STOP = "TRANSFORMATION_STOP_TRANS_WEBSOCK";
private static final String SPARK_SESSION_KILLED_MSG = "Spark session was killed";
//session monitor properties
private static final int SLEEP_TIME_MS = 10000;
private static final int MAX_TEST_FAILED = 3;
private ExecutorService sessionMonitor = null;
private final Transformation transformation;
private ExecutionRequest executionRequest;
private DaemonMessagesClientEndpoint daemonMessagesClientEndpoint = null;
private final MessageEventService messageEventService;
private LogLevel logLevel = null;
private final String host;
private final String port;
private final boolean ssl;
//completion signal used to wait until Transformation is finished
private CountDownLatch transFinishedSignal = new CountDownLatch( 1 );
private AtomicInteger errors = new AtomicInteger();
private static final Map<org.pentaho.di.core.logging.LogLevel, LogLevel> LEVEL_MAP = new HashMap<>();
static {
LEVEL_MAP.put( org.pentaho.di.core.logging.LogLevel.BASIC, LogLevel.BASIC );
LEVEL_MAP.put( org.pentaho.di.core.logging.LogLevel.DEBUG, LogLevel.DEBUG );
LEVEL_MAP.put( org.pentaho.di.core.logging.LogLevel.DETAILED, LogLevel.DETAILED );
LEVEL_MAP.put( org.pentaho.di.core.logging.LogLevel.ERROR, LogLevel.ERROR );
LEVEL_MAP.put( org.pentaho.di.core.logging.LogLevel.MINIMAL, LogLevel.MINIMAL );
LEVEL_MAP.put( org.pentaho.di.core.logging.LogLevel.ROWLEVEL, LogLevel.TRACE );
}
public TransWebSocketEngineAdapter( TransMeta transMeta, String host, String port, boolean ssl ) {
transformation = TransMetaConverter.convert( transMeta );
this.transMeta = transMeta;
this.messageEventService = new MessageEventService();
this.host = host;
this.port = port;
this.ssl = ssl;
}
private DaemonMessagesClientEndpoint getDaemonEndpoint() throws KettleException {
try {
if ( daemonMessagesClientEndpoint == null ) {
daemonMessagesClientEndpoint = new DaemonMessagesClientEndpoint( host, port, ssl, messageEventService );
}
return daemonMessagesClientEndpoint;
} catch ( KettleException e ) {
finishProcess( true );
transFinishedSignal.countDown();
throw e;
}
}
@Override public void setLogLevel( org.pentaho.di.core.logging.LogLevel logLogLevel ) {
this.logLevel = LEVEL_MAP.getOrDefault( logLogLevel, LogLevel.MINIMAL );
}
@Override public void killAll() {
throw new UnsupportedOperationException( "Not yet implemented" );
}
@Override public void stopAll() {
try {
getDaemonEndpoint().sendMessage( new StopMessage( getErrors() == 0 ? "User Request" : "Error reported" ) );
if ( getErrors() == 0 ) {
waitUntilFinished();
}
} catch ( KettleException e ) {
getLogChannel().logDebug( e.getMessage() );
}
}
@Override public void prepareExecution( String[] arguments ) throws KettleException {
activateParameters();
transMeta.activateParameters();
transMeta.setInternalKettleVariables();
Map<String, Object> env = Arrays.stream( transMeta.listVariables() )
.collect( toMap( Function.identity(), transMeta::getVariable ) );
this.executionRequest = new ExecutionRequest( new HashMap<>(), env, transformation, new HashMap<>(), logLevel,
getActingPrincipal( transMeta ) );
setSteps( new ArrayList<>( opsToSteps() ) );
wireStatusToTransListeners();
subscribeToOpLogging();
subscribeToTransLogging();
setReadyToStart( true );
}
private void logToChannel( LogChannelInterface logChannel, LogEntry data ) {
LogLevel logLogLevel = data.getLogLogLevel();
switch ( logLogLevel ) {
case ERROR:
logChannel.logError( data.getMessage(), data.getThrowable() );
break;
case MINIMAL:
logChannel.logMinimal( data.getMessage() );
break;
case BASIC:
logChannel.logBasic( data.getMessage() );
break;
case DETAILED:
logChannel.logDetailed( data.getMessage() );
break;
case DEBUG:
logChannel.logDebug( data.getMessage() );
break;
case TRACE:
logChannel.logRowlevel( data.getMessage() );
break;
}
}
private void subscribeToOpLogging() throws KettleException {
transformation.getOperations().stream().forEach( operation -> {
try {
messageEventService.addHandler( Util.getOperationLogEvent( operation.getId() ),
new MessageEventHandler() {
@Override
public void execute( Message message ) throws MessageEventHandlerExecutionException {
PDIEvent<RemoteSource, LogEntry> event = (PDIEvent<RemoteSource, LogEntry>) message;
LogEntry logEntry = event.getData();
StepInterface stepInterface = findStepInterface( operation.getId(), 0 );
if ( stepInterface != null ) {
LogChannelInterface logChannel = stepInterface.getLogChannel();
logToChannel( logChannel, logEntry );
} else {
// Could not find step, log at transformation level instead
logToChannel( getLogChannel(), logEntry );
}
}
@Override
public String getIdentifier() {
return OPERATION_LOG + operation.getId();
}
} );
} catch ( HandlerRegistrationException e ) {
getLogChannel().logError( "Error registering message handlers", e );
}
} );
}
private void subscribeToTransLogging() throws KettleException {
messageEventService.addHandler( Util.getTransformationLogEvent(),
new MessageEventHandler() {
@Override
public void execute( Message message ) throws MessageEventHandlerExecutionException {
PDIEvent<RemoteSource, LogEntry> event = (PDIEvent<RemoteSource, LogEntry>) message;
LogEntry data = event.getData();
logToChannel( getLogChannel(), data );
}
@Override
public String getIdentifier() {
return TRANSFORMATION_LOG;
}
} );
}
private void wireStatusToTransListeners() throws KettleException {
messageEventService.addHandler( Util.getTransformationStatusEvent(),
new MessageEventHandler() {
@Override
public void execute( Message message ) throws MessageEventHandlerExecutionException {
PDIEvent<RemoteSource, Status> transStatusEvent = (PDIEvent<RemoteSource, Status>) message;
addStepPerformanceSnapShot();
getTransListeners().forEach( l -> {
try {
switch ( transStatusEvent.getData() ) {
case RUNNING:
l.transStarted( TransWebSocketEngineAdapter.this );
l.transActive( TransWebSocketEngineAdapter.this );
break;
case PAUSED:
break;
case STOPPED:
break;
case FAILED:
case FINISHED:
l.transFinished( TransWebSocketEngineAdapter.this );
setFinished( true );
break;
}
} catch ( KettleException e ) {
throw new RuntimeException( e );
}
} );
}
@Override
public String getIdentifier() {
return TRANSFORMATION_STATUS;
}
} );
messageEventService
.addHandler( Util.getTransformationErrorEvent(), new MessageEventHandler() {
@Override
public void execute( Message message ) throws MessageEventHandlerExecutionException {
Throwable throwable = ( (PDIEvent<RemoteSource, LogEntry>) message ).getData().getThrowable();
getLogChannel().logError( "Error Executing Transformation", throwable );
errors.incrementAndGet();
finishProcess( true );
}
@Override
public String getIdentifier() {
return TRANSFORMATION_ERROR;
}
} );
messageEventService
.addHandler( Util.getStopMessage(), new MessageEventHandler() {
@Override
public void execute( Message message ) throws MessageEventHandlerExecutionException {
String stopMessage = ((StopMessage) message ).getReasonPhrase();
if ( SPARK_SESSION_KILLED_MSG.equals( stopMessage ) ) {
errors.incrementAndGet();
getLogChannel().logError( "Finalizing execution: " + stopMessage );
} else {
getLogChannel().logBasic( "Finalizing execution: " + stopMessage );
}
finishProcess( false );
try {
getDaemonEndpoint().close( stopMessage );
} catch ( KettleException e ) {
getLogChannel().logError( "Error finalizing", e );
}
//let's shutdown the session monitor thread
closeSessionMonitor();
// Signal for the the waitUntilFinished blocker...
transFinishedSignal.countDown();
}
@Override
public String getIdentifier() {
return TRANSFORMATION_STOP;
}
} );
}
private Collection<StepMetaDataCombi> opsToSteps() {
Map<Operation, StepMetaDataCombi> operationToCombi = transformation.getOperations().stream()
.collect( toMap( Function.identity(),
op -> {
StepMetaDataCombi combi = new StepMetaDataCombi();
combi.stepMeta = StepMeta.fromXml( (String) op.getConfig().get( TransMetaConverter.STEP_META_CONF_KEY ) );
try {
combi.data = new StepDataInterfaceWebSocketEngineAdapter( op, messageEventService );
combi.step = new StepInterfaceWebSocketEngineAdapter( op, messageEventService, combi.stepMeta, transMeta,
combi.data, this );
} catch ( KettleException e ) {
//TODO: treat the exception
e.printStackTrace();
}
combi.meta = combi.stepMeta.getStepMetaInterface();
combi.stepname = combi.stepMeta.getName();
return combi;
} ) );
return operationToCombi.values();
}
@Override public void startThreads() throws KettleException {
getDaemonEndpoint().sendMessage( executionRequest );
//let's start the session monitor
startSessionMonitor();
}
private void startSessionMonitor() {
getLogChannel().logDebug( "Starting Session Monitor." );
sessionMonitor = Executors.newSingleThreadExecutor();
sessionMonitor.submit( () -> {
int failedTests = 0;
while ( !isFinished() ) {
try {
if ( failedTests > MAX_TEST_FAILED ) {
// Too many tests missed let's close
errors.incrementAndGet();
getLogChannel().logError(
"Session Monitor detected that communication with the server was lost. Finalizing execution." );
finishProcess( false );
// Signal for the the waitUntilFinished blocker...
transFinishedSignal.countDown();
} else {
TimeUnit.MILLISECONDS.sleep( SLEEP_TIME_MS );
getDaemonEndpoint().sessionValid();
if ( failedTests > 0 ) {
getLogChannel()
.logDebug( "Session Monitor - Server Communication restored." );
}
failedTests = 0;
}
} catch ( KettleException e ) {
failedTests++;
getLogChannel()
.logDebug(
"Session Monitor detected communication problem with the server. Retry (" + failedTests + "/"
+ MAX_TEST_FAILED + ")." );
} catch ( InterruptedException e ) {
getLogChannel().logDebug( "Session Monitor was interrupted." );
}
}
closeSessionMonitor();
} );
}
private void closeSessionMonitor() {
if ( sessionMonitor != null && !sessionMonitor.isShutdown() ) {
try {
getLogChannel().logDebug( "Shutting down the Session Monitor." );
sessionMonitor.shutdown();
} finally {
if ( !sessionMonitor.isTerminated() ) {
sessionMonitor.shutdownNow();
}
getLogChannel().logDebug( "Session Monitor shutdown." );
}
}
}
@Override public void waitUntilFinished() {
try {
transFinishedSignal.await();
} catch ( InterruptedException e ) {
throw new RuntimeException( "Waiting for transformation to be finished interrupted!", e );
}
}
@Override
public int getErrors() {
int nrErrors = errors.get();
if ( getSteps() != null ) {
for ( int i = 0; i < getSteps().size(); i++ ) {
nrErrors += getSteps().get( i ).step.getErrors();
}
}
return nrErrors;
}
@Override
public Result getResult() {
Result toRet = new Result();
toRet.setNrErrors( getErrors() );
return toRet;
}
private void finishProcess( boolean emitToAllSteps ) {
setFinished( true );
if ( emitToAllSteps ) {
// emit error on all steps
getSteps().stream().map( stepMetaDataCombi -> stepMetaDataCombi.step ).forEach( step -> {
step.setStopped( true );
step.setRunning( false );
} );
}
getTransListeners().forEach( l -> {
try {
l.transFinished( TransWebSocketEngineAdapter.this );
} catch ( KettleException e1 ) {
getLogChannel().logError( "Error notifying trans listener", e1 );
}
} );
}
// ======================== May want to implement ================================= //
@Override public RowProducer addRowProducer( String stepname, int copynr ) throws KettleException {
throw new UnsupportedOperationException( "Not yet implemented" );
}
private Principal getActingPrincipal( TransMeta transMeta ) {
if ( transMeta.getRepository() == null || transMeta.getRepository().getUserInfo() == null ) {
return ActingPrincipal.ANONYMOUS;
}
return new ActingPrincipal( transMeta.getRepository().getUserInfo().getName() );
}
}
|
[BACKLOG-18598] Avoid NP when LogEntry doesn't have the throwable
|
engine/src/main/java/org/pentaho/di/trans/ael/websocket/TransWebSocketEngineAdapter.java
|
[BACKLOG-18598] Avoid NP when LogEntry doesn't have the throwable
|
<ide><path>ngine/src/main/java/org/pentaho/di/trans/ael/websocket/TransWebSocketEngineAdapter.java
<ide> LogLevel logLogLevel = data.getLogLogLevel();
<ide> switch ( logLogLevel ) {
<ide> case ERROR:
<del> logChannel.logError( data.getMessage(), data.getThrowable() );
<add> if ( data.getThrowable() != null ) {
<add> logChannel.logError( data.getMessage(), data.getThrowable() );
<add> } else {
<add> logChannel.logError( data.getMessage() );
<add> }
<ide> break;
<ide> case MINIMAL:
<ide> logChannel.logMinimal( data.getMessage() );
|
|
Java
|
apache-2.0
|
589b0c42876783d62e39c5648dc21788cf06c967
| 0 |
phimpme/android-prototype,phimpme/android-prototype,phimpme/android-prototype,phimpme/android-prototype
|
package org.fossasia.phimpme;
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import com.facebook.stetho.Stetho;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.twitter.sdk.android.core.DefaultLogger;
import com.twitter.sdk.android.core.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterConfig;
import com.uphyca.stetho_realm.RealmInspectorModulesProvider;
import io.fabric.sdk.android.Fabric;
import org.fossasia.phimpme.gallery.data.Album;
import org.fossasia.phimpme.gallery.data.HandlingAlbums;
import org.fossasia.phimpme.utilities.Constants;
import java.io.File;
import io.realm.Realm;
import io.realm.RealmConfiguration;
/**
* Created by dnld on 28/04/16.
*/
public class MyApplication extends Application {
private HandlingAlbums albums = null;
public static Context applicationContext;
public ImageLoader imageLoader;
private Boolean isPublished = false; // Set this to true at the time of release
public Album getAlbum() {
return albums.dispAlbums.size() > 0 ? albums.getCurrentAlbum() : Album.getEmptyAlbum();
}
@Override
public void onCreate() {
albums = new HandlingAlbums(getApplicationContext());
applicationContext = getApplicationContext();
MultiDex.install(this);
TwitterConfig config = new TwitterConfig.Builder(this)
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig(Constants.TWITTER_CONSUMER_KEY, Constants.TWITTER_CONSUMER_SECRET))
.debug(true)
.build();
Twitter.initialize(config);
/**
* Realm initialization
*/
Realm.init(this);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder()
.name("phimpme.realm")
.schemaVersion(1)
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(realmConfiguration);
super.onCreate();
if (isPublished)
Fabric.with(this, new Crashlytics());
/**
* Stetho initialization
*/
Stetho.initialize(
Stetho.newInitializerBuilder(this)
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
.build());
checkInitImageLoader();
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
}
public HandlingAlbums getAlbums() {
return albums;
}
public void setAlbums(HandlingAlbums albums) {
this.albums = albums;
}
public void updateAlbums() {
albums.loadAlbums(getApplicationContext());
}
private void initImageLoader() {
File cacheDir = com.nostra13.universalimageloader.utils.StorageUtils.getCacheDirectory(this);
int MAXMEMONRY = (int) (Runtime.getRuntime().maxMemory());
// System.out.println("dsa-->"+MAXMEMONRY+" "+(MAXMEMONRY/5));//.memoryCache(new
// LruMemoryCache(50 * 1024 * 1024))
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
this).memoryCacheExtraOptions(480, 800).defaultDisplayImageOptions(defaultOptions)
.diskCacheExtraOptions(480, 800, null).threadPoolSize(3)
.threadPriority(Thread.NORM_PRIORITY - 2)
.tasksProcessingOrder(QueueProcessingType.FIFO)
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new LruMemoryCache(MAXMEMONRY / 5))
.diskCache(new UnlimitedDiskCache(cacheDir))
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
.imageDownloader(new BaseImageDownloader(this)) // default
.imageDecoder(new BaseImageDecoder(false)) // default
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()).build();
this.imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
protected void checkInitImageLoader() {
if (!ImageLoader.getInstance().isInited()) {
initImageLoader();
}
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
|
app/src/main/java/org/fossasia/phimpme/MyApplication.java
|
package org.fossasia.phimpme;
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import com.facebook.stetho.Stetho;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.twitter.sdk.android.core.DefaultLogger;
import com.twitter.sdk.android.core.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterConfig;
import com.uphyca.stetho_realm.RealmInspectorModulesProvider;
import io.fabric.sdk.android.Fabric;
import org.fossasia.phimpme.gallery.data.Album;
import org.fossasia.phimpme.gallery.data.HandlingAlbums;
import org.fossasia.phimpme.utilities.Constants;
import java.io.File;
import io.realm.Realm;
import io.realm.RealmConfiguration;
/**
* Created by dnld on 28/04/16.
*/
public class MyApplication extends Application {
private HandlingAlbums albums = null;
public static Context applicationContext;
public ImageLoader imageLoader;
public Album getAlbum() {
return albums.dispAlbums.size() > 0 ? albums.getCurrentAlbum() : Album.getEmptyAlbum();
}
@Override
public void onCreate() {
albums = new HandlingAlbums(getApplicationContext());
applicationContext = getApplicationContext();
MultiDex.install(this);
TwitterConfig config = new TwitterConfig.Builder(this)
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig(Constants.TWITTER_CONSUMER_KEY, Constants.TWITTER_CONSUMER_SECRET))
.debug(true)
.build();
Twitter.initialize(config);
/**
* Realm initialization
*/
Realm.init(this);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder()
.name("phimpme.realm")
.schemaVersion(1)
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(realmConfiguration);
super.onCreate();
Fabric.with(this, new Crashlytics());
/**
* Stetho initialization
*/
Stetho.initialize(
Stetho.newInitializerBuilder(this)
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
.build());
checkInitImageLoader();
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
}
public HandlingAlbums getAlbums() {
return albums;
}
public void setAlbums(HandlingAlbums albums) {
this.albums = albums;
}
public void updateAlbums() {
albums.loadAlbums(getApplicationContext());
}
private void initImageLoader() {
File cacheDir = com.nostra13.universalimageloader.utils.StorageUtils.getCacheDirectory(this);
int MAXMEMONRY = (int) (Runtime.getRuntime().maxMemory());
// System.out.println("dsa-->"+MAXMEMONRY+" "+(MAXMEMONRY/5));//.memoryCache(new
// LruMemoryCache(50 * 1024 * 1024))
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
this).memoryCacheExtraOptions(480, 800).defaultDisplayImageOptions(defaultOptions)
.diskCacheExtraOptions(480, 800, null).threadPoolSize(3)
.threadPriority(Thread.NORM_PRIORITY - 2)
.tasksProcessingOrder(QueueProcessingType.FIFO)
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new LruMemoryCache(MAXMEMONRY / 5))
.diskCache(new UnlimitedDiskCache(cacheDir))
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
.imageDownloader(new BaseImageDownloader(this)) // default
.imageDecoder(new BaseImageDecoder(false)) // default
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()).build();
this.imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
protected void checkInitImageLoader() {
if (!ImageLoader.getInstance().isInited()) {
initImageLoader();
}
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
|
Removed crashlytics from development (#1082)
|
app/src/main/java/org/fossasia/phimpme/MyApplication.java
|
Removed crashlytics from development (#1082)
|
<ide><path>pp/src/main/java/org/fossasia/phimpme/MyApplication.java
<ide> import com.uphyca.stetho_realm.RealmInspectorModulesProvider;
<ide>
<ide> import io.fabric.sdk.android.Fabric;
<add>
<ide> import org.fossasia.phimpme.gallery.data.Album;
<ide> import org.fossasia.phimpme.gallery.data.HandlingAlbums;
<ide> import org.fossasia.phimpme.utilities.Constants;
<ide> private HandlingAlbums albums = null;
<ide> public static Context applicationContext;
<ide> public ImageLoader imageLoader;
<add> private Boolean isPublished = false; // Set this to true at the time of release
<ide>
<ide> public Album getAlbum() {
<ide> return albums.dispAlbums.size() > 0 ? albums.getCurrentAlbum() : Album.getEmptyAlbum();
<ide> .build();
<ide> Realm.setDefaultConfiguration(realmConfiguration);
<ide> super.onCreate();
<del> Fabric.with(this, new Crashlytics());
<add> if (isPublished)
<add> Fabric.with(this, new Crashlytics());
<ide>
<ide> /**
<ide> * Stetho initialization
<ide> int MAXMEMONRY = (int) (Runtime.getRuntime().maxMemory());
<ide> // System.out.println("dsa-->"+MAXMEMONRY+" "+(MAXMEMONRY/5));//.memoryCache(new
<ide> // LruMemoryCache(50 * 1024 * 1024))
<del> DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
<add> DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
<ide> .cacheInMemory(true)
<ide> .cacheOnDisk(true)
<ide> .build();
<ide> this.imageLoader = ImageLoader.getInstance();
<ide> imageLoader.init(config);
<ide> }
<add>
<ide> protected void checkInitImageLoader() {
<ide> if (!ImageLoader.getInstance().isInited()) {
<ide> initImageLoader();
|
|
Java
|
agpl-3.0
|
5ed5afd9e95a3214f1f079f5e9619239e61b39fc
| 0 |
medsob/Tanaguru,medsob/Tanaguru,dzc34/Asqatasun,Asqatasun/Asqatasun,Asqatasun/Asqatasun,medsob/Tanaguru,dzc34/Asqatasun,Tanaguru/Tanaguru,Tanaguru/Tanaguru,Asqatasun/Asqatasun,Tanaguru/Tanaguru,Tanaguru/Tanaguru,medsob/Tanaguru,dzc34/Asqatasun,dzc34/Asqatasun,Asqatasun/Asqatasun,Asqatasun/Asqatasun,dzc34/Asqatasun
|
/*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2011 Open-S Company
*
* This file is part of Tanaguru.
*
* Tanaguru is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: open-s AT open-s DOT com
*/
package org.opens.tgol.orchestrator;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import org.opens.tanaguru.entity.audit.Audit;
import org.opens.tanaguru.entity.audit.AuditStatus;
import org.opens.tanaguru.entity.parameterization.Parameter;
import org.opens.tanaguru.service.AuditService;
import org.opens.tanaguru.service.AuditServiceListener;
import org.opens.tgol.emailsender.EmailSender;
import org.opens.tgol.entity.contract.*;
import org.opens.tgol.entity.factory.contract.ActFactory;
import org.opens.tgol.entity.scenario.Scenario;
import org.opens.tgol.entity.service.contract.ActDataService;
import org.opens.tgol.entity.service.contract.ScopeDataService;
import org.opens.tgol.entity.service.scenario.ScenarioDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
*
* @author jkowalczyk
*/
public class TanaguruOrchestratorImpl implements TanaguruOrchestrator {
private static final Logger LOGGER = Logger.getLogger(TanaguruOrchestratorImpl.class);
private AuditService auditService;
private ActDataService actDataService;
private ScenarioDataService scenarioDataService;
private ActFactory actFactory;
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
private Map<ScopeEnum, Scope> scopeMap = new EnumMap<ScopeEnum, Scope>(ScopeEnum.class);
private void initializeScopeMap(ScopeDataService ScopeDataService) {
for (Scope scope : ScopeDataService.findAll()) {
scopeMap.put(scope.getCode(), scope);
}
}
private EmailSender emailSender;
/*
* keys to send the user an email at the end of an audit.
*/
private static final String RECIPIENT_KEY = "recipient";
private static final String SUCCESS_SUBJECT_KEY = "success-subject";
private static final String ERROR_SUBJECT_KEY = "error-subject";
private static final String URL_TO_REPLACE = "#webresourceUrl";
private static final String PROJECT_NAME_TO_REPLACE = "#projectName";
private static final String PROJECT_URL_TO_REPLACE = "#projectUrl";
private static final String SUCCESS_MSG_CONTENT_KEY = "success-content";
private static final String SITE_ERROR_MSG_CONTENT_KEY = "site-error-content";
private static final String PAGE_ERROR_MSG_CONTENT_KEY = "page-error-content";
private static final String BUNDLE_NAME = "email-content-I18N";
private static final int DEFAULT_AUDIT_DELAY = 30000;
private String webappUrl;
public String getWebappUrl() {
return webappUrl;
}
public void setWebappUrl(String webappUrl) {
this.webappUrl = webappUrl;
}
private String siteResultUrlSuffix;
public String getSiteResultUrlSuffix() {
return siteResultUrlSuffix;
}
public void setSiteResultUrlSuffix(String siteResultUrlSuffix) {
this.siteResultUrlSuffix = siteResultUrlSuffix;
}
private String scenarioResultUrlSuffix;
public String getScenarioResultUrlSuffix() {
return scenarioResultUrlSuffix;
}
public void setScenarioResultUrlSuffix(String scenarioResultUrlSuffix) {
this.scenarioResultUrlSuffix = scenarioResultUrlSuffix;
}
private String pageResultUrlSuffix;
public String getPageResultUrlSuffix() {
return pageResultUrlSuffix;
}
public void setPageResultUrlSuffix(String pageResultUrlSuffix) {
this.pageResultUrlSuffix = pageResultUrlSuffix;
}
private String groupResultUrlSuffix;
public String getGroupResultUrlSuffix() {
return groupResultUrlSuffix;
}
public void setGroupResultUrlSuffix(String groupResultUrlSuffix) {
this.groupResultUrlSuffix = groupResultUrlSuffix;
}
private String contractUrlSuffix;
public String getContractUrlSuffix() {
return contractUrlSuffix;
}
public void setContractUrlSuffix(String contractUrlSuffix) {
this.contractUrlSuffix = contractUrlSuffix;
}
private int delay = DEFAULT_AUDIT_DELAY;
public int getDelay() {
return delay;
}
public void setDelay(int delay) {
this.delay = delay;
}
private List<String> emailSentToUserExclusionList = new ArrayList<String>();
public void setEmailSentToUserExclusionRawList(String emailSentToUserExclusionRawList) {
this.emailSentToUserExclusionList.addAll(Arrays.asList(emailSentToUserExclusionRawList.split(";")));
}
// public TanaguruOrchestratorImpl(BlockingQueue workQueue) {
// threadPoolTaskExecutor = new ThreadPoolExecutor(
// 10, 100, 300L, TimeUnit.SECONDS, workQueue);
// }
//
// public TanaguruOrchestratorImpl(int corePoolSize,
// int maximumPoolSize,
// long keepAliveTime,
// BlockingQueue workQueue) {
// threadPoolTaskExecutor = new ThreadPoolExecutor(
// corePoolSize, maximumPoolSize,
// keepAliveTime, TimeUnit.SECONDS, workQueue);
// }
@Autowired
public TanaguruOrchestratorImpl(
AuditService auditService,
ActDataService actDataService,
ActFactory actFactory,
ScopeDataService scopeDataService,
ScenarioDataService scenarioDataService,
ThreadPoolTaskExecutor threadPoolTaskExecutor,
EmailSender emailSender) {
this.auditService = auditService;
this.actDataService = actDataService;
this.actFactory = actFactory;
this.scenarioDataService = scenarioDataService;
initializeScopeMap(scopeDataService);
this.threadPoolTaskExecutor = threadPoolTaskExecutor;
this.emailSender = emailSender;
}
@Override
public Audit auditPage(
Contract contract,
String pageUrl,
String clientIp,
Set<Parameter> parameterSet,
Locale locale) {
LOGGER.info("auditPage ");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("pageUrl " + pageUrl);
for (Parameter param : parameterSet) {
LOGGER.debug("param " + param.getValue() + " "+
param.getParameterElement().getParameterElementCode());
}
}
Act act = createAct(contract, ScopeEnum.PAGE, clientIp);
AuditTimeoutThread auditPageThread =
new AuditPageThread(
pageUrl,
auditService,
act,
parameterSet,
locale,
delay);
Audit audit = submitAuditAndLaunch(auditPageThread, act);
return audit;
}
@Override
public Audit auditPageUpload(
Contract contract,
Map<String, String> fileMap,
String clientIp,
Set<Parameter> parameterSet,
Locale locale) {
LOGGER.info("auditPage Upload");
if (LOGGER.isDebugEnabled()) {
for (Parameter param : parameterSet) {
LOGGER.debug("param " + param.getValue() + " "+
param.getParameterElement().getParameterElementCode());
}
}
Act act;
if (fileMap.size()>1) {
act = createAct(contract, ScopeEnum.GROUPOFFILES, clientIp);
} else {
act = createAct(contract, ScopeEnum.FILE, clientIp);
}
AuditTimeoutThread auditPageUploadThread =
new AuditPageUploadThread(
fileMap,
auditService,
act,
parameterSet,
locale,
delay);
Audit audit = submitAuditAndLaunch(auditPageUploadThread, act);
return audit;
}
@Override
public void auditSite(
Contract contract,
String siteUrl,
String clientIp,
Set<Parameter> parameterSet,
Locale locale) {
LOGGER.info("auditSite");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("siteUrl " + siteUrl);
for (Parameter param : parameterSet) {
LOGGER.debug("param " + param.getValue() + " "+
param.getParameterElement().getParameterElementCode());
}
}
Act act = createAct(contract, ScopeEnum.DOMAIN, clientIp);
AuditThread auditSiteThread =
new AuditSiteThread(
siteUrl,
auditService,
act,
parameterSet,
locale);
threadPoolTaskExecutor.submit(auditSiteThread);
}
@Override
public void auditScenario(
Contract contract,
Long idScenario,
String clientIp,
Set<Parameter> parameterSet,
Locale locale) {
LOGGER.info("auditScenario");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Scenario id " + idScenario);
for (Parameter param : parameterSet) {
LOGGER.debug("param " + param.getValue() + " "+
param.getParameterElement().getParameterElementCode());
}
}
Act act = createAct(contract, ScopeEnum.SCENARIO, clientIp);
Scenario scenario = scenarioDataService.read(idScenario);
AuditThread auditScenarioThread =
new AuditScenarioThread(
scenario.getLabel(),
scenario.getContent(),
auditService,
act,
parameterSet,
locale);
threadPoolTaskExecutor.submit(auditScenarioThread);
}
@Override
public Audit auditSite(
Contract contract,
String siteUrl,
final List<String> pageUrlList,
String clientIp,
Set<Parameter> parameterSet,
Locale locale) {
LOGGER.info("auditGroupOfPages");
if (LOGGER.isDebugEnabled()) {
for (String str :pageUrlList) {
LOGGER.debug("pageUrl " + str);
}
for (Parameter param : parameterSet) {
LOGGER.debug("param " + param.getValue() + " "+
param.getParameterElement().getParameterElementCode());
}
}
Act act = createAct(contract, ScopeEnum.GROUPOFPAGES, clientIp);
AuditTimeoutThread auditPageThread =
new AuditGroupOfPagesThread(
siteUrl,
pageUrlList,
auditService,
act,
parameterSet,
locale,
delay);
Audit audit = submitAuditAndLaunch(auditPageThread, act);
return audit;
}
/**
*
* @param auditTimeoutThread
* @param act
* @return
*/
private Audit submitAuditAndLaunch(AuditTimeoutThread auditTimeoutThread, Act act) {
synchronized (auditTimeoutThread) {
Future submitedThread = threadPoolTaskExecutor.submit(auditTimeoutThread);
while (submitedThread!=null && !submitedThread.isDone()) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
LOGGER.error("", ex);
}
if (auditTimeoutThread.isDurationExceedsDelay()) {
LOGGER.debug("Audit Duration ExceedsDelay. The audit result "
+ "is now managed in an asynchronous way.");
break;
}
}
return auditTimeoutThread.getAudit();
}
}
private void sendEmail(Act act, Locale locale) {
String emailTo = act.getContract().getUser().getEmail1();
if (this.emailSentToUserExclusionList.contains(emailTo)) {
LOGGER.debug("Email not set cause user " + emailTo + " belongs to "
+ "exlusion list");
return;
}
ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME, locale);
String emailFrom = bundle.getString(RECIPIENT_KEY);
Set<String> emailToSet = new HashSet<String>();
emailToSet.add(emailTo);
StringBuilder projectName = new StringBuilder();
projectName.append(act.getContract().getLabel());
if (act.getScope().getCode().equals(ScopeEnum.SCENARIO)) {
projectName.append(" - ");
// the name of the scenario is persisted on engine's side as the URL
// of the parent WebResource
projectName.append(act.getWebResource().getURL());
}
if (act.getStatus().equals(ActStatus.COMPLETED)) {
String emailSubject = bundle.getString(SUCCESS_SUBJECT_KEY).replaceAll(PROJECT_NAME_TO_REPLACE, projectName.toString());
StringBuilder emailMessage = new StringBuilder();
emailMessage.append(computeSuccessfulMessageOnActTerminated(act, bundle, projectName.toString()));
emailSender.sendEmail(emailFrom, emailToSet, emailSubject, emailMessage.toString());
LOGGER.debug("success email sent to " + emailTo);
} else if (act.getStatus().equals(ActStatus.ERROR)) {
String emailSubject = bundle.getString(ERROR_SUBJECT_KEY).replaceAll(PROJECT_NAME_TO_REPLACE, projectName.toString());
StringBuilder emailMessage = new StringBuilder();
emailMessage.append(computeFailureMessageOnActTerminated(act, bundle, projectName.toString()));
emailSender.sendEmail(emailFrom, emailToSet, emailSubject, emailMessage.toString());
LOGGER.debug("error email sent " + emailTo);
}
}
/**
*
* @param act
* @param bundle
* @return
*/
private String computeSuccessfulMessageOnActTerminated(Act act, ResourceBundle bundle, String projectName) {
String messageContent =
bundle.getString(SUCCESS_MSG_CONTENT_KEY).
replaceAll(URL_TO_REPLACE, buildResultUrl(act));
return messageContent.replaceAll(PROJECT_NAME_TO_REPLACE, projectName);
}
/**
*
* @param act
* @param bundle
* @return
*/
private String computeFailureMessageOnActTerminated(Act act, ResourceBundle bundle, String projectName) {
String messageContent;
if (act.getScope().getCode().equals(ScopeEnum.DOMAIN)) {
messageContent = bundle.getString(SITE_ERROR_MSG_CONTENT_KEY);
} else {
messageContent = bundle.getString(PAGE_ERROR_MSG_CONTENT_KEY);
}
messageContent = messageContent.replaceAll(PROJECT_URL_TO_REPLACE, buildContractUrl(act.getContract()));
messageContent = messageContent.replaceAll(URL_TO_REPLACE, buildResultUrl(act));
return messageContent.replaceAll(PROJECT_NAME_TO_REPLACE, projectName);
}
/**
*
* @param act
* @return
*/
private String buildResultUrl (Act act) {
StringBuilder strb = new StringBuilder();
strb.append(webappUrl);
ScopeEnum scope = act.getScope().getCode();
if (scope.equals(ScopeEnum.DOMAIN)) {
strb.append(siteResultUrlSuffix);
} else if (scope.equals(ScopeEnum.GROUPOFPAGES) || scope.equals(ScopeEnum.GROUPOFFILES)) {
strb.append(groupResultUrlSuffix);
} else if (scope.equals(ScopeEnum.FILE) || scope.equals(ScopeEnum.PAGE)) {
strb.append(pageResultUrlSuffix);
} else if (scope.equals(ScopeEnum.SCENARIO)) {
strb.append(scenarioResultUrlSuffix);
}
strb.append(act.getWebResource().getId());
return strb.toString();
}
/**
*
* @param act
* @return
*/
private String buildContractUrl (Contract contract) {
StringBuilder strb = new StringBuilder();
strb.append(webappUrl);
strb.append(contractUrlSuffix);
strb.append(contract.getId());
return strb.toString();
}
/**
* This method initializes an act instance and persists it.
* @param contract
* @param scope
* @return
*/
private Act createAct(Contract contract, ScopeEnum scope, String clientIp) {
Date beginDate = new Date();
Act act = actFactory.createAct(beginDate, contract);
act.setStatus(ActStatus.RUNNING);
act.setScope(scopeMap.get(scope));
act.setClientIp(clientIp);
actDataService.saveOrUpdate(act);
return act;
}
/**
*
*/
private abstract class AuditThread implements Runnable, AuditServiceListener {
private AuditService auditService;
public AuditService getAuditService() {
return auditService;
}
public void setAuditService(AuditService auditService) {
this.auditService = auditService;
}
private Set<Parameter> parameterSet = new HashSet<Parameter>();
public Set<Parameter> getParameterSet() {
return parameterSet;
}
public void setParameterSet(Set<Parameter> parameterSet) {
this.parameterSet = parameterSet;
}
private Act currentAct;
public Act getCurrentAct() {
return currentAct;
}
public void setCurrentAct(Act currentAct) {
this.currentAct = currentAct;
}
private Map<Audit, Long> auditExecutionList = new ConcurrentHashMap<Audit, Long>();
public Map<Audit, Long> getAuditExecutionList() {
return auditExecutionList;
}
public void setAuditExecutionList(Map<Audit, Long> auditExecutionList) {
this.auditExecutionList = auditExecutionList;
}
private Map<Long, Audit> auditCompletedList = new ConcurrentHashMap<Long, Audit>();
public Map<Long, Audit> getAuditCompletedList() {
return auditCompletedList;
}
public void setAuditCompletedList(Map<Long, Audit> auditCompletedList) {
this.auditCompletedList = auditCompletedList;
}
private Map<Long, AbstractMap.SimpleImmutableEntry<Audit, Exception>> auditCrashedList = new HashMap<Long, AbstractMap.SimpleImmutableEntry<Audit, Exception>>();
public Map<Long, SimpleImmutableEntry<Audit, Exception>> getAuditCrashedList() {
return auditCrashedList;
}
public void setAuditCrashedList(Map<Long, SimpleImmutableEntry<Audit, Exception>> auditCrashedList) {
this.auditCrashedList = auditCrashedList;
}
private Date startDate;
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
private Audit audit = null;
public Audit getAudit() {
return audit;
}
public void setAudit(Audit audit) {
this.audit = audit;
}
private Locale locale = null;
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public AuditThread(
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale) {
if (parameterSet != null) {
this.parameterSet.addAll(parameterSet);
}
this.auditService = auditService;
this.currentAct = act;
this.locale = locale;
startDate = act.getBeginDate();
}
@Override
public void run() {
this.getAuditService().add(this);
Audit currentAudit = launchAudit();
currentAudit = this.waitForAuditToComplete(currentAudit);
this.getAuditService().remove(this);
this.getCurrentAct().setWebResource(currentAudit.getSubject());
onActTerminated(this.getCurrentAct(), currentAudit);
}
/**
*
* @return
*/
public abstract Audit launchAudit();
@Override
public void auditCompleted(Audit audit) {
LOGGER.debug("AUDIT COMPLETED:" + audit + "," + audit.getSubject().getURL() + "," + (long) (audit.getDateOfCreation().getTime() / 1000) + audit.getId());
Audit auditCompleted = null;
for (Audit auditRunning : this.auditExecutionList.keySet()) {
if (auditRunning.getId().equals(audit.getId())
&& (long) (auditRunning.getDateOfCreation().getTime() / 1000) == (long) (audit.getDateOfCreation().getTime() / 1000)) {
auditCompleted = auditRunning;
break;
}
}
if (auditCompleted != null) {
Long token = this.auditExecutionList.get(auditCompleted);
this.auditExecutionList.remove(auditCompleted);
this.auditCompletedList.put(token, audit);
}
}
@Override
public void auditCrashed(Audit audit, Exception exception) {
LOGGER.error("AUDIT CRASHED:" + audit + "," + audit.getSubject().getURL() + "," + (long) (audit.getDateOfCreation().getTime() / 1000), exception);
Audit auditCrashed = null;
for (Audit auditRunning : this.auditExecutionList.keySet()) {
if (auditRunning.getId().equals(audit.getId())
&& (long) (auditRunning.getDateOfCreation().getTime() / 1000) == (long) (audit.getDateOfCreation().getTime() / 1000)) {
auditCrashed = auditRunning;
break;
}
}
if (auditCrashed != null) {
Long token = this.auditExecutionList.get(auditCrashed);
this.auditExecutionList.remove(auditCrashed);
this.auditCrashedList.put(token, new AbstractMap.SimpleImmutableEntry<Audit, Exception>(audit, exception));
}
}
protected Audit waitForAuditToComplete(Audit audit) {
LOGGER.debug("WAIT FOR AUDIT TO COMPLETE:" + audit + "," + (long) (audit.getDateOfCreation().getTime() / 1000));
Long token = new Date().getTime();
this.getAuditExecutionList().put(audit, token);
// while the audit is not seen as completed or crashed
while (!this.getAuditCompletedList().containsKey(token) && !this.getAuditCrashedList().containsKey(token)) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
LOGGER.error("", ex);
}
}
if ((audit = this.getAuditCompletedList().get(token)) != null) {
this.getAuditCompletedList().remove(token);
return audit;
}
auditCrashed(this.getAuditCrashedList().get(token).getKey(), this.getAuditCrashedList().get(token).getValue());
return null;
}
protected void onActTerminated(Act act, Audit audit) {
LOGGER.debug("act is terminated");
this.audit = audit;
Date endDate = new Date();
act.setEndDate(endDate);
if (audit.getStatus().equals(AuditStatus.COMPLETED)) {
act.setStatus(ActStatus.COMPLETED);
} else {
act.setStatus(ActStatus.ERROR);
}
actDataService.saveOrUpdate(act);
}
}
/**
* Inner class in charge of launching a site audit in a thread. At the end
* the audit, an email has to be sent to the user with the audit info.
*/
private class AuditSiteThread extends AuditThread {
private String siteUrl;
public AuditSiteThread(
String siteUrl,
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale) {
super(auditService, act, parameterSet, locale);
this.siteUrl = siteUrl;
}
@Override
public Audit launchAudit() {
Audit audit = this.getAuditService().auditSite(
this.siteUrl,
this.getParameterSet());
return audit;
}
@Override
protected void onActTerminated(Act act, Audit audit) {
super.onActTerminated(act, audit);
sendEmail(act, getLocale());
LOGGER.info("site audit terminated");
}
}
/**
* Inner class in charge of launching a site audit in a thread. At the end
* the audit, an email has to be sent to the user with the audit info.
*/
private class AuditScenarioThread extends AuditThread {
private String scenarioName;
private String scenario;
public AuditScenarioThread(
String scenarioName,
String scenario,
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale) {
super(auditService, act, parameterSet, locale);
this.scenario = scenario;
this.scenarioName = scenarioName;
}
@Override
public Audit launchAudit() {
Audit audit = this.getAuditService().auditScenario(
this.scenarioName,
this.scenario,
this.getParameterSet());
return audit;
}
@Override
protected void onActTerminated(Act act, Audit audit) {
super.onActTerminated(act, audit);
sendEmail(act, getLocale());
LOGGER.info("scenario audit terminated");
}
}
/**
* Abstract Inner class in charge of launching an audit in a thread. This
* thread has to expose the current audit as an attribute. If the
* audit is not terminated in a given delay, this attribute returns null and
* an email has to be sent to inform the user.
*/
private abstract class AuditTimeoutThread extends AuditThread {
private boolean isAuditTerminatedAfterTimeout = false;
public boolean isAuditTerminatedAfterTimeout() {
return isAuditTerminatedAfterTimeout;
}
public void setAuditTerminatedAfterTimeout(boolean isAuditTerminatedBeforeTimeout) {
this.isAuditTerminatedAfterTimeout = isAuditTerminatedBeforeTimeout;
}
private int delay = DEFAULT_AUDIT_DELAY;
public AuditTimeoutThread (
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale,
int delay) {
super(auditService, act, parameterSet, locale);
this.delay = delay;
}
@Override
protected void onActTerminated(Act act, Audit audit) {
super.onActTerminated(act, audit);
if (isAuditTerminatedAfterTimeout()) {
sendEmail(act, getLocale());
}
}
public boolean isDurationExceedsDelay() {
long currentDuration = new Date().getTime() - getStartDate().getTime();
if (currentDuration > delay) {
LOGGER.debug("Audit Duration has exceeded synchronous delay " + delay);
isAuditTerminatedAfterTimeout = true;
return true;
}
return false;
}
}
/**
*
*/
private class AuditGroupOfPagesThread extends AuditTimeoutThread {
private String siteUrl;
private List<String> pageUrlList = new ArrayList<String>();
public AuditGroupOfPagesThread(
String siteUrl,
List<String> pageUrlList,
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale,
int delay) {
super(auditService, act, parameterSet, locale, delay);
this.siteUrl = siteUrl;
if (pageUrlList != null) {
this.pageUrlList.addAll(pageUrlList);
}
}
@Override
public Audit launchAudit() {
Audit audit = null;
if (!this.pageUrlList.isEmpty()) {
audit = this.getAuditService().auditSite(
this.siteUrl,
this.pageUrlList,
this.getParameterSet());
}
return audit;
}
}
/**
* Inner class in charge of launching a page audit in a thread.
*/
private class AuditPageThread extends AuditTimeoutThread {
private String pageUrl;
public AuditPageThread(
String pageUrl,
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale,
int delay) {
super(auditService, act, parameterSet, locale, delay);
this.pageUrl = pageUrl;
LOGGER.info("auditPage " + pageUrl);
}
@Override
public Audit launchAudit() {
Audit audit = null;
if (this.pageUrl != null) {
audit = this.getAuditService().auditPage(
this.pageUrl,
this.getParameterSet());
}
return audit;
}
}
/**
* Inner class in charge of launching a upload pages audit in a thread.
*/
private class AuditPageUploadThread extends AuditTimeoutThread {
Map<String, String> pageMap = new HashMap<String, String>();
public AuditPageUploadThread(
Map<String, String> pageMap,
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale,
int delay) {
super(auditService, act, parameterSet, locale, delay);
if (pageMap != null) {
this.pageMap.putAll(pageMap);
}
}
@Override
public Audit launchAudit() {
Audit audit = null;
if (!pageMap.isEmpty()) {
audit = this.getAuditService().auditPageUpload(
this.pageMap,
this.getParameterSet());
}
return audit;
}
}
}
|
web-app/tgol-orchestrator/src/main/java/org/opens/tgol/orchestrator/TanaguruOrchestratorImpl.java
|
/*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2011 Open-S Company
*
* This file is part of Tanaguru.
*
* Tanaguru is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: open-s AT open-s DOT com
*/
package org.opens.tgol.orchestrator;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import org.opens.tanaguru.entity.audit.Audit;
import org.opens.tanaguru.entity.audit.AuditStatus;
import org.opens.tanaguru.entity.parameterization.Parameter;
import org.opens.tanaguru.service.AuditService;
import org.opens.tanaguru.service.AuditServiceListener;
import org.opens.tgol.emailsender.EmailSender;
import org.opens.tgol.entity.contract.*;
import org.opens.tgol.entity.factory.contract.ActFactory;
import org.opens.tgol.entity.scenario.Scenario;
import org.opens.tgol.entity.service.contract.ActDataService;
import org.opens.tgol.entity.service.contract.ScopeDataService;
import org.opens.tgol.entity.service.scenario.ScenarioDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
*
* @author jkowalczyk
*/
public class TanaguruOrchestratorImpl implements TanaguruOrchestrator {
private static final Logger LOGGER = Logger.getLogger(TanaguruOrchestratorImpl.class);
private AuditService auditService;
private ActDataService actDataService;
private ScenarioDataService scenarioDataService;
private ActFactory actFactory;
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
private Map<ScopeEnum, Scope> scopeMap = new EnumMap<ScopeEnum, Scope>(ScopeEnum.class);
private void initializeScopeMap(ScopeDataService ScopeDataService) {
for (Scope scope : ScopeDataService.findAll()) {
scopeMap.put(scope.getCode(), scope);
}
}
private EmailSender emailSender;
/*
* keys to send the user an email at the end of an audit.
*/
private static final String RECIPIENT_KEY = "recipient";
private static final String SUCCESS_SUBJECT_KEY = "success-subject";
private static final String ERROR_SUBJECT_KEY = "error-subject";
private static final String URL_TO_REPLACE = "#webresourceUrl";
private static final String PROJECT_NAME_TO_REPLACE = "#projectName";
private static final String PROJECT_URL_TO_REPLACE = "#projectUrl";
private static final String SUCCESS_MSG_CONTENT_KEY = "success-content";
private static final String SITE_ERROR_MSG_CONTENT_KEY = "site-error-content";
private static final String PAGE_ERROR_MSG_CONTENT_KEY = "page-error-content";
private static final String BUNDLE_NAME = "email-content-I18N";
private static final int DEFAULT_AUDIT_DELAY = 30000;
private String webappUrl;
public String getWebappUrl() {
return webappUrl;
}
public void setWebappUrl(String webappUrl) {
this.webappUrl = webappUrl;
}
private String siteResultUrlSuffix;
public String getSiteResultUrlSuffix() {
return siteResultUrlSuffix;
}
public void setSiteResultUrlSuffix(String siteResultUrlSuffix) {
this.siteResultUrlSuffix = siteResultUrlSuffix;
}
private String scenarioResultUrlSuffix;
public String getScenarioResultUrlSuffix() {
return scenarioResultUrlSuffix;
}
public void setScenarioResultUrlSuffix(String scenarioResultUrlSuffix) {
this.scenarioResultUrlSuffix = scenarioResultUrlSuffix;
}
private String pageResultUrlSuffix;
public String getPageResultUrlSuffix() {
return pageResultUrlSuffix;
}
public void setPageResultUrlSuffix(String pageResultUrlSuffix) {
this.pageResultUrlSuffix = pageResultUrlSuffix;
}
private String groupResultUrlSuffix;
public String getGroupResultUrlSuffix() {
return groupResultUrlSuffix;
}
public void setGroupResultUrlSuffix(String groupResultUrlSuffix) {
this.groupResultUrlSuffix = groupResultUrlSuffix;
}
private String contractUrlSuffix;
public String getContractUrlSuffix() {
return contractUrlSuffix;
}
public void setContractUrlSuffix(String contractUrlSuffix) {
this.contractUrlSuffix = contractUrlSuffix;
}
private int delay = DEFAULT_AUDIT_DELAY;
public int getDelay() {
return delay;
}
public void setDelay(int delay) {
this.delay = delay;
}
private List<String> emailSentToUserExclusionList = new ArrayList<String>();
public void setEmailSentToUserExclusionRawList(String emailSentToUserExclusionRawList) {
this.emailSentToUserExclusionList.addAll(Arrays.asList(emailSentToUserExclusionRawList.split(";")));
}
// public TanaguruOrchestratorImpl(BlockingQueue workQueue) {
// threadPoolTaskExecutor = new ThreadPoolExecutor(
// 10, 100, 300L, TimeUnit.SECONDS, workQueue);
// }
//
// public TanaguruOrchestratorImpl(int corePoolSize,
// int maximumPoolSize,
// long keepAliveTime,
// BlockingQueue workQueue) {
// threadPoolTaskExecutor = new ThreadPoolExecutor(
// corePoolSize, maximumPoolSize,
// keepAliveTime, TimeUnit.SECONDS, workQueue);
// }
@Autowired
public TanaguruOrchestratorImpl(
AuditService auditService,
ActDataService actDataService,
ActFactory actFactory,
ScopeDataService scopeDataService,
ScenarioDataService scenarioDataService,
ThreadPoolTaskExecutor threadPoolTaskExecutor,
EmailSender emailSender) {
this.auditService = auditService;
this.actDataService = actDataService;
this.actFactory = actFactory;
this.scenarioDataService = scenarioDataService;
initializeScopeMap(scopeDataService);
this.threadPoolTaskExecutor = threadPoolTaskExecutor;
this.emailSender = emailSender;
}
@Override
public Audit auditPage(
Contract contract,
String pageUrl,
String clientIp,
Set<Parameter> parameterSet,
Locale locale) {
LOGGER.info("auditPage ");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("pageUrl " + pageUrl);
for (Parameter param : parameterSet) {
LOGGER.debug("param " + param.getValue() + " "+
param.getParameterElement().getParameterElementCode());
}
}
Act act = createAct(contract, ScopeEnum.PAGE, clientIp);
AuditTimeoutThread auditPageThread =
new AuditPageThread(
pageUrl,
auditService,
act,
parameterSet,
locale,
delay);
Audit audit = submitAuditAndLaunch(auditPageThread, act);
return audit;
}
@Override
public Audit auditPageUpload(
Contract contract,
Map<String, String> fileMap,
String clientIp,
Set<Parameter> parameterSet,
Locale locale) {
LOGGER.info("auditPage Upload");
if (LOGGER.isDebugEnabled()) {
for (Parameter param : parameterSet) {
LOGGER.debug("param " + param.getValue() + " "+
param.getParameterElement().getParameterElementCode());
}
}
Act act;
if (fileMap.size()>1) {
act = createAct(contract, ScopeEnum.GROUPOFFILES, clientIp);
} else {
act = createAct(contract, ScopeEnum.FILE, clientIp);
}
AuditTimeoutThread auditPageUploadThread =
new AuditPageUploadThread(
fileMap,
auditService,
act,
parameterSet,
locale,
delay);
Audit audit = submitAuditAndLaunch(auditPageUploadThread, act);
return audit;
}
@Override
public void auditSite(
Contract contract,
String siteUrl,
String clientIp,
Set<Parameter> parameterSet,
Locale locale) {
LOGGER.info("auditSite");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("siteUrl " + siteUrl);
for (Parameter param : parameterSet) {
LOGGER.debug("param " + param.getValue() + " "+
param.getParameterElement().getParameterElementCode());
}
}
Act act = createAct(contract, ScopeEnum.DOMAIN, clientIp);
AuditThread auditSiteThread =
new AuditSiteThread(
siteUrl,
auditService,
act,
parameterSet,
locale);
threadPoolTaskExecutor.submit(auditSiteThread);
}
@Override
public void auditScenario(
Contract contract,
Long idScenario,
String clientIp,
Set<Parameter> parameterSet,
Locale locale) {
LOGGER.info("auditScenario");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Scenario id " + idScenario);
for (Parameter param : parameterSet) {
LOGGER.debug("param " + param.getValue() + " "+
param.getParameterElement().getParameterElementCode());
}
}
Act act = createAct(contract, ScopeEnum.SCENARIO, clientIp);
Scenario scenario = scenarioDataService.read(idScenario);
AuditThread auditScenarioThread =
new AuditScenarioThread(
scenario.getLabel(),
scenario.getContent(),
auditService,
act,
parameterSet,
locale);
threadPoolTaskExecutor.submit(auditScenarioThread);
}
@Override
public Audit auditSite(
Contract contract,
String siteUrl,
final List<String> pageUrlList,
String clientIp,
Set<Parameter> parameterSet,
Locale locale) {
LOGGER.info("auditGroupOfPages");
if (LOGGER.isDebugEnabled()) {
for (String str :pageUrlList) {
LOGGER.debug("pageUrl " + str);
}
for (Parameter param : parameterSet) {
LOGGER.debug("param " + param.getValue() + " "+
param.getParameterElement().getParameterElementCode());
}
}
Act act = createAct(contract, ScopeEnum.GROUPOFPAGES, clientIp);
AuditTimeoutThread auditPageThread =
new AuditGroupOfPagesThread(
siteUrl,
pageUrlList,
auditService,
act,
parameterSet,
locale,
delay);
Audit audit = submitAuditAndLaunch(auditPageThread, act);
return audit;
}
/**
*
* @param auditTimeoutThread
* @param act
* @return
*/
private Audit submitAuditAndLaunch(AuditTimeoutThread auditTimeoutThread, Act act) {
synchronized (auditTimeoutThread) {
Future submitedThread = threadPoolTaskExecutor.submit(auditTimeoutThread);
while (submitedThread!=null && !submitedThread.isDone()) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
LOGGER.error("", ex);
}
if (auditTimeoutThread.isDurationExceedsDelay()) {
LOGGER.debug("Audit Duration ExceedsDelay. The audit result "
+ "is now managed in an asynchronous way.");
break;
}
}
return auditTimeoutThread.getAudit();
}
}
private void sendEmail(Act act, Locale locale) {
String emailTo = act.getContract().getUser().getEmail1();
if (this.emailSentToUserExclusionList.contains(emailTo)) {
LOGGER.debug("Email not set cause user " + emailTo + " belongs to "
+ "exlusion list");
return;
}
ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME, locale);
String emailFrom = bundle.getString(RECIPIENT_KEY);
Set<String> emailToSet = new HashSet<String>();
emailToSet.add(emailTo);
StringBuilder projectName = new StringBuilder();
projectName.append(act.getContract().getLabel());
if (act.getScope().getCode().equals(ScopeEnum.SCENARIO)) {
projectName.append(" - ");
// the name of the scenario is persisted on engine's side as the URL
// of the parent WebResource
projectName.append(act.getWebResource().getURL());
}
if (act.getStatus().equals(ActStatus.COMPLETED)) {
String emailSubject = bundle.getString(SUCCESS_SUBJECT_KEY).replaceAll(PROJECT_NAME_TO_REPLACE, projectName.toString());
StringBuilder emailMessage = new StringBuilder();
emailMessage.append(computeSuccessfulMessageOnActTerminated(act, bundle, projectName.toString()));
emailSender.sendEmail(emailFrom, emailToSet, emailSubject, emailMessage.toString());
LOGGER.debug("success email sent to " + emailTo);
} else if (act.getStatus().equals(ActStatus.ERROR)) {
String emailSubject = bundle.getString(ERROR_SUBJECT_KEY).replaceAll(PROJECT_NAME_TO_REPLACE, projectName.toString());
StringBuilder emailMessage = new StringBuilder();
emailMessage.append(computeFailureMessageOnActTerminated(act, bundle, projectName.toString()));
emailSender.sendEmail(emailFrom, emailToSet, emailSubject, emailMessage.toString());
LOGGER.debug("error email sent " + emailTo);
}
}
/**
*
* @param act
* @param bundle
* @return
*/
private String computeSuccessfulMessageOnActTerminated(Act act, ResourceBundle bundle, String projectName) {
String messageContent =
bundle.getString(SUCCESS_MSG_CONTENT_KEY).
replaceAll(URL_TO_REPLACE, buildResultUrl(act));
return messageContent.replaceAll(PROJECT_NAME_TO_REPLACE, projectName);
}
/**
*
* @param act
* @param bundle
* @return
*/
private String computeFailureMessageOnActTerminated(Act act, ResourceBundle bundle, String projectName) {
String messageContent;
if (act.getScope().getCode().equals(ScopeEnum.DOMAIN)) {
messageContent = bundle.getString(SITE_ERROR_MSG_CONTENT_KEY);
} else {
messageContent = bundle.getString(PAGE_ERROR_MSG_CONTENT_KEY);
}
messageContent = messageContent.replaceAll(PROJECT_URL_TO_REPLACE, buildContractUrl(act.getContract()));
messageContent = messageContent.replaceAll(URL_TO_REPLACE, buildResultUrl(act));
return messageContent.replaceAll(PROJECT_NAME_TO_REPLACE, projectName);
}
/**
*
* @param act
* @return
*/
private String buildResultUrl (Act act) {
StringBuilder strb = new StringBuilder();
strb.append(webappUrl);
ScopeEnum scope = act.getScope().getCode();
if (scope.equals(ScopeEnum.DOMAIN)) {
strb.append(siteResultUrlSuffix);
} else if (scope.equals(ScopeEnum.GROUPOFPAGES) || scope.equals(ScopeEnum.GROUPOFFILES)) {
strb.append(groupResultUrlSuffix);
} else if (scope.equals(ScopeEnum.FILE) || scope.equals(ScopeEnum.PAGE)) {
strb.append(pageResultUrlSuffix);
} else if (scope.equals(ScopeEnum.SCENARIO)) {
strb.append(scenarioResultUrlSuffix);
}
strb.append(act.getWebResource().getId());
return strb.toString();
}
/**
*
* @param act
* @return
*/
private String buildContractUrl (Contract contract) {
StringBuilder strb = new StringBuilder();
strb.append(webappUrl);
strb.append(contractUrlSuffix);
strb.append(contract.getId());
return strb.toString();
}
/**
* This method initializes an act instance and persists it.
* @param contract
* @param scope
* @return
*/
private Act createAct(Contract contract, ScopeEnum scope, String clientIp) {
Date beginDate = new Date();
Act act = actFactory.createAct(beginDate, contract);
act.setStatus(ActStatus.RUNNING);
act.setScope(scopeMap.get(scope));
act.setClientIp(clientIp);
actDataService.saveOrUpdate(act);
return act;
}
/**
*
*/
private abstract class AuditThread implements Runnable, AuditServiceListener {
private AuditService auditService;
public AuditService getAuditService() {
return auditService;
}
public void setAuditService(AuditService auditService) {
this.auditService = auditService;
}
private Set<Parameter> parameterSet = new HashSet<Parameter>();
public Set<Parameter> getParameterSet() {
return parameterSet;
}
public void setParameterSet(Set<Parameter> parameterSet) {
this.parameterSet = parameterSet;
}
private Act currentAct;
public Act getCurrentAct() {
return currentAct;
}
public void setCurrentAct(Act currentAct) {
this.currentAct = currentAct;
}
private Map<Audit, Long> auditExecutionList = new ConcurrentHashMap<Audit, Long>();
public Map<Audit, Long> getAuditExecutionList() {
return auditExecutionList;
}
public void setAuditExecutionList(Map<Audit, Long> auditExecutionList) {
this.auditExecutionList = auditExecutionList;
}
private Map<Long, Audit> auditCompletedList = new ConcurrentHashMap<Long, Audit>();
public Map<Long, Audit> getAuditCompletedList() {
return auditCompletedList;
}
public void setAuditCompletedList(Map<Long, Audit> auditCompletedList) {
this.auditCompletedList = auditCompletedList;
}
private Map<Long, AbstractMap.SimpleImmutableEntry<Audit, Exception>> auditCrashedList = new HashMap<Long, AbstractMap.SimpleImmutableEntry<Audit, Exception>>();
public Map<Long, SimpleImmutableEntry<Audit, Exception>> getAuditCrashedList() {
return auditCrashedList;
}
public void setAuditCrashedList(Map<Long, SimpleImmutableEntry<Audit, Exception>> auditCrashedList) {
this.auditCrashedList = auditCrashedList;
}
private Date startDate;
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
private Audit audit = null;
public Audit getAudit() {
return audit;
}
public void setAudit(Audit audit) {
this.audit = audit;
}
private Locale locale = null;
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public AuditThread(
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale) {
if (parameterSet != null) {
this.parameterSet.addAll(parameterSet);
}
this.auditService = auditService;
this.currentAct = act;
this.locale = locale;
startDate = act.getBeginDate();
}
@Override
public void run() {
this.getAuditService().add(this);
Audit currentAudit = launchAudit();
currentAudit = this.waitForAuditToComplete(currentAudit);
this.getAuditService().remove(this);
this.getCurrentAct().setWebResource(currentAudit.getSubject());
onActTerminated(this.getCurrentAct(), currentAudit);
}
/**
*
* @return
*/
public abstract Audit launchAudit();
@Override
public void auditCompleted(Audit audit) {
LOGGER.debug("AUDIT COMPLETED:" + audit + "," + audit.getSubject().getURL() + "," + (long) (audit.getDateOfCreation().getTime() / 1000) + audit.getId());
Audit auditCompleted = null;
for (Audit auditRunning : this.auditExecutionList.keySet()) {
if (auditRunning.getId().equals(audit.getId())
&& (long) (auditRunning.getDateOfCreation().getTime() / 1000) == (long) (audit.getDateOfCreation().getTime() / 1000)) {
auditCompleted = auditRunning;
break;
}
}
if (auditCompleted != null) {
Long token = this.auditExecutionList.get(auditCompleted);
this.auditExecutionList.remove(auditCompleted);
this.auditCompletedList.put(token, audit);
}
}
@Override
public void auditCrashed(Audit audit, Exception exception) {
LOGGER.error("AUDIT CRASHED:" + audit + "," + audit.getSubject().getURL() + "," + (long) (audit.getDateOfCreation().getTime() / 1000), exception);
Audit auditCrashed = null;
for (Audit auditRunning : this.auditExecutionList.keySet()) {
if (auditRunning.getId().equals(audit.getId())
&& (long) (auditRunning.getDateOfCreation().getTime() / 1000) == (long) (audit.getDateOfCreation().getTime() / 1000)) {
auditCrashed = auditRunning;
break;
}
}
if (auditCrashed != null) {
Long token = this.auditExecutionList.get(auditCrashed);
this.auditExecutionList.remove(auditCrashed);
this.auditCrashedList.put(token, new AbstractMap.SimpleImmutableEntry<Audit, Exception>(audit, exception));
}
}
protected Audit waitForAuditToComplete(Audit audit) {
LOGGER.debug("WAIT FOR AUDIT TO COMPLETE:" + audit + "," + (long) (audit.getDateOfCreation().getTime() / 1000));
Long token = new Date().getTime();
this.getAuditExecutionList().put(audit, token);
// while the audit is not seen as completed or crashed
while (!this.getAuditCompletedList().containsKey(token) && !this.getAuditCrashedList().containsKey(token)) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
LOGGER.error("", ex);
}
}
if ((audit = this.getAuditCompletedList().get(token)) != null) {
this.getAuditCompletedList().remove(token);
return audit;
}
auditCrashed(this.getAuditCrashedList().get(token).getKey(), this.getAuditCrashedList().get(token).getValue());
return null;
}
protected void onActTerminated(Act act, Audit audit) {
LOGGER.debug("act is terminated");
this.audit = audit;
Date endDate = new Date();
act.setEndDate(endDate);
if (audit.getStatus().equals(AuditStatus.COMPLETED)) {
act.setStatus(ActStatus.COMPLETED);
} else {
act.setStatus(ActStatus.ERROR);
}
actDataService.saveOrUpdate(act);
}
}
/**
* Inner class in charge of launching a site audit in a thread. At the end
* the audit, an email has to be sent to the user with the audit info.
*/
private class AuditSiteThread extends AuditThread {
private String siteUrl;
public AuditSiteThread(
String siteUrl,
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale) {
super(auditService, act, parameterSet, locale);
this.siteUrl = siteUrl;
}
@Override
public Audit launchAudit() {
Audit audit = this.getAuditService().auditSite(
this.siteUrl,
this.getParameterSet());
return audit;
}
@Override
protected void onActTerminated(Act act, Audit audit) {
super.onActTerminated(act, audit);
sendEmail(act, getLocale());
LOGGER.info("site audit terminated");
}
}
/**
* Inner class in charge of launching a site audit in a thread. At the end
* the audit, an email has to be sent to the user with the audit info.
*/
private class AuditScenarioThread extends AuditThread {
private String scenarioName;
private String scenario;
public AuditScenarioThread(
String scenarioName,
String scenario,
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale) {
super(auditService, act, parameterSet, locale);
this.scenario = scenario;
this.scenarioName = scenarioName;
}
@Override
public Audit launchAudit() {
Audit audit = this.getAuditService().auditScenario(
this.scenarioName,
this.scenario,
this.getParameterSet());
return audit;
}
@Override
protected void onActTerminated(Act act, Audit audit) {
super.onActTerminated(act, audit);
sendEmail(act, getLocale());
LOGGER.info("scenario audit terminated");
}
}
/**
* Abstract Inner class in charge of launching an audit in a thread. This
* thread has to expose the current audit as an attribute. If the
* audit is not terminated in a given delay, this attribute returns null and
* an email has to be sent to inform the user.
*/
private abstract class AuditTimeoutThread extends AuditThread {
private boolean isAuditTerminatedAfterTimeout = false;
public boolean isAuditTerminatedAfterTimeout() {
return isAuditTerminatedAfterTimeout;
}
public void setAuditTerminatedAfterTimeout(boolean isAuditTerminatedBeforeTimeout) {
this.isAuditTerminatedAfterTimeout = isAuditTerminatedBeforeTimeout;
}
private int delay = DEFAULT_AUDIT_DELAY;
public AuditTimeoutThread (
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale,
int delay) {
super(auditService, act, parameterSet, locale);
this.delay = delay;
}
@Override
protected void onActTerminated(Act act, Audit audit) {
super.onActTerminated(act, audit);
if (isAuditTerminatedAfterTimeout()) {
sendEmail(act, getLocale());
}
}
public boolean isDurationExceedsDelay() {
long currentDuration = new Date().getTime() - getStartDate().getTime();
if (currentDuration > delay) {
LOGGER.debug("Audit Duration has exceeded synchronous delay " + delay);
isAuditTerminatedAfterTimeout = true;
return true;
}
return false;
}
}
/**
*
*/
private class AuditGroupOfPagesThread extends AuditTimeoutThread {
private String siteUrl;
private List<String> pageUrlList = new ArrayList<String>();
public AuditGroupOfPagesThread(
String siteUrl,
List<String> pageUrlList,
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale,
int delay) {
super(auditService, act, parameterSet, locale, delay);
this.siteUrl = siteUrl;
if (pageUrlList != null) {
this.pageUrlList.addAll(pageUrlList);
}
}
@Override
public Audit launchAudit() {
Audit audit = null;
if (CollectionUtils.isNotEmpty(this.pageUrlList)) {
audit = this.getAuditService().auditSite(
this.siteUrl,
this.pageUrlList,
this.getParameterSet());
}
return audit;
}
}
/**
* Inner class in charge of launching a page audit in a thread.
*/
private class AuditPageThread extends AuditTimeoutThread {
private String pageUrl;
public AuditPageThread(
String pageUrl,
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale,
int delay) {
super(auditService, act, parameterSet, locale, delay);
this.pageUrl = pageUrl;
LOGGER.info("auditPage " + pageUrl);
}
@Override
public Audit launchAudit() {
Audit audit = null;
if (this.pageUrl != null) {
audit = this.getAuditService().auditPage(
this.pageUrl,
this.getParameterSet());
}
return audit;
}
}
/**
* Inner class in charge of launching a upload pages audit in a thread.
*/
private class AuditPageUploadThread extends AuditTimeoutThread {
Map<String, String> pageMap = new HashMap<String, String>();
public AuditPageUploadThread(
Map<String, String> pageMap,
AuditService auditService,
Act act,
Set<Parameter> parameterSet,
Locale locale,
int delay) {
super(auditService, act, parameterSet, locale, delay);
if (pageMap != null) {
this.pageMap.putAll(pageMap);
}
}
@Override
public Audit launchAudit() {
Audit audit = null;
if (MapUtils.isNotEmpty(pageMap)) {
audit = this.getAuditService().auditPageUpload(
this.pageMap,
this.getParameterSet());
}
return audit;
}
}
}
|
#587 : downgrade commons-collections.jar version from 3.2.1 to 3.1
|
web-app/tgol-orchestrator/src/main/java/org/opens/tgol/orchestrator/TanaguruOrchestratorImpl.java
|
#587 : downgrade commons-collections.jar version from 3.2.1 to 3.1
|
<ide><path>eb-app/tgol-orchestrator/src/main/java/org/opens/tgol/orchestrator/TanaguruOrchestratorImpl.java
<ide> import java.util.*;
<ide> import java.util.concurrent.ConcurrentHashMap;
<ide> import java.util.concurrent.Future;
<del>import org.apache.commons.collections.CollectionUtils;
<del>import org.apache.commons.collections.MapUtils;
<ide> import org.apache.log4j.Logger;
<ide> import org.opens.tanaguru.entity.audit.Audit;
<ide> import org.opens.tanaguru.entity.audit.AuditStatus;
<ide> @Override
<ide> public Audit launchAudit() {
<ide> Audit audit = null;
<del> if (CollectionUtils.isNotEmpty(this.pageUrlList)) {
<add> if (!this.pageUrlList.isEmpty()) {
<ide> audit = this.getAuditService().auditSite(
<ide> this.siteUrl,
<ide> this.pageUrlList,
<ide> @Override
<ide> public Audit launchAudit() {
<ide> Audit audit = null;
<del> if (MapUtils.isNotEmpty(pageMap)) {
<add> if (!pageMap.isEmpty()) {
<ide> audit = this.getAuditService().auditPageUpload(
<ide> this.pageMap,
<ide> this.getParameterSet());
|
|
Java
|
bsd-2-clause
|
c663c1e0dfe264e0e1ef5d87b500f321fcd9ff6a
| 0 |
jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu
|
/*
* Copyright (c) 2015, Absolute Performance, Inc. http://www.absolute-performance.com
* Copyright (c) 2016, Jack J. Woehr [email protected]
* SoftWoehr LLC PO Box 51, Golden CO 80402-0051 http://www.softwoehr.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ublu.command;
import ublu.AS400Factory;
import ublu.Ublu;
import ublu.util.ArgArray;
import ublu.util.Interpreter;
import ublu.util.DataSink;
import ublu.util.Generics.TupleStack;
import ublu.util.Putter;
import ublu.util.Tuple;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.RequestNotSupportedException;
import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Superclass of all commands the interpreter understands.
*
* @see ublu.Ublu
* @author jwoehr
*/
public abstract class Command implements CommandInterface {
private boolean hasUnknownDashCommand;
private AS400 as400;
/**
* Interpreter instance
*/
private Interpreter myInterpreter;
/**
* Command commandName
*/
private String commandName;
/**
* Command commandDescription
*/
private String commandDescription;
/**
* Data source
*/
private DataSink dataSrc;
/**
* Data dest
*/
private DataSink dataDest;
/**
* result code
*/
private COMMANDRESULT commandResult;
/**
* True if so set that the dash-command parsing found an unknown
* dash-command.
*
* @return True if so set that the dash-command parsing found an unknown
* dash-command.
*/
protected boolean havingUnknownDashCommand() {
return hasUnknownDashCommand;
}
/**
* Set true by command if dash-command parsing default case found an unknown
* dash-command.
*
* @param hasUnknownDashCommand true if dash-command parsing default case
* found an unknown dash-command.
*/
protected void setHasUnknownDashCommand(boolean hasUnknownDashCommand) {
this.hasUnknownDashCommand = hasUnknownDashCommand;
}
/**
* Get the AS400 instance (if any) associated with this command.
*
* @return the AS400 instance associated with this command or null if none
*/
protected final AS400 getAs400() {
return as400;
}
/**
* Set the AS400 instance (if any) associated with this command.
*
* @param as400 the AS400 instance associated with this command or null if
* none
*/
protected final void setAs400(AS400 as400) {
this.as400 = as400;
}
/**
* Set the AS400 instance (if any) associated with this command from the arg
* array's next tuple or pop. Gets the next tuple or pop from the arg array
* and instances the as400 member if tuple value is of that class
*
* @param args the argument array for this command
*/
protected final void setAs400fromTupleOrPop(ArgArray args) {
this.as400 = args.nextTupleOrPop().value(AS400.class);
// /* debug */ System.err.println(this.as400);
}
/**
* Get the class of the instance so that static methods can be invoked
*
* @return the class of the instance
*/
public Class<? extends Command> getCommandClass() {
return this.getClass();
}
/**
* Return result code
*
* @return result code
*/
public COMMANDRESULT getCommandResult() {
return commandResult;
}
/**
* Set result code
*
* @param commandResult result code
*/
public final void setCommandResult(COMMANDRESULT commandResult) {
this.commandResult = commandResult;
}
/**
* Get data source
*
* @return data source
*/
protected DataSink getDataSrc() {
return dataSrc;
}
/**
* Set data source
*
* @param dataSrc data source
*/
protected void setDataSrc(DataSink dataSrc) {
this.dataSrc = dataSrc;
}
/**
* Get data dest
*
* @return data dest
*/
protected DataSink getDataDest() {
return dataDest;
}
/**
* Set data dest
*
* @param dataDest data dest
*/
protected void setDataDest(DataSink dataDest) {
this.dataDest = dataDest;
}
/**
* Analyze next lex and return a new data sink. If the lex is "~" it means
* pop the tuple stack for the data sink.
*
* @param argArray the interpreter arg array
* @return a new data sink based on what was parsed
*/
protected static DataSink newDataSink(ArgArray argArray) {
return DataSink.fromSinkName(argArray.next());
}
/**
* Set data dest to data sink specified by next in the arg array
*
* @param args the arg array
*/
protected void setDataDestfromArgArray(ArgArray args) {
setDataDest(newDataSink(args));
}
/**
* Set data src to data sink specified by next in the arg array
*
* @param args the arg array
*/
protected void setDataSrcfromArgArray(ArgArray args) {
setDataSrc(newDataSink(args));
}
/**
* Get interpreter
*
* @return interpreter
*/
protected Interpreter getInterpreter() {
return myInterpreter;
}
/**
* Get the associated application controller instance
*
* @return associated application controller instance
*/
protected Ublu getUblu() {
return getInterpreter().getMyUblu();
}
/**
* Set interpreter
*
* @param myInterpreter interpreter
*/
@Override
public final void setInterpreter(Interpreter myInterpreter) {
this.myInterpreter = myInterpreter;
}
/**
* Get the logger from the Interpreter instance
*
* @return the logger from the Interpreter instance
*/
public Logger getLogger() {
return getInterpreter().getLogger();
}
/**
* Set a tuple value
*
* @param key
* @param value
* @return the tuple set or created
*/
protected Tuple setTuple(String key, Object value) {
return getInterpreter().setTuple(key, value);
}
/**
* Get a tuple by key. If the key is ~ then pop tuple stack for a tuple
*
* @param key a tuple name or ~ for "pop the stack"
* @return tuple the tuple or null
*/
protected Tuple getTuple(String key) {
Tuple t = null;
if (key.equals(ArgArray.POPTUPLE)) {
if (getTupleStack().size() > 0) {
t = getTupleStack().pop();
}
} else {
t = getInterpreter().getTuple(key);
}
return t;
}
/**
* Fetch a Tuple by name and return its value if the value is an instance of
* AS400, otherwise return null.
*
* @param key Tuple name
* @return the AS400 instance or null
*/
protected AS400 getAS400Tuple(String key) {
AS400 anAs400 = null;
Tuple t = getTuple(key);
Object o = t.getValue();
if (o instanceof AS400) {
anAs400 = AS400.class.cast(o);
}
return anAs400;
}
/**
* Get command commandName
*
* @return command commandName
*/
@Override
public String getCommandName() {
return commandName;
}
/**
* Set command commandName
*
* @param name
*/
public final void setCommandName(String name) {
commandName = name;
}
/**
* Get command commandDescription
*
* @return command commandDescription
*/
@Override
public String getCommandDescription() {
return commandDescription;
}
/**
* Set command commandDescription
*
* @param description
*/
protected final void setCommandDescription(String description) {
commandDescription = description;
}
/**
*
* @param name
* @param description
*/
protected void setNameAndDescription(String name, String description) {
setCommandName(name);
setCommandDescription(description);
}
/**
* Get commandName and commandDescription
*
* @return commandName and commandDescription
*/
public final String getNameAndDescription() {
StringBuilder sb = new StringBuilder(getCommandName());
sb.append(getCommandDescription());
return sb.toString();
}
/**
* Set up the Command's instance data for command instance use.
* <p>
* Originally in the code the instances were re-used. So {@code reinit()} is
* a mixture of inits that need to be done one time and some that don't
* really need to be done unless the instance is used, which doesn't happen
* anymore.</p>.
*/
protected void reinit() {
setAs400(null);
setDataDest(new DataSink(DataSink.SINKTYPE.STD, null));
setDataSrc(new DataSink(DataSink.SINKTYPE.STD, null));
setCommandResult(COMMANDRESULT.SUCCESS);
setHasUnknownDashCommand(false);
}
/**
* 0-arity ctor
*/
public Command() {
setCommandName("No command name set");
setCommandDescription("-No description was set for this command.");
}
/**
* Put an object to the data destination
*
* @param o object to put
* @throws SQLException
* @throws IOException
* @throws AS400SecurityException
* @throws ErrorCompletingRequestException
* @throws InterruptedException
* @throws ObjectDoesNotExistException
* @throws RequestNotSupportedException
*
*/
protected void put(Object o) throws SQLException, IOException, AS400SecurityException, ErrorCompletingRequestException, InterruptedException, ObjectDoesNotExistException, RequestNotSupportedException {
new Putter(o, getInterpreter()).put(getDataDest());
}
/**
* Put an object to the data destination flagging whether a newline added
*
* @param o object to put
* @param newline true if a newline should be appended when writing to STD,
* false if a space should be appended
* @throws SQLException
* @throws IOException
* @throws AS400SecurityException
* @throws ErrorCompletingRequestException
* @throws InterruptedException
* @throws ObjectDoesNotExistException
* @throws RequestNotSupportedException
*
*/
protected void put(Object o, boolean newline) throws SQLException, IOException, AS400SecurityException, ErrorCompletingRequestException, InterruptedException, ObjectDoesNotExistException, RequestNotSupportedException {
new Putter(o, getInterpreter()).put(getDataDest(), newline);
}
/**
* Put an object to the data destination flagging whether a space postpended
* and newline added
*
* @param o object to put
* @param space true if a space should be appended
* @param newline true if a newline should be appended when writing to STD
* @throws SQLException
* @throws IOException
* @throws AS400SecurityException
* @throws ErrorCompletingRequestException
* @throws InterruptedException
* @throws ObjectDoesNotExistException
* @throws RequestNotSupportedException
*
*/
protected void put(Object o, boolean space, boolean newline) throws SQLException, IOException, AS400SecurityException, ErrorCompletingRequestException, InterruptedException, ObjectDoesNotExistException, RequestNotSupportedException {
new Putter(o, getInterpreter()).put(getDataDest(), space, newline);
}
/**
* Put an object to the data destination flagging whether a space postpended
* and newline added
*
* @param o object to put
* @param append true if append if data dest is file
* @param space true if a space should be appended
* @param newline true if a newline should be appended when writing to STD
* @throws SQLException
* @throws IOException
* @throws AS400SecurityException
* @throws ErrorCompletingRequestException
* @throws InterruptedException
* @throws ObjectDoesNotExistException
* @throws RequestNotSupportedException
*
*/
protected void put(Object o, boolean append, boolean space, boolean newline) throws SQLException, IOException, AS400SecurityException, ErrorCompletingRequestException, InterruptedException, ObjectDoesNotExistException, RequestNotSupportedException {
new Putter(o, getInterpreter()).put(getDataDest(), append, space, newline);
}
/**
* Put an object to the data destination with the specific charset name to
* use
*
* @param o object to put
* @param charsetName specific charset name to use
* @throws SQLException
* @throws IOException
* @throws AS400SecurityException
* @throws InterruptedException
* @throws ErrorCompletingRequestException
* @throws ObjectDoesNotExistException
* @throws RequestNotSupportedException
*
*/
protected void put(Object o, String charsetName) throws SQLException, IOException, AS400SecurityException, ErrorCompletingRequestException, InterruptedException, ObjectDoesNotExistException, RequestNotSupportedException {
new Putter(o, getInterpreter(), charsetName).put(getDataDest());
}
/**
* Log an error when there are insufficient arguments left in the
* interpreter argument array to satisfy the command.
*
* @param argArray The argument array from the interpreter
*/
protected final void logArgArrayTooShortError(ArgArray argArray) {
getLogger().log(Level.SEVERE, "{0} represents too few arguments to {1}", new Object[]{argArray.size(), getNameAndDescription()});
}
/**
* Log an error when no as400 instance has been provided
*
*/
protected final void logNoAs400() {
getLogger().log(Level.SEVERE, "No as400 instance provided to {0}", getNameAndDescription());
}
/**
* Parse the arg array for system username password in that order (each and
* any tuples or plain words) and come back with an AS400 object that has
* not yet attempted to log in.
*
* @param argArray the arg array to the command where the next three
* elements (either tuple references or plain words) represent system userid
* password
* @return the AS400 object or null
* @throws PropertyVetoException
*/
protected AS400 as400FromArgs(ArgArray argArray) throws PropertyVetoException {
String system = argArray.nextMaybeQuotationTuplePopString();
String username = argArray.nextMaybeQuotationTuplePopString();
String password = argArray.nextMaybeQuotationTuplePopString();
return AS400Factory.newAS400(getInterpreter(), system, username, password);
}
/**
* Parse the arg array for system username password in that order (each and
* any tuples or plain words) and come back with an AS400 object that has
* not yet attempted to log in.
*
* @param argArray the arg array to the command where the next three
* elements (either tuple references or plain words) represent system userid
* password
* @param signon_security_type if set to SIGNON_SECURITY_TYPE.SSL use ssl
* @return the AS400 object or null
* @throws PropertyVetoException
*/
protected AS400 as400FromArgs(ArgArray argArray, AS400Factory.SIGNON_SECURITY_TYPE signon_security_type) throws PropertyVetoException {
String system = argArray.nextMaybeQuotationTuplePopString();
String username = argArray.nextMaybeQuotationTuplePopString();
String password = argArray.nextMaybeQuotationTuplePopString();
return AS400Factory.newAS400(getInterpreter(), system, username, password, signon_security_type);
}
/**
* Set our AS400 instance from instance created by parsing the arg array.
*
* @param argArray the arg array to the command where the next three strings
* are system userid password
* @throws PropertyVetoException
*/
protected void setAs400FromArgs(ArgArray argArray) throws PropertyVetoException {
setAs400(as400FromArgs(argArray));
}
/**
* Extract as400 from a tuple.
*
* @param as400Tuple Tuple nominally holding AS400 instance
* @return the AS400 object or null
*/
protected AS400 as400FromTuple(Tuple as400Tuple) {
AS400 result = null;
if (as400Tuple != null) {
Object o = as400Tuple.getValue();
if (o instanceof AS400) {
result = AS400.class.cast(o);
}
}
return result;
}
/**
* Set our AS400 instance from tuple.
*
* @param as400Tuple Tuple nominally holding AS400 instance
*/
protected void setAs400FromTuple(Tuple as400Tuple) {
setAs400(as400FromTuple(as400Tuple));
}
/**
* Set an error flag in the default case for handling dash-commands.
*
* @param dashCommand the unknown dash-command
*/
protected void unknownDashCommand(String dashCommand) {
getLogger().log(Level.SEVERE, "Unknown dash-command {0} in {1}", new Object[]{dashCommand, getNameAndDescription()});
setHasUnknownDashCommand(true);
}
/**
* Get a string from whatever data sink is the datasrc, either reading one
* line from a file, or toString'ing a tuple, or reading a string from the
* arg array.
*
* @param argArray the command's argarray
* @return a string parsed from whatever the data src is , or null if none
* can be parsed.
* @throws FileNotFoundException
* @throws IOException
*/
protected String getStringFromDataSrc(ArgArray argArray) throws FileNotFoundException, IOException {
String sendString = null;
switch (getDataSrc().getType()) {
case FILE:
File f = new File(getDataSrc().getName());
if (f.exists()) {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
sendString = br.readLine();
}
break;
case STD:
if (!argArray.isEmpty()) {
sendString = argArray.nextMaybeQuotationTuplePopString();
}
break;
case TUPLE:
Tuple t = getTuple(getDataSrc().getName());
if (t != null) {
sendString = t.getValue().toString();
}
break;
}
return sendString;
}
/**
* Get the tuple stack maintained by the interpreter
*
* @return the tuple stack maintained by the interpreter
*/
protected TupleStack getTupleStack() {
return getInterpreter().getTupleStack();
}
/**
* Don't allow null strings coming from non-existent tuples. Set command
* failure if non-existent tuple provided.
*
* @param argArray the rest of the args
* @return String value of tuple or null
*/
protected String nextStringCheckingForNonExistentTuple(ArgArray argArray) {
String result = null;
if (argArray.peekNonExistentTuple()) {
setCommandResult(COMMANDRESULT.FAILURE);
getLogger().log(Level.SEVERE, "Non-existent tuple provided to {0}", getNameAndDescription());
} else {
result = argArray.nextMaybeQuotationTuplePopString();
}
return result;
}
/**
* Don't allow nulls coming from non-existent tuples. Set command failure if
* non-existent tuple provided.
*
* @param argArray the rest of the args
* @return value of tuple or null
*/
protected Object nextTupleValueCheckingForNonExistentTuple(ArgArray argArray) {
Object a = null;
if (argArray.peekNonExistentTuple()) {
setCommandResult(COMMANDRESULT.FAILURE);
getLogger().log(Level.SEVERE, "Non-existent tuple provided to {0}", getNameAndDescription());
} else {
a = getTuple(argArray.next()).getValue();
}
return a;
}
}
|
src/ublu/command/Command.java
|
/*
* Copyright (c) 2015, Absolute Performance, Inc. http://www.absolute-performance.com
* Copyright (c) 2016, Jack J. Woehr [email protected]
* SoftWoehr LLC PO Box 51, Golden CO 80402-0051 http://www.softwoehr.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ublu.command;
import ublu.AS400Factory;
import ublu.Ublu;
import ublu.util.ArgArray;
import ublu.util.Interpreter;
import ublu.util.DataSink;
import ublu.util.Generics.TupleStack;
import ublu.util.Putter;
import ublu.util.Tuple;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.RequestNotSupportedException;
import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Superclass of all commands the interpreter understands.
*
* @see ublu.Ublu
* @author jwoehr
*/
public abstract class Command implements CommandInterface {
private boolean hasUnknownDashCommand;
private AS400 as400;
/**
* ublu instance
*/
private Interpreter myInterpreter;
/**
* Command commandName
*/
protected String commandName;
/**
* Command commandDescription
*/
protected String commandDescription;
/**
* Data source
*/
protected DataSink dataSrc;
/**
* Data dest
*/
protected DataSink dataDest;
/**
* result code
*/
protected COMMANDRESULT commandResult;
/**
* True if so set that the dash-command parsing found an unknown
* dash-command.
*
* @return True if so set that the dash-command parsing found an unknown
* dash-command.
*/
protected boolean havingUnknownDashCommand() {
return hasUnknownDashCommand;
}
/**
* Set true by command if dash-command parsing default case found an unknown
* dash-command.
*
* @param hasUnknownDashCommand true if dash-command parsing default case
* found an unknown dash-command.
*/
protected void setHasUnknownDashCommand(boolean hasUnknownDashCommand) {
this.hasUnknownDashCommand = hasUnknownDashCommand;
}
/**
* Get the AS400 instance (if any) associated with this command.
*
* @return the AS400 instance associated with this command or null if none
*/
protected final AS400 getAs400() {
return as400;
}
/**
* Set the AS400 instance (if any) associated with this command.
*
* @param as400 the AS400 instance associated with this command or null if
* none
*/
protected final void setAs400(AS400 as400) {
this.as400 = as400;
}
/**
* Set the AS400 instance (if any) associated with this command from the arg
* array's next tuple or pop. Gets the next tuple or pop from the arg array
* and instances the as400 member if tuple value is of that class
*
* @param args the argument array for this command
*/
protected final void setAs400fromTupleOrPop(ArgArray args) {
this.as400 = args.nextTupleOrPop().value(AS400.class);
// /* debug */ System.err.println(this.as400);
}
/**
* Get the class of the instance so that static methods can be invoked
*
* @return the class of the instance
*/
public Class<? extends Command> getCommandClass() {
return this.getClass();
}
/**
* Return result code
*
* @return result code
*/
public COMMANDRESULT getCommandResult() {
return commandResult;
}
/**
* Set result code
*
* @param commandResult result code
*/
public final void setCommandResult(COMMANDRESULT commandResult) {
this.commandResult = commandResult;
}
/**
* Get data source
*
* @return data source
*/
protected DataSink getDataSrc() {
return dataSrc;
}
/**
* Set data source
*
* @param dataSrc data source
*/
protected void setDataSrc(DataSink dataSrc) {
this.dataSrc = dataSrc;
}
/**
* Get data dest
*
* @return data dest
*/
protected DataSink getDataDest() {
return dataDest;
}
/**
* Set data dest
*
* @param dataDest data dest
*/
protected void setDataDest(DataSink dataDest) {
this.dataDest = dataDest;
}
/**
* Analyze next lex and return a new data sink. If the lex is "~" it means
* pop the tuple stack for the data sink.
*
* @param argArray the interpreter arg array
* @return a new data sink based on what was parsed
*/
protected static DataSink newDataSink(ArgArray argArray) {
return DataSink.fromSinkName(argArray.next());
}
/**
* Set data dest to data sink specified by next in the arg array
*
* @param args the arg array
*/
protected void setDataDestfromArgArray(ArgArray args) {
setDataDest(newDataSink(args));
}
/**
* Set data src to data sink specified by next in the arg array
*
* @param args the arg array
*/
protected void setDataSrcfromArgArray(ArgArray args) {
setDataSrc(newDataSink(args));
}
/**
* Get interpreter
*
* @return interpreter
*/
protected Interpreter getInterpreter() {
return myInterpreter;
}
/**
* Get the associated application controller instance
*
* @return associated application controller instance
*/
protected Ublu getUblu() {
return getInterpreter().getMyUblu();
}
/**
* Set interpreter
*
* @param myInterpreter interpreter
*/
@Override
public final void setInterpreter(Interpreter myInterpreter) {
this.myInterpreter = myInterpreter;
}
/**
* Get the logger from the Interpreter instance
*
* @return the logger from the Interpreter instance
*/
public Logger getLogger() {
return getInterpreter().getLogger();
}
/**
* Set a tuple value
*
* @param key
* @param value
* @return the tuple set or created
*/
protected Tuple setTuple(String key, Object value) {
return getInterpreter().setTuple(key, value);
}
/**
* Get a tuple by key. If the key is ~ then pop tuple stack for a tuple
*
* @param key a tuple name or ~ for "pop the stack"
* @return tuple the tuple or null
*/
protected Tuple getTuple(String key) {
Tuple t = null;
if (key.equals(ArgArray.POPTUPLE)) {
if (getTupleStack().size() > 0) {
t = getTupleStack().pop();
}
} else {
t = getInterpreter().getTuple(key);
}
return t;
}
/**
* Fetch a Tuple by name and return its value if the value is an instance of
* AS400, otherwise return null.
*
* @param key Tuple name
* @return the AS400 instance or null
*/
protected AS400 getAS400Tuple(String key) {
AS400 anAs400 = null;
Tuple t = getTuple(key);
Object o = t.getValue();
if (o instanceof AS400) {
anAs400 = AS400.class.cast(o);
}
return anAs400;
}
/**
* Get command commandName
*
* @return command commandName
*/
@Override
public String getCommandName() {
return commandName;
}
/**
* Set command commandName
*
* @param name
*/
public final void setCommandName(String name) {
commandName = name;
}
/**
* Get command commandDescription
*
* @return command commandDescription
*/
@Override
public String getCommandDescription() {
return commandDescription;
}
/**
* Set command commandDescription
*
* @param description
*/
protected final void setCommandDescription(String description) {
commandDescription = description;
}
/**
*
* @param name
* @param description
*/
protected void setNameAndDescription(String name, String description) {
setCommandName(name);
setCommandDescription(description);
}
/**
* Get commandName and commandDescription
*
* @return commandName and commandDescription
*/
public final String getNameAndDescription() {
StringBuilder sb = new StringBuilder(getCommandName());
sb.append(getCommandDescription());
return sb.toString();
}
/**
* Set up the Command's instance data for command instance use.
* <p>
* Originally in the code the instances were re-used. So {@code reinit()} is
* a mixture of inits that need to be done one time and some that don't
* really need to be done unless the instance is used, which doesn't happen
* anymore.</p>.
*/
protected void reinit() {
setAs400(null);
setDataDest(new DataSink(DataSink.SINKTYPE.STD, null));
setDataSrc(new DataSink(DataSink.SINKTYPE.STD, null));
setCommandResult(COMMANDRESULT.SUCCESS);
setHasUnknownDashCommand(false);
}
/**
* 0-arity ctor
*/
public Command() {
setCommandName("No command name set");
setCommandDescription("-No description was set for this command.");
}
/**
* Put an object to the data destination
*
* @param o object to put
* @throws SQLException
* @throws IOException
* @throws AS400SecurityException
* @throws ErrorCompletingRequestException
* @throws InterruptedException
* @throws ObjectDoesNotExistException
* @throws RequestNotSupportedException
*
*/
protected void put(Object o) throws SQLException, IOException, AS400SecurityException, ErrorCompletingRequestException, InterruptedException, ObjectDoesNotExistException, RequestNotSupportedException {
new Putter(o, getInterpreter()).put(getDataDest());
}
/**
* Put an object to the data destination flagging whether a newline added
*
* @param o object to put
* @param newline true if a newline should be appended when writing to STD,
* false if a space should be appended
* @throws SQLException
* @throws IOException
* @throws AS400SecurityException
* @throws ErrorCompletingRequestException
* @throws InterruptedException
* @throws ObjectDoesNotExistException
* @throws RequestNotSupportedException
*
*/
protected void put(Object o, boolean newline) throws SQLException, IOException, AS400SecurityException, ErrorCompletingRequestException, InterruptedException, ObjectDoesNotExistException, RequestNotSupportedException {
new Putter(o, getInterpreter()).put(getDataDest(), newline);
}
/**
* Put an object to the data destination flagging whether a space postpended
* and newline added
*
* @param o object to put
* @param space true if a space should be appended
* @param newline true if a newline should be appended when writing to STD
* @throws SQLException
* @throws IOException
* @throws AS400SecurityException
* @throws ErrorCompletingRequestException
* @throws InterruptedException
* @throws ObjectDoesNotExistException
* @throws RequestNotSupportedException
*
*/
protected void put(Object o, boolean space, boolean newline) throws SQLException, IOException, AS400SecurityException, ErrorCompletingRequestException, InterruptedException, ObjectDoesNotExistException, RequestNotSupportedException {
new Putter(o, getInterpreter()).put(getDataDest(), space, newline);
}
/**
* Put an object to the data destination flagging whether a space postpended
* and newline added
*
* @param o object to put
* @param append true if append if data dest is file
* @param space true if a space should be appended
* @param newline true if a newline should be appended when writing to STD
* @throws SQLException
* @throws IOException
* @throws AS400SecurityException
* @throws ErrorCompletingRequestException
* @throws InterruptedException
* @throws ObjectDoesNotExistException
* @throws RequestNotSupportedException
*
*/
protected void put(Object o, boolean append, boolean space, boolean newline) throws SQLException, IOException, AS400SecurityException, ErrorCompletingRequestException, InterruptedException, ObjectDoesNotExistException, RequestNotSupportedException {
new Putter(o, getInterpreter()).put(getDataDest(), append, space, newline);
}
/**
* Put an object to the data destination with the specific charset name to
* use
*
* @param o object to put
* @param charsetName specific charset name to use
* @throws SQLException
* @throws IOException
* @throws AS400SecurityException
* @throws InterruptedException
* @throws ErrorCompletingRequestException
* @throws ObjectDoesNotExistException
* @throws RequestNotSupportedException
*
*/
protected void put(Object o, String charsetName) throws SQLException, IOException, AS400SecurityException, ErrorCompletingRequestException, InterruptedException, ObjectDoesNotExistException, RequestNotSupportedException {
new Putter(o, getInterpreter(), charsetName).put(getDataDest());
}
/**
* Log an error when there are insufficient arguments left in the
* interpreter argument array to satisfy the command.
*
* @param argArray The argument array from the interpreter
*/
protected final void logArgArrayTooShortError(ArgArray argArray) {
getLogger().log(Level.SEVERE, "{0} represents too few arguments to {1}", new Object[]{argArray.size(), getNameAndDescription()});
}
/**
* Log an error when no as400 instance has been provided
*
*/
protected final void logNoAs400() {
getLogger().log(Level.SEVERE, "No as400 instance provided to {0}", getNameAndDescription());
}
/**
* Parse the arg array for system username password in that order (each and
* any tuples or plain words) and come back with an AS400 object that has
* not yet attempted to log in.
*
* @param argArray the arg array to the command where the next three
* elements (either tuple references or plain words) represent system userid
* password
* @return the AS400 object or null
* @throws PropertyVetoException
*/
protected AS400 as400FromArgs(ArgArray argArray) throws PropertyVetoException {
String system = argArray.nextMaybeQuotationTuplePopString();
String username = argArray.nextMaybeQuotationTuplePopString();
String password = argArray.nextMaybeQuotationTuplePopString();
return AS400Factory.newAS400(getInterpreter(), system, username, password);
}
/**
* Parse the arg array for system username password in that order (each and
* any tuples or plain words) and come back with an AS400 object that has
* not yet attempted to log in.
*
* @param argArray the arg array to the command where the next three
* elements (either tuple references or plain words) represent system userid
* password
* @param signon_security_type if set to SIGNON_SECURITY_TYPE.SSL use ssl
* @return the AS400 object or null
* @throws PropertyVetoException
*/
protected AS400 as400FromArgs(ArgArray argArray, AS400Factory.SIGNON_SECURITY_TYPE signon_security_type) throws PropertyVetoException {
String system = argArray.nextMaybeQuotationTuplePopString();
String username = argArray.nextMaybeQuotationTuplePopString();
String password = argArray.nextMaybeQuotationTuplePopString();
return AS400Factory.newAS400(getInterpreter(), system, username, password, signon_security_type);
}
/**
* Set our AS400 instance from instance created by parsing the arg array.
*
* @param argArray the arg array to the command where the next three strings
* are system userid password
* @throws PropertyVetoException
*/
protected void setAs400FromArgs(ArgArray argArray) throws PropertyVetoException {
setAs400(as400FromArgs(argArray));
}
/**
* Extract as400 from a tuple.
*
* @param as400Tuple Tuple nominally holding AS400 instance
* @return the AS400 object or null
*/
protected AS400 as400FromTuple(Tuple as400Tuple) {
AS400 result = null;
if (as400Tuple != null) {
Object o = as400Tuple.getValue();
if (o instanceof AS400) {
result = AS400.class.cast(o);
}
}
return result;
}
/**
* Set our AS400 instance from tuple.
*
* @param as400Tuple Tuple nominally holding AS400 instance
*/
protected void setAs400FromTuple(Tuple as400Tuple) {
setAs400(as400FromTuple(as400Tuple));
}
/**
* Set an error flag in the default case for handling dash-commands.
*
* @param dashCommand the unknown dash-command
*/
protected void unknownDashCommand(String dashCommand) {
getLogger().log(Level.SEVERE, "Unknown dash-command {0} in {1}", new Object[]{dashCommand, getNameAndDescription()});
setHasUnknownDashCommand(true);
}
/**
* Get a string from whatever data sink is the datasrc, either reading one
* line from a file, or toString'ing a tuple, or reading a string from the
* arg array.
*
* @param argArray the command's argarray
* @return a string parsed from whatever the data src is , or null if none
* can be parsed.
* @throws FileNotFoundException
* @throws IOException
*/
protected String getStringFromDataSrc(ArgArray argArray) throws FileNotFoundException, IOException {
String sendString = null;
switch (getDataSrc().getType()) {
case FILE:
File f = new File(getDataSrc().getName());
if (f.exists()) {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
sendString = br.readLine();
}
break;
case STD:
if (!argArray.isEmpty()) {
sendString = argArray.nextMaybeQuotationTuplePopString();
}
break;
case TUPLE:
Tuple t = getTuple(getDataSrc().getName());
if (t != null) {
sendString = t.getValue().toString();
}
break;
}
return sendString;
}
/**
* Get the tuple stack maintained by the interpreter
*
* @return the tuple stack maintained by the interpreter
*/
protected TupleStack getTupleStack() {
return getInterpreter().getTupleStack();
}
/**
* Don't allow null strings coming from non-existent tuples. Set command
* failure if non-existent tuple provided.
*
* @param argArray the rest of the args
* @return String value of tuple or null
*/
protected String nextStringCheckingForNonExistentTuple(ArgArray argArray) {
String result = null;
if (argArray.peekNonExistentTuple()) {
setCommandResult(COMMANDRESULT.FAILURE);
getLogger().log(Level.SEVERE, "Non-existent tuple provided to {0}", getNameAndDescription());
} else {
result = argArray.nextMaybeQuotationTuplePopString();
}
return result;
}
/**
* Don't allow nulls coming from non-existent tuples. Set command failure if
* non-existent tuple provided.
*
* @param argArray the rest of the args
* @return value of tuple or null
*/
protected Object nextTupleValueCheckingForNonExistentTuple(ArgArray argArray) {
Object a = null;
if (argArray.peekNonExistentTuple()) {
setCommandResult(COMMANDRESULT.FAILURE);
getLogger().log(Level.SEVERE, "Non-existent tuple provided to {0}", getNameAndDescription());
} else {
a = getTuple(argArray.next()).getValue();
}
return a;
}
}
|
changed accessors
|
src/ublu/command/Command.java
|
changed accessors
|
<ide><path>rc/ublu/command/Command.java
<ide> private boolean hasUnknownDashCommand;
<ide> private AS400 as400;
<ide> /**
<del> * ublu instance
<add> * Interpreter instance
<ide> */
<ide> private Interpreter myInterpreter;
<ide> /**
<ide> * Command commandName
<ide> */
<del> protected String commandName;
<add> private String commandName;
<ide> /**
<ide> * Command commandDescription
<ide> */
<del> protected String commandDescription;
<add> private String commandDescription;
<ide> /**
<ide> * Data source
<ide> */
<del> protected DataSink dataSrc;
<add> private DataSink dataSrc;
<ide> /**
<ide> * Data dest
<ide> */
<del> protected DataSink dataDest;
<add> private DataSink dataDest;
<ide> /**
<ide> * result code
<ide> */
<del> protected COMMANDRESULT commandResult;
<add> private COMMANDRESULT commandResult;
<ide>
<ide> /**
<ide> * True if so set that the dash-command parsing found an unknown
|
|
Java
|
mit
|
08137b46eb1844f86b03210d770717b9fa66aef2
| 0 |
Azure/azure-sdk-for-java,navalev/azure-sdk-for-java,selvasingh/azure-sdk-for-java,navalev/azure-sdk-for-java,navalev/azure-sdk-for-java,selvasingh/azure-sdk-for-java,Azure/azure-sdk-for-java,selvasingh/azure-sdk-for-java,Azure/azure-sdk-for-java,navalev/azure-sdk-for-java,Azure/azure-sdk-for-java,navalev/azure-sdk-for-java,Azure/azure-sdk-for-java
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.v2;
import com.microsoft.rest.v2.RestException;
import com.microsoft.rest.v2.RestProxy;
import com.microsoft.rest.v2.SwaggerMethodParser;
import com.microsoft.rest.v2.http.HttpRequest;
import com.microsoft.rest.v2.http.HttpResponse;
import com.microsoft.rest.v2.protocol.HttpResponseDecoder;
import com.microsoft.rest.v2.protocol.SerializerEncoding;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
/**
* An abstract class for the different strategies that an OperationStatus can use when checking the
* status of a long running operation.
*/
abstract class PollStrategy {
private final RestProxy restProxy;
private final SwaggerMethodParser methodParser;
private long delayInMilliseconds;
private String status;
PollStrategy(PollStrategyData data) {
this.restProxy = data.restProxy;
this.methodParser = data.methodParser;
this.delayInMilliseconds = data.delayInMilliseconds;
}
abstract static class PollStrategyData implements Serializable {
transient RestProxy restProxy;
transient SwaggerMethodParser methodParser;
long delayInMilliseconds;
PollStrategyData(RestProxy restProxy,
SwaggerMethodParser methodParser,
long delayInMilliseconds) {
this.restProxy = restProxy;
this.methodParser = methodParser;
this.delayInMilliseconds = delayInMilliseconds;
}
abstract PollStrategy initializeStrategy(RestProxy restProxy,
SwaggerMethodParser methodParser);
}
@SuppressWarnings("unchecked")
protected <T> T deserialize(String value, Type returnType) throws IOException {
return (T) restProxy.serializer().deserialize(value, returnType, SerializerEncoding.JSON);
}
protected Single<HttpResponse> ensureExpectedStatus(HttpResponse httpResponse) {
return ensureExpectedStatus(httpResponse, null);
}
protected Single<HttpResponse> ensureExpectedStatus(HttpResponse httpResponse, int[] additionalAllowedStatusCodes) {
return restProxy.ensureExpectedStatus(httpResponse, methodParser, additionalAllowedStatusCodes);
}
protected String fullyQualifiedMethodName() {
return methodParser.fullyQualifiedMethodName();
}
protected boolean expectsResourceResponse() {
return methodParser.expectsResponseBody();
}
/**
* Set the delay in milliseconds to 0.
*/
final void clearDelayInMilliseconds() {
this.delayInMilliseconds = 0;
}
/**
* Update the delay in milliseconds from the provided HTTP poll response.
* @param httpPollResponse The HTTP poll response to update the delay in milliseconds from.
*/
final void updateDelayInMillisecondsFrom(HttpResponse httpPollResponse) {
final Long parsedDelayInMilliseconds = delayInMillisecondsFrom(httpPollResponse);
if (parsedDelayInMilliseconds != null) {
delayInMilliseconds = parsedDelayInMilliseconds;
}
}
static Long delayInMillisecondsFrom(HttpResponse httpResponse) {
Long result = null;
final String retryAfterSecondsString = httpResponse.headerValue("Retry-After");
if (retryAfterSecondsString != null && !retryAfterSecondsString.isEmpty()) {
result = Long.valueOf(retryAfterSecondsString) * 1000;
}
return result;
}
/**
* If this OperationStatus has a retryAfterSeconds value, return an Single that is delayed by the
* number of seconds that are in the retryAfterSeconds value. If this OperationStatus doesn't have
* a retryAfterSeconds value, then return an Single with no delay.
* @return A Single with delay if this OperationStatus has a retryAfterSeconds value.
*/
Completable delayAsync() {
Completable result = Completable.complete();
if (delayInMilliseconds > 0) {
result = result.delay(delayInMilliseconds, TimeUnit.MILLISECONDS);
}
return result;
}
/**
* @return the current status of the long running operation.
*/
String status() {
return status;
}
/**
* Set the current status of the long running operation.
* @param status The current status of the long running operation.
*/
void setStatus(String status) {
this.status = status;
}
protected final HttpResponseDecoder createResponseDecoder() {
return new HttpResponseDecoder(methodParser, restProxy.serializer());
}
/**
* Create a new HTTP poll request.
* @return A new HTTP poll request.
*/
abstract HttpRequest createPollRequest();
/**
* Update the status of this PollStrategy from the provided HTTP poll response.
* @param httpPollResponse The response of the most recent poll request.
* @return A Completable that can be used to chain off of this operation.
*/
abstract Single<HttpResponse> updateFromAsync(HttpResponse httpPollResponse);
/**
* Get whether or not this PollStrategy's long running operation is done.
* @return Whether or not this PollStrategy's long running operation is done.
*/
abstract boolean isDone();
Observable<HttpResponse> sendPollRequestWithDelay() {
return Observable.defer(new Callable<Observable<HttpResponse>>() {
@Override
public Observable<HttpResponse> call() {
return delayAsync()
.andThen(Single.defer(new Callable<Single<HttpResponse>>() {
@Override
public Single<HttpResponse> call() throws Exception {
final HttpRequest pollRequest = createPollRequest();
return restProxy.sendHttpRequestAsync(pollRequest);
}
}))
.flatMap(new Function<HttpResponse, Single<HttpResponse>>() {
@Override
public Single<HttpResponse> apply(HttpResponse response) {
return updateFromAsync(response);
}
})
.toObservable();
}
});
}
Observable<OperationStatus<Object>> createOperationStatusObservable(HttpRequest httpRequest, HttpResponse httpResponse, SwaggerMethodParser methodParser, Type operationStatusResultType) {
OperationStatus<Object> operationStatus;
if (!isDone()) {
operationStatus = new OperationStatus<>(this, httpRequest);
}
else {
try {
final Object resultObject = restProxy.handleRestReturnType(httpRequest, Single.just(httpResponse), methodParser, operationStatusResultType);
operationStatus = new OperationStatus<>(resultObject, status());
} catch (RestException e) {
operationStatus = new OperationStatus<>(e, OperationState.FAILED);
}
}
return Observable.just(operationStatus);
}
Observable<OperationStatus<Object>> pollUntilDoneWithStatusUpdates(final HttpRequest originalHttpRequest, final SwaggerMethodParser methodParser, final Type operationStatusResultType) {
return sendPollRequestWithDelay()
.flatMap(new Function<HttpResponse, Observable<OperationStatus<Object>>>() {
@Override
public Observable<OperationStatus<Object>> apply(HttpResponse httpResponse) {
return createOperationStatusObservable(originalHttpRequest, httpResponse, methodParser, operationStatusResultType);
}
})
.repeat()
.takeUntil(new Predicate<OperationStatus<Object>>() {
@Override
public boolean test(OperationStatus<Object> operationStatus) {
return isDone();
}
});
}
Single<HttpResponse> pollUntilDone() {
return sendPollRequestWithDelay()
.repeat()
.takeUntil(new Predicate<HttpResponse>() {
@Override
public boolean test(HttpResponse ignored) {
return isDone();
}
})
.lastOrError();
}
/**
* @return The data for the strategy.
*/
public abstract Serializable strategyData();
SwaggerMethodParser methodParser() {
return this.methodParser;
}
}
|
azure-client-runtime/src/main/java/com/microsoft/azure/v2/PollStrategy.java
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.v2;
import com.microsoft.rest.v2.RestException;
import com.microsoft.rest.v2.RestProxy;
import com.microsoft.rest.v2.SwaggerMethodParser;
import com.microsoft.rest.v2.http.HttpRequest;
import com.microsoft.rest.v2.http.HttpResponse;
import com.microsoft.rest.v2.protocol.HttpResponseDecoder;
import com.microsoft.rest.v2.protocol.SerializerEncoding;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
/**
* An abstract class for the different strategies that an OperationStatus can use when checking the
* status of a long running operation.
*/
abstract class PollStrategy {
private final RestProxy restProxy;
private final SwaggerMethodParser methodParser;
private long delayInMilliseconds;
private String status;
PollStrategy(PollStrategyData data) {
this.restProxy = data.restProxy;
this.methodParser = data.methodParser;
this.delayInMilliseconds = data.delayInMilliseconds;
}
abstract static class PollStrategyData implements Serializable {
transient RestProxy restProxy;
transient SwaggerMethodParser methodParser;
long delayInMilliseconds;
PollStrategyData(RestProxy restProxy,
SwaggerMethodParser methodParser,
long delayInMilliseconds) {
this.restProxy = restProxy;
this.methodParser = methodParser;
this.delayInMilliseconds = delayInMilliseconds;
}
abstract PollStrategy initializeStrategy(RestProxy restProxy,
SwaggerMethodParser methodParser);
}
@SuppressWarnings("unchecked")
protected <T> T deserialize(String value, Type returnType) throws IOException {
return (T) restProxy.serializer().deserialize(value, returnType, SerializerEncoding.JSON);
}
protected Single<HttpResponse> ensureExpectedStatus(HttpResponse httpResponse) {
return ensureExpectedStatus(httpResponse, null);
}
protected Single<HttpResponse> ensureExpectedStatus(HttpResponse httpResponse, int[] additionalAllowedStatusCodes) {
return restProxy.ensureExpectedStatus(httpResponse, methodParser, additionalAllowedStatusCodes);
}
protected String fullyQualifiedMethodName() {
return methodParser.fullyQualifiedMethodName();
}
protected boolean expectsResourceResponse() {
return methodParser.expectsResponseBody();
}
/**
* Set the delay in milliseconds to 0.
*/
final void clearDelayInMilliseconds() {
this.delayInMilliseconds = 0;
}
/**
* Update the delay in milliseconds from the provided HTTP poll response.
* @param httpPollResponse The HTTP poll response to update the delay in milliseconds from.
*/
final void updateDelayInMillisecondsFrom(HttpResponse httpPollResponse) {
final Long parsedDelayInMilliseconds = delayInMillisecondsFrom(httpPollResponse);
if (parsedDelayInMilliseconds != null) {
delayInMilliseconds = parsedDelayInMilliseconds;
}
}
static Long delayInMillisecondsFrom(HttpResponse httpResponse) {
Long result = null;
final String retryAfterSecondsString = httpResponse.headerValue("Retry-After");
if (retryAfterSecondsString != null && !retryAfterSecondsString.isEmpty()) {
result = Long.valueOf(retryAfterSecondsString) * 1000;
}
return result;
}
/**
* If this OperationStatus has a retryAfterSeconds value, return an Single that is delayed by the
* number of seconds that are in the retryAfterSeconds value. If this OperationStatus doesn't have
* a retryAfterSeconds value, then return an Single with no delay.
* @return A Single with delay if this OperationStatus has a retryAfterSeconds value.
*/
Completable delayAsync() {
Completable result = Completable.complete();
if (delayInMilliseconds > 0) {
result = result.delay(delayInMilliseconds, TimeUnit.MILLISECONDS);
}
return result;
}
/**
* @return the current status of the long running operation.
*/
String status() {
return status;
}
/**
* Set the current status of the long running operation.
* @param status The current status of the long running operation.
*/
void setStatus(String status) {
this.status = status;
}
protected final HttpResponseDecoder createResponseDecoder() {
return new HttpResponseDecoder(methodParser, restProxy.serializer());
}
/**
* Create a new HTTP poll request.
* @return A new HTTP poll request.
*/
abstract HttpRequest createPollRequest();
/**
* Update the status of this PollStrategy from the provided HTTP poll response.
* @param httpPollResponse The response of the most recent poll request.
* @return A Completable that can be used to chain off of this operation.
*/
abstract Single<HttpResponse> updateFromAsync(HttpResponse httpPollResponse);
/**
* Get whether or not this PollStrategy's long running operation is done.
* @return Whether or not this PollStrategy's long running operation is done.
*/
abstract boolean isDone();
Observable<HttpResponse> sendPollRequestWithDelay() {
return Observable.defer(new Callable<Observable<HttpResponse>>() {
@Override
public Observable<HttpResponse> call() {
return delayAsync()
.andThen(Single.defer(new Callable<Single<HttpResponse>>() {
@Override
public Single<HttpResponse> call() throws Exception {
final HttpRequest pollRequest = createPollRequest();
return restProxy.sendHttpRequestAsync(pollRequest);
}
}))
.flatMap(new Function<HttpResponse, Single<HttpResponse>>() {
@Override
public Single<HttpResponse> apply(HttpResponse response) {
return updateFromAsync(response);
}
})
.toObservable();
}
});
}
Observable<OperationStatus<Object>> createOperationStatusObservable(HttpRequest httpRequest, HttpResponse httpResponse, SwaggerMethodParser methodParser, Type operationStatusResultType) {
OperationStatus<Object> operationStatus;
if (!isDone()) {
operationStatus = new OperationStatus<>(this, httpRequest);
}
else {
try {
final Object resultObject = restProxy.handleRestReturnType(httpRequest, Single.just(httpResponse), methodParser, operationStatusResultType);
operationStatus = new OperationStatus<>(resultObject, status());
} catch (RestException e) {
operationStatus = new OperationStatus<>(e, OperationState.FAILED);
}
}
return Observable.just(operationStatus);
}
Observable<OperationStatus<Object>> pollUntilDoneWithStatusUpdates(final HttpRequest originalHttpRequest, final SwaggerMethodParser methodParser, final Type operationStatusResultType) {
return sendPollRequestWithDelay()
.flatMap(new Function<HttpResponse, Observable<OperationStatus<Object>>>() {
@Override
public Observable<OperationStatus<Object>> apply(HttpResponse httpResponse) {
return createOperationStatusObservable(originalHttpRequest, httpResponse, methodParser, operationStatusResultType);
}
})
.repeat()
.takeUntil(new Predicate<OperationStatus<Object>>() {
@Override
public boolean test(OperationStatus<Object> operationStatus) {
return isDone();
}
});
}
Single<HttpResponse> pollUntilDone() {
return sendPollRequestWithDelay()
.repeat()
.takeUntil(new Predicate<HttpResponse>() {
@Override
public boolean test(HttpResponse ignored) {
return isDone();
}
})
.lastOrError();
}
/**
* @erturn The data for the strategy.
*/
public abstract Serializable strategyData();
SwaggerMethodParser methodParser() {
return this.methodParser;
}
}
|
Fix spelling in PollStrategy Javadoc (#392)
|
azure-client-runtime/src/main/java/com/microsoft/azure/v2/PollStrategy.java
|
Fix spelling in PollStrategy Javadoc (#392)
|
<ide><path>zure-client-runtime/src/main/java/com/microsoft/azure/v2/PollStrategy.java
<ide> }
<ide>
<ide> /**
<del> * @erturn The data for the strategy.
<add> * @return The data for the strategy.
<ide> */
<ide> public abstract Serializable strategyData();
<ide>
|
|
Java
|
apache-2.0
|
ca9f2e1dcc73b5140ba6a98217ee5fb77cb80ced
| 0 |
hmusavi/jpo-ode,hmusavi/jpo-ode,hmusavi/jpo-ode,hmusavi/jpo-ode,hmusavi/jpo-ode
|
package us.dot.its.jpo.ode.traveler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.json.JSONObject;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.databind.node.ObjectNode;
import us.dot.its.jpo.ode.OdeProperties;
import us.dot.its.jpo.ode.context.AppContext;
import us.dot.its.jpo.ode.model.Asn1Encoding;
import us.dot.its.jpo.ode.model.Asn1Encoding.EncodingRule;
import us.dot.its.jpo.ode.model.OdeMsgMetadata;
import us.dot.its.jpo.ode.model.OdeMsgPayload;
import us.dot.its.jpo.ode.plugin.RoadSideUnit.RSU;
import us.dot.its.jpo.ode.plugin.j2735.J2735DSRCmsgID;
import us.dot.its.jpo.ode.plugin.j2735.builders.TravelerMessageFromHumanToAsnConverter;
import us.dot.its.jpo.ode.snmp.SnmpSession;
import us.dot.its.jpo.ode.util.JsonUtils;
import us.dot.its.jpo.ode.util.JsonUtils.JsonUtilsException;
import us.dot.its.jpo.ode.util.XmlUtils.XmlUtilsException;
import us.dot.its.jpo.ode.wrapper.MessageProducer;
@Controller
public class TimController {
public static class TimControllerException extends Exception {
private static final long serialVersionUID = 1L;
public TimControllerException(String errMsg, Exception e) {
super(errMsg, e);
}
}
private static final Logger logger = LoggerFactory.getLogger(TimController.class);
private static final String ERRSTR = "error";
private static final int THREADPOOL_MULTIPLIER = 3; // multiplier of threads
// needed
private OdeProperties odeProperties;
private MessageProducer<String, String> messageProducer;
private final ExecutorService threadPool;
@Autowired
public TimController(OdeProperties odeProperties) {
super();
this.odeProperties = odeProperties;
this.messageProducer = MessageProducer.defaultStringMessageProducer(
odeProperties.getKafkaBrokers(), odeProperties.getKafkaProducerType());
this.threadPool = Executors.newFixedThreadPool(odeProperties.getRsuSrmSlots() * THREADPOOL_MULTIPLIER);
}
/**
* Checks given RSU for all TIMs set
*
* @param jsonString
* Request body containing RSU info
* @return list of occupied TIM slots on RSU
*/
@ResponseBody
@CrossOrigin
@RequestMapping(value = "/tim/query", method = RequestMethod.POST)
public synchronized ResponseEntity<String> asyncQueryForTims(@RequestBody String jsonString) { // NOSONAR
if (null == jsonString || jsonString.isEmpty()) {
logger.error("Empty request.");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, "Empty request."));
}
ConcurrentSkipListMap<Integer, Integer> resultTable = new ConcurrentSkipListMap<>();
RSU queryTarget = (RSU) JsonUtils.fromJson(jsonString, RSU.class);
SnmpSession snmpSession = null;
try {
snmpSession = new SnmpSession(queryTarget);
snmpSession.startListen();
} catch (IOException e) {
logger.error("Error creating SNMP session.", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(jsonKeyValue(ERRSTR, "Failed to create SNMP session."));
}
// Repeatedly query the RSU to establish set rows
List<Callable<Object>> queryThreadList = new ArrayList<>();
for (int i = 0; i < odeProperties.getRsuSrmSlots(); i++) {
ScopedPDU pdu = new ScopedPDU();
pdu.add(new VariableBinding(new OID("1.0.15628.4.1.4.1.11.".concat(Integer.toString(i)))));
pdu.setType(PDU.GET);
queryThreadList.add(Executors
.callable(new TimQueryThread(snmpSession.getSnmp(), pdu, snmpSession.getTarget(), resultTable, i)));
}
try {
threadPool.invokeAll(queryThreadList);
} catch (InterruptedException e) { // NOSONAR
logger.error("Error submitting query threads for execution.", e);
threadPool.shutdownNow();
}
try {
snmpSession.endSession();
} catch (IOException e) {
logger.error("Error closing SNMP session.", e);
}
if (resultTable.containsValue(TimQueryThread.TIMEOUT_FLAG)) {
logger.error("TIM query timed out.");
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(jsonKeyValue(ERRSTR, "Query timeout, increase retries."));
} else {
logger.info("TIM query successful: {}", resultTable.keySet());
return ResponseEntity.status(HttpStatus.OK).body("{\"indicies_set\":" + resultTable.keySet() + "}");
}
}
@ResponseBody
@CrossOrigin
@RequestMapping(value = "/tim", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteTim(@RequestBody String jsonString,
@RequestParam(value = "index", required = true) Integer index) { // NOSONAR
if (null == jsonString) {
logger.error("Empty request");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, "Empty request"));
}
RSU queryTarget = (RSU) JsonUtils.fromJson(jsonString, RSU.class);
logger.info("TIM delete call, RSU info {}", queryTarget);
SnmpSession ss = null;
try {
ss = new SnmpSession(queryTarget);
} catch (IOException e) {
logger.error("Error creating TIM delete SNMP session", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(jsonKeyValue(ERRSTR, e.getMessage()));
} catch (NullPointerException e) {
logger.error("TIM query error, malformed JSON", e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, "Malformed JSON"));
}
PDU pdu = new ScopedPDU();
pdu.add(new VariableBinding(new OID("1.0.15628.4.1.4.1.11.".concat(Integer.toString(index))), new Integer32(6)));
pdu.setType(PDU.SET);
ResponseEvent rsuResponse = null;
try {
rsuResponse = ss.set(pdu, ss.getSnmp(), ss.getTarget(), false);
} catch (IOException e) {
logger.error("Error sending TIM query PDU to RSU", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(jsonKeyValue(ERRSTR, e.getMessage()));
}
// Try to explain common errors
HttpStatus returnCode = null;
String bodyMsg = "";
if (null == rsuResponse || null == rsuResponse.getResponse()) {
// Timeout
returnCode = HttpStatus.REQUEST_TIMEOUT;
bodyMsg = jsonKeyValue(ERRSTR, "Timeout.");
} else if (rsuResponse.getResponse().getErrorStatus() == 0) {
// Success
returnCode = HttpStatus.OK;
bodyMsg = jsonKeyValue("deleted_msg", Integer.toString(index));
} else if (rsuResponse.getResponse().getErrorStatus() == 12) {
// Message previously deleted or doesn't exist
returnCode = HttpStatus.BAD_REQUEST;
bodyMsg = jsonKeyValue(ERRSTR, "No message at index ".concat(Integer.toString(index)));
} else if (rsuResponse.getResponse().getErrorStatus() == 10) {
// Invalid index
returnCode = HttpStatus.BAD_REQUEST;
bodyMsg = jsonKeyValue(ERRSTR, "Invalid index ".concat(Integer.toString(index)));
} else {
// Misc error
returnCode = HttpStatus.BAD_REQUEST;
bodyMsg = jsonKeyValue(ERRSTR, rsuResponse.getResponse().getErrorStatusText());
}
logger.info("Delete call response code: {}, message: {}", returnCode, bodyMsg);
return ResponseEntity.status(returnCode).body(bodyMsg);
}
/**
* Deposit a TIM
*
* @param jsonString
* TIM in JSON
* @return list of success/failures
*/
@ResponseBody
@RequestMapping(value = "/tim", method = RequestMethod.POST, produces = "application/json")
@CrossOrigin
public ResponseEntity<String> postTim(@RequestBody String jsonString) {
// Check empty
if (null == jsonString || jsonString.isEmpty()) {
String errMsg = "Empty request.";
logger.error(errMsg);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, errMsg));
}
// Convert JSON to POJO
ObjectNode travelerinputData = null;
try {
travelerinputData = JsonUtils.toObjectNode(jsonString);
logger.debug("J2735TravelerInputData: {}", jsonString);
} catch (Exception e) {
String errMsg = "Malformed or non-compliant JSON.";
logger.error(errMsg, e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, errMsg));
}
// TODO
//((ObjectNode) travelerinputData.get("ode")).put("index", travelerinputData.get("tim").get("index").asInt());
// Craft ASN-encodable TIM
ObjectNode encodableTim;
try {
encodableTim = TravelerMessageFromHumanToAsnConverter
.changeTravelerInformationToAsnValues(travelerinputData);
logger.debug("Encodable TIM: {}", encodableTim);
} catch (Exception e) {
String errMsg = "Error converting to encodable TIM.";
logger.error(errMsg, e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, errMsg));
}
// Encode TIM
try {
publish(encodableTim.toString());
} catch (Exception e) {
String errMsg = "Error sending data to ASN.1 Encoder module: " + e.getMessage();
logger.error(errMsg, e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, errMsg));
}
return ResponseEntity.status(HttpStatus.OK).body("Success");
}
/**
* Takes in a key, value pair and returns a valid json string such as
* {"error":"message"}
*
* @param key
* @param value
* @return
*/
public String jsonKeyValue(String key, String value) {
return "{\"" + key + "\":\"" + value + "\"}";
}
private void publish(String request) throws JsonUtilsException, XmlUtilsException {
JSONObject requestObj = JsonUtils.toJSONObject(request);
//Create valid payload from scratch
OdeMsgPayload payload = new OdeMsgPayload();
payload.setDataType("MessageFrame");
JSONObject payloadObj = JsonUtils.toJSONObject(payload.toJson());
//Create TravelerInformation
JSONObject timObject = new JSONObject();
//requestObj = new JSONObject(requestObj.toString().replace("\"tcontent\":","\"content\":"));
timObject.put("TravelerInformation", requestObj.remove("tim")); //with "tim" removed, the remaining requestObject must go in as "request" element of metadata
//Create a MessageFrame
JSONObject mfObject = new JSONObject();
mfObject.put("value", timObject);//new JSONObject().put("TravelerInformation", requestObj));
mfObject.put("messageId", J2735DSRCmsgID.TravelerInformation.getMsgID());
JSONObject dataObj = new JSONObject();
dataObj.put("MessageFrame", mfObject);
payloadObj.put(AppContext.DATA_STRING, dataObj);
//Create a valid metadata from scratch
OdeMsgMetadata metadata = new OdeMsgMetadata(payload);
JSONObject metaObject = JsonUtils.toJSONObject(metadata.toJson());
metaObject.put("request", requestObj);
//Create an encoding element
//Asn1Encoding enc = new Asn1Encoding("/payload/data/MessageFrame", "MessageFrame", EncodingRule.UPER);
Asn1Encoding enc = new Asn1Encoding("payload/data/MessageFrame/", "MessageFrame", EncodingRule.UPER);
// TODO this nesting is to match encoder schema
metaObject.put("encodings", new JSONObject().put("encodings", JsonUtils.toJSONObject(enc.toJson())));
JSONObject message = new JSONObject();
message.put(AppContext.METADATA_STRING, metaObject);
message.put(AppContext.PAYLOAD_STRING, payloadObj);
JSONObject root = new JSONObject();
root.put("OdeAsn1Data", message);
// workaround for the "content" bug
String outputXml = XML.toString(root);
String fixedXml = outputXml.replaceAll("tcontent>","content>");
// workaround for self-closing tags: transform all "null" fields into empty tags
fixedXml = fixedXml.replaceAll("EMPTY_TAG", "");
logger.debug("Fixed XML: {}", fixedXml);
messageProducer.send(odeProperties.getKafkaTopicAsn1EncoderInput(), null, fixedXml);
}
}
|
jpo-ode-svcs/src/main/java/us/dot/its/jpo/ode/traveler/TimController.java
|
package us.dot.its.jpo.ode.traveler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.json.JSONObject;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.databind.node.ObjectNode;
import us.dot.its.jpo.ode.OdeProperties;
import us.dot.its.jpo.ode.context.AppContext;
import us.dot.its.jpo.ode.model.Asn1Encoding;
import us.dot.its.jpo.ode.model.Asn1Encoding.EncodingRule;
import us.dot.its.jpo.ode.model.OdeMsgMetadata;
import us.dot.its.jpo.ode.model.OdeMsgPayload;
import us.dot.its.jpo.ode.plugin.RoadSideUnit.RSU;
import us.dot.its.jpo.ode.plugin.j2735.J2735DSRCmsgID;
import us.dot.its.jpo.ode.plugin.j2735.builders.TravelerMessageFromHumanToAsnConverter;
import us.dot.its.jpo.ode.snmp.SnmpSession;
import us.dot.its.jpo.ode.util.JsonUtils;
import us.dot.its.jpo.ode.util.JsonUtils.JsonUtilsException;
import us.dot.its.jpo.ode.util.XmlUtils.XmlUtilsException;
import us.dot.its.jpo.ode.wrapper.MessageProducer;
@Controller
public class TimController {
public static class TimControllerException extends Exception {
private static final long serialVersionUID = 1L;
public TimControllerException(String errMsg, Exception e) {
super(errMsg, e);
}
}
private static final Logger logger = LoggerFactory.getLogger(TimController.class);
private static final String ERRSTR = "error";
private static final int THREADPOOL_MULTIPLIER = 3; // multiplier of threads
// needed
private OdeProperties odeProperties;
private MessageProducer<String, String> messageProducer;
private final ExecutorService threadPool;
@Autowired
public TimController(OdeProperties odeProperties) {
super();
this.odeProperties = odeProperties;
this.messageProducer = MessageProducer.defaultStringMessageProducer(
odeProperties.getKafkaBrokers(), odeProperties.getKafkaProducerType());
this.threadPool = Executors.newFixedThreadPool(odeProperties.getRsuSrmSlots() * THREADPOOL_MULTIPLIER);
}
/**
* Checks given RSU for all TIMs set
*
* @param jsonString
* Request body containing RSU info
* @return list of occupied TIM slots on RSU
*/
@ResponseBody
@CrossOrigin
@RequestMapping(value = "/tim/query", method = RequestMethod.POST)
public synchronized ResponseEntity<String> asyncQueryForTims(@RequestBody String jsonString) { // NOSONAR
if (null == jsonString || jsonString.isEmpty()) {
logger.error("Empty request.");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, "Empty request."));
}
ConcurrentSkipListMap<Integer, Integer> resultTable = new ConcurrentSkipListMap<>();
RSU queryTarget = (RSU) JsonUtils.fromJson(jsonString, RSU.class);
SnmpSession snmpSession = null;
try {
snmpSession = new SnmpSession(queryTarget);
snmpSession.startListen();
} catch (IOException e) {
logger.error("Error creating SNMP session.", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(jsonKeyValue(ERRSTR, "Failed to create SNMP session."));
}
// Repeatedly query the RSU to establish set rows
List<Callable<Object>> queryThreadList = new ArrayList<>();
for (int i = 0; i < odeProperties.getRsuSrmSlots(); i++) {
ScopedPDU pdu = new ScopedPDU();
pdu.add(new VariableBinding(new OID("1.0.15628.4.1.4.1.11.".concat(Integer.toString(i)))));
pdu.setType(PDU.GET);
queryThreadList.add(Executors
.callable(new TimQueryThread(snmpSession.getSnmp(), pdu, snmpSession.getTarget(), resultTable, i)));
}
try {
threadPool.invokeAll(queryThreadList);
} catch (InterruptedException e) { // NOSONAR
logger.error("Error submitting query threads for execution.", e);
threadPool.shutdownNow();
}
try {
snmpSession.endSession();
} catch (IOException e) {
logger.error("Error closing SNMP session.", e);
}
if (resultTable.containsValue(TimQueryThread.TIMEOUT_FLAG)) {
logger.error("TIM query timed out.");
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(jsonKeyValue(ERRSTR, "Query timeout, increase retries."));
} else {
logger.info("TIM query successful: {}", resultTable.keySet());
return ResponseEntity.status(HttpStatus.OK).body("{\"indicies_set\":" + resultTable.keySet() + "}");
}
}
@ResponseBody
@CrossOrigin
@RequestMapping(value = "/tim", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteTim(@RequestBody String jsonString,
@RequestParam(value = "index", required = true) Integer index) { // NOSONAR
if (null == jsonString) {
logger.error("Empty request");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, "Empty request"));
}
RSU queryTarget = (RSU) JsonUtils.fromJson(jsonString, RSU.class);
logger.info("TIM delete call, RSU info {}", queryTarget);
SnmpSession ss = null;
try {
ss = new SnmpSession(queryTarget);
} catch (IOException e) {
logger.error("Error creating TIM delete SNMP session", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(jsonKeyValue(ERRSTR, e.getMessage()));
} catch (NullPointerException e) {
logger.error("TIM query error, malformed JSON", e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, "Malformed JSON"));
}
PDU pdu = new ScopedPDU();
pdu.add(new VariableBinding(new OID("1.0.15628.4.1.4.1.11.".concat(Integer.toString(index))), new Integer32(6)));
pdu.setType(PDU.SET);
ResponseEvent rsuResponse = null;
try {
rsuResponse = ss.set(pdu, ss.getSnmp(), ss.getTarget(), false);
} catch (IOException e) {
logger.error("Error sending TIM query PDU to RSU", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(jsonKeyValue(ERRSTR, e.getMessage()));
}
// Try to explain common errors
HttpStatus returnCode = null;
String bodyMsg = "";
if (null == rsuResponse || null == rsuResponse.getResponse()) {
// Timeout
returnCode = HttpStatus.REQUEST_TIMEOUT;
bodyMsg = jsonKeyValue(ERRSTR, "Timeout.");
} else if (rsuResponse.getResponse().getErrorStatus() == 0) {
// Success
returnCode = HttpStatus.OK;
bodyMsg = jsonKeyValue("deleted_msg", Integer.toString(index));
} else if (rsuResponse.getResponse().getErrorStatus() == 12) {
// Message previously deleted or doesn't exist
returnCode = HttpStatus.BAD_REQUEST;
bodyMsg = jsonKeyValue(ERRSTR, "No message at index ".concat(Integer.toString(index)));
} else if (rsuResponse.getResponse().getErrorStatus() == 10) {
// Invalid index
returnCode = HttpStatus.BAD_REQUEST;
bodyMsg = jsonKeyValue(ERRSTR, "Invalid index ".concat(Integer.toString(index)));
} else {
// Misc error
returnCode = HttpStatus.BAD_REQUEST;
bodyMsg = jsonKeyValue(ERRSTR, rsuResponse.getResponse().getErrorStatusText());
}
logger.info("Delete call response code: {}, message: {}", returnCode, bodyMsg);
return ResponseEntity.status(returnCode).body(bodyMsg);
}
/**
* Deposit a TIM
*
* @param jsonString
* TIM in JSON
* @return list of success/failures
*/
@ResponseBody
@RequestMapping(value = "/tim", method = RequestMethod.POST, produces = "application/json")
@CrossOrigin
public ResponseEntity<String> postTim(@RequestBody String jsonString) {
// Check empty
if (null == jsonString || jsonString.isEmpty()) {
String errMsg = "Empty request.";
logger.error(errMsg);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, errMsg));
}
// Convert JSON to POJO
ObjectNode travelerinputData = null;
try {
travelerinputData = JsonUtils.toObjectNode(jsonString);
logger.debug("J2735TravelerInputData: {}", jsonString);
} catch (Exception e) {
String errMsg = "Malformed or non-compliant JSON.";
logger.error(errMsg, e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, errMsg));
}
// TODO
//((ObjectNode) travelerinputData.get("ode")).put("index", travelerinputData.get("tim").get("index").asInt());
// Craft ASN-encodable TIM
ObjectNode encodableTim;
try {
encodableTim = TravelerMessageFromHumanToAsnConverter
.changeTravelerInformationToAsnValues(travelerinputData);
logger.debug("Encodable TIM: {}", encodableTim);
} catch (Exception e) {
String errMsg = "Error converting to encodable TIM.";
logger.error(errMsg, e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, errMsg));
}
// Encode TIM
try {
publish(encodableTim.toString());
} catch (Exception e) {
String errMsg = "Error sending data to ASN.1 Encoder module: " + e.getMessage();
logger.error(errMsg, e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonKeyValue(ERRSTR, errMsg));
}
return ResponseEntity.status(HttpStatus.OK).body("Success");
}
/**
* Takes in a key, value pair and returns a valid json string such as
* {"error":"message"}
*
* @param key
* @param value
* @return
*/
public String jsonKeyValue(String key, String value) {
return "{\"" + key + "\":\"" + value + "\"}";
}
private void publish(String request) throws JsonUtilsException, XmlUtilsException {
JSONObject requestObj = JsonUtils.toJSONObject(request);
//Create valid payload from scratch
OdeMsgPayload payload = new OdeMsgPayload();
payload.setDataType("MessageFrame");
JSONObject payloadObj = JsonUtils.toJSONObject(payload.toJson());
//Create TravelerInformation
JSONObject timObject = new JSONObject();
//requestObj = new JSONObject(requestObj.toString().replace("\"tcontent\":","\"content\":"));
timObject.put("TravelerInformation", requestObj.remove("tim")); //with "tim" removed, the remaining requestObject must go in as "request" element of metadata
//Create a MessageFrame
JSONObject mfObject = new JSONObject();
mfObject.put("value", timObject);//new JSONObject().put("TravelerInformation", requestObj));
mfObject.put("messageId", J2735DSRCmsgID.TravelerInformation.getMsgID());
JSONObject dataObj = new JSONObject();
dataObj.put("MessageFrame", mfObject);
payloadObj.put(AppContext.DATA_STRING, dataObj);
//Create a valid metadata from scratch
OdeMsgMetadata metadata = new OdeMsgMetadata(payload);
JSONObject metaObject = JsonUtils.toJSONObject(metadata.toJson());
metaObject.put("request", requestObj);
//Create an encoding element
//Asn1Encoding enc = new Asn1Encoding("/payload/data/MessageFrame", "MessageFrame", EncodingRule.UPER);
Asn1Encoding enc = new Asn1Encoding("/payload/data/MessageFrame/TravelerInformation", "TravelerInformation", EncodingRule.UPER);
// TODO this nesting is to match encoder schema
metaObject.put("encodings", new JSONObject().put("encodings", JsonUtils.toJSONObject(enc.toJson())));
JSONObject message = new JSONObject();
message.put(AppContext.METADATA_STRING, metaObject);
message.put(AppContext.PAYLOAD_STRING, payloadObj);
JSONObject root = new JSONObject();
root.put("OdeAsn1Data", message);
// workaround for the "content" bug
String outputXml = XML.toString(root);
String fixedXml = outputXml.replaceAll("tcontent>","content>");
// workaround for self-closing tags: transform all "null" fields into empty tags
fixedXml = fixedXml.replaceAll("EMPTY_TAG", "");
logger.debug("Fixed XML: {}", fixedXml);
messageProducer.send(odeProperties.getKafkaTopicAsn1EncoderInput(), null, fixedXml);
}
}
|
ODE-587 revert until can get logging on aem
|
jpo-ode-svcs/src/main/java/us/dot/its/jpo/ode/traveler/TimController.java
|
ODE-587 revert until can get logging on aem
|
<ide><path>po-ode-svcs/src/main/java/us/dot/its/jpo/ode/traveler/TimController.java
<ide>
<ide> //Create an encoding element
<ide> //Asn1Encoding enc = new Asn1Encoding("/payload/data/MessageFrame", "MessageFrame", EncodingRule.UPER);
<del> Asn1Encoding enc = new Asn1Encoding("/payload/data/MessageFrame/TravelerInformation", "TravelerInformation", EncodingRule.UPER);
<add> Asn1Encoding enc = new Asn1Encoding("payload/data/MessageFrame/", "MessageFrame", EncodingRule.UPER);
<ide>
<ide> // TODO this nesting is to match encoder schema
<ide> metaObject.put("encodings", new JSONObject().put("encodings", JsonUtils.toJSONObject(enc.toJson())));
|
|
Java
|
lgpl-2.1
|
error: pathspec 'projects/samskivert/tests/src/java/com/samskivert/util/AdjustTestApp.java' did not match any file(s) known to git
|
5109821d5ceebe220207e08433b402922f25e42f
| 1 |
samskivert/samskivert,samskivert/samskivert
|
//
// $Id: AdjustTestApp.java,v 1.1 2003/01/15 00:47:06 mdb Exp $
package com.samskivert.util;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Does something extraordinary.
*/
public class AdjustTestApp
{
public static void main (String[] args)
{
Config config = new Config("test");
new RuntimeAdjust.IntAdjust(
"This is a test adjustment. It is nice.",
"samskivert.test.int_adjust1", config, 5);
new RuntimeAdjust.IntAdjust(
"This is another test adjustment. It is nice.",
"samskivert.thwack.int_adjust2", config, 15);
new RuntimeAdjust.BooleanAdjust(
"This is a test adjustment. It is nice.",
"samskivert.thwack.boolean_adjust1", config, true);
new RuntimeAdjust.IntAdjust(
"This is an other test adjustment. It is nice.",
"otherpackage.test.int_adjust2", config, 15);
new RuntimeAdjust.BooleanAdjust(
"This is a an other test adjustment. It is nice.",
"otherpackage.test.boolean_adjust1", config, false);
new RuntimeAdjust.EnumAdjust(
"This is yet an other test adjustment.",
"otherpackage.test.enum_adjust1", config,
new String[] { "debug", "info", "warning" }, "info");
JPanel editor = RuntimeAdjust.createAdjustEditor();
JFrame frame = new JFrame();
((JComponent)frame.getContentPane()).setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
frame.getContentPane().add(editor, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.show();
}
}
|
projects/samskivert/tests/src/java/com/samskivert/util/AdjustTestApp.java
|
A test app for the runtime adjustment stuff.
git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@1016 6335cc39-0255-0410-8fd6-9bcaacd3b74c
|
projects/samskivert/tests/src/java/com/samskivert/util/AdjustTestApp.java
|
A test app for the runtime adjustment stuff.
|
<ide><path>rojects/samskivert/tests/src/java/com/samskivert/util/AdjustTestApp.java
<add>//
<add>// $Id: AdjustTestApp.java,v 1.1 2003/01/15 00:47:06 mdb Exp $
<add>
<add>package com.samskivert.util;
<add>
<add>import java.awt.BorderLayout;
<add>import javax.swing.BorderFactory;
<add>import javax.swing.JComponent;
<add>import javax.swing.JFrame;
<add>import javax.swing.JPanel;
<add>
<add>/**
<add> * Does something extraordinary.
<add> */
<add>public class AdjustTestApp
<add>{
<add> public static void main (String[] args)
<add> {
<add> Config config = new Config("test");
<add> new RuntimeAdjust.IntAdjust(
<add> "This is a test adjustment. It is nice.",
<add> "samskivert.test.int_adjust1", config, 5);
<add> new RuntimeAdjust.IntAdjust(
<add> "This is another test adjustment. It is nice.",
<add> "samskivert.thwack.int_adjust2", config, 15);
<add> new RuntimeAdjust.BooleanAdjust(
<add> "This is a test adjustment. It is nice.",
<add> "samskivert.thwack.boolean_adjust1", config, true);
<add>
<add> new RuntimeAdjust.IntAdjust(
<add> "This is an other test adjustment. It is nice.",
<add> "otherpackage.test.int_adjust2", config, 15);
<add> new RuntimeAdjust.BooleanAdjust(
<add> "This is a an other test adjustment. It is nice.",
<add> "otherpackage.test.boolean_adjust1", config, false);
<add> new RuntimeAdjust.EnumAdjust(
<add> "This is yet an other test adjustment.",
<add> "otherpackage.test.enum_adjust1", config,
<add> new String[] { "debug", "info", "warning" }, "info");
<add>
<add> JPanel editor = RuntimeAdjust.createAdjustEditor();
<add> JFrame frame = new JFrame();
<add> ((JComponent)frame.getContentPane()).setBorder(
<add> BorderFactory.createEmptyBorder(5, 5, 5, 5));
<add> frame.getContentPane().add(editor, BorderLayout.CENTER);
<add> frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
<add> frame.pack();
<add> frame.show();
<add> }
<add>}
|
|
Java
|
apache-2.0
|
3a3e7c70ec70b1dcb16b88b4ff3703737dd1a3b9
| 0 |
JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.nuget.tests.integration.feed.server;
import jetbrains.buildServer.nuget.feed.server.index.NuGetIndexEntry;
import jetbrains.buildServer.nuget.tests.integration.Paths;
import jetbrains.buildServer.util.XmlUtil;
import org.jetbrains.annotations.NotNull;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author Eugene Petrenko ([email protected])
* Date: 13.01.12 20:25
*/
public class NuGetJavaFeedContentPerformanceTest extends NuGetJavaFeedIntegrationTestBase {
private static <T> int count(Iterator<T> itz) {
int c = 0;
while(itz.hasNext()) {
c++;
itz.next();
}
return c;
}
@Test(dataProvider = "nugetFeedLibrariesData")
public void test_list_no_query_5000(final NugetFeedLibrary library) throws IOException {
setODataSerializer(library);
do_test_list_packages(5000, 100, "");
}
@Test(dataProvider = "nugetFeedLibrariesData")
public void test_list_query_by_id_5000(final NugetFeedLibrary library) throws IOException {
setODataSerializer(library);
do_test_list_packages(5000, 0.4, "?$filter=Id%20eq%20'Foo'");
}
@Test(dataProvider = "nugetFeedLibrariesData")
public void test_list_query_search_5000(final NugetFeedLibrary library) throws IOException {
setODataSerializer(library);
do_test_list_packages(
5000,
2,
"?$filter=(((Id%20ne%20null)%20and%20substringof('mm',tolower(Id)))%20or%20((Description%20ne%20null)%20and%20substringof('mm',tolower(Description))))%20or%20((Tags%20ne%20null)%20and%20substringof('%20mm%20',tolower(Tags)))" +
"&$orderby=Id" +
"&$skip=0" +
"&$top=30");
}
@Test(dataProvider = "nugetFeedLibrariesData")
public void test_list_query_search_50000(final NugetFeedLibrary library) throws IOException {
setODataSerializer(library);
do_test_list_packages(
50000,
5,
"?$filter=(((Id%20ne%20null)%20and%20substringof('mm',tolower(Id)))%20or%20((Description%20ne%20null)%20and%20substringof('mm',tolower(Description))))%20or%20((Tags%20ne%20null)%20and%20substringof('%20mm%20',tolower(Tags)))" +
"&$orderby=Id" +
"&$skip=0" +
"&$top=30");
}
@Test(dataProvider = "nugetFeedLibrariesData")
public void test_list_isLatestVersion_50000(final NugetFeedLibrary library) throws IOException {
setODataSerializer(library);
do_test_list_packages(
50000,
2,
"?$filter=IsLatestVersion" +
"&$orderby=Id" +
"&$skip=0" +
"&$top=30");
}
private void do_test_list_packages(int sz, double time, @NotNull final String query) throws IOException {
NuGetIndexEntry base = addPackage(Paths.getTestDataPath("/packages/CommonServiceLocator.1.0.nupkg"), true);
for(int i = 1; i < sz; i ++) {
addMockPackage(base, false);
}
Assert.assertEquals(myIndex.getAll().size(), sz);
final AtomicReference<String> s = new AtomicReference<>();
try {
assertTime(time, "aaa", 5, () -> {
String req = openRequest("Packages()" + query);
s.set(req);
});
} finally {
final String req = s.get();
System.out.println("req.length() = " + req.length());
System.out.println(req);
System.out.println(XmlUtil.to_s(XmlUtil.from_s(req)));
}
}
}
|
nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/feed/server/NuGetJavaFeedContentPerformanceTest.java
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.nuget.tests.integration.feed.server;
import jetbrains.buildServer.nuget.feed.server.index.NuGetIndexEntry;
import jetbrains.buildServer.nuget.tests.integration.Paths;
import jetbrains.buildServer.util.XmlUtil;
import org.jetbrains.annotations.NotNull;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author Eugene Petrenko ([email protected])
* Date: 13.01.12 20:25
*/
public class NuGetJavaFeedContentPerformanceTest extends NuGetJavaFeedIntegrationTestBase {
private static <T> int count(Iterator<T> itz) {
int c = 0;
while(itz.hasNext()) {
c++;
itz.next();
}
return c;
}
@Test(dataProvider = "nugetFeedLibrariesData")
public void test_list_no_query_5000(final NugetFeedLibrary library) throws IOException {
setODataSerializer(library);
do_test_list_packages(5000, 100, "");
}
@Test(dataProvider = "nugetFeedLibrariesData")
public void test_list_query_by_id_5000(final NugetFeedLibrary library) throws IOException {
setODataSerializer(library);
do_test_list_packages(5000, 0.4, "?$filter=Id%20eq%20'Foo'");
}
@Test(dataProvider = "nugetFeedLibrariesData")
public void test_list_query_search_5000(final NugetFeedLibrary library) throws IOException {
setODataSerializer(library);
do_test_list_packages(
5000,
2,
"?$filter=(((Id%20ne%20null)%20and%20substringof('mm',tolower(Id)))%20or%20((Description%20ne%20null)%20and%20substringof('mm',tolower(Description))))%20or%20((Tags%20ne%20null)%20and%20substringof('%20mm%20',tolower(Tags)))" +
"&$orderby=Id" +
"&$skip=0" +
"&$top=30");
}
@Test(dataProvider = "nugetFeedLibrariesData")
public void test_list_query_search_50000(final NugetFeedLibrary library) throws IOException {
setODataSerializer(library);
do_test_list_packages(
50000,
5,
"?$filter=(((Id%20ne%20null)%20and%20substringof('mm',tolower(Id)))%20or%20((Description%20ne%20null)%20and%20substringof('mm',tolower(Description))))%20or%20((Tags%20ne%20null)%20and%20substringof('%20mm%20',tolower(Tags)))" +
"&$orderby=Id" +
"&$skip=0" +
"&$top=30");
}
@Test(dataProvider = "nugetFeedLibrariesData")
public void test_list_isLatestVersion_50000(final NugetFeedLibrary library) throws IOException {
setODataSerializer(library);
do_test_list_packages(
50000,
0.4,
"?$filter=IsLatestVersion" +
"&$orderby=Id" +
"&$skip=0" +
"&$top=30");
}
private void do_test_list_packages(int sz, double time, @NotNull final String query) throws IOException {
NuGetIndexEntry base = addPackage(Paths.getTestDataPath("/packages/CommonServiceLocator.1.0.nupkg"), true);
for(int i = 1; i < sz; i ++) {
addMockPackage(base, false);
}
Assert.assertEquals(myIndex.getAll().size(), sz);
final AtomicReference<String> s = new AtomicReference<>();
try {
assertTime(time, "aaa", 5, () -> {
String req = openRequest("Packages()" + query);
s.set(req);
});
} finally {
final String req = s.get();
System.out.println("req.length() = " + req.length());
System.out.println(req);
System.out.println(XmlUtil.to_s(XmlUtil.from_s(req)));
}
}
}
|
Increase time for performance test
|
nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/feed/server/NuGetJavaFeedContentPerformanceTest.java
|
Increase time for performance test
|
<ide><path>uget-tests/src/jetbrains/buildServer/nuget/tests/integration/feed/server/NuGetJavaFeedContentPerformanceTest.java
<ide> setODataSerializer(library);
<ide> do_test_list_packages(
<ide> 50000,
<del> 0.4,
<add> 2,
<ide> "?$filter=IsLatestVersion" +
<ide> "&$orderby=Id" +
<ide> "&$skip=0" +
|
|
Java
|
apache-2.0
|
000861fb8dd04b45f7a6c445dc2abd4696cf6ae0
| 0 |
CognizantQAHub/Cognizant-Intelligent-Test-Scripter,CognizantQAHub/Cognizant-Intelligent-Test-Scripter,CognizantQAHub/Cognizant-Intelligent-Test-Scripter,CognizantQAHub/Cognizant-Intelligent-Test-Scripter
|
/*
* Copyright 2014 - 2019 Cognizant Technology Solutions
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cognizant.cognizantits.ide.main.mainui.components.testdesign.tree;
import com.cognizant.cognizantits.datalib.component.Project;
import com.cognizant.cognizantits.datalib.component.Scenario;
import com.cognizant.cognizantits.datalib.component.TestCase;
import com.cognizant.cognizantits.datalib.model.DataItem;
import com.cognizant.cognizantits.datalib.model.Meta;
import com.cognizant.cognizantits.datalib.model.Tag;
import com.cognizant.cognizantits.ide.main.mainui.components.testdesign.TestDesign;
import com.cognizant.cognizantits.ide.main.mainui.components.testdesign.tree.model.GroupNode;
import com.cognizant.cognizantits.ide.main.mainui.components.testdesign.tree.model.ProjectTreeModel;
import com.cognizant.cognizantits.ide.main.mainui.components.testdesign.tree.model.ScenarioNode;
import com.cognizant.cognizantits.ide.main.mainui.components.testdesign.tree.model.TestCaseNode;
import com.cognizant.cognizantits.ide.main.mainui.components.testdesign.tree.model.TestPlanTreeModel;
import com.cognizant.cognizantits.ide.main.ui.ProjectProperties;
import com.cognizant.cognizantits.ide.main.utils.Utils;
import com.cognizant.cognizantits.ide.main.utils.dnd.TransferActionListener;
import com.cognizant.cognizantits.ide.main.utils.keys.Keystroke;
import com.cognizant.cognizantits.ide.main.utils.tree.TreeSelectionRenderer;
import com.cognizant.cognizantits.ide.settings.IconSettings;
import com.cognizant.cognizantits.ide.util.Canvas;
import com.cognizant.cognizantits.ide.util.Notification;
import com.cognizant.cognizantits.ide.util.Validator;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.tree.TreePath;
/**
*
*
*/
public class ProjectTree implements ActionListener {
private static final Logger LOGGER = Logger.getLogger(ProjectTree.class.getName());
ProjectPopupMenu popupMenu;
private final ProjectProperties projectProperties;
private final JTree tree;
private final TestDesign testDesign;
ProjectTreeModel treeModel = new TestPlanTreeModel();
public ProjectTree(TestDesign testDesign) {
this.testDesign = testDesign;
tree = new JTree();
projectProperties = new ProjectProperties(testDesign.getsMainFrame());
init();
}
ProjectTreeModel getNewTreeModel() {
return new TestPlanTreeModel();
}
ProjectPopupMenu getNewPopupMenu() {
return new ProjectPopupMenu();
}
private void init() {
popupMenu = getNewPopupMenu();
treeModel = getNewTreeModel();
tree.setModel(treeModel);
tree.setToggleClickCount(0);
tree.setEditable(true);
tree.setInvokesStopCellEditing(true);
tree.setComponentPopupMenu(popupMenu);
tree.setDragEnabled(true);
tree.setTransferHandler(new ProjectDnD(this));
tree.getInputMap(JComponent.WHEN_FOCUSED).put(Keystroke.NEW, "New");
tree.getInputMap(JComponent.WHEN_FOCUSED).put(Keystroke.DELETE, "Delete");
tree.getInputMap(JComponent.WHEN_FOCUSED).put(Keystroke.ALTENTER, "AltEnter");
tree.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ESCAPE"), "Escape");
tree.getActionMap().put("AltEnter", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
showDetails();
}
});
tree.getActionMap().put("New", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
onNewAction();
}
});
tree.getActionMap().put("Delete", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
onDeleteAction();
}
});
tree.getActionMap().put("Escape", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
if (tree.isEditing()) {
tree.cancelEditing();
}
}
});
tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
loadTableModelForSelection();
}
}
});
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent pme) {
onRightClick();
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent pme) {
// Not Needed
}
@Override
public void popupMenuCanceled(PopupMenuEvent pme) {
// Not Needed
}
});
setTreeIcon();
tree.getCellEditor().addCellEditorListener(new CellEditorListener() {
@Override
public void editingStopped(ChangeEvent ce) {
if (!checkAndRename()) {
tree.getCellEditor().cancelCellEditing();
}
}
@Override
public void editingCanceled(ChangeEvent ce) {
// Not Needed
}
});
}
private void setTreeIcon() {
tree.setFont(new Font("Arial", Font.PLAIN, 11));
new TreeSelectionRenderer(tree) {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean isLeaf, int row, boolean focused) {
Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, isLeaf, row, focused);
if (value instanceof GroupNode) {
setIcons(IconSettings.getIconSettings().getReusableFolder());
} else if (value instanceof ScenarioNode) {
setIcons(IconSettings.getIconSettings().getTestPlanScenario());
} else if (value instanceof TestCaseNode) {
setIcons(IconSettings.getIconSettings().getTestPlanTestCase());
} else {
setIcons(IconSettings.getIconSettings().getTestPlanRoot());
}
return c;
}
void setIcons(Icon icon) {
setLeafIcon(icon);
setClosedIcon(icon);
setOpenIcon(icon);
setIcon(icon);
}
};
}
public void loadTableModelForSelection() {
Object selected = getSelectedTestCase();
if (selected == null) {
selected = getSelectedScenario();
}
testDesign.loadTableModelForSelection(selected);
}
private void onRightClick() {
TreePath path = tree.getSelectionPath();
if (path != null) {
togglePopupMenu(tree.getSelectionPath().getLastPathComponent());
} else {
popupMenu.setVisible(false);
}
}
protected void togglePopupMenu(Object selected) {
if (selected instanceof ScenarioNode) {
popupMenu.forScenario();
} else if (selected instanceof TestCaseNode) {
popupMenu.forTestCase();
} else if (selected instanceof GroupNode) {
popupMenu.forTestPlan();
}
}
protected void onNewAction() {
if (getSelectedScenarioNode() != null) {
addTestCase();
} else if (getSelectedGroupNode() != null) {
addScenario();
}
}
protected void onDeleteAction() {
deleteTestCases();
deleteScenarios();
}
@Override
public void actionPerformed(ActionEvent ae) {
switch (ae.getActionCommand()) {
case "Add Scenario":
addScenario();
break;
case "Rename Scenario":
tree.startEditingAtPath(new TreePath(getSelectedScenarioNode().getPath()));
break;
case "Delete Scenario":
deleteScenarios();
break;
case "Add TestCase":
addTestCase();
break;
case "Rename TestCase":
tree.startEditingAtPath(new TreePath(getSelectedTestCaseNode().getPath()));
break;
case "Delete TestCase":
deleteTestCases();
break;
case "Sort":
sort();
break;
case "Edit Tag":
editTag();
break;
case "Make As Reusable/TestCase":
makeAsReusableRTestCase();
break;
case "Details":
showDetails();
break;
case "Manual Testcase":
convertToManual();
break;
case "Get Impacted TestCases":
getImpactedTestCases();
break;
case "Get CmdLine Syntax":
getCmdLineSyntax();
break;
default:
throw new UnsupportedOperationException();
}
}
public ProjectTreeModel getTreeModel() {
return treeModel;
}
private void addScenario() {
ScenarioNode scNode = treeModel.addScenario(getSelectedGroupNode(),
testDesign.getProject().addScenario(fetchNewScenarioName()));
selectAndScrollTo(new TreePath(scNode.getPath()));
}
private String fetchNewScenarioName() {
String newScenarioName = "NewScenario";
for (int i = 0;; i++) {
if (testDesign.getProject().getScenarioByName(newScenarioName) == null) {
break;
}
newScenarioName = "NewScenario" + i;
}
return newScenarioName;
}
private void addTestCase() {
ScenarioNode scenarioNode = getSelectedScenarioNode();
if (scenarioNode != null) {
TestCase testcase;
String testCaseName = fetchNewTestCaseName(scenarioNode.getScenario());
testcase = scenarioNode.getScenario().addTestCase(testCaseName);
testDesign.loadTableModelForSelection(testcase);
selectAndScrollTo(new TreePath(treeModel.
addTestCase(scenarioNode, testcase).getPath()));
}
}
private String fetchNewTestCaseName(Scenario scenario) {
String newTestCaseName = "NewTestCase";
for (int i = 0;; i++) {
if (scenario.getTestCaseByName(newTestCaseName) == null) {
break;
}
newTestCaseName = "NewTestCase" + i;
}
return newTestCaseName;
}
protected Boolean checkAndRename() {
String name = tree.getCellEditor().getCellEditorValue().toString().trim();
if (Validator.isValidName(name)) {
ScenarioNode scenarioNode = getSelectedScenarioNode();
if (scenarioNode != null && !scenarioNode.toString().equals(name)) {
if (scenarioNode.getScenario().rename(name)) {
getTreeModel().reload(scenarioNode);
renameScenario(scenarioNode.getScenario());
testDesign.getScenarioComp().refreshTitle();
return true;
} else {
Notification.show("Scenario " + name + " Already present");
return false;
}
}
TestCaseNode testCaseNode = getSelectedTestCaseNode();
if (testCaseNode != null && !testCaseNode.toString().equals(name)) {
if (testCaseNode.getTestCase().rename(name)) {
getTreeModel().reload(testCaseNode);
testDesign.getTestCaseComp().refreshTitle();
return true;
} else {
Notification.show("Testcase '" + name + "' Already present in Scenario - " + getSelectedTestCase().getScenario().getName());
}
}
}
return false;
}
void renameScenario(Scenario scenario) {
getTestDesign().getReusableTree()
.getTreeModel().onScenarioRename(scenario);
}
private void deleteScenarios() {
List<ScenarioNode> scenarioNodes = getSelectedScenarioNodes();
if (!scenarioNodes.isEmpty()) {
int option = JOptionPane.showConfirmDialog(null,
"<html><body><p style='width: 200px;'>"
+ "Are you sure want to delete the following Scenarios?<br>"
+ scenarioNodes
+ "</p></body></html>",
"Delete Scenario",
JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
LOGGER.log(Level.INFO, "Delete Scenarios approved for {0}; {1}",
new Object[]{scenarioNodes.size(), scenarioNodes});
for (ScenarioNode scenarioNode : scenarioNodes) {
deleteTestCases(TestCaseNode.toList(scenarioNode.children()));
scenarioNode.getScenario().delete();
getTreeModel().removeNodeFromParent(scenarioNode);
}
}
}
}
private void deleteTestCases() {
List<TestCaseNode> testcaseNodes = getSelectedTestCaseNodes();
if (!testcaseNodes.isEmpty()) {
int option = JOptionPane.showConfirmDialog(null,
"<html><body><p style='width: 200px;'>"
+ "Are you sure want to delete the following TestCases?<br>"
+ testcaseNodes
+ "</p></body></html>",
"Delete TestCase",
JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
LOGGER.log(Level.INFO, "Delete TestCases approved for {0}; {1}",
new Object[]{testcaseNodes.size(), testcaseNodes});
deleteTestCases(testcaseNodes);
}
}
}
private void deleteTestCases(List<TestCaseNode> testcaseNodes) {
TestCase loadedTestCase = testDesign.getTestCaseComp().getCurrentTestCase();
Boolean shouldRemove = false;
for (TestCaseNode testcaseNode : testcaseNodes) {
if (!shouldRemove) {
shouldRemove = Objects.equals(loadedTestCase, testcaseNode.getTestCase());
}
testcaseNode.getTestCase().delete();
getTreeModel().removeNodeFromParent(testcaseNode);
}
if (shouldRemove) {
testDesign.getTestCaseComp().resetTable();
}
}
private Scenario getSelectedScenario() {
ScenarioNode scenarioNode = getSelectedScenarioNode();
if (scenarioNode != null) {
return scenarioNode.getScenario();
}
return null;
}
private List<Scenario> getSelectedScenarios() {
List<Scenario> scenarios = new ArrayList<>();
TreePath[] paths = tree.getSelectionPaths();
if (paths != null && paths.length > 0) {
for (TreePath path : paths) {
if (path.getLastPathComponent() instanceof ScenarioNode) {
scenarios.add(((ScenarioNode) path.getLastPathComponent()).getScenario());
}
}
}
return scenarios;
}
private List<TestCase> getSelectedTestCases() {
List<TestCase> testcases = new ArrayList<>();
TreePath[] paths = tree.getSelectionPaths();
if (paths != null && paths.length > 0) {
for (TreePath path : paths) {
if (path.getLastPathComponent() instanceof TestCaseNode) {
testcases.add(((TestCaseNode) path.getLastPathComponent()).getTestCase());
}
}
}
return testcases;
}
protected GroupNode getSelectedGroupNode() {
List<GroupNode> groups = getSelectedGroupNodes();
if (groups.isEmpty()) {
return null;
}
return groups.get(0);
}
protected List<GroupNode> getSelectedGroupNodes() {
List<GroupNode> groupNodes = new ArrayList<>();
TreePath[] paths = tree.getSelectionPaths();
if (paths != null && paths.length > 0) {
for (TreePath path : paths) {
if (path.getLastPathComponent() instanceof GroupNode) {
groupNodes.add((GroupNode) path.getLastPathComponent());
}
}
}
return groupNodes;
}
private ScenarioNode getSelectedScenarioNode() {
List<ScenarioNode> scenarioNodes = getSelectedScenarioNodes();
if (scenarioNodes.isEmpty()) {
return null;
}
return scenarioNodes.get(0);
}
protected List<ScenarioNode> getSelectedScenarioNodes() {
List<ScenarioNode> scenarioNodes = new ArrayList<>();
TreePath[] paths = tree.getSelectionPaths();
if (paths != null && paths.length > 0) {
for (TreePath path : paths) {
if (path.getLastPathComponent() instanceof ScenarioNode) {
scenarioNodes.add((ScenarioNode) path.getLastPathComponent());
}
}
}
return scenarioNodes;
}
protected TestCase getSelectedTestCase() {
TestCaseNode testcaseNode = getSelectedTestCaseNode();
if (testcaseNode != null) {
return testcaseNode.getTestCase();
}
return null;
}
private TestCaseNode getSelectedTestCaseNode() {
List<TestCaseNode> tcNodes = getSelectedTestCaseNodes();
if (tcNodes.isEmpty()) {
return null;
}
return tcNodes.get(0);
}
protected List<TestCaseNode> getSelectedTestCaseNodes() {
List<TestCaseNode> tcNodes = new ArrayList<>();
TreePath[] paths = tree.getSelectionPaths();
if (paths != null && paths.length > 0) {
for (TreePath path : paths) {
if (path.getLastPathComponent() instanceof TestCaseNode) {
tcNodes.add((TestCaseNode) path.getLastPathComponent());
}
}
}
return tcNodes;
}
protected void selectAndScrollTo(final TreePath path) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
tree.setSelectionPath(path);
tree.scrollPathToVisible(path);
tree.removeSelectionPath(path);
tree.addSelectionPaths(new TreePath[]{path.getParentPath(), path});
}
});
}
private void makeAsReusableRTestCase() {
if (!getSelectedTestCaseNodes().isEmpty()) {
for (TestCaseNode testCaseNode : getSelectedTestCaseNodes()) {
testCaseNode.getTestCase().toggleAsReusable();
getTreeModel().removeNodeFromParent(testCaseNode);
makeAsReusableRTestCase(testCaseNode.getTestCase());
}
}
}
void makeAsReusableRTestCase(TestCase testCase) {
getTestDesign().getReusableTree().getTreeModel().addTestCase(testCase);
}
private void convertToManual() {
if (!getSelectedScenarios().isEmpty()) {
testDesign.getsMainFrame().getStepMap().convertScenarios(
Utils.saveDialog("Manual TestCase.csv"), getSelectedScenarios());
} else if (!getSelectedTestCases().isEmpty()) {
testDesign.getsMainFrame().getStepMap().convertTestCase(
Utils.saveDialog("Manual TestCase.csv"), getSelectedTestCases());
} else {
testDesign.getsMainFrame().getStepMap().convertScenarios(
Utils.saveDialog("Manual TestCase.csv"), getProject().getScenarios());
}
}
private void sort() {
if (tree.getSelectionPath() != null) {
getTreeModel().sort(tree.getSelectionPath().getLastPathComponent());
}
}
private void editTag() {
TreePath[] sel = tree.getSelectionPaths();
if (sel != null && sel.length > 0) {
if (sel.length > 1) {
editTag(Arrays.asList(sel));
} else {
editTag(sel[0]);
}
}
}
private Tag onAddTag(String tag) {
getProject().getInfo().addMeta(Meta.createTag(tag));
return Tag.create(tag);
}
private void onRemoveTag(Tag tag) {
getProject().getInfo().removeAll(tag);
}
private void editTag(DataItem tc) {
TagEditorDialog.build(testDesign.getsMainFrame(),
getProject().getInfo().getAllTags(tc.getTags()), tc.getTags(),
this::onRemoveTag, this::onAddTag)
.withTitle(editTagTitle(tc.getName())).show(tc::setTags);
}
private void editTag(Meta scn) {
TagEditorDialog.build(testDesign.getsMainFrame(),
getProject().getInfo().getAllTags(scn.getTags()), scn.getTags(),
this::onRemoveTag, this::onAddTag)
.withTitle(editTagTitle(scn.getName())).show(scn::setTags);
}
private String editTagTitle(String t) {
return String.format("Edit Tag: %s", t);
}
private void editTag(TreePath path) {
if (path.getLastPathComponent() instanceof TestCaseNode) {
TestCase tcn = ((TestCaseNode) path.getLastPathComponent()).getTestCase();
editTag(getProject().getInfo().getData()
.findOrCreate(tcn.getName(), tcn.getScenario().getName()));
} else if (path.getLastPathComponent() instanceof ScenarioNode) {
Scenario scn = ((ScenarioNode) path.getLastPathComponent()).getScenario();
editTag(getProject().getInfo().findScenarioOrCreate(scn.getName()));
}
}
private void editTag(List<TreePath> paths) {
paths.stream().forEach(this::editTag);
}
private void getImpactedTestCases() {
TestCase testCase = getSelectedTestCase();
if (testCase != null) {
String scenarioName = testCase.getScenario().getName();
String testCaseName = testCase.getName();
testDesign.getImpactUI().loadForTestCase(getProject()
.getImpactedTestCaseTestCases(scenarioName, testCaseName), scenarioName, testCaseName);
} else {
Notification.show("Select a Valid TestCase");
}
}
private void getCmdLineSyntax() {
TestCase testCase = getSelectedTestCase();
if (testCase != null) {
String scenarioName = testCase.getScenario().getName();
String testCaseName = testCase.getName();
String syntax = String.format(
"%s -run -project_location \"%s\" -scenario \"%s\" -testcase \"%s\" -browser \"%s\"",
getBatRCommand(),
getProject().getLocation(),
scenarioName,
testCaseName,
getTestDesign().getDefaultBrowser());
Utils.copyTextToClipboard(syntax);
Notification.show("Syntax has been copied to Clipboard");
} else {
Notification.show("Select a Valid TestCase");
}
}
private String getBatRCommand() {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("windows")) {
return "Run.bat";
}
return "Run.command";
}
private void showDetails() {
TreePath path = tree.getSelectionPath();
if (path != null) {
showProjDetails();
}
}
private void showProjDetails() {
projectProperties.loadForCurrentProject();
// projectProperties.pack();
projectProperties.setLocationRelativeTo(null);
projectProperties.setVisible(true);
}
public final JTree getTree() {
return tree;
}
public final Project getProject() {
return testDesign.getProject();
}
public final TestDesign getTestDesign() {
return testDesign;
}
public final void load() {
treeModel.setProject(testDesign.getProject());
treeModel.reload();
getTree().setSelectionPath(new TreePath(treeModel.getFirstNode().getPath()));
loadTableModelForSelection();
}
class ProjectPopupMenu extends JPopupMenu {
protected JMenuItem addScenario;
protected JMenuItem renameScenario;
protected JMenuItem deleteScenario;
protected JMenuItem addTestCase;
protected JMenuItem renameTestCase;
protected JMenuItem deleteTestCase;
protected JMenuItem toggleReusable;
protected JMenuItem impactAnalysis;
protected JMenuItem copy;
protected JMenuItem cut;
protected JMenuItem paste;
protected JMenuItem sort;
protected JMenuItem getCmdSyntax;
public ProjectPopupMenu() {
init();
}
protected final void init() {
add(addScenario = create("Add Scenario", Keystroke.NEW));
add(renameScenario = create("Rename Scenario", Keystroke.RENAME));
add(deleteScenario = create("Delete Scenario", Keystroke.DELETE));
addSeparator();
add(addTestCase = create("Add TestCase", Keystroke.NEW));
add(renameTestCase = create("Rename TestCase", Keystroke.RENAME));
add(deleteTestCase = create("Delete TestCase", Keystroke.DELETE));
addSeparator();
JMenu menu = new JMenu("Export As");
menu.add(create("Manual Testcase", null));
add(menu);
add(toggleReusable = create("Make As Reusable/TestCase", null));
toggleReusable.setText("Make As Reusable");
addSeparator();
setCCP();
addSeparator();
add(impactAnalysis = create("Get Impacted TestCases", null));
add(getCmdSyntax = create("Get CmdLine Syntax", null));
addSeparator();
add(sort = create("Sort", null));
addSeparator();
add(create("Details", Keystroke.ALTENTER));
sort.setIcon(Canvas.EmptyIcon);
}
protected void forScenario() {
renameScenario.setEnabled(true);
deleteScenario.setEnabled(true);
addTestCase.setEnabled(true);
addScenario.setEnabled(false);
renameTestCase.setEnabled(false);
deleteTestCase.setEnabled(false);
toggleReusable.setEnabled(false);
impactAnalysis.setEnabled(false);
getCmdSyntax.setEnabled(false);
copy.setEnabled(true);
cut.setEnabled(false);
paste.setEnabled(true);
sort.setEnabled(true);
}
protected void forTestCase() {
addScenario.setEnabled(false);
renameScenario.setEnabled(false);
deleteScenario.setEnabled(false);
addTestCase.setEnabled(false);
renameTestCase.setEnabled(true);
deleteTestCase.setEnabled(true);
toggleReusable.setEnabled(true);
impactAnalysis.setEnabled(true);
getCmdSyntax.setEnabled(true);
copy.setEnabled(true);
cut.setEnabled(true);
paste.setEnabled(true);
sort.setEnabled(false);
}
protected void forTestPlan() {
addScenario.setEnabled(true);
renameScenario.setEnabled(false);
deleteScenario.setEnabled(false);
addTestCase.setEnabled(false);
renameTestCase.setEnabled(false);
deleteTestCase.setEnabled(false);
toggleReusable.setEnabled(false);
impactAnalysis.setEnabled(false);
getCmdSyntax.setEnabled(false);
copy.setEnabled(false);
cut.setEnabled(false);
paste.setEnabled(true);
sort.setEnabled(true);
}
protected JMenuItem create(String name, KeyStroke keyStroke) {
JMenuItem menuItem = new JMenuItem(name);
menuItem.setActionCommand(name);
menuItem.setAccelerator(keyStroke);
menuItem.addActionListener(ProjectTree.this);
return menuItem;
}
private void setCCP() {
TransferActionListener actionListener = new TransferActionListener();
cut = new JMenuItem("Cut");
cut.setActionCommand((String) TransferHandler.getCutAction().getValue(Action.NAME));
cut.addActionListener(actionListener);
cut.setAccelerator(Keystroke.CUT);
cut.setMnemonic(KeyEvent.VK_T);
add(cut);
copy = new JMenuItem("Copy");
copy.setActionCommand((String) TransferHandler.getCopyAction().getValue(Action.NAME));
copy.addActionListener(actionListener);
copy.setAccelerator(Keystroke.COPY);
copy.setMnemonic(KeyEvent.VK_C);
add(copy);
paste = new JMenuItem("Paste");
paste.setActionCommand((String) TransferHandler.getPasteAction().getValue(Action.NAME));
paste.addActionListener(actionListener);
paste.setAccelerator(Keystroke.PASTE);
paste.setMnemonic(KeyEvent.VK_P);
add(paste);
}
}
}
|
IDE/src/main/java/com/cognizant/cognizantits/ide/main/mainui/components/testdesign/tree/ProjectTree.java
|
/*
* Copyright 2014 - 2017 Cognizant Technology Solutions
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cognizant.cognizantits.ide.main.mainui.components.testdesign.tree;
import com.cognizant.cognizantits.datalib.component.Project;
import com.cognizant.cognizantits.datalib.component.Scenario;
import com.cognizant.cognizantits.datalib.component.TestCase;
import com.cognizant.cognizantits.datalib.model.DataItem;
import com.cognizant.cognizantits.datalib.model.Meta;
import com.cognizant.cognizantits.datalib.model.Tag;
import com.cognizant.cognizantits.ide.main.mainui.components.testdesign.TestDesign;
import com.cognizant.cognizantits.ide.main.mainui.components.testdesign.tree.model.GroupNode;
import com.cognizant.cognizantits.ide.main.mainui.components.testdesign.tree.model.ProjectTreeModel;
import com.cognizant.cognizantits.ide.main.mainui.components.testdesign.tree.model.ScenarioNode;
import com.cognizant.cognizantits.ide.main.mainui.components.testdesign.tree.model.TestCaseNode;
import com.cognizant.cognizantits.ide.main.mainui.components.testdesign.tree.model.TestPlanTreeModel;
import com.cognizant.cognizantits.ide.main.ui.ProjectProperties;
import com.cognizant.cognizantits.ide.main.utils.Utils;
import com.cognizant.cognizantits.ide.main.utils.dnd.TransferActionListener;
import com.cognizant.cognizantits.ide.main.utils.keys.Keystroke;
import com.cognizant.cognizantits.ide.main.utils.tree.TreeSelectionRenderer;
import com.cognizant.cognizantits.ide.settings.IconSettings;
import com.cognizant.cognizantits.ide.util.Canvas;
import com.cognizant.cognizantits.ide.util.Notification;
import com.cognizant.cognizantits.ide.util.Validator;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.tree.TreePath;
/**
*
*
*/
public class ProjectTree implements ActionListener {
private static final Logger LOGGER = Logger.getLogger(ProjectTree.class.getName());
ProjectPopupMenu popupMenu;
private final ProjectProperties projectProperties;
private final JTree tree;
private final TestDesign testDesign;
ProjectTreeModel treeModel = new TestPlanTreeModel();
public ProjectTree(TestDesign testDesign) {
this.testDesign = testDesign;
tree = new JTree();
projectProperties = new ProjectProperties(testDesign.getsMainFrame());
init();
}
ProjectTreeModel getNewTreeModel() {
return new TestPlanTreeModel();
}
ProjectPopupMenu getNewPopupMenu() {
return new ProjectPopupMenu();
}
private void init() {
popupMenu = getNewPopupMenu();
treeModel = getNewTreeModel();
tree.setModel(treeModel);
tree.setToggleClickCount(0);
tree.setEditable(true);
tree.setInvokesStopCellEditing(true);
tree.setComponentPopupMenu(popupMenu);
tree.setDragEnabled(true);
tree.setTransferHandler(new ProjectDnD(this));
tree.getInputMap(JComponent.WHEN_FOCUSED).put(Keystroke.NEW, "New");
tree.getInputMap(JComponent.WHEN_FOCUSED).put(Keystroke.DELETE, "Delete");
tree.getInputMap(JComponent.WHEN_FOCUSED).put(Keystroke.ALTENTER, "AltEnter");
tree.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ESCAPE"), "Escape");
tree.getActionMap().put("AltEnter", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
showDetails();
}
});
tree.getActionMap().put("New", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
onNewAction();
}
});
tree.getActionMap().put("Delete", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
onDeleteAction();
}
});
tree.getActionMap().put("Escape", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
if (tree.isEditing()) {
tree.cancelEditing();
}
}
});
tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
loadTableModelForSelection();
}
}
});
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent pme) {
onRightClick();
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent pme) {
// Not Needed
}
@Override
public void popupMenuCanceled(PopupMenuEvent pme) {
// Not Needed
}
});
setTreeIcon();
tree.getCellEditor().addCellEditorListener(new CellEditorListener() {
@Override
public void editingStopped(ChangeEvent ce) {
if (!checkAndRename()) {
tree.getCellEditor().cancelCellEditing();
}
}
@Override
public void editingCanceled(ChangeEvent ce) {
// Not Needed
}
});
}
private void setTreeIcon() {
tree.setFont(new Font("Arial", Font.PLAIN, 11));
new TreeSelectionRenderer(tree) {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean isLeaf, int row, boolean focused) {
Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, isLeaf, row, focused);
if (value instanceof GroupNode) {
setIcons(IconSettings.getIconSettings().getReusableFolder());
} else if (value instanceof ScenarioNode) {
setIcons(IconSettings.getIconSettings().getTestPlanScenario());
} else if (value instanceof TestCaseNode) {
setIcons(IconSettings.getIconSettings().getTestPlanTestCase());
} else {
setIcons(IconSettings.getIconSettings().getTestPlanRoot());
}
return c;
}
void setIcons(Icon icon) {
setLeafIcon(icon);
setClosedIcon(icon);
setOpenIcon(icon);
setIcon(icon);
}
};
}
public void loadTableModelForSelection() {
Object selected = getSelectedTestCase();
if (selected == null) {
selected = getSelectedScenario();
}
testDesign.loadTableModelForSelection(selected);
}
private void onRightClick() {
TreePath path = tree.getSelectionPath();
if (path != null) {
togglePopupMenu(tree.getSelectionPath().getLastPathComponent());
} else {
popupMenu.setVisible(false);
}
}
protected void togglePopupMenu(Object selected) {
if (selected instanceof ScenarioNode) {
popupMenu.forScenario();
} else if (selected instanceof TestCaseNode) {
popupMenu.forTestCase();
} else if (selected instanceof GroupNode) {
popupMenu.forTestPlan();
}
}
protected void onNewAction() {
if (getSelectedScenarioNode() != null) {
addTestCase();
} else if (getSelectedGroupNode() != null) {
addScenario();
}
}
protected void onDeleteAction() {
deleteTestCases();
deleteScenarios();
}
@Override
public void actionPerformed(ActionEvent ae) {
switch (ae.getActionCommand()) {
case "Add Scenario":
addScenario();
break;
case "Rename Scenario":
tree.startEditingAtPath(new TreePath(getSelectedScenarioNode().getPath()));
break;
case "Delete Scenario":
deleteScenarios();
break;
case "Add TestCase":
addTestCase();
break;
case "Rename TestCase":
tree.startEditingAtPath(new TreePath(getSelectedTestCaseNode().getPath()));
break;
case "Delete TestCase":
deleteTestCases();
break;
case "Sort":
sort();
break;
case "Edit Tag":
editTag();
break;
case "Make As Reusable/TestCase":
makeAsReusableRTestCase();
break;
case "Details":
showDetails();
break;
case "Manual Testcase":
convertToManual();
break;
case "Get Impacted TestCases":
getImpactedTestCases();
break;
case "Get CmdLine Syntax":
getCmdLineSyntax();
break;
default:
throw new UnsupportedOperationException();
}
}
public ProjectTreeModel getTreeModel() {
return treeModel;
}
private void addScenario() {
ScenarioNode scNode = treeModel.addScenario(getSelectedGroupNode(),
testDesign.getProject().addScenario(fetchNewScenarioName()));
selectAndScrollTo(new TreePath(scNode.getPath()));
}
private String fetchNewScenarioName() {
String newScenarioName = "NewScenario";
for (int i = 0;; i++) {
if (testDesign.getProject().getScenarioByName(newScenarioName) == null) {
break;
}
newScenarioName = "NewScenario" + i;
}
return newScenarioName;
}
private void addTestCase() {
ScenarioNode scenarioNode = getSelectedScenarioNode();
if (scenarioNode != null) {
TestCase testcase;
String testCaseName = fetchNewTestCaseName(scenarioNode.getScenario());
testcase = scenarioNode.getScenario().addTestCase(testCaseName);
testDesign.loadTableModelForSelection(testcase);
selectAndScrollTo(new TreePath(treeModel.
addTestCase(scenarioNode, testcase).getPath()));
}
}
private String fetchNewTestCaseName(Scenario scenario) {
String newTestCaseName = "NewTestCase";
for (int i = 0;; i++) {
if (scenario.getTestCaseByName(newTestCaseName) == null) {
break;
}
newTestCaseName = "NewTestCase" + i;
}
return newTestCaseName;
}
protected Boolean checkAndRename() {
String name = tree.getCellEditor().getCellEditorValue().toString().trim();
if (Validator.isValidName(name)) {
ScenarioNode scenarioNode = getSelectedScenarioNode();
if (scenarioNode != null && !scenarioNode.toString().equals(name)) {
if (scenarioNode.getScenario().rename(name)) {
getTreeModel().reload(scenarioNode);
renameScenario(scenarioNode.getScenario());
testDesign.getScenarioComp().refreshTitle();
return true;
} else {
Notification.show("Scenario " + name + " Already present");
return false;
}
}
TestCaseNode testCaseNode = getSelectedTestCaseNode();
if (testCaseNode != null && !testCaseNode.toString().equals(name)) {
if (testCaseNode.getTestCase().rename(name)) {
getTreeModel().reload(testCaseNode);
testDesign.getTestCaseComp().refreshTitle();
return true;
} else {
Notification.show("Testcase '" + name + "' Already present in Scenario - " + getSelectedTestCase().getScenario().getName());
}
}
}
return false;
}
void renameScenario(Scenario scenario) {
getTestDesign().getReusableTree()
.getTreeModel().onScenarioRename(scenario);
}
private void deleteScenarios() {
List<ScenarioNode> scenarioNodes = getSelectedScenarioNodes();
if (!scenarioNodes.isEmpty()) {
int option = JOptionPane.showConfirmDialog(null,
"<html><body><p style='width: 200px;'>"
+ "Are you sure want to delete the following Scenarios?<br>"
+ scenarioNodes
+ "</p></body></html>",
"Delete Scenario",
JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
LOGGER.log(Level.INFO, "Delete Scenarios approved for {0}; {1}",
new Object[]{scenarioNodes.size(), scenarioNodes});
for (ScenarioNode scenarioNode : scenarioNodes) {
deleteTestCases(Collections.list(scenarioNode.children()));
scenarioNode.getScenario().delete();
getTreeModel().removeNodeFromParent(scenarioNode);
}
}
}
}
private void deleteTestCases() {
List<TestCaseNode> testcaseNodes = getSelectedTestCaseNodes();
if (!testcaseNodes.isEmpty()) {
int option = JOptionPane.showConfirmDialog(null,
"<html><body><p style='width: 200px;'>"
+ "Are you sure want to delete the following TestCases?<br>"
+ testcaseNodes
+ "</p></body></html>",
"Delete TestCase",
JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
LOGGER.log(Level.INFO, "Delete TestCases approved for {0}; {1}",
new Object[]{testcaseNodes.size(), testcaseNodes});
deleteTestCases(testcaseNodes);
}
}
}
private void deleteTestCases(List<TestCaseNode> testcaseNodes) {
TestCase loadedTestCase = testDesign.getTestCaseComp().getCurrentTestCase();
Boolean shouldRemove = false;
for (TestCaseNode testcaseNode : testcaseNodes) {
if (!shouldRemove) {
shouldRemove = Objects.equals(loadedTestCase, testcaseNode.getTestCase());
}
testcaseNode.getTestCase().delete();
getTreeModel().removeNodeFromParent(testcaseNode);
}
if (shouldRemove) {
testDesign.getTestCaseComp().resetTable();
}
}
private Scenario getSelectedScenario() {
ScenarioNode scenarioNode = getSelectedScenarioNode();
if (scenarioNode != null) {
return scenarioNode.getScenario();
}
return null;
}
private List<Scenario> getSelectedScenarios() {
List<Scenario> scenarios = new ArrayList<>();
TreePath[] paths = tree.getSelectionPaths();
if (paths != null && paths.length > 0) {
for (TreePath path : paths) {
if (path.getLastPathComponent() instanceof ScenarioNode) {
scenarios.add(((ScenarioNode) path.getLastPathComponent()).getScenario());
}
}
}
return scenarios;
}
private List<TestCase> getSelectedTestCases() {
List<TestCase> testcases = new ArrayList<>();
TreePath[] paths = tree.getSelectionPaths();
if (paths != null && paths.length > 0) {
for (TreePath path : paths) {
if (path.getLastPathComponent() instanceof TestCaseNode) {
testcases.add(((TestCaseNode) path.getLastPathComponent()).getTestCase());
}
}
}
return testcases;
}
protected GroupNode getSelectedGroupNode() {
List<GroupNode> groups = getSelectedGroupNodes();
if (groups.isEmpty()) {
return null;
}
return groups.get(0);
}
protected List<GroupNode> getSelectedGroupNodes() {
List<GroupNode> groupNodes = new ArrayList<>();
TreePath[] paths = tree.getSelectionPaths();
if (paths != null && paths.length > 0) {
for (TreePath path : paths) {
if (path.getLastPathComponent() instanceof GroupNode) {
groupNodes.add((GroupNode) path.getLastPathComponent());
}
}
}
return groupNodes;
}
private ScenarioNode getSelectedScenarioNode() {
List<ScenarioNode> scenarioNodes = getSelectedScenarioNodes();
if (scenarioNodes.isEmpty()) {
return null;
}
return scenarioNodes.get(0);
}
protected List<ScenarioNode> getSelectedScenarioNodes() {
List<ScenarioNode> scenarioNodes = new ArrayList<>();
TreePath[] paths = tree.getSelectionPaths();
if (paths != null && paths.length > 0) {
for (TreePath path : paths) {
if (path.getLastPathComponent() instanceof ScenarioNode) {
scenarioNodes.add((ScenarioNode) path.getLastPathComponent());
}
}
}
return scenarioNodes;
}
protected TestCase getSelectedTestCase() {
TestCaseNode testcaseNode = getSelectedTestCaseNode();
if (testcaseNode != null) {
return testcaseNode.getTestCase();
}
return null;
}
private TestCaseNode getSelectedTestCaseNode() {
List<TestCaseNode> tcNodes = getSelectedTestCaseNodes();
if (tcNodes.isEmpty()) {
return null;
}
return tcNodes.get(0);
}
protected List<TestCaseNode> getSelectedTestCaseNodes() {
List<TestCaseNode> tcNodes = new ArrayList<>();
TreePath[] paths = tree.getSelectionPaths();
if (paths != null && paths.length > 0) {
for (TreePath path : paths) {
if (path.getLastPathComponent() instanceof TestCaseNode) {
tcNodes.add((TestCaseNode) path.getLastPathComponent());
}
}
}
return tcNodes;
}
protected void selectAndScrollTo(final TreePath path) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
tree.setSelectionPath(path);
tree.scrollPathToVisible(path);
tree.removeSelectionPath(path);
tree.addSelectionPaths(new TreePath[]{path.getParentPath(), path});
}
});
}
private void makeAsReusableRTestCase() {
if (!getSelectedTestCaseNodes().isEmpty()) {
for (TestCaseNode testCaseNode : getSelectedTestCaseNodes()) {
testCaseNode.getTestCase().toggleAsReusable();
getTreeModel().removeNodeFromParent(testCaseNode);
makeAsReusableRTestCase(testCaseNode.getTestCase());
}
}
}
void makeAsReusableRTestCase(TestCase testCase) {
getTestDesign().getReusableTree().getTreeModel().addTestCase(testCase);
}
private void convertToManual() {
if (!getSelectedScenarios().isEmpty()) {
testDesign.getsMainFrame().getStepMap().convertScenarios(
Utils.saveDialog("Manual TestCase.csv"), getSelectedScenarios());
} else if (!getSelectedTestCases().isEmpty()) {
testDesign.getsMainFrame().getStepMap().convertTestCase(
Utils.saveDialog("Manual TestCase.csv"), getSelectedTestCases());
} else {
testDesign.getsMainFrame().getStepMap().convertScenarios(
Utils.saveDialog("Manual TestCase.csv"), getProject().getScenarios());
}
}
private void sort() {
if (tree.getSelectionPath() != null) {
getTreeModel().sort(tree.getSelectionPath().getLastPathComponent());
}
}
private void editTag() {
TreePath[] sel = tree.getSelectionPaths();
if (sel != null && sel.length > 0) {
if (sel.length > 1) {
editTag(Arrays.asList(sel));
} else {
editTag(sel[0]);
}
}
}
private Tag onAddTag(String tag) {
getProject().getInfo().addMeta(Meta.createTag(tag));
return Tag.create(tag);
}
private void onRemoveTag(Tag tag) {
getProject().getInfo().removeAll(tag);
}
private void editTag(DataItem tc) {
TagEditorDialog.build(testDesign.getsMainFrame(),
getProject().getInfo().getAllTags(tc.getTags()), tc.getTags(),
this::onRemoveTag, this::onAddTag)
.withTitle(editTagTitle(tc.getName())).show(tc::setTags);
}
private void editTag(Meta scn) {
TagEditorDialog.build(testDesign.getsMainFrame(),
getProject().getInfo().getAllTags(scn.getTags()), scn.getTags(),
this::onRemoveTag, this::onAddTag)
.withTitle(editTagTitle(scn.getName())).show(scn::setTags);
}
private String editTagTitle(String t) {
return String.format("Edit Tag: %s", t);
}
private void editTag(TreePath path) {
if (path.getLastPathComponent() instanceof TestCaseNode) {
TestCase tcn = ((TestCaseNode) path.getLastPathComponent()).getTestCase();
editTag(getProject().getInfo().getData()
.findOrCreate(tcn.getName(), tcn.getScenario().getName()));
} else if (path.getLastPathComponent() instanceof ScenarioNode) {
Scenario scn = ((ScenarioNode) path.getLastPathComponent()).getScenario();
editTag(getProject().getInfo().findScenarioOrCreate(scn.getName()));
}
}
private void editTag(List<TreePath> paths) {
paths.stream().forEach(this::editTag);
}
private void getImpactedTestCases() {
TestCase testCase = getSelectedTestCase();
if (testCase != null) {
String scenarioName = testCase.getScenario().getName();
String testCaseName = testCase.getName();
testDesign.getImpactUI().loadForTestCase(getProject()
.getImpactedTestCaseTestCases(scenarioName, testCaseName), scenarioName, testCaseName);
} else {
Notification.show("Select a Valid TestCase");
}
}
private void getCmdLineSyntax() {
TestCase testCase = getSelectedTestCase();
if (testCase != null) {
String scenarioName = testCase.getScenario().getName();
String testCaseName = testCase.getName();
String syntax = String.format(
"%s -run -project_location \"%s\" -scenario \"%s\" -testcase \"%s\" -browser \"%s\"",
getBatRCommand(),
getProject().getLocation(),
scenarioName,
testCaseName,
getTestDesign().getDefaultBrowser());
Utils.copyTextToClipboard(syntax);
Notification.show("Syntax has been copied to Clipboard");
} else {
Notification.show("Select a Valid TestCase");
}
}
private String getBatRCommand() {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("windows")) {
return "Run.bat";
}
return "Run.command";
}
private void showDetails() {
TreePath path = tree.getSelectionPath();
if (path != null) {
showProjDetails();
}
}
private void showProjDetails() {
projectProperties.loadForCurrentProject();
// projectProperties.pack();
projectProperties.setLocationRelativeTo(null);
projectProperties.setVisible(true);
}
public final JTree getTree() {
return tree;
}
public final Project getProject() {
return testDesign.getProject();
}
public final TestDesign getTestDesign() {
return testDesign;
}
public final void load() {
treeModel.setProject(testDesign.getProject());
treeModel.reload();
getTree().setSelectionPath(new TreePath(treeModel.getFirstNode().getPath()));
loadTableModelForSelection();
}
class ProjectPopupMenu extends JPopupMenu {
protected JMenuItem addScenario;
protected JMenuItem renameScenario;
protected JMenuItem deleteScenario;
protected JMenuItem addTestCase;
protected JMenuItem renameTestCase;
protected JMenuItem deleteTestCase;
protected JMenuItem toggleReusable;
protected JMenuItem impactAnalysis;
protected JMenuItem copy;
protected JMenuItem cut;
protected JMenuItem paste;
protected JMenuItem sort;
protected JMenuItem getCmdSyntax;
public ProjectPopupMenu() {
init();
}
protected final void init() {
add(addScenario = create("Add Scenario", Keystroke.NEW));
add(renameScenario = create("Rename Scenario", Keystroke.RENAME));
add(deleteScenario = create("Delete Scenario", Keystroke.DELETE));
addSeparator();
add(addTestCase = create("Add TestCase", Keystroke.NEW));
add(renameTestCase = create("Rename TestCase", Keystroke.RENAME));
add(deleteTestCase = create("Delete TestCase", Keystroke.DELETE));
addSeparator();
JMenu menu = new JMenu("Export As");
menu.add(create("Manual Testcase", null));
add(menu);
add(toggleReusable = create("Make As Reusable/TestCase", null));
toggleReusable.setText("Make As Reusable");
addSeparator();
setCCP();
addSeparator();
add(impactAnalysis = create("Get Impacted TestCases", null));
add(getCmdSyntax = create("Get CmdLine Syntax", null));
addSeparator();
add(sort = create("Sort", null));
addSeparator();
add(create("Details", Keystroke.ALTENTER));
sort.setIcon(Canvas.EmptyIcon);
}
protected void forScenario() {
renameScenario.setEnabled(true);
deleteScenario.setEnabled(true);
addTestCase.setEnabled(true);
addScenario.setEnabled(false);
renameTestCase.setEnabled(false);
deleteTestCase.setEnabled(false);
toggleReusable.setEnabled(false);
impactAnalysis.setEnabled(false);
getCmdSyntax.setEnabled(false);
copy.setEnabled(true);
cut.setEnabled(false);
paste.setEnabled(true);
sort.setEnabled(true);
}
protected void forTestCase() {
addScenario.setEnabled(false);
renameScenario.setEnabled(false);
deleteScenario.setEnabled(false);
addTestCase.setEnabled(false);
renameTestCase.setEnabled(true);
deleteTestCase.setEnabled(true);
toggleReusable.setEnabled(true);
impactAnalysis.setEnabled(true);
getCmdSyntax.setEnabled(true);
copy.setEnabled(true);
cut.setEnabled(true);
paste.setEnabled(true);
sort.setEnabled(false);
}
protected void forTestPlan() {
addScenario.setEnabled(true);
renameScenario.setEnabled(false);
deleteScenario.setEnabled(false);
addTestCase.setEnabled(false);
renameTestCase.setEnabled(false);
deleteTestCase.setEnabled(false);
toggleReusable.setEnabled(false);
impactAnalysis.setEnabled(false);
getCmdSyntax.setEnabled(false);
copy.setEnabled(false);
cut.setEnabled(false);
paste.setEnabled(true);
sort.setEnabled(true);
}
protected JMenuItem create(String name, KeyStroke keyStroke) {
JMenuItem menuItem = new JMenuItem(name);
menuItem.setActionCommand(name);
menuItem.setAccelerator(keyStroke);
menuItem.addActionListener(ProjectTree.this);
return menuItem;
}
private void setCCP() {
TransferActionListener actionListener = new TransferActionListener();
cut = new JMenuItem("Cut");
cut.setActionCommand((String) TransferHandler.getCutAction().getValue(Action.NAME));
cut.addActionListener(actionListener);
cut.setAccelerator(Keystroke.CUT);
cut.setMnemonic(KeyEvent.VK_T);
add(cut);
copy = new JMenuItem("Copy");
copy.setActionCommand((String) TransferHandler.getCopyAction().getValue(Action.NAME));
copy.addActionListener(actionListener);
copy.setAccelerator(Keystroke.COPY);
copy.setMnemonic(KeyEvent.VK_C);
add(copy);
paste = new JMenuItem("Paste");
paste.setActionCommand((String) TransferHandler.getPasteAction().getValue(Action.NAME));
paste.addActionListener(actionListener);
paste.setAccelerator(Keystroke.PASTE);
paste.setMnemonic(KeyEvent.VK_P);
add(paste);
}
}
}
|
Java 9 changes
|
IDE/src/main/java/com/cognizant/cognizantits/ide/main/mainui/components/testdesign/tree/ProjectTree.java
|
Java 9 changes
|
<ide><path>DE/src/main/java/com/cognizant/cognizantits/ide/main/mainui/components/testdesign/tree/ProjectTree.java
<ide> /*
<del> * Copyright 2014 - 2017 Cognizant Technology Solutions
<add> * Copyright 2014 - 2019 Cognizant Technology Solutions
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> LOGGER.log(Level.INFO, "Delete Scenarios approved for {0}; {1}",
<ide> new Object[]{scenarioNodes.size(), scenarioNodes});
<ide> for (ScenarioNode scenarioNode : scenarioNodes) {
<del> deleteTestCases(Collections.list(scenarioNode.children()));
<add> deleteTestCases(TestCaseNode.toList(scenarioNode.children()));
<ide> scenarioNode.getScenario().delete();
<ide> getTreeModel().removeNodeFromParent(scenarioNode);
<ide> }
|
|
Java
|
apache-2.0
|
e122ef74812c71b74fa6794a4b484e211586f188
| 0 |
nvoron23/titan,anvie/titan,elkingtonmcb/titan,samanalysis/titan,wangbf/titan,englishtown/titan,elkingtonmcb/titan,fengshao0907/titan,jankotek/titan,mwpnava/titan,banjiewen/titan,elkingtonmcb/titan,qiuqiyuan/titan,mwpnava/titan,jamestyack/titan,anuragkh/titan,wangbf/titan,elubow/titan,jankotek/titan,elkingtonmcb/titan,amcp/titan,englishtown/titan,infochimps-forks/titan,wangbf/titan,jamestyack/titan,samanalysis/titan,kangkot/titan,nvoron23/titan,ThiagoGarciaAlves/titan,tomersagi/titan,samanalysis/titan,qiuqiyuan/titan,fengshao0907/titan,kalatestimine/titan,wangbf/titan,kangkot/titan,mbrukman/titan,anuragkh/titan,mbrukman/titan,mbrukman/titan,boorad/titan,pluradj/titan,qiuqiyuan/titan,pluradj/titan,CYPP/titan,boorad/titan,ThiagoGarciaAlves/titan,ThiagoGarciaAlves/titan,samanalysis/titan,jankotek/titan,mbrukman/titan,qiuqiyuan/titan,evanv/titan,hortonworks/titan,dylanht/titan,kangkot/titan,evanv/titan,pluradj/titan,boorad/titan,anvie/titan,kalatestimine/titan,elubow/titan,infochimps-forks/titan,elubow/titan,jankotek/titan,xlcupid/titan,fengshao0907/titan,wangbf/titan,hortonworks/titan,evanv/titan,thinkaurelius/titan,boorad/titan,tomersagi/titan,amcp/titan,evanv/titan,anvie/titan,jamestyack/titan,CYPP/titan,twilmes/titan,mwpnava/titan,pluradj/titan,kalatestimine/titan,banjiewen/titan,dylanht/titan,ThiagoGarciaAlves/titan,infochimps-forks/titan,mwpnava/titan,xlcupid/titan,nvoron23/titan,graben1437/titan,nvoron23/titan,evanv/titan,thinkaurelius/titan,anvie/titan,twilmes/titan,jamestyack/titan,anuragkh/titan,xlcupid/titan,jamestyack/titan,anuragkh/titan,fengshao0907/titan,hortonworks/titan,englishtown/titan,twilmes/titan,kangkot/titan,twilmes/titan,kangkot/titan,thinkaurelius/titan,dylanht/titan,fengshao0907/titan,englishtown/titan,elkingtonmcb/titan,graben1437/titan,amcp/titan,hortonworks/titan,anvie/titan,jankotek/titan,thinkaurelius/titan,kalatestimine/titan,dylanht/titan,tomersagi/titan,twilmes/titan,anuragkh/titan,infochimps-forks/titan,CYPP/titan,xlcupid/titan,banjiewen/titan,mwpnava/titan,kalatestimine/titan,amcp/titan,xlcupid/titan,elubow/titan,tomersagi/titan,CYPP/titan,banjiewen/titan,ThiagoGarciaAlves/titan,hortonworks/titan,graben1437/titan,qiuqiyuan/titan,graben1437/titan,tomersagi/titan,infochimps-forks/titan,mbrukman/titan
|
package com.thinkaurelius.titan.diskstorage.keycolumnvalue.keyvalue;
import com.thinkaurelius.titan.diskstorage.StaticBuffer;
import com.thinkaurelius.titan.diskstorage.StorageException;
import com.thinkaurelius.titan.diskstorage.keycolumnvalue.KeyColumnValueStore;
import com.thinkaurelius.titan.diskstorage.keycolumnvalue.StoreTransaction;
import com.thinkaurelius.titan.diskstorage.util.RecordIterator;
/**
* @author Matthias Broecheler ([email protected])
*/
public interface CacheStore extends KeyValueStore {
/**
* Sets the value associated with key "key" to "value" if the current value associated with this key is "oldValue", otherwise
* it throws an {@link CacheUpdateException}.
*
* @param key
* @param value
* @param oldValue
* @param txh
* @throws StorageException
*/
public void replace(StaticBuffer key, StaticBuffer value, StaticBuffer oldValue, StoreTransaction txh) throws StorageException;
/**
* Returns an iterator over all keys in this store that match the given KeySelector. The keys may be
* ordered but not necessarily.
*
* @return An iterator over all keys in this store.
*/
public RecordIterator<KeyValueEntry> getKeys(KeySelector selector, StoreTransaction txh) throws StorageException;
}
|
titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/keycolumnvalue/keyvalue/CacheStore.java
|
package com.thinkaurelius.titan.diskstorage.keycolumnvalue.keyvalue;
import com.thinkaurelius.titan.diskstorage.StaticBuffer;
import com.thinkaurelius.titan.diskstorage.StorageException;
import com.thinkaurelius.titan.diskstorage.keycolumnvalue.KeyColumnValueStore;
import com.thinkaurelius.titan.diskstorage.keycolumnvalue.StoreTransaction;
import com.thinkaurelius.titan.diskstorage.util.RecordIterator;
/**
* @author Matthias Broecheler ([email protected])
*/
public interface CacheStore extends KeyValueStore {
/**
* Insert a new value into cache for the given key.
*
* @param key The key to use for insertion.
* @param value The new value to assign the key.
* @param tx The transactional context for the change.
*
* @throws StorageException
*/
public void insert(StaticBuffer key, StaticBuffer value, StoreTransaction tx) throws StorageException;
/**
* Sets the value associated with key "key" to "value" if the current value associated with this key is "oldValue", otherwise
* it throws an {@link CacheUpdateException}.
*
* @param key
* @param value
* @param oldValue
* @param txh
* @throws StorageException
*/
public void replace(StaticBuffer key, StaticBuffer value, StaticBuffer oldValue, StoreTransaction txh) throws StorageException;
/**
* Returns an iterator over all keys in this store that match the given KeySelector. The keys may be
* ordered but not necessarily.
*
* @return An iterator over all keys in this store.
*/
public RecordIterator<KeyValueEntry> getKeys(KeySelector selector, StoreTransaction txh) throws StorageException;
}
|
remove redundant CacheStore.insert method
|
titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/keycolumnvalue/keyvalue/CacheStore.java
|
remove redundant CacheStore.insert method
|
<ide><path>itan-core/src/main/java/com/thinkaurelius/titan/diskstorage/keycolumnvalue/keyvalue/CacheStore.java
<ide> */
<ide>
<ide> public interface CacheStore extends KeyValueStore {
<del> /**
<del> * Insert a new value into cache for the given key.
<del> *
<del> * @param key The key to use for insertion.
<del> * @param value The new value to assign the key.
<del> * @param tx The transactional context for the change.
<del> *
<del> * @throws StorageException
<del> */
<del> public void insert(StaticBuffer key, StaticBuffer value, StoreTransaction tx) throws StorageException;
<del>
<ide> /**
<ide> * Sets the value associated with key "key" to "value" if the current value associated with this key is "oldValue", otherwise
<ide> * it throws an {@link CacheUpdateException}.
|
|
Java
|
apache-2.0
|
fe373e2963df2ecaf1e2476695ff7fd0101ded73
| 0 |
lizhi5753186/facebook-android-sdk,Limbika/facebook-android-sdk,couchbaselabs/facebook-android-sdk,RabbleApp/facebook-android-sdk,bitcellar-labs/facebook-android-sdk,satoshi-okawa/facebook-android-sdk-test1,MarkHappy/Facebook_SDK,mindjolt/facebook-android-sdk,Flutterbee/facebook-android-sdk,TimeIncOSS/facebook-android-sdk,quizlet/facebook-android-sdk,lizhi5753186/facebook-android-sdk,Limbika/facebook-android-sdk,TechSmith/facebook-android-sdk,couchbaselabs/facebook-android-sdk,GrioSF/facebook-android-sdk,ribot/facebook-android-sdk,satoshi-okawa/facebook-android-sdk-test1,CristianOliveiraDaRosa/facebook-android-sdk,scalio/facebook-android-sdk,minhduc3404/facebookSdk,taisukeoe/facebook-android-sdk,taisukeoe/facebook-android-sdk,Flutterbee/facebook-android-sdk,TimeIncOSS/facebook-android-sdk,PioneerLab/facebook-android-sdk,PioneerLab/facebook-android-sdk,MKrishtop/facebook-android-sdk,mindjolt/facebook-android-sdk,MKrishtop/facebook-android-sdk,MarkHappy/Facebook_SDK,GrioSF/facebook-android-sdk,scalio/facebook-android-sdk,RabbleApp/facebook-android-sdk,TechSmith/facebook-android-sdk,CristianOliveiraDaRosa/facebook-android-sdk,minhduc3404/facebookSdk,bitcellar-labs/facebook-android-sdk,quizlet/facebook-android-sdk,ribot/facebook-android-sdk
|
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Contains logic for converting a JSONObject obtained from
* querying /me/home to a HTML string that can be rendered
* in WebKit.
*
* @author yariv
*/
class StreamRenderer {
private StringBuilder sb;
/**
* The main function for rendering the stream JSONObject.
*
* @param data
* @return
*/
public static String render(JSONObject data) {
StreamRenderer renderer = new StreamRenderer();
return renderer.doRender(data);
}
/**
* Renders the HTML for a single post.
*
* @param post
* @return
* @throws JSONException
*/
public static String renderSinglePost(JSONObject post)
throws JSONException {
StreamRenderer renderer = new StreamRenderer();
renderer.renderPost(post);
return renderer.getResult();
}
/**
* Renders the HTML for a single comment.
*
* @param comment
* @return
*/
public static String renderSingleComment(JSONObject comment) {
StreamRenderer renderer = new StreamRenderer();
renderer.renderComment(comment);
return renderer.getResult();
}
private StreamRenderer() {
this.sb = new StringBuilder();
}
/**
* Returns a SimpleDateFormat object we use for
* parsing and rendering timestamps.
*
* @return
*/
public static SimpleDateFormat getDateFormat() {
return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
}
/**
* Returns the result html.
*
* @return
*/
private String getResult() {
return sb.toString();
}
private String doRender(JSONObject data) {
try {
JSONArray posts = data.getJSONArray("data");
String[] chunks = {
"<html><head>",
"<link rel=\"stylesheet\" href=\"file:///android_asset/stream.css\" type=\"text/css\">",
"<script src=\"file:///android_asset/stream.js\"></script>",
"</head>",
"<body>",
"<div id=\"header\">"
};
append(chunks);
renderLink("app://logout", "logout");
renderStatusBox();
append("<div id=\"posts\">");
for (int i = 0; i < posts.length(); i++) {
renderPost(posts.getJSONObject(i));
}
append("</div></body></html>");
return getResult();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
/**
* Renders the "what's on your mind?" box and the Share button.
*/
private void renderStatusBox() {
String[] chunks = new String[] {
"</div><div class=\"clear\"></div>",
"<div id=\"status_box\">",
"<input id=\"status_input\" value=\" What's on your mind?\"",
" onfocus=\"onStatusBoxFocus(this);\"/>",
"<button id=\"status_submit\" class=\"hidden\" onclick=\"updateStatus();\">Share</button>",
"<div class=\"clear\"></div>",
"</div>"
};
append(chunks);
}
/**
* Renders a single post
*
* @param post
* @throws JSONException
*/
private void renderPost(JSONObject post) throws JSONException {
append("<div class=\"post\">");
renderFrom(post);
renderTo(post);
renderMessage(post);
renderAttachment(post);
renderActionLinks(post);
renderLikes(post);
renderComments(post);
renderCommentBox(post);
append("</div>");
}
/**
* Renders the author's name
*
* @param post
* @throws JSONException
*/
private void renderFrom(JSONObject post) throws JSONException {
JSONObject from = post.getJSONObject("from");
String fromName = from.getString("name");
String fromId = from.getString("id");
renderAuthor(fromId, fromName);
}
/**
* If it's a wall post on a friend's fall, renders
* the recipient's name preceded by a '>'.
*
* @param post
* @throws JSONException
*/
private void renderTo(JSONObject post) throws JSONException {
JSONObject to = post.optJSONObject("to");
if (to != null) {
JSONObject toData = to.getJSONArray("data").getJSONObject(0);
String toName = toData.getString("name");
String toId = toData.getString("id");
append(" > ");
renderProfileLink(toId, toName);
}
}
/**
* Renders a link to a user.
*
* @param id
* @param name
*/
private void renderProfileLink(String id, String name) {
renderLink(getProfileUrl(id), name);
}
private String getProfileUrl(String id) {
return "http://touch.facebook.com/#/profile.php?id=" + id;
}
/**
* Renders the author pic and name.
*
* @param id
* @param name
*/
private void renderAuthor(String id, String name) {
String[] chunks = {
"<div class=\"profile_pic_container\">",
"<a href=\"", getProfileUrl(id),
"\"><img class=\"profile_pic\" src=\"http://graph.facebook.com/",
id, "/picture\"/></a>",
"</div>"
};
append(chunks);
renderProfileLink(id, name);
}
/**
* Renders the post message.
*
* @param post
*/
private void renderMessage(JSONObject post) {
String message = post.optString("message");
String[] chunks = {
" <span class=\"msg\">", message, "</span>",
"<div class=\"clear\"></div>"};
append(chunks);
}
/**
* Renders the attachment.
*
* @param post
*/
private void renderAttachment(JSONObject post) {
String name = post.optString("name");
String link = post.optString("link");
String picture = post.optString("picture");
String source = post.optString("source"); // for videos
String caption = post.optString("caption");
String description = post.optString("description");
String[] fields = new String[] {
name, link, picture, source, caption, description
};
boolean hasAttachment = false;
for (String field : fields) {
if (field.length() != 0) {
hasAttachment = true;
break;
}
}
if (!hasAttachment) {
return;
}
append("<div class=\"attachment\">");
if (name != "") {
append("<div class=\"title\">");
if (link != null) {
renderLink(link, name);
} else {
append(name);
}
append("</div>");
}
if (caption != "") {
append("<div class=\"caption\">" + caption + "</div>");
}
if (picture != "") {
append("<div class=\"picture\">");
String img = "<img src=\"" + picture + "\"/>";
if (link != "") {
renderLink(link, img);
} else {
append(img);
}
append("</div>");
}
if (description != "") {
append("<div class=\"description\">" + description + "</div>");
}
append("<div class=\"clear\"></div></div>");
}
/**
* Renders an anchor tag
*
* @param href
* @param text
*/
private void renderLink(String href, String text) {
append(new String[] {
"<a href=\"",
href,
"\">",
text,
"</a>"
});
}
/**
* Renders the posts' action links.
*
* @param post
*/
private void renderActionLinks(JSONObject post) {
HashSet<String> actions = getActions(post);
append("<div class=\"action_links\">");
append("<div class=\"action_link\">");
renderTimeStamp(post);
append("</div>");
String post_id = post.optString("id");
if (actions.contains("Comment")) {
renderActionLink(post_id, "Comment", "comment");
}
boolean canLike = actions.contains("Like");
renderActionLink(post_id, "Like", "like", canLike);
renderActionLink(post_id, "Unlike", "unlike", !canLike);
append("<div class=\"clear\"></div></div>");
}
/**
* Renders a single visible action link.
*
* @param post_id
* @param title
* @param func
*/
private void renderActionLink(String post_id, String title, String func) {
renderActionLink(post_id, title, func, true);
}
/**
* Renders an action link with optional visibility.
*
* @param post_id
* @param title
* @param func
* @param visible
*/
private void renderActionLink(String post_id, String title, String func, boolean visible) {
String extraClass = visible ? "" : "hidden";
String[] chunks = new String[] {
"<div id=\"", func, post_id, "\" class=\"action_link ", extraClass, "\">",
"<a href=\"#\" onclick=\"",func, "('", post_id, "'); return false;\">",
title,
"</a></div>"
};
append(chunks);
}
/**
* Renders the post's timestamp.
*
* @param post
*/
private void renderTimeStamp(JSONObject post) {
String dateStr = post.optString("created_time");
SimpleDateFormat formatter = getDateFormat();
ParsePosition pos = new ParsePosition(0);
long then = formatter.parse(dateStr, pos).getTime();
long now = new Date().getTime();
long seconds = (now - then)/1000;
long minutes = seconds/60;
long hours = minutes/60;
long days = hours/24;
String friendly = null;
long num = 0;
if (days > 0) {
num = days;
friendly = days + " day";
} else if (hours > 0) {
num = hours;
friendly = hours + " hour";
} else if (minutes > 0) {
num = minutes;
friendly = minutes + " minute";
} else {
num = seconds;
friendly = seconds + " second";
}
if (num > 1) {
friendly += "s";
}
String[] chunks = new String[] {
"<div class=\"timestamp\">",
friendly,
" ago",
"</div>"
};
append(chunks);
}
/**
* Returns the available actions for the post.
*
* @param post
* @return
*/
private HashSet<String> getActions(JSONObject post) {
HashSet<String> actionsSet = new HashSet<String>();
JSONArray actions = post.optJSONArray("actions");
if (actions != null) {
for (int j = 0; j < actions.length(); j++) {
JSONObject action = actions.optJSONObject(j);
String actionName = action.optString("name");
actionsSet.add(actionName);
}
}
return actionsSet;
}
/**
* Renders the 'x people like this' text,
*
* @param post
*/
private void renderLikes(JSONObject post) {
int numLikes = post.optInt("likes", 0);
if (numLikes > 0) {
String desc = numLikes == 1 ?
"person likes this" :
"people like this";
String[] chunks = new String[] {
"<div class=\"like_icon\">",
"<img src=\"file:///android_asset/like_icon.png\"/>",
"</div>",
"<div class=\"num_likes\">",
new Integer(numLikes).toString(),
" ",
desc,
"</div>"
};
append(chunks);
}
}
/**
* Renders the post's comments.
*
* @param post
* @throws JSONException
*/
private void renderComments(JSONObject post) throws JSONException {
append("<div class=\"comments\" id=\"comments" + post.optString("id") + "\">");
JSONObject comments = post.optJSONObject("comments");
if (comments != null) {
JSONArray data = comments.optJSONArray("data");
for (int j = 0; j < data.length(); j++) {
JSONObject comment = data.getJSONObject(j);
renderComment(comment);
}
}
append("</div>");
}
/**
* Renders an individual comment.
*
* @param comment
*/
private void renderComment(JSONObject comment) {
JSONObject from = comment.optJSONObject("from");
String authorId = from.optString("id");
String authorName = from.optString("name");
String message = comment.optString("message");
append("<div class=\"comment\">");
renderAuthor(authorId, authorName);
String[] chunks = {
" ",
message,
"</div>"
};
append(chunks);
}
/**
* Renders the new comment input box.
*
* @param post
*/
private void renderCommentBox(JSONObject post) {
String id = post.optString("id");
String[] chunks = new String[] {
"<div class=\"comment_box\" id=\"comment_box", id, "\">",
"<input id=\"comment_box_input", id, "\"/>",
"<button onclick=\"postComment('", id , "');\">Post</button>",
"<div class=\"clear\"></div>",
"</div>"
};
append(chunks);
}
private void append(String str) {
sb.append(str);
}
private void append(String[] chunks) {
for (String chunk : chunks) {
sb.append(chunk);
}
}
}
|
examples/stream/src/com/facebook/stream/StreamRenderer.java
|
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Contains logic for converting a JSONObject obtained from
* querying /me/home to a HTML string that can be rendered
* in WebKit.
*
* @author yariv
*/
class StreamRenderer {
private StringBuilder sb;
/**
* The main function for rendering the stream JSONObject.
*
* @param data
* @return
*/
public static String render(JSONObject data) {
StreamRenderer renderer = new StreamRenderer();
return renderer.doRender(data);
}
/**
* Renders the HTML for a single post.
*
* @param post
* @return
* @throws JSONException
*/
public static String renderSinglePost(JSONObject post)
throws JSONException {
StreamRenderer renderer = new StreamRenderer();
renderer.renderPost(post);
return renderer.getResult();
}
/**
* Renders the HTML for a single comment.
*
* @param comment
* @return
*/
public static String renderSingleComment(JSONObject comment) {
StreamRenderer renderer = new StreamRenderer();
renderer.renderComment(comment);
return renderer.getResult();
}
private StreamRenderer() {
this.sb = new StringBuilder();
}
/**
* Returns a SimpleDateFormat object we use for
* parsing and rendering timestamps.
*
* @return
*/
public static SimpleDateFormat getDateFormat() {
return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
}
/**
* Returns the result html.
*
* @return
*/
private String getResult() {
return sb.toString();
}
private String doRender(JSONObject data) {
try {
JSONArray posts = data.getJSONArray("data");
String[] chunks = {
"<html><head>",
"<link rel=\"stylesheet\" href=\"file:///android_asset/stream.css\" type=\"text/css\">",
"<script src=\"file:///android_asset/stream.js\"></script>",
"</head>",
"<body>",
"<div id=\"header\">"
};
append(chunks);
renderLink("app://logout", "logout");
renderStatusBox();
append("<div id=\"posts\">");
for (int i = 0; i < posts.length(); i++) {
renderPost(posts.getJSONObject(i));
}
append("</div></body></html>");
return getResult();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
/**
* Renders the "what's on your mind?" box and the Share button.
*/
private void renderStatusBox() {
String[] chunks = new String[] {
"</div><div class=\"clear\"></div>",
"<div id=\"status_box\">",
"<input id=\"status_input\" value=\" What's on your mind?\"",
" onfocus=\"onStatusBoxFocus(this);\"/>",
"<button id=\"status_submit\" class=\"hidden\" onclick=\"updateStatus();\">Share</button>",
"<div class=\"clear\"></div>",
"</div>"
};
append(chunks);
}
/**
* Renders a single post
*
* @param post
* @throws JSONException
*/
private void renderPost(JSONObject post) throws JSONException {
append("<div class=\"post\">");
renderFrom(post);
renderTo(post);
renderMessage(post);
renderAttachment(post);
renderActionLinks(post);
renderLikes(post);
renderComments(post);
renderCommentBox(post);
append("</div>");
}
/**
* Renders the author's name
*
* @param post
* @throws JSONException
*/
private void renderFrom(JSONObject post) throws JSONException {
JSONObject from = post.getJSONObject("from");
String fromName = from.getString("name");
String fromId = from.getString("id");
renderAuthor(fromId, fromName);
}
/**
* If it's a wall post on a friend's fall, renders
* the recipient's name preceded by a '>'.
*
* @param post
* @throws JSONException
*/
private void renderTo(JSONObject post) throws JSONException {
JSONObject to = post.optJSONObject("to");
if (to != null) {
JSONObject toData = to.getJSONArray("data").getJSONObject(0);
String toName = toData.getString("name");
String toId = toData.getString("id");
append(" > ");
renderProfileLink(toId, toName);
}
}
/**
* Renders a link to a user.
*
* @param id
* @param name
*/
private void renderProfileLink(String id, String name) {
renderLink(getProfileUrl(id), name);
}
private String getProfileUrl(String id) {
return "http://touch.facebook.com/profile.php?id=" + id;
}
/**
* Renders the author pic and name.
*
* @param id
* @param name
*/
private void renderAuthor(String id, String name) {
String[] chunks = {
"<div class=\"profile_pic_container\">",
"<a href=\"", getProfileUrl(id),
"\"><img class=\"profile_pic\" src=\"http://graph.facebook.com/",
id, "/picture\"/></a>",
"</div>"
};
append(chunks);
renderProfileLink(id, name);
}
/**
* Renders the post message.
*
* @param post
*/
private void renderMessage(JSONObject post) {
String message = post.optString("message");
String[] chunks = {
" <span class=\"msg\">", message, "</span>",
"<div class=\"clear\"></div>"};
append(chunks);
}
/**
* Renders the attachment.
*
* @param post
*/
private void renderAttachment(JSONObject post) {
String name = post.optString("name");
String link = post.optString("link");
String picture = post.optString("picture");
String source = post.optString("source"); // for videos
String caption = post.optString("caption");
String description = post.optString("description");
String[] fields = new String[] {
name, link, picture, source, caption, description
};
boolean hasAttachment = false;
for (String field : fields) {
if (field.length() != 0) {
hasAttachment = true;
break;
}
}
if (!hasAttachment) {
return;
}
append("<div class=\"attachment\">");
if (name != "") {
append("<div class=\"title\">");
if (link != null) {
renderLink(link, name);
} else {
append(name);
}
append("</div>");
}
if (caption != "") {
append("<div class=\"caption\">" + caption + "</div>");
}
if (picture != "") {
append("<div class=\"picture\">");
String img = "<img src=\"" + picture + "\"/>";
if (link != "") {
renderLink(link, img);
} else {
append(img);
}
append("</div>");
}
if (description != "") {
append("<div class=\"description\">" + description + "</div>");
}
append("<div class=\"clear\"></div></div>");
}
/**
* Renders an anchor tag
*
* @param href
* @param text
*/
private void renderLink(String href, String text) {
append(new String[] {
"<a href=\"",
href,
"\">",
text,
"</a>"
});
}
/**
* Renders the posts' action links.
*
* @param post
*/
private void renderActionLinks(JSONObject post) {
HashSet<String> actions = getActions(post);
append("<div class=\"action_links\">");
append("<div class=\"action_link\">");
renderTimeStamp(post);
append("</div>");
String post_id = post.optString("id");
if (actions.contains("Comment")) {
renderActionLink(post_id, "Comment", "comment");
}
boolean canLike = actions.contains("Like");
renderActionLink(post_id, "Like", "like", canLike);
renderActionLink(post_id, "Unlike", "unlike", !canLike);
append("<div class=\"clear\"></div></div>");
}
/**
* Renders a single visible action link.
*
* @param post_id
* @param title
* @param func
*/
private void renderActionLink(String post_id, String title, String func) {
renderActionLink(post_id, title, func, true);
}
/**
* Renders an action link with optional visibility.
*
* @param post_id
* @param title
* @param func
* @param visible
*/
private void renderActionLink(String post_id, String title, String func, boolean visible) {
String extraClass = visible ? "" : "hidden";
String[] chunks = new String[] {
"<div id=\"", func, post_id, "\" class=\"action_link ", extraClass, "\">",
"<a href=\"#\" onclick=\"",func, "('", post_id, "'); return false;\">",
title,
"</a></div>"
};
append(chunks);
}
/**
* Renders the post's timestamp.
*
* @param post
*/
private void renderTimeStamp(JSONObject post) {
String dateStr = post.optString("created_time");
SimpleDateFormat formatter = getDateFormat();
ParsePosition pos = new ParsePosition(0);
long then = formatter.parse(dateStr, pos).getTime();
long now = new Date().getTime();
long seconds = (now - then)/1000;
long minutes = seconds/60;
long hours = minutes/60;
long days = hours/24;
String friendly = null;
long num = 0;
if (days > 0) {
num = days;
friendly = days + " day";
} else if (hours > 0) {
num = hours;
friendly = hours + " hour";
} else if (minutes > 0) {
num = minutes;
friendly = minutes + " minute";
} else {
num = seconds;
friendly = seconds + " second";
}
if (num > 1) {
friendly += "s";
}
String[] chunks = new String[] {
"<div class=\"timestamp\">",
friendly,
" ago",
"</div>"
};
append(chunks);
}
/**
* Returns the available actions for the post.
*
* @param post
* @return
*/
private HashSet<String> getActions(JSONObject post) {
HashSet<String> actionsSet = new HashSet<String>();
JSONArray actions = post.optJSONArray("actions");
if (actions != null) {
for (int j = 0; j < actions.length(); j++) {
JSONObject action = actions.optJSONObject(j);
String actionName = action.optString("name");
actionsSet.add(actionName);
}
}
return actionsSet;
}
/**
* Renders the 'x people like this' text,
*
* @param post
*/
private void renderLikes(JSONObject post) {
int numLikes = post.optInt("likes", 0);
if (numLikes > 0) {
String desc = numLikes == 1 ?
"person likes this" :
"people like this";
String[] chunks = new String[] {
"<div class=\"like_icon\">",
"<img src=\"file:///android_asset/like_icon.png\"/>",
"</div>",
"<div class=\"num_likes\">",
new Integer(numLikes).toString(),
" ",
desc,
"</div>"
};
append(chunks);
}
}
/**
* Renders the post's comments.
*
* @param post
* @throws JSONException
*/
private void renderComments(JSONObject post) throws JSONException {
append("<div class=\"comments\" id=\"comments" + post.optString("id") + "\">");
JSONObject comments = post.optJSONObject("comments");
if (comments != null) {
JSONArray data = comments.optJSONArray("data");
for (int j = 0; j < data.length(); j++) {
JSONObject comment = data.getJSONObject(j);
renderComment(comment);
}
}
append("</div>");
}
/**
* Renders an individual comment.
*
* @param comment
*/
private void renderComment(JSONObject comment) {
JSONObject from = comment.optJSONObject("from");
String authorId = from.optString("id");
String authorName = from.optString("name");
String message = comment.optString("message");
append("<div class=\"comment\">");
renderAuthor(authorId, authorName);
String[] chunks = {
" ",
message,
"</div>"
};
append(chunks);
}
/**
* Renders the new comment input box.
*
* @param post
*/
private void renderCommentBox(JSONObject post) {
String id = post.optString("id");
String[] chunks = new String[] {
"<div class=\"comment_box\" id=\"comment_box", id, "\">",
"<input id=\"comment_box_input", id, "\"/>",
"<button onclick=\"postComment('", id , "');\">Post</button>",
"<div class=\"clear\"></div>",
"</div>"
};
append(chunks);
}
private void append(String str) {
sb.append(str);
}
private void append(String[] chunks) {
for (String chunk : chunks) {
sb.append(chunk);
}
}
}
|
fix profile urls
|
examples/stream/src/com/facebook/stream/StreamRenderer.java
|
fix profile urls
|
<ide><path>xamples/stream/src/com/facebook/stream/StreamRenderer.java
<ide> }
<ide>
<ide> private String getProfileUrl(String id) {
<del> return "http://touch.facebook.com/profile.php?id=" + id;
<add> return "http://touch.facebook.com/#/profile.php?id=" + id;
<ide> }
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
8b04d4ce2c37c26b2b4b663283125a5dd9a3cd7a
| 0 |
pferraro/undertow,jamezp/undertow,wildfly-security-incubator/undertow,rhusar/undertow,TomasHofman/undertow,nkhuyu/undertow,stuartwdouglas/undertow,n1hility/undertow,msfm/undertow,darranl/undertow,amannm/undertow,jstourac/undertow,nkhuyu/undertow,grassjedi/undertow,golovnin/undertow,golovnin/undertow,soul2zimate/undertow,yonglehou/undertow,aradchykov/undertow,aradchykov/undertow,rogerchina/undertow,baranowb/undertow,darranl/undertow,aldaris/undertow,amannm/undertow,marschall/undertow,TomasHofman/undertow,jasonchaffee/undertow,pedroigor/undertow,popstr/undertow,ctomc/undertow,Karm/undertow,emag/codereading-undertow,soul2zimate/undertow,pferraro/undertow,Karm/undertow,jamezp/undertow,ctomc/undertow,ctomc/undertow,yonglehou/undertow,undertow-io/undertow,undertow-io/undertow,stuartwdouglas/undertow,grassjedi/undertow,aldaris/undertow,rogerchina/undertow,popstr/undertow,amannm/undertow,jasonchaffee/undertow,aldaris/undertow,biddyweb/undertow,biddyweb/undertow,rhatlapa/undertow,yonglehou/undertow,pedroigor/undertow,baranowb/undertow,rogerchina/undertow,jasonchaffee/undertow,soul2zimate/undertow,Karm/undertow,pferraro/undertow,pedroigor/undertow,marschall/undertow,baranowb/undertow,rhusar/undertow,grassjedi/undertow,darranl/undertow,n1hility/undertow,rhatlapa/undertow,undertow-io/undertow,aradchykov/undertow,TomasHofman/undertow,msfm/undertow,nkhuyu/undertow,golovnin/undertow,marschall/undertow,emag/codereading-undertow,wildfly-security-incubator/undertow,biddyweb/undertow,msfm/undertow,wildfly-security-incubator/undertow,jamezp/undertow,popstr/undertow,rhusar/undertow,jstourac/undertow,jstourac/undertow,rhatlapa/undertow,n1hility/undertow,stuartwdouglas/undertow
|
/*
* Copyright 2012 JBoss, by Red Hat, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.websockets.protocol.server;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpOpenListener;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.HttpTransferEncodingHandler;
import io.undertow.websockets.StreamSinkFrameChannel;
import io.undertow.websockets.StreamSourceFrameChannel;
import io.undertow.websockets.WebSocketChannel;
import io.undertow.websockets.WebSocketFrameType;
import io.undertow.websockets.handler.WebSocketConnectionCallback;
import io.undertow.websockets.handler.WebSocketProtocolHandshakeHandler;
import org.xnio.BufferAllocator;
import org.xnio.ByteBufferSlicePool;
import org.xnio.ChannelExceptionHandler;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.IoUtils;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.Pooled;
import org.xnio.Xnio;
import org.xnio.XnioWorker;
import org.xnio.channels.AcceptingChannel;
import org.xnio.channels.ConnectedStreamChannel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
/**
* @author <a href="mailto:[email protected]">Norman Maurer</a>
*/
public class AutobahnWebSocketServer {
private HttpOpenListener openListener;
private XnioWorker worker;
private AcceptingChannel<? extends ConnectedStreamChannel> server;
private Xnio xnio;
private final int port;
public AutobahnWebSocketServer(int port) {
this.port = port;
}
public void run() {
xnio = Xnio.getInstance("nio");
try {
worker = xnio.createWorker(OptionMap.builder()
.set(Options.WORKER_WRITE_THREADS, 4)
.set(Options.WORKER_READ_THREADS, 4)
.set(Options.CONNECTION_HIGH_WATER, 1000000)
.set(Options.CONNECTION_LOW_WATER, 1000000)
.set(Options.WORKER_TASK_CORE_THREADS, 10)
.set(Options.WORKER_TASK_MAX_THREADS, 12)
.set(Options.TCP_NODELAY, true)
.set(Options.CORK, true)
.getMap());
OptionMap serverOptions = OptionMap.builder()
.set(Options.WORKER_ACCEPT_THREADS, 4)
.set(Options.TCP_NODELAY, true)
.set(Options.REUSE_ADDRESSES, true)
.getMap();
openListener = new HttpOpenListener(new ByteBufferSlicePool(BufferAllocator.DIRECT_BYTE_BUFFER_ALLOCATOR, 8192, 8192 * 8192));
ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
server = worker.createStreamServer(new InetSocketAddress(port), acceptListener, serverOptions);
setRootHandler(new WebSocketProtocolHandshakeHandler("/", new WebSocketConnectionCallback() {
@Override
public void onConnect(final HttpServerExchange exchange, final WebSocketChannel channel) {
channel.getReceiveSetter().set(new Receiver());
channel.resumeReceives();
}
}));
server.resumeAccepts();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private final class Receiver implements ChannelListener<WebSocketChannel> {
@Override
public void handleEvent(final WebSocketChannel channel) {
try {
final StreamSourceFrameChannel ws = channel.receive();
if (ws == null) {
return;
}
final WebSocketFrameType type;
if (ws.getType() == WebSocketFrameType.PING) {
// if a ping is send the autobahn testsuite expects a PONG when echo back
type = WebSocketFrameType.PONG;
} else {
type = ws.getType();
}
long size = ws.getPayloadSize();
final StreamSinkFrameChannel sink = channel.send(type, size);
sink.setFinalFragment(ws.isFinalFragment());
sink.setRsv(ws.getRsv());
ChannelListeners.initiateTransfer(Long.MAX_VALUE, ws, sink, new ChannelListener<StreamSourceFrameChannel>() {
@Override
public void handleEvent(StreamSourceFrameChannel streamSourceFrameChannel) {
IoUtils.safeClose(streamSourceFrameChannel);
}
}, new ChannelListener<StreamSinkFrameChannel>() {
@Override
public void handleEvent(StreamSinkFrameChannel streamSinkFrameChannel) {
try {
streamSinkFrameChannel.shutdownWrites();
} catch (IOException e) {
e.printStackTrace();
IoUtils.safeClose(streamSinkFrameChannel, channel);
return;
}
streamSinkFrameChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener(
new ChannelListener<StreamSinkFrameChannel>() {
@Override
public void handleEvent(StreamSinkFrameChannel streamSinkFrameChannel) {
streamSinkFrameChannel.getWriteSetter().set(null);
IoUtils.safeClose(streamSinkFrameChannel);
if (type == WebSocketFrameType.CLOSE) {
IoUtils.safeClose(channel);
}
}
}, new ChannelExceptionHandler<StreamSinkFrameChannel>() {
@Override
public void handleException(StreamSinkFrameChannel o, IOException e) {
e.printStackTrace();
}
}));
}
}, new ChannelExceptionHandler<StreamSourceFrameChannel>() {
@Override
public void handleException(StreamSourceFrameChannel streamSourceFrameChannel, IOException e) {
e.printStackTrace();
IoUtils.safeClose(streamSourceFrameChannel, channel);
}
}, new ChannelExceptionHandler<StreamSinkFrameChannel>() {
@Override
public void handleException(StreamSinkFrameChannel streamSinkFrameChannel, IOException e) {
e.printStackTrace();
IoUtils.safeClose(streamSinkFrameChannel, channel);
}
}, channel.getBufferPool());
if (ws.getType() == WebSocketFrameType.PONG) {
IoUtils.safeClose(ws);
return;
}
} catch (IOException e) {
e.printStackTrace();
IoUtils.safeClose(channel);
}
}
}
/**
* Sets the root handler for the default web server
*
* @param rootHandler The handler to use
*/
private void setRootHandler(HttpHandler rootHandler) {
final HttpTransferEncodingHandler ph = new HttpTransferEncodingHandler();
ph.setNext(rootHandler);
openListener.setRootHandler(ph);
}
public static void main(String args[]) {
new AutobahnWebSocketServer(7777).run();
}
}
|
websockets/src/test/java/io/undertow/websockets/protocol/server/AutobahnWebSocketServer.java
|
/*
* Copyright 2012 JBoss, by Red Hat, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.websockets.protocol.server;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpOpenListener;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.HttpTransferEncodingHandler;
import io.undertow.websockets.StreamSinkFrameChannel;
import io.undertow.websockets.StreamSourceFrameChannel;
import io.undertow.websockets.WebSocketChannel;
import io.undertow.websockets.WebSocketFrameType;
import io.undertow.websockets.handler.WebSocketConnectionCallback;
import io.undertow.websockets.handler.WebSocketProtocolHandshakeHandler;
import org.xnio.BufferAllocator;
import org.xnio.Buffers;
import org.xnio.ByteBufferSlicePool;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.IoUtils;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.Xnio;
import org.xnio.XnioWorker;
import org.xnio.channels.AcceptingChannel;
import org.xnio.channels.ConnectedStreamChannel;
import org.xnio.channels.StreamSinkChannel;
import org.xnio.channels.StreamSourceChannel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
/**
* @author <a href="mailto:[email protected]">Norman Maurer</a>
*/
public class AutobahnWebSocketServer {
private HttpOpenListener openListener;
private XnioWorker worker;
private AcceptingChannel<? extends ConnectedStreamChannel> server;
private Xnio xnio;
private final int port;
public AutobahnWebSocketServer(int port) {
this.port = port;
}
public void run() {
xnio = Xnio.getInstance("nio");
try {
worker = xnio.createWorker(OptionMap.builder()
.set(Options.WORKER_WRITE_THREADS, 4)
.set(Options.WORKER_READ_THREADS, 4)
.set(Options.CONNECTION_HIGH_WATER, 1000000)
.set(Options.CONNECTION_LOW_WATER, 1000000)
.set(Options.WORKER_TASK_CORE_THREADS, 10)
.set(Options.WORKER_TASK_MAX_THREADS, 12)
.set(Options.TCP_NODELAY, true)
.set(Options.CORK, true)
.getMap());
OptionMap serverOptions = OptionMap.builder()
.set(Options.WORKER_ACCEPT_THREADS, 4)
.set(Options.TCP_NODELAY, true)
.set(Options.REUSE_ADDRESSES, true)
.getMap();
openListener = new HttpOpenListener(new ByteBufferSlicePool(BufferAllocator.DIRECT_BYTE_BUFFER_ALLOCATOR, 8192, 8192 * 8192));
ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
server = worker.createStreamServer(new InetSocketAddress(port), acceptListener, serverOptions);
setRootHandler(new WebSocketProtocolHandshakeHandler("/", new WebSocketConnectionCallback() {
@Override
public void onConnect(final HttpServerExchange exchange, final WebSocketChannel channel) {
channel.getReceiveSetter().set(new Receiver());
channel.resumeReceives();
}
}));
server.resumeAccepts();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private final class Receiver implements ChannelListener<WebSocketChannel> {
@Override
public void handleEvent(final WebSocketChannel channel) {
try {
final StreamSourceFrameChannel ws = channel.receive();
if (ws == null) {
return;
}
long size = ws.getPayloadSize();
if (size == -1) {
// Fix this
size = 128 * 1024;
}
final ByteBuffer buffer;
if (size == 0) {
buffer = Buffers.EMPTY_BYTE_BUFFER;
} else {
buffer = ByteBuffer.allocate((int) size);
}
for (;;) {
int r = ws.read(buffer);
if (r == 0) {
ws.getReadSetter().set(new ChannelListener<StreamSourceChannel>() {
@Override
public void handleEvent(StreamSourceChannel ch) {
try {
for (;;) {
int r = ch.read(buffer);
if (r == 0) {
return;
} else if (r == -1) {
break;
}
}
write(channel, (StreamSourceFrameChannel) ch, buffer);
} catch (IOException e) {
e.printStackTrace();
IoUtils.safeClose(ch);
IoUtils.safeClose(channel);
}
}
});
return;
} else if (r == -1) {
break;
}
}
if (ws.getType() == WebSocketFrameType.PONG) {
IoUtils.safeClose(ws);
return;
}
write(channel, ws, buffer);
} catch (IOException e) {
e.printStackTrace();
IoUtils.safeClose(channel);
}
}
}
private void write(final WebSocketChannel channel, final StreamSourceFrameChannel source, final ByteBuffer buffer) throws IOException {
buffer.flip();
final WebSocketFrameType type;
if (source.getType() == WebSocketFrameType.PING) {
// if a ping is send the autobahn testsuite expects a PONG when echo back
type = WebSocketFrameType.PONG;
} else {
type = source.getType();
}
StreamSinkFrameChannel sink = channel.send(type, buffer.remaining());
sink.setFinalFragment(source.isFinalFragment());
sink.setRsv(source.getRsv());
source.close();
while(buffer.hasRemaining()) {
if (sink.write(buffer) == 0) {
sink.getWriteSetter().set(new ChannelListener<StreamSinkFrameChannel>() {
@Override
public void handleEvent(StreamSinkFrameChannel ch) {
try {
while(buffer.hasRemaining()) {
if (ch.write(buffer) == 0) {
return;
}
}
ch.shutdownWrites();
if (!ch.flush()) {
ch.getWriteSetter().set(ChannelListeners.flushingChannelListener(new ChannelListener<StreamSinkChannel>() {
@Override
public void handleEvent(final StreamSinkChannel ch) {
ch.getWriteSetter().set(null);
IoUtils.safeClose(ch, source);
if (type == WebSocketFrameType.CLOSE) {
IoUtils.safeClose(channel);
}
}
}, ChannelListeners.closingChannelExceptionHandler()));
ch.resumeWrites();
} else {
ch.getWriteSetter().set(null);
IoUtils.safeClose(ch, source);
if (type == WebSocketFrameType.CLOSE) {
IoUtils.safeClose(channel);
}
}
} catch (IOException e) {
e.printStackTrace();
ch.getWriteSetter().set(null);
IoUtils.safeClose(ch, channel, source);
}
}
});
sink.resumeWrites();
return;
}
}
sink.shutdownWrites();
if (!sink.flush()) {
sink.getWriteSetter().set(ChannelListeners.flushingChannelListener(new ChannelListener<StreamSinkChannel>() {
@Override
public void handleEvent(final StreamSinkChannel ch) {
ch.getWriteSetter().set(null);
IoUtils.safeClose(ch, source);
if (type == WebSocketFrameType.CLOSE) {
IoUtils.safeClose(channel);
}
}
}, ChannelListeners.closingChannelExceptionHandler()));
sink.resumeWrites();
} else {
IoUtils.safeClose(sink, source);
if (type == WebSocketFrameType.CLOSE) {
IoUtils.safeClose(channel);
}
}
}
/**
* Sets the root handler for the default web server
*
* @param rootHandler The handler to use
*/
private void setRootHandler(HttpHandler rootHandler) {
final HttpTransferEncodingHandler ph = new HttpTransferEncodingHandler();
ph.setNext(rootHandler);
openListener.setRootHandler(ph);
}
public static void main(String args[]) {
new AutobahnWebSocketServer(7777).run();
}
}
|
Use transfer for the autobahn tests
|
websockets/src/test/java/io/undertow/websockets/protocol/server/AutobahnWebSocketServer.java
|
Use transfer for the autobahn tests
|
<ide><path>ebsockets/src/test/java/io/undertow/websockets/protocol/server/AutobahnWebSocketServer.java
<ide> import io.undertow.websockets.handler.WebSocketConnectionCallback;
<ide> import io.undertow.websockets.handler.WebSocketProtocolHandshakeHandler;
<ide> import org.xnio.BufferAllocator;
<del>import org.xnio.Buffers;
<ide> import org.xnio.ByteBufferSlicePool;
<add>import org.xnio.ChannelExceptionHandler;
<ide> import org.xnio.ChannelListener;
<ide> import org.xnio.ChannelListeners;
<ide> import org.xnio.IoUtils;
<ide> import org.xnio.OptionMap;
<ide> import org.xnio.Options;
<add>import org.xnio.Pooled;
<ide> import org.xnio.Xnio;
<ide> import org.xnio.XnioWorker;
<ide> import org.xnio.channels.AcceptingChannel;
<ide> import org.xnio.channels.ConnectedStreamChannel;
<del>import org.xnio.channels.StreamSinkChannel;
<del>import org.xnio.channels.StreamSourceChannel;
<ide>
<ide> import java.io.IOException;
<ide> import java.net.InetSocketAddress;
<ide> return;
<ide> }
<ide>
<add> final WebSocketFrameType type;
<add> if (ws.getType() == WebSocketFrameType.PING) {
<add> // if a ping is send the autobahn testsuite expects a PONG when echo back
<add> type = WebSocketFrameType.PONG;
<add> } else {
<add> type = ws.getType();
<add> }
<ide> long size = ws.getPayloadSize();
<del> if (size == -1) {
<del> // Fix this
<del> size = 128 * 1024;
<del> }
<ide>
<del> final ByteBuffer buffer;
<del> if (size == 0) {
<del> buffer = Buffers.EMPTY_BYTE_BUFFER;
<del> } else {
<del> buffer = ByteBuffer.allocate((int) size);
<del> }
<del> for (;;) {
<del> int r = ws.read(buffer);
<del> if (r == 0) {
<del> ws.getReadSetter().set(new ChannelListener<StreamSourceChannel>() {
<add> final StreamSinkFrameChannel sink = channel.send(type, size);
<add> sink.setFinalFragment(ws.isFinalFragment());
<add> sink.setRsv(ws.getRsv());
<add> ChannelListeners.initiateTransfer(Long.MAX_VALUE, ws, sink, new ChannelListener<StreamSourceFrameChannel>() {
<ide> @Override
<del> public void handleEvent(StreamSourceChannel ch) {
<del> try {
<del> for (;;) {
<del> int r = ch.read(buffer);
<del> if (r == 0) {
<del> return;
<del> } else if (r == -1) {
<del> break;
<add> public void handleEvent(StreamSourceFrameChannel streamSourceFrameChannel) {
<add> IoUtils.safeClose(streamSourceFrameChannel);
<add> }
<add> }, new ChannelListener<StreamSinkFrameChannel>() {
<add> @Override
<add> public void handleEvent(StreamSinkFrameChannel streamSinkFrameChannel) {
<add> try {
<add> streamSinkFrameChannel.shutdownWrites();
<add> } catch (IOException e) {
<add> e.printStackTrace();
<add> IoUtils.safeClose(streamSinkFrameChannel, channel);
<add> return;
<add> }
<add>
<add> streamSinkFrameChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener(
<add> new ChannelListener<StreamSinkFrameChannel>() {
<add> @Override
<add> public void handleEvent(StreamSinkFrameChannel streamSinkFrameChannel) {
<add> streamSinkFrameChannel.getWriteSetter().set(null);
<add> IoUtils.safeClose(streamSinkFrameChannel);
<add> if (type == WebSocketFrameType.CLOSE) {
<add> IoUtils.safeClose(channel);
<ide> }
<ide> }
<del> write(channel, (StreamSourceFrameChannel) ch, buffer);
<del> } catch (IOException e) {
<del> e.printStackTrace();
<del> IoUtils.safeClose(ch);
<del> IoUtils.safeClose(channel);
<del> }
<add> }, new ChannelExceptionHandler<StreamSinkFrameChannel>() {
<add> @Override
<add> public void handleException(StreamSinkFrameChannel o, IOException e) {
<add> e.printStackTrace();
<add> }
<add> }));
<add> }
<add> }, new ChannelExceptionHandler<StreamSourceFrameChannel>() {
<add> @Override
<add> public void handleException(StreamSourceFrameChannel streamSourceFrameChannel, IOException e) {
<add> e.printStackTrace();
<add> IoUtils.safeClose(streamSourceFrameChannel, channel);
<add> }
<add> }, new ChannelExceptionHandler<StreamSinkFrameChannel>() {
<add> @Override
<add> public void handleException(StreamSinkFrameChannel streamSinkFrameChannel, IOException e) {
<add> e.printStackTrace();
<ide>
<add> IoUtils.safeClose(streamSinkFrameChannel, channel);
<ide> }
<del> });
<del> return;
<del> } else if (r == -1) {
<del> break;
<del> }
<del> }
<add> }, channel.getBufferPool());
<ide> if (ws.getType() == WebSocketFrameType.PONG) {
<ide> IoUtils.safeClose(ws);
<ide> return;
<ide> }
<del> write(channel, ws, buffer);
<ide> } catch (IOException e) {
<ide> e.printStackTrace();
<ide> IoUtils.safeClose(channel);
<ide> }
<ide> }
<del> }
<del>
<del> private void write(final WebSocketChannel channel, final StreamSourceFrameChannel source, final ByteBuffer buffer) throws IOException {
<del> buffer.flip();
<del> final WebSocketFrameType type;
<del> if (source.getType() == WebSocketFrameType.PING) {
<del> // if a ping is send the autobahn testsuite expects a PONG when echo back
<del> type = WebSocketFrameType.PONG;
<del> } else {
<del> type = source.getType();
<del> }
<del> StreamSinkFrameChannel sink = channel.send(type, buffer.remaining());
<del> sink.setFinalFragment(source.isFinalFragment());
<del> sink.setRsv(source.getRsv());
<del> source.close();
<del>
<del> while(buffer.hasRemaining()) {
<del> if (sink.write(buffer) == 0) {
<del> sink.getWriteSetter().set(new ChannelListener<StreamSinkFrameChannel>() {
<del> @Override
<del> public void handleEvent(StreamSinkFrameChannel ch) {
<del> try {
<del> while(buffer.hasRemaining()) {
<del> if (ch.write(buffer) == 0) {
<del> return;
<del> }
<del> }
<del> ch.shutdownWrites();
<del> if (!ch.flush()) {
<del> ch.getWriteSetter().set(ChannelListeners.flushingChannelListener(new ChannelListener<StreamSinkChannel>() {
<del> @Override
<del> public void handleEvent(final StreamSinkChannel ch) {
<del> ch.getWriteSetter().set(null);
<del>
<del> IoUtils.safeClose(ch, source);
<del> if (type == WebSocketFrameType.CLOSE) {
<del> IoUtils.safeClose(channel);
<del> }
<del> }
<del> }, ChannelListeners.closingChannelExceptionHandler()));
<del> ch.resumeWrites();
<del> } else {
<del> ch.getWriteSetter().set(null);
<del> IoUtils.safeClose(ch, source);
<del>
<del> if (type == WebSocketFrameType.CLOSE) {
<del> IoUtils.safeClose(channel);
<del> }
<del>
<del> }
<del> } catch (IOException e) {
<del> e.printStackTrace();
<del> ch.getWriteSetter().set(null);
<del> IoUtils.safeClose(ch, channel, source);
<del>
<del> }
<del> }
<del> });
<del> sink.resumeWrites();
<del> return;
<del> }
<del> }
<del> sink.shutdownWrites();
<del> if (!sink.flush()) {
<del> sink.getWriteSetter().set(ChannelListeners.flushingChannelListener(new ChannelListener<StreamSinkChannel>() {
<del> @Override
<del> public void handleEvent(final StreamSinkChannel ch) {
<del> ch.getWriteSetter().set(null);
<del> IoUtils.safeClose(ch, source);
<del> if (type == WebSocketFrameType.CLOSE) {
<del> IoUtils.safeClose(channel);
<del> }
<del> }
<del> }, ChannelListeners.closingChannelExceptionHandler()));
<del> sink.resumeWrites();
<del> } else {
<del> IoUtils.safeClose(sink, source);
<del> if (type == WebSocketFrameType.CLOSE) {
<del> IoUtils.safeClose(channel);
<del> }
<del> }
<del>
<ide> }
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
5ddf0278883a9c0587441c831383cd31784ce53e
| 0 |
pwoodworth/intellij-community,izonder/intellij-community,amith01994/intellij-community,petteyg/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,blademainer/intellij-community,da1z/intellij-community,vladmm/intellij-community,hurricup/intellij-community,samthor/intellij-community,da1z/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,da1z/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,allotria/intellij-community,ryano144/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,clumsy/intellij-community,xfournet/intellij-community,blademainer/intellij-community,petteyg/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,nicolargo/intellij-community,supersven/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,signed/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,petteyg/intellij-community,da1z/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,samthor/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,caot/intellij-community,apixandru/intellij-community,supersven/intellij-community,apixandru/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,amith01994/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,izonder/intellij-community,kool79/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,retomerz/intellij-community,asedunov/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,slisson/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,supersven/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,ibinti/intellij-community,semonte/intellij-community,retomerz/intellij-community,da1z/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,samthor/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,da1z/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,fnouama/intellij-community,kool79/intellij-community,holmes/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,holmes/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,jagguli/intellij-community,retomerz/intellij-community,dslomov/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,da1z/intellij-community,izonder/intellij-community,signed/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,amith01994/intellij-community,petteyg/intellij-community,fitermay/intellij-community,fnouama/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,caot/intellij-community,youdonghai/intellij-community,allotria/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,fitermay/intellij-community,allotria/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,holmes/intellij-community,izonder/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,fitermay/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,signed/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,nicolargo/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,caot/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,caot/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,allotria/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,retomerz/intellij-community,signed/intellij-community,Distrotech/intellij-community,signed/intellij-community,semonte/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,caot/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,kool79/intellij-community,apixandru/intellij-community,diorcety/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,diorcety/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,amith01994/intellij-community,signed/intellij-community,ol-loginov/intellij-community,caot/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,izonder/intellij-community,ahb0327/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,supersven/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,supersven/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,asedunov/intellij-community,hurricup/intellij-community,dslomov/intellij-community,asedunov/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,dslomov/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,blademainer/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,kdwink/intellij-community,asedunov/intellij-community,semonte/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,kool79/intellij-community,izonder/intellij-community,kdwink/intellij-community,asedunov/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,vladmm/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,izonder/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,adedayo/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,amith01994/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,FHannes/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,izonder/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,asedunov/intellij-community,slisson/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,slisson/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,kdwink/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,kdwink/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,caot/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,fitermay/intellij-community,ryano144/intellij-community,signed/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,izonder/intellij-community,ryano144/intellij-community,fitermay/intellij-community,fitermay/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,izonder/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,xfournet/intellij-community,jagguli/intellij-community,dslomov/intellij-community,ryano144/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,ibinti/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,signed/intellij-community,petteyg/intellij-community,xfournet/intellij-community,samthor/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,fnouama/intellij-community,kdwink/intellij-community,holmes/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,semonte/intellij-community,fitermay/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,kool79/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,da1z/intellij-community,suncycheng/intellij-community,semonte/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,retomerz/intellij-community,slisson/intellij-community,holmes/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,semonte/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,signed/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ibinti/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,samthor/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,holmes/intellij-community,holmes/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,allotria/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,fitermay/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,signed/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,allotria/intellij-community,signed/intellij-community,dslomov/intellij-community,youdonghai/intellij-community
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.table.TableView;
import com.intellij.util.SmartList;
import com.intellij.util.ui.EditableModel;
import com.intellij.util.ui.ElementProducer;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.util.*;
import java.util.List;
/**
* @author Konstantin Bulenkov
*
* @see #createDecorator(javax.swing.JList)
* @see #createDecorator(javax.swing.JTable)
* @see #createDecorator(javax.swing.JTree)
*/
@SuppressWarnings("UnusedDeclaration")
public abstract class ToolbarDecorator implements CommonActionsPanel.ListenerFactory {
protected Border myPanelBorder;
protected Border myToolbarBorder;
protected boolean myAddActionEnabled;
protected boolean myEditActionEnabled;
protected boolean myRemoveActionEnabled;
protected boolean myUpActionEnabled;
protected boolean myDownActionEnabled;
protected Border myActionsPanelBorder;
private final List<AnActionButton> myExtraActions = new SmartList<AnActionButton>();
private ActionToolbarPosition myToolbarPosition;
protected AnActionButtonRunnable myAddAction;
protected AnActionButtonRunnable myEditAction;
protected AnActionButtonRunnable myRemoveAction;
protected AnActionButtonRunnable myUpAction;
protected AnActionButtonRunnable myDownAction;
private String myAddName;
private String myEditName;
private String myRemoveName;
private String myMoveUpName;
private String myMoveDownName;
private AnActionButtonUpdater myAddActionUpdater = null;
private AnActionButtonUpdater myRemoveActionUpdater = null;
private AnActionButtonUpdater myEditActionUpdater = null;
private AnActionButtonUpdater myMoveUpActionUpdater = null;
private AnActionButtonUpdater myMoveDownActionUpdater = null;
private Dimension myPreferredSize;
private CommonActionsPanel myActionsPanel;
private Comparator<AnActionButton> myButtonComparator;
private boolean myAsUsualTopToolbar = false;
private Icon myAddIcon;
private boolean myForcedDnD = false;
protected abstract JComponent getComponent();
protected abstract void updateButtons();
protected void updateExtraElementActions(boolean someElementSelected) {
for (AnActionButton action : myExtraActions) {
if (action instanceof ElementActionButton) {
action.setEnabled(someElementSelected);
}
}
}
public final CommonActionsPanel getActionsPanel() {
return myActionsPanel;
}
public ToolbarDecorator initPosition() {
setToolbarPosition(SystemInfo.isMac ? ActionToolbarPosition.BOTTOM : ActionToolbarPosition.RIGHT);
return this;
}
public ToolbarDecorator setAsUsualTopToolbar() {
myAsUsualTopToolbar = true;
setToolbarPosition(ActionToolbarPosition.TOP);
return this;
}
public static ToolbarDecorator createDecorator(@NotNull JTable table) {
return new TableToolbarDecorator(table, null).initPosition();
}
public static ToolbarDecorator createDecorator(@NotNull JTree tree) {
return createDecorator(tree, null);
}
private static ToolbarDecorator createDecorator(@NotNull JTree tree, @Nullable ElementProducer<?> producer) {
return new TreeToolbarDecorator(tree, producer).initPosition();
}
public static ToolbarDecorator createDecorator(@NotNull JList list) {
return new ListToolbarDecorator(list, null).initPosition();
}
public static ToolbarDecorator createDecorator(@NotNull JList list, EditableModel editableModel) {
return new ListToolbarDecorator(list, editableModel).initPosition();
}
public static <T> ToolbarDecorator createDecorator(@NotNull TableView<T> table, @Nullable ElementProducer<T> producer) {
return new TableToolbarDecorator(table, producer).initPosition();
}
public ToolbarDecorator disableAddAction() {
myAddActionEnabled = false;
return this;
}
public ToolbarDecorator disableRemoveAction() {
myRemoveActionEnabled = false;
return this;
}
public ToolbarDecorator disableUpAction() {
myUpActionEnabled = false;
return this;
}
public ToolbarDecorator disableUpDownActions() {
myUpActionEnabled = false;
myDownActionEnabled = false;
return this;
}
public ToolbarDecorator disableDownAction() {
myDownActionEnabled = false;
return this;
}
public ToolbarDecorator setPanelBorder(Border border) {
myPanelBorder = border;
return this;
}
public ToolbarDecorator setToolbarBorder(Border border) {
myActionsPanelBorder = border;
return this;
}
public ToolbarDecorator setButtonComparator(Comparator<AnActionButton> buttonComparator) {
myButtonComparator = buttonComparator;
return this;
}
public ToolbarDecorator setButtonComparator(String...actionNames) {
final List<String> names = Arrays.asList(actionNames);
myButtonComparator = new Comparator<AnActionButton>() {
@Override
public int compare(AnActionButton o1, AnActionButton o2) {
final String t1 = o1.getTemplatePresentation().getText();
final String t2 = o2.getTemplatePresentation().getText();
if (t1 == null || t2 == null) return 0;
final int ind1 = names.indexOf(t1);
final int ind2 = names.indexOf(t2);
if (ind1 == -1 && ind2 >= 0) return 1;
if (ind2 == -1 && ind1 >= 0) return -1;
return ind1 - ind2;
}
};
return this;
}
public ToolbarDecorator setLineBorder(int top, int left, int bottom, int right) {
return setToolbarBorder(new CustomLineBorder(top, left, bottom, right));
}
public ToolbarDecorator addExtraAction(AnActionButton action) {
myExtraActions.add(action);
return this;
}
public ToolbarDecorator setToolbarPosition(ActionToolbarPosition position) {
myToolbarPosition = position;
myActionsPanelBorder = new CustomLineBorder(myToolbarPosition == ActionToolbarPosition.BOTTOM ? 1 : 0,
myToolbarPosition == ActionToolbarPosition.RIGHT ? 1 : 0,
myToolbarPosition == ActionToolbarPosition.TOP ? 1 : 0,
myToolbarPosition == ActionToolbarPosition.LEFT ? 1 : 0);
return this;
}
public ToolbarDecorator setAddAction(AnActionButtonRunnable action) {
myAddActionEnabled = action != null;
myAddAction = action;
return this;
}
public ToolbarDecorator setEditAction(AnActionButtonRunnable action) {
myEditActionEnabled = action != null;
myEditAction = action;
return this;
}
public ToolbarDecorator setRemoveAction(AnActionButtonRunnable action) {
myRemoveActionEnabled = action != null;
myRemoveAction = action;
return this;
}
public ToolbarDecorator setMoveUpAction(AnActionButtonRunnable action) {
myUpActionEnabled = action != null;
myUpAction = action;
return this;
}
public ToolbarDecorator setMoveDownAction(AnActionButtonRunnable action) {
myDownActionEnabled = action != null;
myDownAction = action;
return this;
}
public ToolbarDecorator setAddActionName(String name) {
myAddName = name;
return this;
}
public ToolbarDecorator setEditActionName(String name) {
myEditName = name;
return this;
}
public ToolbarDecorator setRemoveActionName(String name) {
myRemoveName = name;
return this;
}
public ToolbarDecorator setMoveUpActionName(String name) {
myMoveUpName = name;
return this;
}
public ToolbarDecorator setMoveDownActionName(String name) {
myMoveDownName = name;
return this;
}
public ToolbarDecorator setAddActionUpdater(AnActionButtonUpdater updater) {
myAddActionUpdater = updater;
return this;
}
public ToolbarDecorator setRemoveActionUpdater(AnActionButtonUpdater updater) {
myRemoveActionUpdater = updater;
return this;
}
public ToolbarDecorator setEditActionUpdater(AnActionButtonUpdater updater) {
myEditActionUpdater = updater;
return this;
}
public ToolbarDecorator setMoveUpActionUpdater(AnActionButtonUpdater updater) {
myMoveUpActionUpdater = updater;
return this;
}
public ToolbarDecorator setMoveDownActionUpdater(AnActionButtonUpdater updater) {
myMoveDownActionUpdater = updater;
return this;
}
public ToolbarDecorator setForcedDnD() {
myForcedDnD = true;
return this;
}
public ToolbarDecorator setActionGroup(@NotNull ActionGroup actionGroup) {
AnAction[] actions = actionGroup.getChildren(null);
for (AnAction action : actions) {
if (!(action instanceof Separator)) {
addExtraAction(AnActionButton.fromAction(action));
}
}
return this;
}
public ToolbarDecorator setPreferredSize(Dimension size) {
myPreferredSize = size;
return this;
}
public ToolbarDecorator setVisibleRowCount(int rowCount) {
return this;//do nothing by default
}
public ToolbarDecorator setAddIcon(Icon addIcon) {
myAddIcon = addIcon;
return this;
}
/**
* @return panel that contains wrapped component (with added scrollpane) and toolbar panel.
*/
public JPanel createPanel() {
final CommonActionsPanel.Buttons[] buttons = getButtons();
final JComponent contextComponent = getComponent();
myActionsPanel = new CommonActionsPanel(this, contextComponent,
myToolbarPosition,
myExtraActions.toArray(new AnActionButton[myExtraActions.size()]),
myButtonComparator,
myAddName, myRemoveName, myMoveUpName, myMoveDownName, myEditName,
myAddIcon, buttons);
final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(contextComponent, true);
if (myPreferredSize != null) {
scrollPane.setPreferredSize(myPreferredSize);
}
final JPanel panel = new JPanel(new BorderLayout()) {
@Override
public void addNotify() {
super.addNotify();
updateButtons();
}
};
panel.add(scrollPane, BorderLayout.CENTER);
panel.add(myActionsPanel, getPlacement());
installUpdaters();
updateButtons();
installDnD();
panel.putClientProperty(ActionToolbar.ACTION_TOOLBAR_PROPERTY_KEY, myActionsPanel.getComponent(0));
Border mainBorder = myPanelBorder != null ? myPanelBorder : IdeBorderFactory.createBorder(SideBorder.ALL);
if (myAsUsualTopToolbar) {
scrollPane.setBorder(mainBorder);
} else {
myActionsPanel.setBorder(myActionsPanelBorder);
panel.setBorder(mainBorder);
}
return panel;
}
private void installUpdaters() {
if (myAddActionEnabled && myAddAction != null && myAddActionUpdater != null) {
myActionsPanel.getAnActionButton(CommonActionsPanel.Buttons.ADD).addCustomUpdater(myAddActionUpdater);
}
if (myEditActionEnabled && myEditAction != null && myEditActionUpdater != null) {
myActionsPanel.getAnActionButton(CommonActionsPanel.Buttons.EDIT).addCustomUpdater(myEditActionUpdater);
}
if (myRemoveActionEnabled && myRemoveAction != null && myRemoveActionUpdater != null) {
myActionsPanel.getAnActionButton(CommonActionsPanel.Buttons.REMOVE).addCustomUpdater(myRemoveActionUpdater);
}
if (myUpActionEnabled && myUpAction != null && myMoveUpActionUpdater != null) {
myActionsPanel.getAnActionButton(CommonActionsPanel.Buttons.UP).addCustomUpdater(myMoveUpActionUpdater);
}
if (myDownActionEnabled && myDownAction != null && myMoveDownActionUpdater != null) {
myActionsPanel.getAnActionButton(CommonActionsPanel.Buttons.DOWN).addCustomUpdater(myMoveDownActionUpdater);
}
}
protected void installDnD() {
if ((myForcedDnD || (myUpAction != null && myUpActionEnabled
&& myDownAction != null && myDownActionEnabled))
&& !ApplicationManager.getApplication().isHeadlessEnvironment()
&& isModelEditable()) {
installDnDSupport();
}
}
protected abstract void installDnDSupport();
protected abstract boolean isModelEditable();
private Object getPlacement() {
switch (myToolbarPosition) {
case TOP: return BorderLayout.NORTH;
case LEFT: return BorderLayout.WEST;
case BOTTOM: return BorderLayout.SOUTH;
case RIGHT: return BorderLayout.EAST;
}
return BorderLayout.SOUTH;
}
private CommonActionsPanel.Buttons[] getButtons() {
final ArrayList<CommonActionsPanel.Buttons> buttons = new ArrayList<CommonActionsPanel.Buttons>();
final HashMap<CommonActionsPanel.Buttons, Pair<Boolean, AnActionButtonRunnable>> map =
new HashMap<CommonActionsPanel.Buttons, Pair<Boolean, AnActionButtonRunnable>>();
map.put(CommonActionsPanel.Buttons.ADD, Pair.create(myAddActionEnabled, myAddAction));
map.put(CommonActionsPanel.Buttons.REMOVE, Pair.create(myRemoveActionEnabled, myRemoveAction));
map.put(CommonActionsPanel.Buttons.EDIT, Pair.create(myEditActionEnabled, myEditAction));
map.put(CommonActionsPanel.Buttons.UP, Pair.create(myUpActionEnabled, myUpAction));
map.put(CommonActionsPanel.Buttons.DOWN, Pair.create(myDownActionEnabled, myDownAction));
for (CommonActionsPanel.Buttons button : CommonActionsPanel.Buttons.values()) {
final Pair<Boolean, AnActionButtonRunnable> action = map.get(button);
if (action != null && action.first != null && action.first && action.second != null) {
buttons.add(button);
}
}
return buttons.toArray(new CommonActionsPanel.Buttons[buttons.size()]);
}
@Override
public CommonActionsPanel.Listener createListener(final CommonActionsPanel panel) {
return new CommonActionsPanel.Listener() {
@Override
public void doAdd() {
if (myAddAction != null) {
myAddAction.run(panel.getAnActionButton(CommonActionsPanel.Buttons.ADD));
}
}
@Override
public void doEdit() {
if (myEditAction != null) {
myEditAction.run(panel.getAnActionButton(CommonActionsPanel.Buttons.EDIT));
}
}
@Override
public void doRemove() {
if (myRemoveAction != null) {
myRemoveAction.run(panel.getAnActionButton(CommonActionsPanel.Buttons.REMOVE));
}
}
@Override
public void doUp() {
if (myUpAction != null) {
myUpAction.run(panel.getAnActionButton(CommonActionsPanel.Buttons.UP));
}
}
@Override
public void doDown() {
if (myDownAction != null) {
myDownAction.run(panel.getAnActionButton(CommonActionsPanel.Buttons.DOWN));
}
}
};
}
public static AnActionButton findAddButton(@NotNull JComponent container) {
return findButton(container, CommonActionsPanel.Buttons.ADD);
}
public static AnActionButton findEditButton(@NotNull JComponent container) {
return findButton(container, CommonActionsPanel.Buttons.EDIT);
}
public static AnActionButton findRemoveButton(@NotNull JComponent container) {
return findButton(container, CommonActionsPanel.Buttons.REMOVE);
}
public static AnActionButton findUpButton(@NotNull JComponent container) {
return findButton(container, CommonActionsPanel.Buttons.UP);
}
public static AnActionButton findDownButton(@NotNull JComponent container) {
return findButton(container, CommonActionsPanel.Buttons.DOWN);
}
private static AnActionButton findButton(JComponent comp, CommonActionsPanel.Buttons type) {
final CommonActionsPanel panel = UIUtil.findComponentOfType(comp, CommonActionsPanel.class);
if (panel != null) {
return panel.getAnActionButton(type);
}
//noinspection ConstantConditions
return null;
}
/**
* Marker interface, button will be disabled if no selected element
*/
public abstract static class ElementActionButton extends AnActionButton {
public ElementActionButton(String text, String description, @Nullable Icon icon) {
super(text, description, icon);
}
public ElementActionButton(String text, Icon icon) {
super(text, icon);
}
public ElementActionButton() {
}
public ElementActionButton(String text) {
super(text);
}
}
}
|
platform/platform-api/src/com/intellij/ui/ToolbarDecorator.java
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.actionSystem.ActionToolbarPosition;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.table.TableView;
import com.intellij.util.SmartList;
import com.intellij.util.ui.EditableModel;
import com.intellij.util.ui.ElementProducer;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.util.*;
import java.util.List;
/**
* @author Konstantin Bulenkov
*
* @see #createDecorator(javax.swing.JList)
* @see #createDecorator(javax.swing.JTable)
* @see #createDecorator(javax.swing.JTree)
*/
@SuppressWarnings("UnusedDeclaration")
public abstract class ToolbarDecorator implements CommonActionsPanel.ListenerFactory {
protected Border myPanelBorder;
protected Border myToolbarBorder;
protected boolean myAddActionEnabled;
protected boolean myEditActionEnabled;
protected boolean myRemoveActionEnabled;
protected boolean myUpActionEnabled;
protected boolean myDownActionEnabled;
protected Border myActionsPanelBorder;
private final List<AnActionButton> myExtraActions = new SmartList<AnActionButton>();
private ActionToolbarPosition myToolbarPosition;
protected AnActionButtonRunnable myAddAction;
protected AnActionButtonRunnable myEditAction;
protected AnActionButtonRunnable myRemoveAction;
protected AnActionButtonRunnable myUpAction;
protected AnActionButtonRunnable myDownAction;
private String myAddName;
private String myEditName;
private String myRemoveName;
private String myMoveUpName;
private String myMoveDownName;
private AnActionButtonUpdater myAddActionUpdater = null;
private AnActionButtonUpdater myRemoveActionUpdater = null;
private AnActionButtonUpdater myEditActionUpdater = null;
private AnActionButtonUpdater myMoveUpActionUpdater = null;
private AnActionButtonUpdater myMoveDownActionUpdater = null;
private Dimension myPreferredSize;
private CommonActionsPanel myActionsPanel;
private Comparator<AnActionButton> myButtonComparator;
private boolean myAsUsualTopToolbar = false;
private Icon myAddIcon;
private boolean myForcedDnD = false;
protected abstract JComponent getComponent();
protected abstract void updateButtons();
protected void updateExtraElementActions(boolean someElementSelected) {
for (AnActionButton action : myExtraActions) {
if (action instanceof ElementActionButton) {
action.setEnabled(someElementSelected);
}
}
}
public final CommonActionsPanel getActionsPanel() {
return myActionsPanel;
}
public ToolbarDecorator initPosition() {
setToolbarPosition(SystemInfo.isMac ? ActionToolbarPosition.BOTTOM : ActionToolbarPosition.RIGHT);
return this;
}
public ToolbarDecorator setAsUsualTopToolbar() {
myAsUsualTopToolbar = true;
setToolbarPosition(ActionToolbarPosition.TOP);
return this;
}
public static ToolbarDecorator createDecorator(@NotNull JTable table) {
return new TableToolbarDecorator(table, null).initPosition();
}
public static ToolbarDecorator createDecorator(@NotNull JTree tree) {
return createDecorator(tree, null);
}
private static ToolbarDecorator createDecorator(@NotNull JTree tree, @Nullable ElementProducer<?> producer) {
return new TreeToolbarDecorator(tree, producer).initPosition();
}
public static ToolbarDecorator createDecorator(@NotNull JList list) {
return new ListToolbarDecorator(list, null).initPosition();
}
public static ToolbarDecorator createDecorator(@NotNull JList list, EditableModel editableModel) {
return new ListToolbarDecorator(list, editableModel).initPosition();
}
public static <T> ToolbarDecorator createDecorator(@NotNull TableView<T> table, @Nullable ElementProducer<T> producer) {
return new TableToolbarDecorator(table, producer).initPosition();
}
public ToolbarDecorator disableAddAction() {
myAddActionEnabled = false;
return this;
}
public ToolbarDecorator disableRemoveAction() {
myRemoveActionEnabled = false;
return this;
}
public ToolbarDecorator disableUpAction() {
myUpActionEnabled = false;
return this;
}
public ToolbarDecorator disableUpDownActions() {
myUpActionEnabled = false;
myDownActionEnabled = false;
return this;
}
public ToolbarDecorator disableDownAction() {
myDownActionEnabled = false;
return this;
}
public ToolbarDecorator setPanelBorder(Border border) {
myPanelBorder = border;
return this;
}
public ToolbarDecorator setToolbarBorder(Border border) {
myActionsPanelBorder = border;
return this;
}
public ToolbarDecorator setButtonComparator(Comparator<AnActionButton> buttonComparator) {
myButtonComparator = buttonComparator;
return this;
}
public ToolbarDecorator setButtonComparator(String...actionNames) {
final List<String> names = Arrays.asList(actionNames);
myButtonComparator = new Comparator<AnActionButton>() {
@Override
public int compare(AnActionButton o1, AnActionButton o2) {
final String t1 = o1.getTemplatePresentation().getText();
final String t2 = o2.getTemplatePresentation().getText();
if (t1 == null || t2 == null) return 0;
final int ind1 = names.indexOf(t1);
final int ind2 = names.indexOf(t2);
if (ind1 == -1 && ind2 >= 0) return 1;
if (ind2 == -1 && ind1 >= 0) return -1;
return ind1 - ind2;
}
};
return this;
}
public ToolbarDecorator setLineBorder(int top, int left, int bottom, int right) {
return setToolbarBorder(new CustomLineBorder(top, left, bottom, right));
}
public ToolbarDecorator addExtraAction(AnActionButton action) {
myExtraActions.add(action);
return this;
}
public ToolbarDecorator setToolbarPosition(ActionToolbarPosition position) {
myToolbarPosition = position;
myActionsPanelBorder = new CustomLineBorder(myToolbarPosition == ActionToolbarPosition.BOTTOM ? 1 : 0,
myToolbarPosition == ActionToolbarPosition.RIGHT ? 1 : 0,
myToolbarPosition == ActionToolbarPosition.TOP ? 1 : 0,
myToolbarPosition == ActionToolbarPosition.LEFT ? 1 : 0);
return this;
}
public ToolbarDecorator setAddAction(AnActionButtonRunnable action) {
myAddActionEnabled = action != null;
myAddAction = action;
return this;
}
public ToolbarDecorator setEditAction(AnActionButtonRunnable action) {
myEditActionEnabled = action != null;
myEditAction = action;
return this;
}
public ToolbarDecorator setRemoveAction(AnActionButtonRunnable action) {
myRemoveActionEnabled = action != null;
myRemoveAction = action;
return this;
}
public ToolbarDecorator setMoveUpAction(AnActionButtonRunnable action) {
myUpActionEnabled = action != null;
myUpAction = action;
return this;
}
public ToolbarDecorator setMoveDownAction(AnActionButtonRunnable action) {
myDownActionEnabled = action != null;
myDownAction = action;
return this;
}
public ToolbarDecorator setAddActionName(String name) {
myAddName = name;
return this;
}
public ToolbarDecorator setEditActionName(String name) {
myEditName = name;
return this;
}
public ToolbarDecorator setRemoveActionName(String name) {
myRemoveName = name;
return this;
}
public ToolbarDecorator setMoveUpActionName(String name) {
myMoveUpName = name;
return this;
}
public ToolbarDecorator setMoveDownActionName(String name) {
myMoveDownName = name;
return this;
}
public ToolbarDecorator setAddActionUpdater(AnActionButtonUpdater updater) {
myAddActionUpdater = updater;
return this;
}
public ToolbarDecorator setRemoveActionUpdater(AnActionButtonUpdater updater) {
myRemoveActionUpdater = updater;
return this;
}
public ToolbarDecorator setEditActionUpdater(AnActionButtonUpdater updater) {
myEditActionUpdater = updater;
return this;
}
public ToolbarDecorator setMoveUpActionUpdater(AnActionButtonUpdater updater) {
myMoveUpActionUpdater = updater;
return this;
}
public ToolbarDecorator setMoveDownActionUpdater(AnActionButtonUpdater updater) {
myMoveDownActionUpdater = updater;
return this;
}
public ToolbarDecorator setForcedDnD() {
myForcedDnD = true;
return this;
}
public ToolbarDecorator setActionGroup(@NotNull ActionGroup actionGroup) {
AnAction[] actions = actionGroup.getChildren(null);
for (AnAction action : actions) {
addExtraAction(AnActionButton.fromAction(action));
}
return this;
}
public ToolbarDecorator setPreferredSize(Dimension size) {
myPreferredSize = size;
return this;
}
public ToolbarDecorator setVisibleRowCount(int rowCount) {
return this;//do nothing by default
}
public ToolbarDecorator setAddIcon(Icon addIcon) {
myAddIcon = addIcon;
return this;
}
/**
* @return panel that contains wrapped component (with added scrollpane) and toolbar panel.
*/
public JPanel createPanel() {
final CommonActionsPanel.Buttons[] buttons = getButtons();
final JComponent contextComponent = getComponent();
myActionsPanel = new CommonActionsPanel(this, contextComponent,
myToolbarPosition,
myExtraActions.toArray(new AnActionButton[myExtraActions.size()]),
myButtonComparator,
myAddName, myRemoveName, myMoveUpName, myMoveDownName, myEditName,
myAddIcon, buttons);
final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(contextComponent, true);
if (myPreferredSize != null) {
scrollPane.setPreferredSize(myPreferredSize);
}
final JPanel panel = new JPanel(new BorderLayout()) {
@Override
public void addNotify() {
super.addNotify();
updateButtons();
}
};
panel.add(scrollPane, BorderLayout.CENTER);
panel.add(myActionsPanel, getPlacement());
installUpdaters();
updateButtons();
installDnD();
panel.putClientProperty(ActionToolbar.ACTION_TOOLBAR_PROPERTY_KEY, myActionsPanel.getComponent(0));
Border mainBorder = myPanelBorder != null ? myPanelBorder : IdeBorderFactory.createBorder(SideBorder.ALL);
if (myAsUsualTopToolbar) {
scrollPane.setBorder(mainBorder);
} else {
myActionsPanel.setBorder(myActionsPanelBorder);
panel.setBorder(mainBorder);
}
return panel;
}
private void installUpdaters() {
if (myAddActionEnabled && myAddAction != null && myAddActionUpdater != null) {
myActionsPanel.getAnActionButton(CommonActionsPanel.Buttons.ADD).addCustomUpdater(myAddActionUpdater);
}
if (myEditActionEnabled && myEditAction != null && myEditActionUpdater != null) {
myActionsPanel.getAnActionButton(CommonActionsPanel.Buttons.EDIT).addCustomUpdater(myEditActionUpdater);
}
if (myRemoveActionEnabled && myRemoveAction != null && myRemoveActionUpdater != null) {
myActionsPanel.getAnActionButton(CommonActionsPanel.Buttons.REMOVE).addCustomUpdater(myRemoveActionUpdater);
}
if (myUpActionEnabled && myUpAction != null && myMoveUpActionUpdater != null) {
myActionsPanel.getAnActionButton(CommonActionsPanel.Buttons.UP).addCustomUpdater(myMoveUpActionUpdater);
}
if (myDownActionEnabled && myDownAction != null && myMoveDownActionUpdater != null) {
myActionsPanel.getAnActionButton(CommonActionsPanel.Buttons.DOWN).addCustomUpdater(myMoveDownActionUpdater);
}
}
protected void installDnD() {
if ((myForcedDnD || (myUpAction != null && myUpActionEnabled
&& myDownAction != null && myDownActionEnabled))
&& !ApplicationManager.getApplication().isHeadlessEnvironment()
&& isModelEditable()) {
installDnDSupport();
}
}
protected abstract void installDnDSupport();
protected abstract boolean isModelEditable();
private Object getPlacement() {
switch (myToolbarPosition) {
case TOP: return BorderLayout.NORTH;
case LEFT: return BorderLayout.WEST;
case BOTTOM: return BorderLayout.SOUTH;
case RIGHT: return BorderLayout.EAST;
}
return BorderLayout.SOUTH;
}
private CommonActionsPanel.Buttons[] getButtons() {
final ArrayList<CommonActionsPanel.Buttons> buttons = new ArrayList<CommonActionsPanel.Buttons>();
final HashMap<CommonActionsPanel.Buttons, Pair<Boolean, AnActionButtonRunnable>> map =
new HashMap<CommonActionsPanel.Buttons, Pair<Boolean, AnActionButtonRunnable>>();
map.put(CommonActionsPanel.Buttons.ADD, Pair.create(myAddActionEnabled, myAddAction));
map.put(CommonActionsPanel.Buttons.REMOVE, Pair.create(myRemoveActionEnabled, myRemoveAction));
map.put(CommonActionsPanel.Buttons.EDIT, Pair.create(myEditActionEnabled, myEditAction));
map.put(CommonActionsPanel.Buttons.UP, Pair.create(myUpActionEnabled, myUpAction));
map.put(CommonActionsPanel.Buttons.DOWN, Pair.create(myDownActionEnabled, myDownAction));
for (CommonActionsPanel.Buttons button : CommonActionsPanel.Buttons.values()) {
final Pair<Boolean, AnActionButtonRunnable> action = map.get(button);
if (action != null && action.first != null && action.first && action.second != null) {
buttons.add(button);
}
}
return buttons.toArray(new CommonActionsPanel.Buttons[buttons.size()]);
}
@Override
public CommonActionsPanel.Listener createListener(final CommonActionsPanel panel) {
return new CommonActionsPanel.Listener() {
@Override
public void doAdd() {
if (myAddAction != null) {
myAddAction.run(panel.getAnActionButton(CommonActionsPanel.Buttons.ADD));
}
}
@Override
public void doEdit() {
if (myEditAction != null) {
myEditAction.run(panel.getAnActionButton(CommonActionsPanel.Buttons.EDIT));
}
}
@Override
public void doRemove() {
if (myRemoveAction != null) {
myRemoveAction.run(panel.getAnActionButton(CommonActionsPanel.Buttons.REMOVE));
}
}
@Override
public void doUp() {
if (myUpAction != null) {
myUpAction.run(panel.getAnActionButton(CommonActionsPanel.Buttons.UP));
}
}
@Override
public void doDown() {
if (myDownAction != null) {
myDownAction.run(panel.getAnActionButton(CommonActionsPanel.Buttons.DOWN));
}
}
};
}
public static AnActionButton findAddButton(@NotNull JComponent container) {
return findButton(container, CommonActionsPanel.Buttons.ADD);
}
public static AnActionButton findEditButton(@NotNull JComponent container) {
return findButton(container, CommonActionsPanel.Buttons.EDIT);
}
public static AnActionButton findRemoveButton(@NotNull JComponent container) {
return findButton(container, CommonActionsPanel.Buttons.REMOVE);
}
public static AnActionButton findUpButton(@NotNull JComponent container) {
return findButton(container, CommonActionsPanel.Buttons.UP);
}
public static AnActionButton findDownButton(@NotNull JComponent container) {
return findButton(container, CommonActionsPanel.Buttons.DOWN);
}
private static AnActionButton findButton(JComponent comp, CommonActionsPanel.Buttons type) {
final CommonActionsPanel panel = UIUtil.findComponentOfType(comp, CommonActionsPanel.class);
if (panel != null) {
return panel.getAnActionButton(type);
}
//noinspection ConstantConditions
return null;
}
/**
* Marker interface, button will be disabled if no selected element
*/
public abstract static class ElementActionButton extends AnActionButton {
public ElementActionButton(String text, String description, @Nullable Icon icon) {
super(text, description, icon);
}
public ElementActionButton(String text, Icon icon) {
super(text, icon);
}
public ElementActionButton() {
}
public ElementActionButton(String text) {
super(text);
}
}
}
|
skip separators when adding actions from action group
|
platform/platform-api/src/com/intellij/ui/ToolbarDecorator.java
|
skip separators when adding actions from action group
|
<ide><path>latform/platform-api/src/com/intellij/ui/ToolbarDecorator.java
<ide> /*
<del> * Copyright 2000-2013 JetBrains s.r.o.
<add> * Copyright 2000-2014 JetBrains s.r.o.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> package com.intellij.ui;
<ide>
<del>import com.intellij.openapi.actionSystem.ActionGroup;
<del>import com.intellij.openapi.actionSystem.ActionToolbar;
<del>import com.intellij.openapi.actionSystem.ActionToolbarPosition;
<del>import com.intellij.openapi.actionSystem.AnAction;
<add>import com.intellij.openapi.actionSystem.*;
<ide> import com.intellij.openapi.application.ApplicationManager;
<ide> import com.intellij.openapi.util.Pair;
<ide> import com.intellij.openapi.util.SystemInfo;
<ide> public ToolbarDecorator setActionGroup(@NotNull ActionGroup actionGroup) {
<ide> AnAction[] actions = actionGroup.getChildren(null);
<ide> for (AnAction action : actions) {
<del> addExtraAction(AnActionButton.fromAction(action));
<add> if (!(action instanceof Separator)) {
<add> addExtraAction(AnActionButton.fromAction(action));
<add> }
<ide> }
<ide> return this;
<ide> }
|
|
Java
|
lgpl-2.1
|
9b5334885b74ae3472b2c419be0807b8f7b8f4bc
| 0 |
MenoData/Time4J
|
package net.time4j.i18n;
import net.time4j.Meridiem;
import net.time4j.Month;
import net.time4j.PlainDate;
import net.time4j.PlainTime;
import net.time4j.Quarter;
import net.time4j.Weekday;
import net.time4j.base.ResourceLoader;
import net.time4j.engine.AttributeQuery;
import net.time4j.engine.Chronology;
import net.time4j.format.Attributes;
import net.time4j.format.CalendarText;
import net.time4j.format.Leniency;
import net.time4j.format.OutputContext;
import net.time4j.format.TextProvider;
import net.time4j.format.TextWidth;
import net.time4j.format.expert.ChronoFormatter;
import net.time4j.format.expert.PatternType;
import net.time4j.history.HistoricEra;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Calendar;
import java.util.Locale;
import java.util.MissingResourceException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
@RunWith(JUnit4.class)
public class CalendricalNamesTest {
@Test
public void getInstance_Chronology_Locale() {
Chronology<PlainTime> chronology = Chronology.lookup(PlainTime.class);
Locale locale = Locale.GERMAN;
CalendarText expResult =
CalendarText.getInstance("iso8601", locale);
CalendarText result =
CalendarText.getInstance(chronology, locale);
assertThat(result, is(expResult));
}
@Test
public void getInstance_String_Locale() {
Locale locale = Locale.US;
CalendarText result = CalendarText.getInstance("iso8601", locale);
TextProvider p = null;
for (TextProvider tmp : ResourceLoader.getInstance().services(TextProvider.class)) {
if (
isCalendarTypeSupported(tmp, "iso8601")
&& isLocaleSupported(tmp, locale)
) {
p = tmp;
break;
}
}
if (p != null) {
assertThat(result.toString(), is(p.toString()));
}
result = CalendarText.getInstance("xyz", locale);
assertThat(result.toString(), is("FallbackProvider(xyz/en_US)"));
}
@Test
public void printMonthsDE() {
TextWidth textWidth = TextWidth.NARROW;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.GERMAN);
String result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.MARCH);
assertThat(result, is("M"));
textWidth = TextWidth.WIDE;
result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.MARCH);
assertThat(result, is("März"));
textWidth = TextWidth.WIDE;
result =
instance.getStdMonths(textWidth, OutputContext.STANDALONE)
.print(Month.MARCH);
assertThat(result, is("März"));
textWidth = TextWidth.SHORT;
result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.SEPTEMBER);
assertThat(result, is("Sept."));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.SEPTEMBER);
assertThat(result, is("Sept."));
}
@Test
public void printMonthsKAB() { // ISO-639-3
OutputContext oc = OutputContext.FORMAT;
TextWidth textWidth = TextWidth.WIDE;
CalendarText instance =
CalendarText.getInstance("iso8601", new Locale("kab"));
String result =
instance.getStdMonths(textWidth, oc).print(Month.JANUARY);
assertThat(result, is("Yennayer"));
}
@Test
public void printMonthsRU() {
OutputContext oc = OutputContext.FORMAT;
TextWidth textWidth = TextWidth.NARROW;
CalendarText instance =
CalendarText.getInstance("iso8601", new Locale("ru"));
String result =
instance.getStdMonths(textWidth, oc).print(Month.FEBRUARY);
assertThat(result, is("Ф"));
textWidth = TextWidth.WIDE;
result =
instance.getStdMonths(textWidth, oc)
.print(Month.MARCH);
assertThat(result, is("марта"));
textWidth = TextWidth.WIDE;
result =
instance.getStdMonths(textWidth, OutputContext.STANDALONE)
.print(Month.MARCH);
assertThat(result, is("март"));
}
@Test
public void printMonthsZH() {
TextWidth textWidth = TextWidth.NARROW;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.SIMPLIFIED_CHINESE);
String result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.MARCH);
assertThat(result, is("3"));
textWidth = TextWidth.WIDE;
result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.MARCH);
assertThat(result, is("三月"));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.MARCH);
assertThat(result, is("3月"));
}
@Test
public void parseMonths() {
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.GERMAN);
OutputContext outputContext = OutputContext.FORMAT;
ParsePosition status = new ParsePosition(0);
Month value =
instance.getStdMonths(TextWidth.ABBREVIATED, outputContext)
.parse("Sept.", status, Month.class);
assertThat(value, is(Month.SEPTEMBER));
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.WIDE, outputContext)
.parse("MÄR", status, Month.class, toAttributes(true, true));
assertThat(value, is(Month.MARCH));
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.WIDE, outputContext)
.parse("MÄRz", status, Month.class, toAttributes(true, false));
assertThat(value, is(Month.MARCH));
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.SHORT, outputContext)
.parse("MÄ", status, Month.class, toAttributes(true, true));
assertThat(value, is(Month.MARCH));
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.SHORT, outputContext)
.parse("Sept.", status, Month.class);
assertThat(value, is(Month.SEPTEMBER));
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.NARROW, outputContext)
.parse("m", status, Month.class, toAttributes(true, false));
assertThat(value, nullValue()); // ambivalent - March or May
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.NARROW, outputContext)
.parse("d", status, Month.class, toAttributes(true, false));
assertThat(value, is(Month.DECEMBER));
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.WIDE, outputContext)
.parse("ju", status, Month.class, toAttributes(true, true));
assertThat(value, nullValue()); // ambivalent - June or July
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.WIDE, outputContext)
.parse("jul", status, Month.class, toAttributes(true, true));
assertThat(value, is(Month.JULY));
Locale locale = Locale.JAPAN;
DateFormatSymbols dfs = DateFormatSymbols.getInstance(locale);
instance =
CalendarText.getInstance("iso8601", locale);
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.NARROW, outputContext)
.parse(
dfs.getShortMonths()[Calendar.MARCH],
status,
Month.class);
assertThat(value, is(Month.MARCH));
}
@Test
public void printQuartersEN() {
TextWidth textWidth = TextWidth.NARROW;
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.ENGLISH);
String result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q3);
assertThat(result, is("3"));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q3);
assertThat(result, is("Q3"));
textWidth = TextWidth.WIDE;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q3);
assertThat(result, is("3rd quarter"));
}
@Test
public void printQuartersDE() {
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.GERMAN);
TextWidth textWidth = TextWidth.NARROW;
String result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("1"));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("Q1"));
textWidth = TextWidth.WIDE;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("1. Quartal"));
}
@Test
public void printQuartersZH() {
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.SIMPLIFIED_CHINESE);
TextWidth textWidth = TextWidth.NARROW;
String result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("1"));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("1季度"));
textWidth = TextWidth.WIDE;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("第一季度"));
}
@Test
public void printQuartersAR() {
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", new Locale("ar"));
TextWidth textWidth = TextWidth.NARROW;
String result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q4);
assertThat(result, is("٤"));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("الربع الأول"));
textWidth = TextWidth.WIDE;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q2);
assertThat(result, is("الربع الثاني"));
}
@Test
public void printQuartersRU() {
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", new Locale("ru"));
TextWidth textWidth = TextWidth.ABBREVIATED;
String result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q4);
assertThat(result, is("4-й кв."));
textWidth = TextWidth.WIDE;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q2);
assertThat(result, is("2-й квартал"));
}
@Test
public void parseQuarters() {
TextWidth textWidth = TextWidth.SHORT;
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.GERMAN);
Quarter result =
instance.getQuarters(textWidth, outputContext)
.parse("Q3", new ParsePosition(0), Quarter.class);
assertThat(result, is(Quarter.Q3));
}
@Test
public void printWeekdaysEN() {
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.ENGLISH);
TextWidth textWidth;
String result;
textWidth = TextWidth.NARROW;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("F"));
textWidth = TextWidth.SHORT;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("Fr"));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("Fri"));
textWidth = TextWidth.WIDE;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("Friday"));
}
@Test
public void printWeekdaysES() {
TextWidth textWidth = TextWidth.WIDE;
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", new Locale("es"));
String result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.SATURDAY);
assertThat(result, is("sábado"));
textWidth = TextWidth.NARROW;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.SATURDAY);
assertThat(result, is("S"));
textWidth = TextWidth.WIDE;
outputContext = OutputContext.STANDALONE;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.SATURDAY);
assertThat(result, is("sábado"));
}
@Test
public void printWeekdaysZH() {
TextWidth textWidth = TextWidth.ABBREVIATED;
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.SIMPLIFIED_CHINESE);
String result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.SUNDAY);
assertThat(result, is("周日"));
}
@Test
public void printWeekdaysZH_TW() {
TextWidth textWidth = TextWidth.ABBREVIATED;
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.TRADITIONAL_CHINESE);
String result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.SUNDAY);
assertThat(result, is("週日"));
}
@Test
public void printWeekdaysDE() {
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.GERMAN);
TextWidth textWidth = TextWidth.NARROW;
String result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("F"));
textWidth = TextWidth.SHORT;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("Fr."));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("Fr."));
textWidth = TextWidth.WIDE;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("Freitag"));
}
@Test
public void parseCzechWithMultipleContextInSmartMode() throws ParseException {
ChronoFormatter<PlainDate> f =
ChronoFormatter.ofDatePattern("d. MMMM uuuu", PatternType.CLDR, new Locale("cs"));
PlainDate expected = PlainDate.of(2016, 1, 1);
assertThat(
f.parse("1. leden 2016"),
is(expected));
assertThat(
f.parse("1. ledna 2016"),
is(expected));
}
@Test(expected=ParseException.class)
public void parseCzechWithMultipleContextInStrictMode1() throws ParseException {
ChronoFormatter<PlainDate> f =
ChronoFormatter.ofDatePattern("d. MMMM uuuu", PatternType.CLDR, new Locale("cs")).with(Leniency.STRICT);
f.parse("1. leden 2016"); // standalone but parser expects embedded format mode (symbol M)
}
@Test(expected=ParseException.class)
public void parseCzechWithMultipleContextInStrictMode2() throws ParseException {
ChronoFormatter<PlainDate> f =
ChronoFormatter.ofDatePattern("d. LLLL uuuu", PatternType.CLDR, new Locale("cs")).with(Leniency.STRICT);
f.parse("1. ledna 2016"); // embedded format but parser expects standalone mode (symbol L)
}
@Test
public void parseWeekdays() {
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.GERMAN);
Weekday w =
instance.getWeekdays(TextWidth.WIDE, OutputContext.FORMAT)
.parse("FRE", new ParsePosition(0), Weekday.class, toAttributes(true, true));
assertThat(w, is(Weekday.FRIDAY));
instance = CalendarText.getInstance("iso8601", Locale.ENGLISH);
Weekday w2 =
instance.getWeekdays(TextWidth.WIDE, OutputContext.FORMAT)
.parse("FRI", new ParsePosition(0), Weekday.class, toAttributes(true, true));
assertThat(w2, is(Weekday.FRIDAY));
}
@Test
public void eras() throws ClassNotFoundException {
assertThat(
Chronology.lookup(PlainDate.class)
.getCalendarSystem()
.getEras()
.isEmpty(),
is(true));
TextWidth textWidth = TextWidth.WIDE;
CalendarText instance = CalendarText.getInstance("iso8601", Locale.GERMAN);
String result = instance.getEras(textWidth).print(HistoricEra.AD);
assertThat(result, is("n. Chr."));
}
@Test
public void printMeridiems() {
TextWidth textWidth = TextWidth.WIDE;
CalendarText instance = CalendarText.getInstance("iso8601", Locale.ENGLISH);
assertThat(instance.getMeridiems(textWidth, OutputContext.FORMAT).print(Meridiem.PM), is("pm"));
assertThat(instance.getMeridiems(textWidth, OutputContext.STANDALONE).print(Meridiem.PM), is("PM"));
}
@Test
public void parseMeridiems() {
TextWidth textWidth = TextWidth.WIDE;
CalendarText instance = CalendarText.getInstance("iso8601", Locale.ENGLISH);
Meridiem result1 =
instance.getMeridiems(textWidth, OutputContext.FORMAT).parse(
"pm", new ParsePosition(0), Meridiem.class, Leniency.STRICT);
assertThat(result1, is(Meridiem.PM));
Meridiem result2 =
instance.getMeridiems(textWidth, OutputContext.STANDALONE).parse(
"PM", new ParsePosition(0), Meridiem.class, Leniency.STRICT);
assertThat(result2, is(Meridiem.PM));
}
@Test
public void textFormsDelegate() {
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.ENGLISH);
assertThat(
instance.getTextForms(PlainTime.AM_PM_OF_DAY).print(Meridiem.PM),
is("PM"));
}
@Test(expected=MissingResourceException.class)
public void textFormsException() {
CalendarText instance =
CalendarText.getInstance("xyz", Locale.ENGLISH);
instance.getTextForms(PlainTime.AM_PM_OF_DAY);
}
@Test
public void printQuartersVietnam() {
TextWidth textWidth = TextWidth.WIDE;
OutputContext outputContext = OutputContext.STANDALONE;
CalendarText instance =
CalendarText.getInstance("iso8601", new Locale("vi"));
String result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.MONDAY);
// test for switching from standalone to format context
assertThat(result, is("Thứ Hai"));
}
private static boolean isCalendarTypeSupported(
TextProvider p,
String calendarType
) {
for (String c : p.getSupportedCalendarTypes()) {
if (c.equals(calendarType)) {
return true;
}
}
return false;
}
private static boolean isLocaleSupported(
TextProvider p,
Locale locale
) {
for (Locale l : p.getAvailableLocales()) {
String lang = locale.getLanguage();
String country = locale.getCountry();
if (
lang.equals(l.getLanguage())
&& (country.isEmpty() || country.equals(l.getCountry()))
) {
return true;
}
}
return false;
}
private static AttributeQuery toAttributes(
boolean caseInsensitive,
boolean partialCompare
) {
return new Attributes.Builder()
.set(Attributes.PARSE_CASE_INSENSITIVE, caseInsensitive)
.set(Attributes.PARSE_PARTIAL_COMPARE, partialCompare)
.build();
}
}
|
base/src/test/java/net/time4j/i18n/CalendricalNamesTest.java
|
package net.time4j.i18n;
import net.time4j.Meridiem;
import net.time4j.Month;
import net.time4j.PlainDate;
import net.time4j.PlainTime;
import net.time4j.Quarter;
import net.time4j.Weekday;
import net.time4j.base.ResourceLoader;
import net.time4j.engine.AttributeQuery;
import net.time4j.engine.Chronology;
import net.time4j.format.Attributes;
import net.time4j.format.CalendarText;
import net.time4j.format.Leniency;
import net.time4j.format.OutputContext;
import net.time4j.format.TextProvider;
import net.time4j.format.TextWidth;
import net.time4j.format.expert.ChronoFormatter;
import net.time4j.format.expert.PatternType;
import net.time4j.history.HistoricEra;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Calendar;
import java.util.Locale;
import java.util.MissingResourceException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
@RunWith(JUnit4.class)
public class CalendricalNamesTest {
@Test
public void getInstance_Chronology_Locale() {
Chronology<PlainTime> chronology = Chronology.lookup(PlainTime.class);
Locale locale = Locale.GERMAN;
CalendarText expResult =
CalendarText.getInstance("iso8601", locale);
CalendarText result =
CalendarText.getInstance(chronology, locale);
assertThat(result, is(expResult));
}
@Test
public void getInstance_String_Locale() {
Locale locale = Locale.US;
CalendarText result = CalendarText.getInstance("iso8601", locale);
TextProvider p = null;
for (TextProvider tmp : ResourceLoader.getInstance().services(TextProvider.class)) {
if (
isCalendarTypeSupported(tmp, "iso8601")
&& isLocaleSupported(tmp, locale)
) {
p = tmp;
break;
}
}
if (p != null) {
assertThat(result.toString(), is(p.toString()));
}
result = CalendarText.getInstance("xyz", locale);
assertThat(result.toString(), is("FallbackProvider(xyz/en_US)"));
}
@Test
public void printMonthsDE() {
TextWidth textWidth = TextWidth.NARROW;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.GERMAN);
String result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.MARCH);
assertThat(result, is("M"));
textWidth = TextWidth.WIDE;
result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.MARCH);
assertThat(result, is("März"));
textWidth = TextWidth.WIDE;
result =
instance.getStdMonths(textWidth, OutputContext.STANDALONE)
.print(Month.MARCH);
assertThat(result, is("März"));
textWidth = TextWidth.SHORT;
result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.SEPTEMBER);
assertThat(result, is("Sept."));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.SEPTEMBER);
assertThat(result, is("Sept."));
}
@Test
public void printMonthsKAB() { // ISO-639-3
OutputContext oc = OutputContext.FORMAT;
TextWidth textWidth = TextWidth.WIDE;
CalendarText instance =
CalendarText.getInstance("iso8601", new Locale("kab"));
String result =
instance.getStdMonths(textWidth, oc).print(Month.JANUARY);
assertThat(result, is("Yennayer"));
}
@Test
public void printMonthsRU() {
OutputContext oc = OutputContext.FORMAT;
TextWidth textWidth = TextWidth.NARROW;
CalendarText instance =
CalendarText.getInstance("iso8601", new Locale("ru"));
String result =
instance.getStdMonths(textWidth, oc).print(Month.FEBRUARY);
assertThat(result, is("Ф"));
textWidth = TextWidth.WIDE;
result =
instance.getStdMonths(textWidth, oc)
.print(Month.MARCH);
assertThat(result, is("марта"));
textWidth = TextWidth.WIDE;
result =
instance.getStdMonths(textWidth, OutputContext.STANDALONE)
.print(Month.MARCH);
assertThat(result, is("март"));
}
@Test
public void printMonthsZH() {
TextWidth textWidth = TextWidth.NARROW;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.SIMPLIFIED_CHINESE);
String result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.MARCH);
assertThat(result, is("3"));
textWidth = TextWidth.WIDE;
result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.MARCH);
assertThat(result, is("三月"));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getStdMonths(textWidth, OutputContext.FORMAT)
.print(Month.MARCH);
assertThat(result, is("3月"));
}
@Test
public void parseMonths() {
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.GERMAN);
OutputContext outputContext = OutputContext.FORMAT;
ParsePosition status = new ParsePosition(0);
Month value =
instance.getStdMonths(TextWidth.ABBREVIATED, outputContext)
.parse("Sept.", status, Month.class);
assertThat(value, is(Month.SEPTEMBER));
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.WIDE, outputContext)
.parse("MÄR", status, Month.class, toAttributes(true, true));
assertThat(value, is(Month.MARCH));
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.WIDE, outputContext)
.parse("MÄRz", status, Month.class, toAttributes(true, false));
assertThat(value, is(Month.MARCH));
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.SHORT, outputContext)
.parse("MÄ", status, Month.class, toAttributes(true, true));
assertThat(value, is(Month.MARCH));
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.SHORT, outputContext)
.parse("Sept.", status, Month.class);
assertThat(value, is(Month.SEPTEMBER));
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.NARROW, outputContext)
.parse("m", status, Month.class, toAttributes(true, false));
assertThat(value, nullValue()); // ambivalent - March or May
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.NARROW, outputContext)
.parse("d", status, Month.class, toAttributes(true, false));
assertThat(value, is(Month.DECEMBER));
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.WIDE, outputContext)
.parse("ju", status, Month.class, toAttributes(true, true));
assertThat(value, nullValue()); // ambivalent - June or July
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.WIDE, outputContext)
.parse("jul", status, Month.class, toAttributes(true, true));
assertThat(value, is(Month.JULY));
Locale locale = Locale.JAPAN;
DateFormatSymbols dfs = DateFormatSymbols.getInstance(locale);
instance =
CalendarText.getInstance("iso8601", locale);
status.setIndex(0);
value =
instance.getStdMonths(TextWidth.NARROW, outputContext)
.parse(
dfs.getShortMonths()[Calendar.MARCH],
status,
Month.class);
assertThat(value, is(Month.MARCH));
}
@Test
public void printQuartersEN() {
TextWidth textWidth = TextWidth.NARROW;
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.ENGLISH);
String result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q3);
assertThat(result, is("3"));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q3);
assertThat(result, is("Q3"));
textWidth = TextWidth.WIDE;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q3);
assertThat(result, is("3rd quarter"));
}
@Test
public void printQuartersDE() {
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.GERMAN);
TextWidth textWidth = TextWidth.NARROW;
String result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("1"));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("Q1"));
textWidth = TextWidth.WIDE;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("1. Quartal"));
}
@Test
public void printQuartersZH() {
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.SIMPLIFIED_CHINESE);
TextWidth textWidth = TextWidth.NARROW;
String result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("1"));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("1季度"));
textWidth = TextWidth.WIDE;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("第一季度"));
}
@Test
public void printQuartersAR() {
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", new Locale("ar"));
TextWidth textWidth = TextWidth.NARROW;
String result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q4);
assertThat(result, is("٤"));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q1);
assertThat(result, is("الربع الأول"));
textWidth = TextWidth.WIDE;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q2);
assertThat(result, is("الربع الثاني"));
}
@Test
public void printQuartersRU() {
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", new Locale("ru"));
TextWidth textWidth = TextWidth.ABBREVIATED;
String result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q4);
assertThat(result, is("4-й кв."));
textWidth = TextWidth.WIDE;
result =
instance.getQuarters(textWidth, outputContext)
.print(Quarter.Q2);
assertThat(result, is("2-й квартал"));
}
@Test
public void parseQuarters() {
TextWidth textWidth = TextWidth.SHORT;
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.GERMAN);
Quarter result =
instance.getQuarters(textWidth, outputContext)
.parse("Q3", new ParsePosition(0), Quarter.class);
assertThat(result, is(Quarter.Q3));
}
@Test
public void printWeekdaysEN() {
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.ENGLISH);
TextWidth textWidth;
String result;
textWidth = TextWidth.NARROW;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("F"));
textWidth = TextWidth.SHORT;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("Fr"));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("Fri"));
textWidth = TextWidth.WIDE;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("Friday"));
}
@Test
public void printWeekdaysES() {
TextWidth textWidth = TextWidth.WIDE;
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", new Locale("es"));
String result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.SATURDAY);
assertThat(result, is("sábado"));
textWidth = TextWidth.NARROW;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.SATURDAY);
assertThat(result, is("S"));
textWidth = TextWidth.WIDE;
outputContext = OutputContext.STANDALONE;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.SATURDAY);
assertThat(result, is("sábado"));
}
@Test
public void printWeekdaysZH() {
TextWidth textWidth = TextWidth.ABBREVIATED;
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.SIMPLIFIED_CHINESE);
String result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.SUNDAY);
assertThat(result, is("周日"));
}
@Test
public void printWeekdaysZH_TW() {
TextWidth textWidth = TextWidth.ABBREVIATED;
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.TRADITIONAL_CHINESE);
String result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.SUNDAY);
assertThat(result, is("週日"));
}
@Test
public void printWeekdaysDE() {
OutputContext outputContext = OutputContext.FORMAT;
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.GERMAN);
TextWidth textWidth = TextWidth.NARROW;
String result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("F"));
textWidth = TextWidth.SHORT;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("Fr."));
textWidth = TextWidth.ABBREVIATED;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("Fr."));
textWidth = TextWidth.WIDE;
result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.FRIDAY);
assertThat(result, is("Freitag"));
}
@Test
public void parseCzechWithMultipleContextInSmartMode() throws ParseException {
ChronoFormatter<PlainDate> f =
ChronoFormatter.ofDatePattern("d. MMMM uuuu", PatternType.CLDR, new Locale("cs"));
PlainDate expected = PlainDate.of(2016, 1, 1);
assertThat(
f.parse("1. leden 2016"),
is(expected));
assertThat(
f.parse("1. ledna 2016"),
is(expected));
}
@Test(expected=ParseException.class)
public void parseCzechWithMultipleContextInStrictMode1() throws ParseException {
ChronoFormatter<PlainDate> f =
ChronoFormatter.ofDatePattern("d. MMMM uuuu", PatternType.CLDR, new Locale("cs")).with(Leniency.STRICT);
f.parse("1. leden 2016"); // standalone but parser expects embedded format mode (symbol M)
}
@Test(expected=ParseException.class)
public void parseCzechWithMultipleContextInStrictMode2() throws ParseException {
ChronoFormatter<PlainDate> f =
ChronoFormatter.ofDatePattern("d. LLLL uuuu", PatternType.CLDR, new Locale("cs")).with(Leniency.STRICT);
f.parse("1. ledna 2016"); // embedded format but parser expects standalone mode (symbol L)
}
@Test
public void parseWeekdays() {
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.GERMAN);
Weekday w =
instance.getWeekdays(TextWidth.WIDE, OutputContext.FORMAT)
.parse("FRE", new ParsePosition(0), Weekday.class, toAttributes(true, true));
assertThat(w, is(Weekday.FRIDAY));
instance = CalendarText.getInstance("iso8601", Locale.ENGLISH);
Weekday w2 =
instance.getWeekdays(TextWidth.WIDE, OutputContext.FORMAT)
.parse("FRI", new ParsePosition(0), Weekday.class, toAttributes(true, true));
assertThat(w2, is(Weekday.FRIDAY));
}
@Test
public void eras() throws ClassNotFoundException {
assertThat(
Chronology.lookup(PlainDate.class)
.getCalendarSystem()
.getEras()
.isEmpty(),
is(true));
TextWidth textWidth = TextWidth.WIDE;
CalendarText instance = CalendarText.getInstance("iso8601", Locale.GERMAN);
String result = instance.getEras(textWidth).print(HistoricEra.AD);
assertThat(result, is("n. Chr."));
}
@Test
public void printMeridiems() {
TextWidth textWidth = TextWidth.WIDE;
CalendarText instance = CalendarText.getInstance("iso8601", Locale.ENGLISH);
assertThat(instance.getMeridiems(textWidth, OutputContext.FORMAT).print(Meridiem.PM), is("pm"));
assertThat(instance.getMeridiems(textWidth, OutputContext.STANDALONE).print(Meridiem.PM), is("PM"));
}
@Test
public void parseMeridiems() {
TextWidth textWidth = TextWidth.WIDE;
CalendarText instance = CalendarText.getInstance("iso8601", Locale.ENGLISH);
Meridiem result1 =
instance.getMeridiems(textWidth, OutputContext.FORMAT).parse(
"pm", new ParsePosition(0), Meridiem.class, Leniency.STRICT);
assertThat(result1, is(Meridiem.PM));
Meridiem result2 =
instance.getMeridiems(textWidth, OutputContext.STANDALONE).parse(
"PM", new ParsePosition(0), Meridiem.class, Leniency.STRICT);
assertThat(result2, is(Meridiem.PM));
}
@Test
public void textFormsDelegate() {
CalendarText instance =
CalendarText.getInstance("iso8601", Locale.ENGLISH);
assertThat(
instance.getTextForms(PlainTime.AM_PM_OF_DAY).print(Meridiem.PM),
is("PM"));
}
@Test(expected=MissingResourceException.class)
public void textFormsException() {
CalendarText instance =
CalendarText.getInstance("xyz", Locale.ENGLISH);
instance.getTextForms(PlainTime.AM_PM_OF_DAY);
}
@Test
public void printQuartersVietnam() {
TextWidth textWidth = TextWidth.WIDE;
OutputContext outputContext = OutputContext.STANDALONE;
CalendarText instance =
CalendarText.getInstance("iso8601", new Locale("vi"));
String result =
instance.getWeekdays(textWidth, outputContext)
.print(Weekday.MONDAY);
// test for switching from standalone to format context
assertThat(result, is("Thứ Hai"));
}
private static boolean isCalendarTypeSupported(
TextProvider p,
String calendarType
) {
for (String c : p.getSupportedCalendarTypes()) {
if (c.equals(calendarType)) {
return true;
}
}
return false;
}
private static boolean isLocaleSupported(
TextProvider p,
Locale locale
) {
for (Locale l : p.getAvailableLocales()) {
String lang = locale.getLanguage();
String country = locale.getCountry();
if (
lang.equals(l.getLanguage())
&& (country.isEmpty() || country.equals(l.getCountry()))
) {
return true;
}
}
return false;
}
private static AttributeQuery toAttributes(
boolean caseInsensitive,
boolean partialCompare
) {
return new Attributes.Builder()
.set(Attributes.PARSE_CASE_INSENSITIVE, caseInsensitive)
.set(Attributes.PARSE_PARTIAL_COMPARE, partialCompare)
.build();
}
}
|
code formatting
|
base/src/test/java/net/time4j/i18n/CalendricalNamesTest.java
|
code formatting
|
<ide><path>ase/src/test/java/net/time4j/i18n/CalendricalNamesTest.java
<ide> assertThat(result, is("Thứ Hai"));
<ide> }
<ide>
<del> private static boolean isCalendarTypeSupported(
<add> private static boolean isCalendarTypeSupported(
<ide> TextProvider p,
<ide> String calendarType
<ide> ) {
|
|
JavaScript
|
mit
|
71bcad15a79d3ade2b5c340e51d48fab33733d7d
| 0 |
infernojs/inferno,infernojs/inferno,trueadm/inferno,trueadm/inferno
|
import updateFragment from './updateFragment';
import fragmentValueTypes from '../enum/fragmentValueTypes';
import updateFragmentList from './updateFragmentList';
import clearEventListeners from '../../browser/events/clearEventListeners';
import addEventListener from '../../browser/events/addEventListener';
import events from '../../browser/events/shared/events';
import isSVG from '../../util/isSVG';
import { setAttribute } from '../../browser/template/DOMOperations';
//TODO updateFragmentValue and updateFragmentValues uses *similar* code, that could be
//refactored to by more DRY. although, this causes a significant performance cost
//on the v8 compiler. need to explore how to refactor without introducing this performance cost
export default function updateFragmentValues(context, oldFragment, fragment, component) {
let componentsToUpdate = [];
for (let i = 0, length = fragment.templateValues.length; i < length; i++) {
let element = oldFragment.templateElements[i];
let type = oldFragment.templateTypes[i];
fragment.templateElements[i] = element;
fragment.templateTypes[i] = type;
if (fragment.templateValues[i] !== oldFragment.templateValues[i]) {
switch (type) {
case fragmentValueTypes.LIST:
case fragmentValueTypes.LIST_REPLACE:
updateFragmentList(context, oldFragment.templateValues[i], fragment.templateValues[i], element, component);
break;
case fragmentValueTypes.TEXT:
element.firstChild.nodeValue = fragment.templateValues[i];
break;
case fragmentValueTypes.TEXT_DIRECT:
element.nodeValue = fragment.templateValues[i];
break;
case fragmentValueTypes.FRAGMENT:
case fragmentValueTypes.FRAGMENT_REPLACE:
updateFragment(context, oldFragment.templateValues[i], fragment.templateValues[i], element, component);
break;
case fragmentValueTypes.ATTR_CLASS:
if (isSVG) {
element.setAttribute('class', fragment.templateValues[i]);
} else {
element.className = fragment.templateValues[i];
}
break;
case fragmentValueTypes.ATTR_ID:
element.id = fragment.templateValues[i];
break;
case fragmentValueTypes.ATTR_VALUE:
element.value = fragment.templateValues[i];
break;
case fragmentValueTypes.ATTR_NAME:
element.name = fragment.templateValues[i];
break;
case fragmentValueTypes.ATTR_TYPE:
element.type = fragment.templateValues[i];
break;
case fragmentValueTypes.ATTR_LABEL:
element.label = fragment.templateValues[i];
break;
case fragmentValueTypes.ATTR_PLACEHOLDER:
element.placeholder = fragment.templateValues[i];
break;
case fragmentValueTypes.ATTR_WIDTH:
if (isSVG) {
element.setAttribute('width', fragment.templateValues[i]);
} else {
element.width = fragment.templateValues[i];
}
return;
case fragmentValueTypes.ATTR_HEIGHT:
if (isSVG) {
element.setAttribute('height', fragment.templateValues[i]);
} else {
element.height = fragment.templateValues[i];
}
return;
default:
//component prop, update it
if (element.props) {
element.props[type] = fragment.templateValues[i];
let alreadyInQueue = false;
for (let s = 0; s < componentsToUpdate.length; s++) {
if (componentsToUpdate[s] === element) {
alreadyInQueue = true;
}
}
if (alreadyInQueue === false) {
componentsToUpdate.push(element);
}
} else {
if (events[type] !== undefined) {
clearEventListeners(element, type);
addEventListener(element, type, fragment.templateValues[i]);
} else {
setAttribute(element, type, fragment.templateValues[i]);
}
}
}
}
}
if (componentsToUpdate.length > 0) {
for (let i = 0; i < componentsToUpdate.length; i++) {
componentsToUpdate[i].forceUpdate();
}
}
}
|
src/universal/core/updateFragmentValues.js
|
import updateFragment from './updateFragment';
import fragmentValueTypes from '../enum/fragmentValueTypes';
import updateFragmentList from './updateFragmentList';
import clearEventListeners from '../../browser/events/clearEventListeners';
import addEventListener from '../../browser/events/addEventListener';
import events from '../../browser/events/shared/events';
import isSVG from '../../util/isSVG';
import { setAttribute } from '../../browser/template/DOMOperations';
//TODO updateFragmentValue and updateFragmentValues uses *similar* code, that could be
//refactored to by more DRY. although, this causes a significant performance cost
//on the v8 compiler. need to explore how to refactor without introducing this performance cost
export default function updateFragmentValues(context, oldFragment, fragment, component) {
let componentsToUpdate = [];
for (let i = 0, length = fragment.templateValues.length; i < length; i++) {
let element = oldFragment.templateElements[i];
let type = oldFragment.templateTypes[i];
fragment.templateElements[i] = element;
fragment.templateTypes[i] = type;
if (fragment.templateValues[i] !== oldFragment.templateValues[i]) {
switch (type) {
case fragmentValueTypes.LIST:
case fragmentValueTypes.LIST_REPLACE:
updateFragmentList(context, oldFragment.templateValues[i], fragment.templateValues[i], element, component);
break;
case fragmentValueTypes.TEXT:
element.firstChild.nodeValue = fragment.templateValues[i];
break;
case fragmentValueTypes.TEXT_DIRECT:
element.nodeValue = fragment.templateValues[i];
break;
case fragmentValueTypes.FRAGMENT:
case fragmentValueTypes.FRAGMENT_REPLACE:
updateFragment(context, oldFragment.templateValues[i], fragment.templateValues[i], element, component);
break;
case fragmentValueTypes.ATTR_CLASS:
if (isSVG) {
element.setAttribute('class', fragment.templateValues[i]);
} else {
element.className = fragment.templateValues[i];
}
return;
case fragmentValueTypes.ATTR_ID:
element.id = fragment.templateValues[i];
return;
case fragmentValueTypes.ATTR_VALUE:
element.value = fragment.templateValues[i];
return;
case fragmentValueTypes.ATTR_NAME:
element.name = fragment.templateValues[i];
return;
case fragmentValueTypes.ATTR_TYPE:
element.type = fragment.templateValues[i];
return;
case fragmentValueTypes.ATTR_LABEL:
element.label = fragment.templateValues[i];
return;
case fragmentValueTypes.ATTR_PLACEHOLDER:
element.placeholder = fragment.templateValues[i];
return;
case fragmentValueTypes.ATTR_WIDTH:
if (isSVG) {
element.setAttribute('width', fragment.templateValues[i]);
} else {
element.width = fragment.templateValues[i];
}
return;
case fragmentValueTypes.ATTR_HEIGHT:
if (isSVG) {
element.setAttribute('height', fragment.templateValues[i]);
} else {
element.height = fragment.templateValues[i];
}
return;
default:
//component prop, update it
if (element.props) {
element.props[type] = fragment.templateValues[i];
let alreadyInQueue = false;
for (let s = 0; s < componentsToUpdate.length; s++) {
if (componentsToUpdate[s] === element) {
alreadyInQueue = true;
}
}
if (alreadyInQueue === false) {
componentsToUpdate.push(element);
}
} else {
if (events[type] !== undefined) {
clearEventListeners(element, type);
addEventListener(element, type, fragment.templateValues[i]);
} else {
setAttribute(element, type, fragment.templateValues[i]);
}
}
}
}
}
if (componentsToUpdate.length > 0) {
for (let i = 0; i < componentsToUpdate.length; i++) {
componentsToUpdate[i].forceUpdate();
}
}
}
|
more changes
|
src/universal/core/updateFragmentValues.js
|
more changes
|
<ide><path>rc/universal/core/updateFragmentValues.js
<ide> } else {
<ide> element.className = fragment.templateValues[i];
<ide> }
<del> return;
<add> break;
<ide> case fragmentValueTypes.ATTR_ID:
<ide> element.id = fragment.templateValues[i];
<del> return;
<add> break;
<ide> case fragmentValueTypes.ATTR_VALUE:
<ide> element.value = fragment.templateValues[i];
<del> return;
<add> break;
<ide> case fragmentValueTypes.ATTR_NAME:
<ide> element.name = fragment.templateValues[i];
<del> return;
<add> break;
<ide> case fragmentValueTypes.ATTR_TYPE:
<ide> element.type = fragment.templateValues[i];
<del> return;
<add> break;
<ide> case fragmentValueTypes.ATTR_LABEL:
<ide> element.label = fragment.templateValues[i];
<del> return;
<add> break;
<ide> case fragmentValueTypes.ATTR_PLACEHOLDER:
<ide> element.placeholder = fragment.templateValues[i];
<del> return;
<add> break;
<ide> case fragmentValueTypes.ATTR_WIDTH:
<ide> if (isSVG) {
<ide> element.setAttribute('width', fragment.templateValues[i]);
|
|
Java
|
mit
|
error: pathspec 'src/sim/components/queue/DepartureFlowStatistics.java' did not match any file(s) known to git
|
7959f3860a823708080f5ec4d3d26c5cdf87e781
| 1 |
easobral/simulator,easobral/simulator
|
package sim.components.queue;
import java.io.IOException;
import java.io.OutputStream;
import sim.components.basic.DepartureListener;
import sim.components.basic.Job;
import sim.components.basic.Node;
import sim.timer.Timer;
public class DepartureFlowStatistics implements DepartureListener {
OutputStream out;
Double last_arrival = 0D;
Node node;
public DepartureFlowStatistics(Node node, OutputStream out) {
this.node = node;
node.addDepartureListener(this);
this.out=out;
}
@Override
public void onDeparture(Job job) {
Double time = Timer.now();
Double interval = time - last_arrival;
String line = "" + time + " " + interval;
last_arrival = time;
try {
out.write(line.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
src/sim/components/queue/DepartureFlowStatistics.java
|
criado e feito o sistema de estatísticas de saída
|
src/sim/components/queue/DepartureFlowStatistics.java
|
criado e feito o sistema de estatísticas de saída
|
<ide><path>rc/sim/components/queue/DepartureFlowStatistics.java
<add>package sim.components.queue;
<add>
<add>import java.io.IOException;
<add>import java.io.OutputStream;
<add>
<add>import sim.components.basic.DepartureListener;
<add>import sim.components.basic.Job;
<add>import sim.components.basic.Node;
<add>import sim.timer.Timer;
<add>
<add>public class DepartureFlowStatistics implements DepartureListener {
<add> OutputStream out;
<add> Double last_arrival = 0D;
<add> Node node;
<add>
<add> public DepartureFlowStatistics(Node node, OutputStream out) {
<add> this.node = node;
<add> node.addDepartureListener(this);
<add> this.out=out;
<add> }
<add>
<add> @Override
<add> public void onDeparture(Job job) {
<add> Double time = Timer.now();
<add> Double interval = time - last_arrival;
<add> String line = "" + time + " " + interval;
<add> last_arrival = time;
<add> try {
<add> out.write(line.getBytes());
<add> } catch (IOException e) {
<add> // TODO Auto-generated catch block
<add> e.printStackTrace();
<add> }
<add> }
<add>}
|
|
Java
|
mit
|
832a1c4bc8b73a1d742ed817c766eeaa18af6b11
| 0 |
chenichadowitz/intelligent-chess-engine
|
import java.util.*;
public abstract class Board {
protected boolean playersTurn = true; // whiteturn if true
public boolean getTurn(){ return playersTurn;}
protected ArrayList<Piece> pieces = new ArrayList<Piece>();
public ArrayList<Piece> getPieces(){ return pieces;}
protected LinkedList<Piece>[][] boardState = (LinkedList<Piece>[][])new LinkedList[8][8];
public boolean[] statusOfSquare(int[] square){
boolean[] squareStatus = {false,true};
//possible returns are:
//true,true = occupied by white piece
//true,false = occupied by black piece
//false,true = unoccupied on board
//false,false = unoccupied off board
if(square[0] < 0 || square[1] < 0 || square[0] > 7 || square[1] > 7){
squareStatus[1] = false;
return squareStatus;
}
else{
for(int searcher = 0; searcher < pieces.size(); searcher ++){
if (pieces.get(searcher).getPosition() == square){
squareStatus[0] = true;
squareStatus[1] = pieces.get(searcher).getColor();
return squareStatus;
}
}
}
return squareStatus;
}
public void switchTurn(){playersTurn = !playersTurn;}
public void update(int[] square){
//fill in code
}
public void display(){
//cheni's code
}
public void takePiece(Piece taken){
for(Integer[] square: taken.getMoves()){
//fill in code
}
}
abstract boolean movePiece(Piece movingPiece, int[] square);
}
|
src/Board.java
|
import java.util.*;
public abstract class Board {
protected boolean playersTurn = true; // whiteturn if true
public boolean getTurn(){ return playersTurn;}
protected ArrayList<Piece> pieces = new ArrayList<Piece>();
public ArrayList<Piece> getPieces(){ return pieces;}
protected LinkedList<Piece>[][] boardState = (LinkedList<Piece>[][])new LinkedList[8][8];
public boolean[] statusOfSquare(int[] square){
boolean[] squareStatus = {false,true};
//possible returns are:
//true,true = occupied by white piece
//true,false = occupied by black piece
//false,true = unoccupied on board
//false,false = unoccupied off board
if(square[0] < 0 || square[1] < 0 || square[0] > 7 || square[1] > 7){
squareStatus[1] = false;
return squareStatus;
}
else{
for(int searcher = 0; searcher < pieces.size(); searcher ++){
if (pieces.get(searcher).getPosition() == square){
squareStatus[0] = true;
squareStatus[1] = pieces.get(searcher).getColor();
return squareStatus;
}
}
}
return squareStatus;
}
public void switchTurn(){playersTurn = !playersTurn;}
public void update(int[] square){
//fill in code
}
public void display(){
//cheni's code
}
abstract boolean movePiece(Piece movingPiece, int[] square);
}
|
began implementing boardState
|
src/Board.java
|
began implementing boardState
|
<ide><path>rc/Board.java
<ide> public void display(){
<ide> //cheni's code
<ide> }
<add> public void takePiece(Piece taken){
<add> for(Integer[] square: taken.getMoves()){
<add> //fill in code
<add> }
<add> }
<ide>
<ide> abstract boolean movePiece(Piece movingPiece, int[] square);
<ide> }
|
|
Java
|
apache-2.0
|
7da310d0d1f6ed2ae81ade212024f7385cf555c2
| 0 |
DenverM80/ds3_java_sdk,SpectraLogic/ds3_java_sdk,SpectraLogic/ds3_java_sdk,rpmoore/ds3_java_sdk,SpectraLogic/ds3_java_sdk,DenverM80/ds3_java_sdk,RachelTucker/ds3_java_sdk,RachelTucker/ds3_java_sdk,RachelTucker/ds3_java_sdk,rpmoore/ds3_java_sdk,DenverM80/ds3_java_sdk,SpectraLogic/ds3_java_sdk,rpmoore/ds3_java_sdk,rpmoore/ds3_java_sdk,RachelTucker/ds3_java_sdk,DenverM80/ds3_java_sdk
|
/*
* ******************************************************************************
* Copyright 2014-2015 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
package com.spectralogic.ds3client;
import com.spectralogic.ds3client.commands.*;
import com.spectralogic.ds3client.commands.notifications.*;
import com.spectralogic.ds3client.models.bulk.Node;
import com.spectralogic.ds3client.networking.ConnectionDetails;
import java.io.Closeable;
import java.io.IOException;
import java.security.SignatureException;
/**
* The main interface for communicating with a DS3 appliance. All communication with a DS3 appliance starts with
* this class.
*
* See {@link Ds3ClientBuilder} on what options can be used to create a Ds3Client instance.
*/
public interface Ds3Client extends Closeable {
ConnectionDetails getConnectionDetails();
/**
* Gets the list of buckets.
* @param request The Service Request object used to customize the HTTP request, {@link com.spectralogic.ds3client.commands.GetServiceRequest}
* @return The response object contains the list of buckets that the user has access to.
* @throws IOException
* @throws SignatureException
*/
GetServiceResponse getService(GetServiceRequest request)
throws IOException, SignatureException;
/**
* Gets the list of objects in a bucket.
* @param request The Get Bucket Request object used to customize the HTTP request. The bucket request object has
* several options for customizing the request. See {@link com.spectralogic.ds3client.commands.GetBucketRequest} for the full list of options
* that can be configured.
* @return The response object contains the list of objects that a bucket contains. There is some additional
* information that is returned which is used for pagination, {@link GetBucketResponse} for the full
* list of properties
* that are returned.
* @throws IOException
* @throws SignatureException
*/
GetBucketResponse getBucket(GetBucketRequest request)
throws IOException, SignatureException;
/**
* Puts a new bucket to a DS3 endpoint
* @param request The Put Bucket Request object used to customize the HTTP request. The put bucket request object
* has some options for customizing the request. See {@link PutBucketRequest} for the full list of
* options that can be configured.
* @return The response object is returned primarily to be consistent with the rest of the API. Additional data
* may be returned here in the future but nothing is currently. See {@link PutBucketResponse} for the most
* up to date information on what is returned.
* @throws IOException
* @throws SignatureException
*/
PutBucketResponse putBucket(PutBucketRequest request)
throws IOException, SignatureException;
/**
* Performs a HTTP HEAD for a bucket. The HEAD will return information about if the bucket exists, or if the user
* has access to that bucket.
* @param request The Head Bucket Request object used to customize the HTTP request. See {@link HeadBucketRequest}.
* @return The response object is returned and contains the status of the bucket. See {@link HeadBucketResponse} for
* the full list of status that a bucket can be in.
* @throws IOException
* @throws SignatureException
*/
HeadBucketResponse headBucket(HeadBucketRequest request)
throws IOException, SignatureException;
/**
* Deletes a bucket from a DS3 endpoint. <b>Note:</b> all objects must be deleted first before deleteBucket will
* succeed.
* @param request The Delete Bucket Request object used to customize the HTTP request. The delete bucket request object
* has some options for customizing the request. See {@link DeleteBucketRequest} for the full list of
* options that can be configured.
* @return The response object is returned primarily to be consistent with the rest of the API. Additional data
* may be returned here in the future but nothing is currently. See {@link com.spectralogic.ds3client.commands.DeleteBucketResponse} for the most
* up to date information on what is returned.
* @throws IOException
* @throws SignatureException
*/
DeleteBucketResponse deleteBucket(
DeleteBucketRequest request) throws IOException, SignatureException;
/**
* Recursively deletes the specified folder from a DS3 endpoint.
* @param request The Delete Folder Request object used to customize the HTTP request. The put bucket request object
* has some options for customizing the request. See {@link DeleteFolderRequest} for the full list of
* options that can be configured.
* @return The response object is returned primarily to be consistent with the rest of the API. Additional data
* may be returned here in the future but nothing is currently. See {@link DeleteFolderResponse} for the most
* up to date information on what is returned.
* @throws IOException
* @throws SignatureException
*/
DeleteFolderResponse deleteFolder(
DeleteFolderRequest request) throws IOException, SignatureException;
/**
* Deletes an object in a bucket from a DS3 endpoint
* @param request The Delete Object Request object used to customize the HTTP request. The delete object request object
* has some options for customizing the request. See {@link DeleteObjectRequest} for the full list of
* options that can be configured.
* @return The response object is returned primarily to be consistent with the rest of the API. Additional data
* may be returned here in the future but nothing is currently. See {@link DeleteObjectResponse} for the most
* up to date information on what is returned.
* @throws IOException
* @throws SignatureException
*/
DeleteObjectResponse deleteObject(DeleteObjectRequest request)
throws IOException, SignatureException;
/**
* Deletes multiple objects in a bucket from a DS3 endpoint
* @param request The Delete Multiple Objects Request object used to customize the HTTP request. The delete multiple
* objects request has some options for customizing the request. See {@link DeleteMultipleObjectsRequest}
* for the most up to date information on what is returned.
* @return The response object is returned primarily to be consistent with the rest of the API. Additional data
* may be returned here in the future but nothing is currently. See {@link DeleteMultipleObjectsResponse} for
* the most up to date information on what is returned.
* @throws IOException
* @throws SignatureException
*/
DeleteMultipleObjectsResponse deleteMultipleObjects(DeleteMultipleObjectsRequest request)
throws IOException, SignatureException;
/**
* Retrieves an object from DS3
* @param request The Get Object Request object used to customize the HTTP request. The get object request object
* has some options for customizing the request. See {@link GetObjectRequest} for the full list of
* options that can be configured.
* @return The response object contains a stream that can be used to read the contents of the object from. See
* {@link com.spectralogic.ds3client.commands.GetObjectResponse} for any other properties.
* @throws IOException
* @throws SignatureException
*/
GetObjectResponse getObject(GetObjectRequest request)
throws IOException, SignatureException;
/**
* Retrieves all objects from DS3
* @param request The Get Objects Request object used to customize the HTTP request. The get objects request object
* has some options for customizing the request. See {@link GetObjectsRequest} for the full list of
* options that can be configured.
* @return The response object contains a list of objects. See {@link GetObjectsResponse} for the most up to date
* information on what is returned.
* @throws IOException
* @throws SignatureException
*/
GetObjectsResponse getObjects(GetObjectsRequest request)
throws IOException, SignatureException;
/**
* Puts a new object to an existing bucket. The call will fail if the bucket does not exist.
* @param request The Put Object Request object used to customize the HTTP request. The put object request object
* has some options for customizing the request. See {@link PutObjectRequest} for the full list of
* options that can be configured.
* @return The response object is returned primarily to be consistent with the rest of the API. Additional data
* may be returned here in the future but nothing is currently. See {@link PutObjectResponse} for the most
* up to date information on what is returned.
* @throws IOException
* @throws SignatureException
*/
PutObjectResponse putObject(PutObjectRequest request)
throws IOException, SignatureException;
/**
* Performs an HTTP HEAD for an object. If the object exists then a successful response is returned and any metadata
* associated with the object.
* @param request The Object to perform the HTTP HEAD for.
* @return If successful a response is returned with any metadata that was assigned with the object was created.
* @throws IOException
* @throws SignatureException
*/
HeadObjectResponse headObject(HeadObjectRequest request)
throws IOException, SignatureException;
/**
* Primes the Ds3 appliance for a Bulk Get. This does not perform the gets for each individual files. See
* {@link #getObject(GetObjectRequest)} for performing the get.
* @param request The Bulk Get Request object used to customize the HTTP request. The bulk get request object
* has some options for customizing the request. See {@link BulkGetRequest} for the full list of
* options that can be configured.
* @return The response object contains a list of lists of files to get from the DS3 endpoint. Make sure that the
* files are gotten in the order specified in the response.
* @throws IOException
* @throws SignatureException
*/
BulkGetResponse bulkGet(BulkGetRequest request)
throws IOException, SignatureException;
/**
* Primes the Ds3 appliance for a Bulk Put. This does not perform the puts for each individual files. See
* {@link #putObject(PutObjectRequest)} for performing the put.
* @param request The Bulk Put Request object used to customize the HTTP request. The bulk put request object
* has some options for customizing the request. See {@link BulkPutRequest} for the full list of
* options that can be configured.
* @return The response object contains a list of lists of files to put to the DS3 endpoint. Make sure that the
* files are put in the order specified in the response.
* @throws IOException
* @throws SignatureException
*/
BulkPutResponse bulkPut(BulkPutRequest request)
throws IOException, SignatureException;
/**
* Requests that the server allocate space for a given ChunkId in a BulkPutResponse.
* For best performance, run this call before putting objects for an object
* list.
* @return Whether the server responded with allocated, retry later, or not found.
* @throws IOException
* @throws SignatureException
*/
AllocateJobChunkResponse allocateJobChunk(AllocateJobChunkRequest request)
throws IOException, SignatureException;
/**
* Returns all of the chunks immediately available for get from the server
* for a given JobId in a BulkGetResponse.
* @return Whether the server responded with the available chunks, retry later, or not found.
* @throws IOException
* @throws SignatureException
*/
GetAvailableJobChunksResponse getAvailableJobChunks(GetAvailableJobChunksRequest request)
throws IOException, SignatureException;
/**
* Returns all of the jobs currently on the black pearl.
* @return A list of jobs.
* @throws IOException
* @throws SignatureException
*/
GetJobsResponse getJobs(GetJobsRequest request)
throws IOException, SignatureException;
/**
* Returns details about a bulk job given a job id.
* @return A master object list.
* @throws IOException
* @throws SignatureException
*/
GetJobResponse getJob(GetJobRequest request)
throws IOException, SignatureException;
/**
* Cancels an in-progress job.
* @throws IOException
* @throws SignatureException
*/
CancelJobResponse cancelJob(CancelJobRequest request)
throws IOException, SignatureException;
/**
* Updates the last modified date of a job and returns the job details.
* @return A master object list.
* @throws IOException
* @throws SignatureException
*/
ModifyJobResponse modifyJob(ModifyJobRequest request)
throws IOException, SignatureException;
DeleteTapeDriveResponse deleteTapeDrive(DeleteTapeDriveRequest request)
throws IOException, SignatureException;
DeleteTapePartitionResponse deleteTapePartition(DeleteTapePartitionRequest request)
throws IOException, SignatureException;
/**
* Returns a list of tapes.
* @throws IOException
* @throws SignatureException
*/
GetTapesResponse getTapes(GetTapesRequest request)
throws IOException, SignatureException;
DeleteTapeResponse deleteTape(DeleteTapeRequest request)
throws IOException, SignatureException;
/**
* Returns the information for a single tape.
* @throws IOException
* @throws SignatureException
*/
GetTapeResponse getTape(GetTapeRequest request)
throws IOException, SignatureException;
NotificationResponse createObjectCachedNotification(CreateObjectCachedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getObjectCachedNotification(GetObjectCachedNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deleteObjectCachedNotification(DeleteObjectCachedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse createJobCompletedNotification(CreateJobCompletedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getJobCompletedNotification(GetJobCompletedNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deleteJobCompleteNotification(DeleteJobCompletedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse createJobCreatedNotification(CreateJobCreatedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getJobCreatedNotification(GetJobCreatedNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deleteJobCreatedNotification(DeleteJobCreatedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse createObjectLostNotification(CreateObjectLostNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getObjectLostNotification(GetObjectLostNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deleteObjectLostNotification(DeleteObjectLostNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse createObjectPersistedNotification(CreateObjectPersistedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getObjectPersistedNotification(GetObjectPersistedNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deleteObjectPersistedNotification(DeleteObjectPersistedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse createPartitionFailureNotification(CreatePartitionFailureNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getPartitionFailureNotification(GetPartitionFailureNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deletePartitionFailureNotification(DeletePartitionFailureNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse createTapeFailureNotification(CreateTapeFailureNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getTapeFailureNotification(GetTapeFailureNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deleteTapeFailureNotification(DeleteTapeFailureNotificationRequest request)
throws IOException, SignatureException;
GetSystemHealthResponse getSystemHealth(GetSystemHealthRequest request)
throws IOException, SignatureException;
GetSystemInformationResponse getSystemInformation(GetSystemInformationRequest request)
throws IOException, SignatureException;
GetTapeLibrariesResponse getTapeLibraries(GetTapeLibrariesRequest request)
throws IOException, SignatureException;
GetTapeLibraryResponse getTapeLibrary(GetTapeLibraryRequest request)
throws IOException, SignatureException;
GetTapeDrivesResponse getTapeDrives(GetTapeDrivesRequest request)
throws IOException, SignatureException;
GetTapeDriveResponse getTapeDrive(GetTapeDriveRequest request)
throws IOException, SignatureException;
GetTapeFailureResponse getTapeFailure(GetTapeFailureRequest request)
throws IOException, SignatureException;
/**
* Creates a new Ds3Client instance for the system pointed to by Node.
*/
Ds3Client newForNode(Node node);
}
|
ds3-sdk/src/main/java/com/spectralogic/ds3client/Ds3Client.java
|
/*
* ******************************************************************************
* Copyright 2014-2015 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
package com.spectralogic.ds3client;
import com.spectralogic.ds3client.commands.*;
import com.spectralogic.ds3client.commands.notifications.*;
import com.spectralogic.ds3client.models.bulk.Node;
import com.spectralogic.ds3client.networking.ConnectionDetails;
import java.io.Closeable;
import java.io.IOException;
import java.security.SignatureException;
/**
* The main interface for communicating with a DS3 appliance. All communication with a DS3 appliance starts with
* this class.
*
* See {@link Ds3ClientBuilder} on what options can be used to create a Ds3Client instance.
*/
public interface Ds3Client extends Closeable {
ConnectionDetails getConnectionDetails();
/**
* Gets the list of buckets.
* @param request The Service Request object used to customize the HTTP request, {@link com.spectralogic.ds3client.commands.GetServiceRequest}
* @return The response object contains the list of buckets that the user has access to.
* @throws IOException
* @throws SignatureException
*/
GetServiceResponse getService(GetServiceRequest request)
throws IOException, SignatureException;
/**
* Gets the list of objects in a bucket.
* @param request The Get Bucket Request object used to customize the HTTP request. The bucket request object has
* several options for customizing the request. See {@link com.spectralogic.ds3client.commands.GetBucketRequest} for the full list of options
* that can be configured.
* @return The response object contains the list of objects that a bucket contains. There is some additional
* information that is returned which is used for pagination, {@link GetBucketResponse} for the full
* list of properties
* that are returned.
* @throws IOException
* @throws SignatureException
*/
GetBucketResponse getBucket(GetBucketRequest request)
throws IOException, SignatureException;
/**
* Puts a new bucket to a DS3 endpoint
* @param request The Put Bucket Request object used to customize the HTTP request. The put bucket request object
* has some options for customizing the request. See {@link PutBucketRequest} for the full list of
* options that can be configured.
* @return The response object is returned primarily to be consistent with the rest of the API. Additional data
* may be returned here in the future but nothing is currently. See {@link PutBucketResponse} for the most
* up to date information on what is returned.
* @throws IOException
* @throws SignatureException
*/
PutBucketResponse putBucket(PutBucketRequest request)
throws IOException, SignatureException;
/**
* Performs a HTTP HEAD for a bucket. The HEAD will return information about if the bucket exists, or if the user
* has access to that bucket.
* @param request The Head Bucket Request object used to customize the HTTP request. See {@link HeadBucketRequest}.
* @return The response object is returned and contains the status of the bucket. See {@link HeadBucketResponse} for
* the full list of status that a bucket can be in.
* @throws IOException
* @throws SignatureException
*/
HeadBucketResponse headBucket(HeadBucketRequest request)
throws IOException, SignatureException;
/**
* Deletes a bucket from a DS3 endpoint. <b>Note:</b> all objects must be deleted first before deleteBucket will
* succeed.
* @param request The Delete Bucket Request object used to customize the HTTP request. The delete bucket request object
* has some options for customizing the request. See {@link DeleteBucketRequest} for the full list of
* options that can be configured.
* @return The response object is returned primarily to be consistent with the rest of the API. Additional data
* may be returned here in the future but nothing is currently. See {@link com.spectralogic.ds3client.commands.DeleteBucketResponse} for the most
* up to date information on what is returned.
* @throws IOException
* @throws SignatureException
*/
DeleteBucketResponse deleteBucket(
DeleteBucketRequest request) throws IOException, SignatureException;
/**
* Recursively deletes the specified folder from a DS3 endpoint.
* @param request The Delete Folder Request object used to customize the HTTP request. The put bucket request object
* has some options for customizing the request. See {@link DeleteFolderRequest} for the full list of
* options that can be configured.
* @return The response object is returned primarily to be consistent with the rest of the API. Additional data
* may be returned here in the future but nothing is currently. See {@link DeleteFolderResponse} for the most
* up to date information on what is returned.
* @throws IOException
* @throws SignatureException
*/
DeleteFolderResponse deleteFolder(
DeleteFolderRequest request) throws IOException, SignatureException;
/**
* Deletes an object in a bucket from a DS3 endpoint
* @param request The Put Bucket Request object used to customize the HTTP request. The put bucket request object
* has some options for customizing the request. See {@link PutBucketRequest} for the full list of
* options that can be configured.
* @return The response object is returned primarily to be consistent with the rest of the API. Additional data
* may be returned here in the future but nothing is currently. See {@link DeleteObjectResponse} for the most
* up to date information on what is returned.
* @throws IOException
* @throws SignatureException
*/
DeleteObjectResponse deleteObject(DeleteObjectRequest request)
throws IOException, SignatureException;
DeleteMultipleObjectsResponse deleteMultipleObjects(DeleteMultipleObjectsRequest request)
throws IOException, SignatureException;
/**
* Retrieves an object from DS3
* @param request The Get Object Request object used to customize the HTTP request. The get object request object
* has some options for customizing the request. See {@link GetObjectRequest} for the full list of
* options that can be configured.
* @return The response object contains a stream that can be used to read the contents of the object from. See
* {@link com.spectralogic.ds3client.commands.GetObjectResponse} for any other properties.
* @throws IOException
* @throws SignatureException
*/
GetObjectResponse getObject(GetObjectRequest request)
throws IOException, SignatureException;
/**
* Retrieves all objects from DS3
* @param request The Get Objects Request object used to customize the HTTP request. The get objects request object
* has some options for customizing the request. See {@link GetObjectsRequest} for the full list of
* options that can be configured.
* @return The response object contains a list of objects. See {@link GetObjectsResponse} for the most up to date
* information on what is returned.
* @throws IOException
* @throws SignatureException
*/
GetObjectsResponse getObjects(GetObjectsRequest request)
throws IOException, SignatureException;
/**
* Puts a new object to an existing bucket. The call will fail if the bucket does not exist.
* @param request The Put Object Request object used to customize the HTTP request. The put object request object
* has some options for customizing the request. See {@link PutObjectRequest} for the full list of
* options that can be configured.
* @return The response object is returned primarily to be consistent with the rest of the API. Additional data
* may be returned here in the future but nothing is currently. See {@link PutObjectResponse} for the most
* up to date information on what is returned.
* @throws IOException
* @throws SignatureException
*/
PutObjectResponse putObject(PutObjectRequest request)
throws IOException, SignatureException;
/**
* Performs an HTTP HEAD for an object. If the object exists then a successful response is returned and any metadata
* associated with the object.
* @param request The Object to perform the HTTP HEAD for.
* @return If successful a response is returned with any metadata that was assigned with the object was created.
* @throws IOException
* @throws SignatureException
*/
HeadObjectResponse headObject(HeadObjectRequest request)
throws IOException, SignatureException;
/**
* Primes the Ds3 appliance for a Bulk Get. This does not perform the gets for each individual files. See
* {@link #getObject(GetObjectRequest)} for performing the get.
* @param request The Bulk Get Request object used to customize the HTTP request. The bulk get request object
* has some options for customizing the request. See {@link BulkGetRequest} for the full list of
* options that can be configured.
* @return The response object contains a list of lists of files to get from the DS3 endpoint. Make sure that the
* files are gotten in the order specified in the response.
* @throws IOException
* @throws SignatureException
*/
BulkGetResponse bulkGet(BulkGetRequest request)
throws IOException, SignatureException;
/**
* Primes the Ds3 appliance for a Bulk Put. This does not perform the puts for each individual files. See
* {@link #putObject(PutObjectRequest)} for performing the put.
* @param request The Bulk Put Request object used to customize the HTTP request. The bulk put request object
* has some options for customizing the request. See {@link BulkPutRequest} for the full list of
* options that can be configured.
* @return The response object contains a list of lists of files to put to the DS3 endpoint. Make sure that the
* files are put in the order specified in the response.
* @throws IOException
* @throws SignatureException
*/
BulkPutResponse bulkPut(BulkPutRequest request)
throws IOException, SignatureException;
/**
* Requests that the server allocate space for a given ChunkId in a BulkPutResponse.
* For best performance, run this call before putting objects for an object
* list.
* @return Whether the server responded with allocated, retry later, or not found.
* @throws IOException
* @throws SignatureException
*/
AllocateJobChunkResponse allocateJobChunk(AllocateJobChunkRequest request)
throws IOException, SignatureException;
/**
* Returns all of the chunks immediately available for get from the server
* for a given JobId in a BulkGetResponse.
* @return Whether the server responded with the available chunks, retry later, or not found.
* @throws IOException
* @throws SignatureException
*/
GetAvailableJobChunksResponse getAvailableJobChunks(GetAvailableJobChunksRequest request)
throws IOException, SignatureException;
/**
* Returns all of the jobs currently on the black pearl.
* @return A list of jobs.
* @throws IOException
* @throws SignatureException
*/
GetJobsResponse getJobs(GetJobsRequest request)
throws IOException, SignatureException;
/**
* Returns details about a bulk job given a job id.
* @return A master object list.
* @throws IOException
* @throws SignatureException
*/
GetJobResponse getJob(GetJobRequest request)
throws IOException, SignatureException;
/**
* Cancels an in-progress job.
* @throws IOException
* @throws SignatureException
*/
CancelJobResponse cancelJob(CancelJobRequest request)
throws IOException, SignatureException;
/**
* Updates the last modified date of a job and returns the job details.
* @return A master object list.
* @throws IOException
* @throws SignatureException
*/
ModifyJobResponse modifyJob(ModifyJobRequest request)
throws IOException, SignatureException;
DeleteTapeDriveResponse deleteTapeDrive(DeleteTapeDriveRequest request)
throws IOException, SignatureException;
DeleteTapePartitionResponse deleteTapePartition(DeleteTapePartitionRequest request)
throws IOException, SignatureException;
/**
* Returns a list of tapes.
* @throws IOException
* @throws SignatureException
*/
GetTapesResponse getTapes(GetTapesRequest request)
throws IOException, SignatureException;
DeleteTapeResponse deleteTape(DeleteTapeRequest request)
throws IOException, SignatureException;
/**
* Returns the information for a single tape.
* @throws IOException
* @throws SignatureException
*/
GetTapeResponse getTape(GetTapeRequest request)
throws IOException, SignatureException;
NotificationResponse createObjectCachedNotification(CreateObjectCachedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getObjectCachedNotification(GetObjectCachedNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deleteObjectCachedNotification(DeleteObjectCachedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse createJobCompletedNotification(CreateJobCompletedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getJobCompletedNotification(GetJobCompletedNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deleteJobCompleteNotification(DeleteJobCompletedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse createJobCreatedNotification(CreateJobCreatedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getJobCreatedNotification(GetJobCreatedNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deleteJobCreatedNotification(DeleteJobCreatedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse createObjectLostNotification(CreateObjectLostNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getObjectLostNotification(GetObjectLostNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deleteObjectLostNotification(DeleteObjectLostNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse createObjectPersistedNotification(CreateObjectPersistedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getObjectPersistedNotification(GetObjectPersistedNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deleteObjectPersistedNotification(DeleteObjectPersistedNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse createPartitionFailureNotification(CreatePartitionFailureNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getPartitionFailureNotification(GetPartitionFailureNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deletePartitionFailureNotification(DeletePartitionFailureNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse createTapeFailureNotification(CreateTapeFailureNotificationRequest request)
throws IOException, SignatureException;
NotificationResponse getTapeFailureNotification(GetTapeFailureNotificationRequest request)
throws IOException, SignatureException;
DeleteNotificationResponse deleteTapeFailureNotification(DeleteTapeFailureNotificationRequest request)
throws IOException, SignatureException;
GetSystemHealthResponse getSystemHealth(GetSystemHealthRequest request)
throws IOException, SignatureException;
GetSystemInformationResponse getSystemInformation(GetSystemInformationRequest request)
throws IOException, SignatureException;
GetTapeLibrariesResponse getTapeLibraries(GetTapeLibrariesRequest request)
throws IOException, SignatureException;
GetTapeLibraryResponse getTapeLibrary(GetTapeLibraryRequest request)
throws IOException, SignatureException;
GetTapeDrivesResponse getTapeDrives(GetTapeDrivesRequest request)
throws IOException, SignatureException;
GetTapeDriveResponse getTapeDrive(GetTapeDriveRequest request)
throws IOException, SignatureException;
GetTapeFailureResponse getTapeFailure(GetTapeFailureRequest request)
throws IOException, SignatureException;
/**
* Creates a new Ds3Client instance for the system pointed to by Node.
*/
Ds3Client newForNode(Node node);
}
|
Update Ds3Client.java
|
ds3-sdk/src/main/java/com/spectralogic/ds3client/Ds3Client.java
|
Update Ds3Client.java
|
<ide><path>s3-sdk/src/main/java/com/spectralogic/ds3client/Ds3Client.java
<ide>
<ide> /**
<ide> * Deletes an object in a bucket from a DS3 endpoint
<del> * @param request The Put Bucket Request object used to customize the HTTP request. The put bucket request object
<del> * has some options for customizing the request. See {@link PutBucketRequest} for the full list of
<add> * @param request The Delete Object Request object used to customize the HTTP request. The delete object request object
<add> * has some options for customizing the request. See {@link DeleteObjectRequest} for the full list of
<ide> * options that can be configured.
<ide> * @return The response object is returned primarily to be consistent with the rest of the API. Additional data
<ide> * may be returned here in the future but nothing is currently. See {@link DeleteObjectResponse} for the most
<ide> DeleteObjectResponse deleteObject(DeleteObjectRequest request)
<ide> throws IOException, SignatureException;
<ide>
<add> /**
<add> * Deletes multiple objects in a bucket from a DS3 endpoint
<add> * @param request The Delete Multiple Objects Request object used to customize the HTTP request. The delete multiple
<add> * objects request has some options for customizing the request. See {@link DeleteMultipleObjectsRequest}
<add> * for the most up to date information on what is returned.
<add> * @return The response object is returned primarily to be consistent with the rest of the API. Additional data
<add> * may be returned here in the future but nothing is currently. See {@link DeleteMultipleObjectsResponse} for
<add> * the most up to date information on what is returned.
<add> * @throws IOException
<add> * @throws SignatureException
<add> */
<ide> DeleteMultipleObjectsResponse deleteMultipleObjects(DeleteMultipleObjectsRequest request)
<ide> throws IOException, SignatureException;
<ide>
|
|
Java
|
agpl-3.0
|
9048ad337c9d917d0975473e86d4c8ccbb91e0e9
| 0 |
elki-project/elki,elki-project/elki,elki-project/elki
|
package experimentalcode.hettab.outlier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import de.lmu.ifi.dbs.elki.algorithm.DistanceBasedAlgorithm;
import de.lmu.ifi.dbs.elki.data.DatabaseObject;
import de.lmu.ifi.dbs.elki.database.AssociationID;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.DistanceResultPair;
import de.lmu.ifi.dbs.elki.distance.DoubleDistance;
import de.lmu.ifi.dbs.elki.math.MinMax;
import de.lmu.ifi.dbs.elki.result.AnnotationFromHashMap;
import de.lmu.ifi.dbs.elki.result.AnnotationResult;
import de.lmu.ifi.dbs.elki.result.MultiResult;
import de.lmu.ifi.dbs.elki.result.OrderingFromHashMap;
import de.lmu.ifi.dbs.elki.result.OrderingResult;
import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult;
import de.lmu.ifi.dbs.elki.result.outlier.OutlierScoreMeta;
import de.lmu.ifi.dbs.elki.result.outlier.QuotientOutlierScoreMeta;
import de.lmu.ifi.dbs.elki.utilities.documentation.Description;
import de.lmu.ifi.dbs.elki.utilities.documentation.Reference;
import de.lmu.ifi.dbs.elki.utilities.documentation.Title;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.GreaterConstraint;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter;
/**
* INFLO provides the Mining Algorithms (Two-way Search Method) for Influence
* Outliers using Symmetric Relationship
* <p>
* Reference: <br>
* <p>
* Jin, W., Tung, A., Han, J., and Wang, W. 2006<br />
* Ranking outliers using symmetric neighborhood relationship< br/>
* In Proc. Pacific-Asia Conf. on Knowledge Discovery and Data Mining (PAKDD),
* Singapore
* </p>
*
* @author Ahmed Hettab
* @param <O> the type of DatabaseObject the algorithm is applied on
*/
@Title("INFLO: Influenced Outlierness Factor")
@Description("Ranking Outliers Using Symmetric Neigborhood Relationship")
@Reference(authors = "Jin, W., Tung, A., Han, J., and Wang, W", title = "Ranking outliers using symmetric neighborhood relationship", booktitle = "Proc. Pacific-Asia Conf. on Knowledge Discovery and Data Mining (PAKDD), Singapore, 2006", url = "http://dx.doi.org/10.1007/11731139_68")
public class INFLO<O extends DatabaseObject> extends DistanceBasedAlgorithm<O, DoubleDistance, MultiResult> {
/**
* OptionID for {@link #M_PARAM}
*/
public static final OptionID M_ID = OptionID.getOrCreateOptionID("inflo.m", "The threshold");
/**
* Parameter to specify if any object is a Core Object must be a double
* greater than 0.0
* <p>
* see paper "Two-way search method" 3.2
* <p>
* Key: {@code -inflo.m}
* </p>
*/
private final DoubleParameter M_PARAM = new DoubleParameter(M_ID, new GreaterConstraint(0.0), 1.0);
/**
* Holds the value of {@link #M_PARAM}.
*/
private double m;
/**
* OptionID for {@link #K_PARAM}
*/
public static final OptionID K_ID = OptionID.getOrCreateOptionID("inflo.k", "The number of nearest neighbors of an object to be considered for computing its INFLO_SCORE.");
/**
* Parameter to specify the number of nearest neighbors of an object to be
* considered for computing its INFLO_SCORE. must be an integer greater than
* 1.
* <p>
* Key: {@code -inflo.k}
* </p>
*/
private final IntParameter K_PARAM = new IntParameter(K_ID, new GreaterConstraint(1));
/**
* Holds the value of {@link #K_PARAM}.
*/
private int k;
/**
* Holds a set of processed ids.
*/
protected Set<Integer> processedIDs;
/**
* The association id to associate the INFLO_SCORE of an object for the INFLO
* algorithm.
*/
public static final AssociationID<Double> INFLO_SCORE = AssociationID.getOrCreateAssociationID("inflo", Double.class);
/**
* Constructor, adhering to
* {@link de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameterizable}
*
* @param config Parameterization
*/
public INFLO(Parameterization config) {
super(config);
if(config.grab(K_PARAM)) {
k = K_PARAM.getValue();
}
if(config.grab(M_PARAM)) {
m = M_PARAM.getValue();
}
}
@Override
protected MultiResult runInTime(Database<O> database) throws IllegalStateException {
processedIDs = new HashSet<Integer>(database.size());
HashSet<Integer> pruned = new HashSet<Integer>();
// KNNS
HashMap<Integer, Vector<Integer>> knns = new HashMap<Integer, Vector<Integer>>();
// RNNS
HashMap<Integer, Vector<Integer>> rnns = new HashMap<Integer, Vector<Integer>>();
// density
HashMap<Integer, Double> density = new HashMap<Integer, Double>();
// init knns and rnns
for(Integer id : database) {
knns.put(id, new Vector<Integer>());
rnns.put(id, new Vector<Integer>());
}
for(Integer id : database) {
// if not visited count=0
int count = rnns.get(id).size();
Vector<Integer> s;
if(!processedIDs.contains(id)) {
List<DistanceResultPair<DoubleDistance>> list = database.kNNQueryForID(id, k, getDistanceFunction());
for(DistanceResultPair<DoubleDistance> d : list) {
knns.get(id).add(d.second);
}
processedIDs.add(id);
s = knns.get(id);
density.put(id, 1 / list.get(k - 1).getDistance().doubleValue());
}
else {
s = knns.get(id);
}
for(Integer q : s) {
List<DistanceResultPair<DoubleDistance>> listQ;
if(!processedIDs.contains(q)) {
listQ = database.kNNQueryForID(q, k, getDistanceFunction());
for(DistanceResultPair<DoubleDistance> dq : listQ) {
knns.get(q).add(dq.second);
}
density.put(q, 1 / listQ.get(k - 1).getDistance().doubleValue());
processedIDs.add(q);
}
if(knns.get(q).contains(id)) {
rnns.get(q).add(id);
rnns.get(id).add(q);
count++;
}
}
if(count >= s.size() * m) {
pruned.add(id);
}
}
// Calculate INFLO for any Object
// IF Object is pruned INFLO=1.0
MinMax<Double> inflominmax = new MinMax<Double>();
HashMap<Integer, Double> inflos = new HashMap<Integer, Double>();
for(Integer id : database) {
if(!pruned.contains(id)) {
Vector<Integer> knn = knns.get(id);
Vector<Integer> rnn = rnns.get(id);
double denP = density.get(id);
knn.addAll(rnn);
double den = 0;
for(Integer q : knn) {
double denQ = density.get(q);
den = den + denQ;
}
den = den / rnn.size();
den = den / denP;
inflos.put(id, den);
// update minimum and maximum
inflominmax.put(den);
}
if(pruned.contains(id)) {
inflos.put(id, 1.0);
inflominmax.put(1.0);
}
}
// Build result representation.
AnnotationResult<Double> scoreResult = new AnnotationFromHashMap<Double>(INFLO_SCORE, inflos);
OrderingResult orderingResult = new OrderingFromHashMap<Double>(inflos, true);
OutlierScoreMeta scoreMeta = new QuotientOutlierScoreMeta(inflominmax.getMin(), inflominmax.getMax(), 0.0, Double.POSITIVE_INFINITY, 1.0);
return new OutlierResult(scoreMeta, scoreResult, orderingResult);
}
}
|
src/experimentalcode/hettab/outlier/INFLO.java
|
package experimentalcode.hettab.outlier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import de.lmu.ifi.dbs.elki.algorithm.DistanceBasedAlgorithm;
import de.lmu.ifi.dbs.elki.data.DatabaseObject;
import de.lmu.ifi.dbs.elki.database.AssociationID;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.DistanceResultPair;
import de.lmu.ifi.dbs.elki.distance.DoubleDistance;
import de.lmu.ifi.dbs.elki.math.MinMax;
import de.lmu.ifi.dbs.elki.result.AnnotationFromHashMap;
import de.lmu.ifi.dbs.elki.result.AnnotationResult;
import de.lmu.ifi.dbs.elki.result.MultiResult;
import de.lmu.ifi.dbs.elki.result.OrderingFromHashMap;
import de.lmu.ifi.dbs.elki.result.OrderingResult;
import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult;
import de.lmu.ifi.dbs.elki.result.outlier.OutlierScoreMeta;
import de.lmu.ifi.dbs.elki.result.outlier.QuotientOutlierScoreMeta;
import de.lmu.ifi.dbs.elki.utilities.documentation.Description;
import de.lmu.ifi.dbs.elki.utilities.documentation.Reference;
import de.lmu.ifi.dbs.elki.utilities.documentation.Title;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.GreaterConstraint;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter;
/**
* INFLO provides the Mining Algorithms (Two-way Search Method) for Influence
* Outliers using Symmetric Relationship
* <p>
* Reference: <br>
* <p>
* Jin, W., Tung, A., Han, J., and Wang, W. 2006. Ranking outliers using
* symmetric neighborhood relationship In Proc. Pacific-Asia Conf. on Knowledge
* Discovery and Data Mining (PAKDD), Singapore"
* </p>
*
* @author Ahmed Hettab
* @param <O> the type of DatabaseObject the algorithm is applied on
* @param <D> the type of Distance used
*/
@Title("INFLO: Influenced Outlierness Factor")
@Description("Ranking Outliers Using Symmetric Neigborhood Relationship")
@Reference(authors = "Jin, W., Tung, A., Han, J., and Wang, W", title = "Ranking outliers using symmetric neighborhood relationship.", booktitle = "Proc. Pacific-Asia Conf. on Knowledge Discovery and Data Mining (PAKDD), Singapore, 2006")
public class INFLO<O extends DatabaseObject> extends DistanceBasedAlgorithm<O, DoubleDistance, MultiResult> {
/**
* OptionID for {@link #M_PARAM}
*/
public static final OptionID M_ID = OptionID.getOrCreateOptionID("inflo.m", "The Threshold");
/**
* Parameter to specify if any object is a Core Object must be a double
* greater than 0.0
* <p>
* see paper "Two-way search method" 3.2
* <p>
* Key: {@code -inflo.m}
* </p>
*/
private final DoubleParameter M_PARAM = new DoubleParameter(M_ID, new GreaterConstraint(0.0), 1.0);
/**
* Holds the value of {@link #M_PARAM}.
*/
private double m;
/**
* OptionID for {@link #K_PARAM}
*/
public static final OptionID K_ID = OptionID.getOrCreateOptionID("inflo.k", "The number of nearest neighbors of an object to be considered for computing its INFLO_SCORE.");
/**
* Parameter to specify the number of nearest neighbors of an object to be
* considered for computing its INFLO_SCORE. must be an integer greater than
* 1.
* <p>
* Key: {@code -inflo.k}
* </p>
*/
private final IntParameter K_PARAM = new IntParameter(K_ID, new GreaterConstraint(1));
/**
* Holds the value of {@link #K_PARAM}.
*/
private int k;
/**
* Holds a set of processed ids.
*/
protected Set<Integer> processedIDs;
/**
* The association id to associate the INFLO_SCORE of an object for the INFLO
* algorithm.
*/
public static final AssociationID<Double> INFLO_SCORE = AssociationID.getOrCreateAssociationID("inflo", Double.class);
public INFLO(Parameterization config) {
super(config);
// parameter minpts
if (config.grab(K_PARAM)) {
k = K_PARAM.getValue();
}
if (config.grab(M_PARAM)) {
m = M_PARAM.getValue();
}
}
/**
*
*/
@Override
protected MultiResult runInTime(Database<O> database) throws IllegalStateException {
processedIDs = new HashSet<Integer>(database.size());
HashSet<Integer> pruned = new HashSet<Integer>();
// KNNS
HashMap<Integer, Vector<Integer>> knns = new HashMap<Integer, Vector<Integer>>();
// RNNS
HashMap<Integer, Vector<Integer>> rnns = new HashMap<Integer, Vector<Integer>>();
// density
HashMap<Integer, Double> density = new HashMap<Integer, Double>();
// init knns and rnns
for(Integer id : database) {
knns.put(id, new Vector<Integer>());
rnns.put(id, new Vector<Integer>());
}
for(Integer id : database) {
// if not visited count=0
int count = rnns.get(id).size();
Vector<Integer> s;
if(!processedIDs.contains(id)) {
List<DistanceResultPair<DoubleDistance>> list = database.kNNQueryForID(id, k, getDistanceFunction());
for(DistanceResultPair<DoubleDistance> d : list) {
knns.get(id).add(d.second);
}
processedIDs.add(id);
s = knns.get(id);
density.put(id, 1 / list.get(k - 1).getDistance().doubleValue());
}
else {
s = knns.get(id);
}
for(Integer q : s) {
List<DistanceResultPair<DoubleDistance>> listQ;
if(!processedIDs.contains(q)) {
listQ = database.kNNQueryForID(q, k, getDistanceFunction());
for(DistanceResultPair<DoubleDistance> dq : listQ) {
knns.get(q).add(dq.second);
}
density.put(q, 1 / listQ.get(k - 1).getDistance().doubleValue());
processedIDs.add(q);
}
if(knns.get(q).contains(id)) {
rnns.get(q).add(id);
rnns.get(id).add(q);
count++;
}
}
if(count >= s.size() * m) {
pruned.add(id);
}
}
// Calculate INFLO for any Object
// IF Object is pruned INFLO=1.0
MinMax<Double> inflominmax = new MinMax<Double>();
HashMap<Integer, Double> inflos = new HashMap<Integer, Double>();
for(Integer id : database) {
if(!pruned.contains(id)) {
Vector<Integer> knn = knns.get(id);
Vector<Integer> rnn = rnns.get(id);
double denP = density.get(id);
knn.addAll(rnn);
double den = 0;
for(Integer q : knn) {
double denQ = density.get(q);
den = den + denQ;
}
den = den / rnn.size();
den = den / denP;
inflos.put(id, den);
// update minimum and maximum
inflominmax.put(den);
}
if(pruned.contains(id)) {
inflos.put(id, 1.0);
inflominmax.put(1.0);
}
}
// Build result representation.
AnnotationResult<Double> scoreResult = new AnnotationFromHashMap<Double>(INFLO_SCORE, inflos);
OrderingResult orderingResult = new OrderingFromHashMap<Double>(inflos, true);
OutlierScoreMeta scoreMeta = new QuotientOutlierScoreMeta(inflominmax.getMin(), inflominmax.getMax(), 0.0, Double.POSITIVE_INFINITY,1.0);
return new OutlierResult(scoreMeta, scoreResult, orderingResult);
}
}
|
Prepare for release with 0.3
|
src/experimentalcode/hettab/outlier/INFLO.java
|
Prepare for release with 0.3
|
<ide><path>rc/experimentalcode/hettab/outlier/INFLO.java
<ide> * <p>
<ide> * Reference: <br>
<ide> * <p>
<del> * Jin, W., Tung, A., Han, J., and Wang, W. 2006. Ranking outliers using
<del> * symmetric neighborhood relationship In Proc. Pacific-Asia Conf. on Knowledge
<del> * Discovery and Data Mining (PAKDD), Singapore"
<add> * Jin, W., Tung, A., Han, J., and Wang, W. 2006<br />
<add> * Ranking outliers using symmetric neighborhood relationship< br/>
<add> * In Proc. Pacific-Asia Conf. on Knowledge Discovery and Data Mining (PAKDD),
<add> * Singapore
<ide> * </p>
<ide> *
<ide> * @author Ahmed Hettab
<ide> * @param <O> the type of DatabaseObject the algorithm is applied on
<del> * @param <D> the type of Distance used
<ide> */
<ide> @Title("INFLO: Influenced Outlierness Factor")
<ide> @Description("Ranking Outliers Using Symmetric Neigborhood Relationship")
<del>@Reference(authors = "Jin, W., Tung, A., Han, J., and Wang, W", title = "Ranking outliers using symmetric neighborhood relationship.", booktitle = "Proc. Pacific-Asia Conf. on Knowledge Discovery and Data Mining (PAKDD), Singapore, 2006")
<add>@Reference(authors = "Jin, W., Tung, A., Han, J., and Wang, W", title = "Ranking outliers using symmetric neighborhood relationship", booktitle = "Proc. Pacific-Asia Conf. on Knowledge Discovery and Data Mining (PAKDD), Singapore, 2006", url = "http://dx.doi.org/10.1007/11731139_68")
<ide> public class INFLO<O extends DatabaseObject> extends DistanceBasedAlgorithm<O, DoubleDistance, MultiResult> {
<ide> /**
<ide> * OptionID for {@link #M_PARAM}
<ide> */
<del> public static final OptionID M_ID = OptionID.getOrCreateOptionID("inflo.m", "The Threshold");
<add> public static final OptionID M_ID = OptionID.getOrCreateOptionID("inflo.m", "The threshold");
<ide>
<ide> /**
<ide> * Parameter to specify if any object is a Core Object must be a double
<ide> */
<ide> public static final AssociationID<Double> INFLO_SCORE = AssociationID.getOrCreateAssociationID("inflo", Double.class);
<ide>
<add> /**
<add> * Constructor, adhering to
<add> * {@link de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameterizable}
<add> *
<add> * @param config Parameterization
<add> */
<ide> public INFLO(Parameterization config) {
<ide> super(config);
<del> // parameter minpts
<del> if (config.grab(K_PARAM)) {
<del> k = K_PARAM.getValue();
<del> }
<del> if (config.grab(M_PARAM)) {
<del> m = M_PARAM.getValue();
<add> if(config.grab(K_PARAM)) {
<add> k = K_PARAM.getValue();
<add> }
<add> if(config.grab(M_PARAM)) {
<add> m = M_PARAM.getValue();
<ide> }
<ide> }
<ide>
<del> /**
<del> *
<del> */
<ide> @Override
<ide> protected MultiResult runInTime(Database<O> database) throws IllegalStateException {
<ide> processedIDs = new HashSet<Integer>(database.size());
<ide> // Build result representation.
<ide> AnnotationResult<Double> scoreResult = new AnnotationFromHashMap<Double>(INFLO_SCORE, inflos);
<ide> OrderingResult orderingResult = new OrderingFromHashMap<Double>(inflos, true);
<del> OutlierScoreMeta scoreMeta = new QuotientOutlierScoreMeta(inflominmax.getMin(), inflominmax.getMax(), 0.0, Double.POSITIVE_INFINITY,1.0);
<add> OutlierScoreMeta scoreMeta = new QuotientOutlierScoreMeta(inflominmax.getMin(), inflominmax.getMax(), 0.0, Double.POSITIVE_INFINITY, 1.0);
<ide> return new OutlierResult(scoreMeta, scoreResult, orderingResult);
<ide> }
<ide> }
|
|
JavaScript
|
mit
|
42c03a67045ca3fd4c984aa613ad86d4fe042d39
| 0 |
micromaomao/schsrch,micromaomao/schsrch,micromaomao/schsrch,micromaomao/schsrch
|
module.exports = (db, mongoose) => {
let docSchema = new mongoose.Schema({
subject: {type: 'String', index: true, required: true},
time: {type: 'String', index: true, required: true}, // Eg. s12, w15, y16 (i.e. for speciman paper)
type: {type: 'String', index: true, required: true}, // Eg. qp, ms, sp, sm etc.
paper: {type: 'Number', index: true, required: true},
variant: {type: 'Number', index: true, required: true},
doc: {type: Buffer, required: true},
fileType: {type: 'String', default: 'pdf', required: true},
numPages: {type: 'Number', required: true},
})
let indexSchema = new mongoose.Schema({
doc: {type: 'ObjectId', required: true},
page: {type: 'Number', required: true}, // starts from 0
content: {type: 'String', required: true},
sspdfCache: {type: 'Object', default: null}
})
let feedbackSchema = new mongoose.Schema({
time: {type: 'Number', index: true, required: true},
ip: {type: 'String', required: true},
email: {type: 'String', index: true, required: false, validate: {
validator: v => {
return typeof v === 'string' && (v === '' || /.+@.+\..+/i.test(v)) && v.length <= 5000
},
message: 'Check your email address for typos'
}},
text: {type: 'String', required: [true, 'Feedback content required'], validate: {
validator: v => {
return typeof v === 'string' && (v.length > 0 && v.length <= 5000)
},
message: 'Your feedback must not be empty, and it must not contain more than 5000 characters'
}},
search: {type: 'String', required: false, validate: {
validator: v => {
return (v === null) || (typeof v === 'string' && v.length > 0 && v.length <= 5000)
}
}}
})
let requestRecordSchema = new mongoose.Schema({
ip: {type: 'String', index: true, required: true},
time: {type: 'Number', index: true, required: true},
requestType: {type: 'String', index: true},
search: {type: 'String', default: null},
targetId: {type: 'ObjectId', default: null},
targetPage: {type: 'Number', default: null}
})
let PastPaperIndex
let PastPaperDoc
let PastPaperFeedback
let PastPaperRequestRecord
indexSchema.static('search', query => new Promise((resolve, reject) => {
query = query.replace(/["'\+\-]/g, '')
let aggreArray
let queryPerfixMatch = query.match(/^(\d{4})\s+(.+)$/)
if (queryPerfixMatch) {
aggreArray = [{$match: {$text: {$search: queryPerfixMatch[2]}}}]
} else {
aggreArray = [{$match: {$text: {$search: query}}}]
}
aggreArray.push({$addFields: {sspdfCache: null}})
aggreArray.push({$sort: {mgScore: {$meta: 'textScore'}}})
aggreArray.push({$lookup: {from: 'pastpaperdocs', localField: 'doc', foreignField: '_id', as: 'doc'}})
aggreArray.push({$addFields: {tDoc: {$arrayElemAt: ['$doc', 0]}}})
aggreArray.push({$project: {doc: false, 'tDoc.doc': false}})
if (queryPerfixMatch) {
aggreArray.push({$match: {'tDoc.subject': queryPerfixMatch[1]}})
}
aggreArray.push({$limit: 30})
PastPaperIndex.aggregate(aggreArray).then(res => {
resolve(res.map(mgDoc => (mgDoc.tDoc ? {
doc: mgDoc.tDoc,
index: {
_id: mgDoc._id,
content: mgDoc.content,
page: mgDoc.page,
doc: mgDoc.tDoc._id
}
} : null)).filter(x => x !== null))
}, reject)
}))
indexSchema.index({content: 'text'})
docSchema.index({subject: true, time: true, paper: true, variant: true})
try {
PastPaperIndex = db.model('pastPaperIndex', indexSchema)
} catch (e) {
PastPaperIndex = db.model('pastPaperIndex')
}
try {
PastPaperDoc = db.model('pastPaperDoc', docSchema)
} catch (e) {
PastPaperDoc = db.model('pastPaperDoc')
}
try {
PastPaperFeedback = db.model('pastPaperFeedback', feedbackSchema)
} catch (e) {
PastPaperFeedback = db.model('pastPaperFeedback')
}
try {
PastPaperRequestRecord = db.model('pastPaperRequestRecord', requestRecordSchema)
} catch (e) {
PastPaperRequestRecord = db.model('pastPaperRequestRecord')
}
return {PastPaperDoc, PastPaperIndex, PastPaperFeedback, PastPaperRequestRecord}
}
|
lib/dbModel.js
|
module.exports = (db, mongoose) => {
let docSchema = new mongoose.Schema({
subject: {type: 'String', index: true, required: true},
time: {type: 'String', index: true, required: true}, // Eg. s12, w15, y16 (i.e. for speciman paper)
type: {type: 'String', index: true, required: true}, // Eg. qp, ms, sp, sm etc.
paper: {type: 'Number', index: true, required: true},
variant: {type: 'Number', index: true, required: true},
doc: {type: Buffer, required: true},
fileType: {type: 'String', default: 'pdf', required: true},
numPages: {type: 'Number', required: true},
})
let indexSchema = new mongoose.Schema({
doc: {type: 'ObjectId', required: true},
page: {type: 'Number', required: true}, // starts from 0
content: {type: 'String', required: true},
sspdfCache: {type: 'Object', default: null}
})
let feedbackSchema = new mongoose.Schema({
time: {type: 'Number', index: true, required: true},
ip: {type: 'String', required: true},
email: {type: 'String', index: true, required: false, validate: {
validator: v => {
return typeof v === 'string' && (v === '' || /.+@.+\..+/i.test(v)) && v.length <= 5000
},
message: 'Check your email address for typos'
}},
text: {type: 'String', required: [true, 'Feedback content required'], validate: {
validator: v => {
return typeof v === 'string' && (v.length > 0 && v.length <= 5000)
},
message: 'Your feedback must not be empty, and it must not contain more than 5000 characters'
}},
search: {type: 'String', required: false, validate: {
validator: v => {
return (v === null) || (typeof v === 'string' && v.length > 0 && v.length <= 5000)
}
}}
})
let requestRecordSchema = new mongoose.Schema({
ip: {type: 'String', index: true, required: true},
time: {type: 'Number', index: true, required: true},
requestType: {type: 'String', index: true},
search: {type: 'String', default: null},
targetId: {type: 'ObjectId', default: null},
targetPage: {type: 'Number', default: null}
})
let PastPaperIndex
let PastPaperDoc
let PastPaperFeedback
let PastPaperRequestRecord
indexSchema.static('search', query => new Promise((resolve, reject) => {
query = query.replace(/["'\+\-]/g, '')
let aggreArray
let queryPerfixMatch = query.match(/^(\d{4})\s+(.+)$/)
if (queryPerfixMatch) {
aggreArray = [{$match: {$text: {$search: queryPerfixMatch[2]}}}]
} else {
aggreArray = [{$match: {$text: {$search: query}}}]
}
aggreArray.push({$project: {sspdfCache: false}})
aggreArray.push({$sort: {mgScore: {$meta: 'textScore'}}})
aggreArray.push({$lookup: {from: 'pastpaperdocs', localField: 'doc', foreignField: '_id', as: 'doc'}})
aggreArray.push({$addFields: {tDoc: {$arrayElemAt: ['$doc', 0]}}})
aggreArray.push({$project: {doc: false, 'tDoc.doc': false}})
if (queryPerfixMatch) {
aggreArray.push({$match: {'tDoc.subject': queryPerfixMatch[1]}})
}
aggreArray.push({$limit: 30})
PastPaperIndex.aggregate(aggreArray).then(res => {
resolve(res.map(mgDoc => (mgDoc.tDoc ? {
doc: mgDoc.tDoc,
index: {
_id: mgDoc._id,
content: mgDoc.content,
page: mgDoc.page,
doc: mgDoc.tDoc._id
}
} : null)).filter(x => x !== null))
}, reject)
}))
indexSchema.index({content: 'text'})
docSchema.index({subject: true, time: true, paper: true, variant: true})
try {
PastPaperIndex = db.model('pastPaperIndex', indexSchema)
} catch (e) {
PastPaperIndex = db.model('pastPaperIndex')
}
try {
PastPaperDoc = db.model('pastPaperDoc', docSchema)
} catch (e) {
PastPaperDoc = db.model('pastPaperDoc')
}
try {
PastPaperFeedback = db.model('pastPaperFeedback', feedbackSchema)
} catch (e) {
PastPaperFeedback = db.model('pastPaperFeedback')
}
try {
PastPaperRequestRecord = db.model('pastPaperRequestRecord', requestRecordSchema)
} catch (e) {
PastPaperRequestRecord = db.model('pastPaperRequestRecord')
}
return {PastPaperDoc, PastPaperIndex, PastPaperFeedback, PastPaperRequestRecord}
}
|
Use $addFields to clear memory before sort instead of using $project which don't seems to work.
|
lib/dbModel.js
|
Use $addFields to clear memory before sort instead of using $project which don't seems to work.
|
<ide><path>ib/dbModel.js
<ide> } else {
<ide> aggreArray = [{$match: {$text: {$search: query}}}]
<ide> }
<del> aggreArray.push({$project: {sspdfCache: false}})
<add> aggreArray.push({$addFields: {sspdfCache: null}})
<ide> aggreArray.push({$sort: {mgScore: {$meta: 'textScore'}}})
<ide> aggreArray.push({$lookup: {from: 'pastpaperdocs', localField: 'doc', foreignField: '_id', as: 'doc'}})
<ide> aggreArray.push({$addFields: {tDoc: {$arrayElemAt: ['$doc', 0]}}})
|
|
JavaScript
|
unlicense
|
a472bbc56b82a0a316d2ca411a7d456d7edb99d9
| 0 |
stephband/dom,stephband/dom
|
import '../polyfills/element.scrollintoview.js';
import { by, curry, get, isDefined, overload, requestTick } from '../../fn/module.js';
import { append, box, classes, create, delegate, Event, events, features, fragmentFromChildren, isInternalLink, isPrimaryButton, tag, query, ready, remove, trigger } from '../module.js';
var DEBUG = false;
const selector = ".locateable, [locateable]";
const on = events.on;
const byTop = by(get('top'));
const nothing = {};
const scrollOptions = {
// Overridden on window load
behavior: 'auto',
block: 'start'
};
export const config = {
scrollIdleDuration: 0.18
};
let hashTime = -Infinity;
let frameTime = -Infinity;
let scrollTop = document.scrollingElement.scrollTop;
let locateables, locatedNode, scrollPaddingTop, frame;
function queryLinks(id) {
return query('a[href$="#' + id + '"]', document.body)
.filter(isInternalLink);
}
function addOn(node) {
node.classList.add('on');
}
function removeOn(node) {
node.classList.remove('on');
}
function locate(node) {
node.classList.add('located');
queryLinks(node.id).forEach(addOn);
locatedNode = node;
}
function unlocate() {
if (!locatedNode) { return; }
locatedNode.classList.remove('located');
queryLinks(locatedNode.id).forEach(removeOn);
locatedNode = undefined;
}
function update(time) {
frame = undefined;
// Update things that rarely change only when we have not updated recently
if (frameTime < time - config.scrollIdleDuration * 1000) {
locateables = query(selector, document);
scrollPaddingTop = parseInt(getComputedStyle(document.documentElement).scrollPaddingTop, 10);
}
frameTime = time;
const boxes = locateables.map(box).sort(byTop);
let n = -1;
while (boxes[++n]) {
// Stop on locateable lower than the break
if (boxes[n].top > scrollPaddingTop + 1) {
break;
}
}
--n;
// Before the first or after the last locateable. (The latter
// should not be possible according to the above while loop)
if (n < 0 || n >= boxes.length) {
if (locatedNode) {
unlocate();
window.history.replaceState(nothing, '', '#');
}
return;
}
var node = locateables[n];
if (locatedNode && node === locatedNode) {
return;
}
unlocate();
locate(node);
window.history.replaceState(nothing, '', '#' + node.id);
}
function scroll(e) {
if (DEBUG) {
console.log(e.type, e.timeStamp, window.location.hash, document.scrollingElement.scrollTop);
}
const aMomentAgo = e.timeStamp - config.scrollIdleDuration * 1000;
// Keep a record of scrollTop in order to restore it in Safari,
// where popstate and hashchange are preceeded by a scroll jump
scrollTop = document.scrollingElement.scrollTop;
// For a moment after the last hashchange dont update while
// smooth scrolling settles to the right place.
if (hashTime > aMomentAgo) {
hashTime = e.timeStamp;
return;
}
// Is frame already cued?
if (frame) {
return;
}
frame = requestAnimationFrame(update);
}
function popstate(e) {
if (DEBUG) {
console.log(e.type, e.timeStamp, window.location.hash, document.scrollingElement.scrollTop);
}
// Record the timeStamp
hashTime = e.timeStamp;
// Remove current located
unlocate();
const hash = window.location.hash;
const id = hash.slice(1);
if (!id) {
if (!features.scrollBehavior) {
// In Safari, popstate and hashchange are preceeded by scroll jump -
// restore previous scrollTop.
document.scrollingElement.scrollTop = scrollTop;
// Then animate
document.body.scrollIntoView(scrollOptions);
}
return;
}
// Is there a node with that id?
const node = document.getElementById(id);
if (!node) { return; }
// The page is on the move
locate(node);
// Implement smooth scroll for browsers that do not have it
if (!features.scrollBehavior) {
// In Safari, popstate and hashchange are preceeded by scroll jump -
// restore previous scrollTop.
document.scrollingElement.scrollTop = scrollTop;
// Then animate
node.scrollIntoView(scrollOptions);
}
}
function load(e) {
popstate(e);
scroll(e);
// Start listening to popstate and scroll
window.addEventListener('popstate', popstate);
window.addEventListener('scroll', scroll);
// Scroll smoothly from now on
scrollOptions.behavior = 'smooth';
}
window.addEventListener('load', load);
|
js/locateable.js
|
import '../polyfills/element.scrollintoview.js';
import { by, curry, get, isDefined, overload, requestTick } from '../../fn/module.js';
import { append, box, classes, create, delegate, Event, events, features, fragmentFromChildren, isInternalLink, isPrimaryButton, tag, query, ready, remove, trigger } from '../module.js';
var DEBUG = false;
const selector = ".locateable, [locateable]";
const on = events.on;
const byTop = by(get('top'));
const nothing = {};
const scrollOptions = {
// Overridden on window load
behavior: 'auto',
block: 'start'
};
export const config = {
scrollIdleDuration: 0.18
};
let hashTime = -Infinity;
let frameTime = -Infinity;
let scrollTop = document.scrollingElement.scrollTop;
let locateables, locatedNode, scrollPaddingTop, frame;
function queryLinks(id) {
return query('a[href$="#' + id + '"]', document.body)
.filter(isInternalLink);
}
function addOn(node) {
node.classList.add('on');
}
function removeOn(node) {
node.classList.remove('on');
}
function locate(node) {
node.classList.add('located');
queryLinks(node.id).forEach(addOn);
locatedNode = node;
}
function unlocate() {
if (!locatedNode) { return; }
locatedNode.classList.remove('located');
queryLinks(locatedNode.id).forEach(removeOn);
locatedNode = undefined;
}
function update(time) {
frame = undefined;
// Update things that rarely change only when we have not updated recently
if (frameTime < time - config.scrollIdleDuration * 1000) {
locateables = query(selector, document);
scrollPaddingTop = parseInt(getComputedStyle(document.documentElement).scrollPaddingTop, 10);
}
frameTime = time;
const boxes = locateables.map(box).sort(byTop);
let n = -1;
while (boxes[++n]) {
// Stop on locateable lower than the break
if (boxes[n].top >= scrollPaddingTop) {
break;
}
}
--n;
// Before the first or after the last locateable. (The latter
// should not be possible according to the above while loop)
if (n < 0 || n >= boxes.length) {
if (locatedNode) {
unlocate();
window.history.replaceState(nothing, '', '#');
}
return;
}
var node = locateables[n];
if (locatedNode && node === locatedNode) {
return;
}
unlocate();
locate(node);
window.history.replaceState(nothing, '', '#' + node.id);
}
function scroll(e) {
if (DEBUG) {
console.log(e.type, e.timeStamp, window.location.hash, document.scrollingElement.scrollTop);
}
const aMomentAgo = e.timeStamp - config.scrollIdleDuration * 1000;
// Keep a record of scrollTop in order to restore it in Safari,
// where popstate and hashchange are preceeded by a scroll jump
scrollTop = document.scrollingElement.scrollTop;
// For a moment after the last hashchange dont update while
// smooth scrolling settles to the right place.
if (hashTime > aMomentAgo) {
hashTime = e.timeStamp;
return;
}
// Is frame already cued?
if (frame) {
return;
}
frame = requestAnimationFrame(update);
}
function popstate(e) {
if (DEBUG) {
console.log(e.type, e.timeStamp, window.location.hash, document.scrollingElement.scrollTop);
}
// Record the timeStamp
hashTime = e.timeStamp;
// Remove current located
unlocate();
const hash = window.location.hash;
const id = hash.slice(1);
if (!id) {
if (!features.scrollBehavior) {
// In Safari, popstate and hashchange are preceeded by scroll jump -
// restore previous scrollTop.
document.scrollingElement.scrollTop = scrollTop;
// Then animate
document.body.scrollIntoView(scrollOptions);
}
return;
}
// Is there a node with that id?
const node = document.getElementById(id);
if (!node) { return; }
// The page is on the move
locate(node);
// Implement smooth scroll for browsers that do not have it
if (!features.scrollBehavior) {
// In Safari, popstate and hashchange are preceeded by scroll jump -
// restore previous scrollTop.
document.scrollingElement.scrollTop = scrollTop;
// Then animate
node.scrollIntoView(scrollOptions);
}
}
function load(e) {
popstate(e);
scroll(e);
// Start listening to popstate and scroll
window.addEventListener('popstate', popstate);
window.addEventListener('scroll', scroll);
// Scroll smoothly from now on
scrollOptions.behavior = 'smooth';
}
window.addEventListener('load', load);
|
Fix 1px scrollTopError
|
js/locateable.js
|
Fix 1px scrollTopError
|
<ide><path>s/locateable.js
<ide>
<ide> while (boxes[++n]) {
<ide> // Stop on locateable lower than the break
<del> if (boxes[n].top >= scrollPaddingTop) {
<add> if (boxes[n].top > scrollPaddingTop + 1) {
<ide> break;
<ide> }
<ide> }
|
|
JavaScript
|
isc
|
fd17d20dfd1dddf7d8febae00915c8d585d55010
| 0 |
gorillamania/node_geoip_server
|
/* vim: set expandtab tabstop=2 shiftwidth=2: */
// Load the http module to create an http server.
var geoip = require('geoip'),
path = require('path'),
http = require('http'),
url = require('url');
// Command line options
var args = require('optimist')
.options('port', {
default: 9042,
alias: 'p'
}).describe('port', 'port to run the server on')
.options('geodb', {
default: './GeoLiteCity.dat',
alias: 'g'
}).describe('geodb', 'path to the GeoLiteCity database from MaxMind')
.options('help', {
default: false,
alias: 'h'
}).describe('help', 'this help message')
.alias('help', '?')
.usage("Usage: $0");
var argv = args.argv;
if (argv.help) {
args.showHelp();
process.exit(0);
}
// Can we open the geo database?
if (! path.existsSync(argv.geodb)) {
console.error("The geodb file doesn't exist: %s", argv.geodb);
process.exit(1);
}
try {
var city = new geoip.City(argv.geodb);
} catch(e) {
console.error("Error loading the geodb file: %s", e);
console.trace(e);
process.exit(1);
}
function getIp(request) {
var get = url.parse(request.url, true).query;
if (get.ip) {
return get.ip;
} else if (request.headers['x-forwarded-for']) {
// TODO: parse multi level x-forwarded-for
return request.headers['x-forwarded-for'];
} else {
return request.connection.remoteAddress;
}
}
function formatResult(request, lookup) {
var get = url.parse(request.url, true).query,
json = JSON.stringify(lookup);
if (get.callback) {
var callback = get.callback.replace(/[^A-Za-z.\_$]/, '_');
return callback + '(' + json + ')';
} else {
return json;
}
}
// Configure our HTTP server to respond
var server = http.createServer(function (request, response) {
var ip = getIp(request);
city.lookup(ip, function(err, data) {
if (err) {
console.error("lookup failed for ", ip, err);
response.writeHead(200, {"Content-Type": "text/javascript"});
response.end(formatResult(request, {}));
} else if (data) {
console.log("lookup worked for ip", ip);
response.writeHead(200, {"Content-Type": "text/javascript"});
response.end(formatResult(request, data));
}
});
});
server.listen(argv.port);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:%s/, using %s", argv.port, argv.geodb);
|
app.js
|
/* vim: set expandtab tabstop=2 shiftwidth=2: */
// Load the http module to create an http server.
var geoip = require('geoip'),
path = require('path'),
http = require('http'),
url = require('url');
// Command line options
var args = require('optimist')
.options('port', {
default: 9042,
alias: 'p'
}).describe('port', 'port to run the server on')
.options('geodb', {
default: './GeoLiteCity.dat',
alias: 'g'
}).describe('geodb', 'path to the GeoLiteCity database from MaxMind')
.options('help', {
default: false,
alias: 'h'
}).describe('help', 'this help message')
.alias('help', '?')
.usage("Usage: $0");
var argv = args.argv;
if (argv.help) {
args.showHelp();
process.exit(0);
}
// Can we open the geo database?
if (! path.existsSync(argv.geodb)) {
console.error("The geodb file doesn't exist: %s", argv.geodb);
process.exit(1);
}
try {
var city = new geoip.City(argv.geodb);
} catch(e) {
console.error("Error loading the geodb file: %s", e);
console.trace(e);
process.exit(1);
}
function getIp(request) {
var get = url.parse(request.url, true).query;
if (get.ip) {
return get.ip;
} else if (request.headers['x-forwarded-for']) {
// TODO: parse multi level x-forwarded-for
return request.headers['x-forwarded-for'];
} else {
return request.connection.remoteAddress;
}
}
function formatResult(request, lookup) {
var get = url.parse(request.url, true).query,
json = JSON.stringify(lookup);
if (get.callback) {
var callback = get.callback.replace(/[^A-Za-z.\_$]/, '_');
return callback + '(' + json + ')';
} else {
return json;
}
}
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
var ip = getIp(request);
city.lookup(ip, function(err, data) {
if (err) {
console.error("lookup failed for ", ip, err);
response.writeHead(200, {"Content-Type": "text/javascript"});
response.end(formatResult(request, {}));
} else if (data) {
console.log("lookup worked for ip", ip);
response.writeHead(200, {"Content-Type": "text/javascript"});
response.end(formatResult(request, data));
}
});
});
server.listen(argv.port);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:%s/, using %s", argv.port, argv.geodb);
|
clean up comment
|
app.js
|
clean up comment
|
<ide><path>pp.js
<ide> }
<ide> }
<ide>
<del>// Configure our HTTP server to respond with Hello World to all requests.
<add>// Configure our HTTP server to respond
<ide> var server = http.createServer(function (request, response) {
<ide> var ip = getIp(request);
<ide> city.lookup(ip, function(err, data) {
|
|
Java
|
mit
|
2f0fd89957a8c2d606b706b2122564288d5d2a6d
| 0 |
ggajos/ot-clean
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 opentangerine.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.opentangerine.clean;
import com.google.common.collect.Lists;
import com.jcabi.log.Logger;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;
import org.apache.commons.io.FileUtils;
/**
* This is initial class, should be changed to something else.
*
* // FIXME GG: in progress, refactor to more modular form
*
* @author Grzegorz Gajos ([email protected])
* @version $Id$
* @since 0.5
*/
interface Cleanable {
/**
* Clean. This method should cleanup specific path using provided
* delete handler.
*
* @param delete Deletion handler.
* @param path Working directory.
*/
void clean(final Delete delete, final Path path);
/**
* Display information about matching configuration.
*
* @param path Working directory.
* @param console Console.
*/
void display(final Path path, final Console console);
/**
* Check if matching.
*
* @param path Working directory.
* @return True if cleanable.
*/
boolean match(final Path path);
Cleanable MAVEN = new Definition(
"Maven",
path -> path.resolve("pom.xml").toFile().exists(),
(delete, path) -> delete.file(path.resolve("target"))
);
/**
* Cleanup Grails structure.
*/
Cleanable GRAILS_2 = new Definition(
"Grails 2",
path -> {
boolean success;
final File file = path
.resolve("application.properties")
.toFile();
try {
success = file.exists() && FileUtils
.readFileToString(file)
.contains("app.grails.version");
} catch (IOException ioe) {
Logger.debug(Cleanable.class, "Unable to read %s %[exception]s", file, ioe);
success = false;
}
return success;
},
(delete, path) -> {
Yconfig yconf = new Yconfig();
yconf.setDeletes(Lists.newArrayList("target", "**/*.log"));
yconf
.filesToDelete(path)
.forEach(delete::file);
}
);
/**
* Cleanup using yaml configuration file.
*/
Cleanable YCLEAN = new Definition(
".clean.yml",
path -> path.resolve(".clean.yml").toFile().exists(),
(delete, path) -> {
Yconfig
.load(path.resolve(".clean.yml").toFile())
.filesToDelete(path)
.forEach(delete::file);
}
);
/**
* List of all available cleaners.
*/
List<Cleanable> ALL = Lists.newArrayList(
MAVEN,
GRAILS_2,
YCLEAN
);
final class Definition implements Cleanable {
/**
* Name of the cleaning definition.
*/
private String name;
/**
* Matching behaviour.
*/
private Function<Path, Boolean> matcher;
/**
* Cleaning behaviour.
*/
private BiConsumer<Delete, Path> cleaner;
/**
* Ctor.
*
* @param cname Name of the cleaner.
* @param cmatcher Matching behaviour.
* @param ccleaner Cleaning behaviour.
*/
public Definition(
final String cname,
final Function<Path, Boolean> cmatcher,
final BiConsumer<Delete, Path> ccleaner
) {
this.name = cname;
this.matcher = cmatcher;
this.cleaner = ccleaner;
}
@Override
public void clean(final Delete delete, final Path path) {
if(this.match(path)) {
this.cleaner.accept(delete, path);
}
}
@Override
public boolean match(final Path path) {
return this.matcher.apply(path);
}
@Override
public void display(final Path path, final Console console) {
console.print(
String.format(
"[%s]: %s", this.name, path
)
);
}
}
}
|
src/main/java/com/opentangerine/clean/Cleanable.java
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 opentangerine.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.opentangerine.clean;
import com.google.common.collect.Lists;
import com.jcabi.log.Logger;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import org.apache.commons.io.FileUtils;
/**
* This is initial class, should be changed to something else.
*
* // FIXME GG: in progress, refactor to more modular form
*
* @author Grzegorz Gajos ([email protected])
* @version $Id$
* @since 0.5
*/
interface Cleanable {
/**
* Clean. This method should cleanup specific path using provided
* delete handler.
*
* @param delete Deletion handler.
* @param path Working directory.
*/
void clean(final Delete delete, final Path path);
/**
* Display information about matching configuration.
*
* @param path Working directory.
* @param console Console.
*/
void display(final Path path, final Console console);
/**
* Check if matching.
*
* @param path Working directory.
* @return True if cleanable.
*/
boolean match(final Path path);
Cleanable MAVEN = new Cleanable() {
@Override
public void clean(final Delete delete, final Path path) {
if (this.match(path)) {
delete.file(path.resolve("target"));
}
}
@Override
public boolean match(final Path path) {
return path.resolve("pom.xml").toFile().exists();
}
@Override
public void display(final Path path, final Console console) {
console.print(
String.format(
"[Maven]: %s", path
)
);
}
};
/**
* Cleanup Grails structure.
*/
Cleanable GRAILS_2 = new Cleanable() {
// FIXME GG: in progress, make it more dry
@Override
public void clean(final Delete delete, final Path path) {
if (this.match(path)) {
Yconfig yconf = new Yconfig();
yconf.setDeletes(Lists.newArrayList("target", "**/*.log"));
yconf
.filesToDelete(path)
.forEach(delete::file);
}
}
// FIXME GG: in progress, extract to different method
// and cleanup
@Override
public boolean match(final Path path) {
boolean success;
final File file = path
.resolve("application.properties")
.toFile();
try {
success = file.exists() && FileUtils
.readFileToString(file)
.contains("app.grails.version");
} catch (IOException ioe) {
Logger.debug(this, "Unable to read %s %[exception]s", file, ioe);
success = false;
}
return success;
}
@Override
public void display(final Path path, final Console console) {
console.print(
String.format(
"[Maven]: %s", path
)
);
}
};
/**
* Cleanup using yaml configuration file.
*/
Cleanable YCLEAN = new Cleanable() {
@Override
public void clean(final Delete delete, final Path path) {
if (this.match(path)) {
Yconfig
.load(file(path))
.filesToDelete(path)
.forEach(delete::file);
}
}
@Override
public boolean match(final Path path) {
return file(path).exists();
}
@Override
public void display(final Path path, final Console console) {
console.print(
String.format(
"[.clean.yml]: %s", path
)
);
}
/**
* Returns configuration file.
*
* @param path Working directory.
* @return Clean yml file.
*/
private File file(final Path path) {
return path.resolve(".clean.yml").toFile();
}
};
List<Cleanable> ALL = Lists.newArrayList(
MAVEN,
GRAILS_2,
YCLEAN
);
}
|
0.11: refactoring, snapshot 4
|
src/main/java/com/opentangerine/clean/Cleanable.java
|
0.11: refactoring, snapshot 4
|
<ide><path>rc/main/java/com/opentangerine/clean/Cleanable.java
<ide> import java.io.IOException;
<ide> import java.nio.file.Path;
<ide> import java.util.List;
<add>import java.util.function.BiConsumer;
<add>import java.util.function.Function;
<ide> import org.apache.commons.io.FileUtils;
<ide>
<ide> /**
<ide> */
<ide> boolean match(final Path path);
<ide>
<del> Cleanable MAVEN = new Cleanable() {
<del>
<del> @Override
<del> public void clean(final Delete delete, final Path path) {
<del> if (this.match(path)) {
<del> delete.file(path.resolve("target"));
<del> }
<del> }
<del>
<del> @Override
<del> public boolean match(final Path path) {
<del> return path.resolve("pom.xml").toFile().exists();
<del> }
<del>
<del> @Override
<del> public void display(final Path path, final Console console) {
<del> console.print(
<del> String.format(
<del> "[Maven]: %s", path
<del> )
<del> );
<del> }
<del> };
<add> Cleanable MAVEN = new Definition(
<add> "Maven",
<add> path -> path.resolve("pom.xml").toFile().exists(),
<add> (delete, path) -> delete.file(path.resolve("target"))
<add> );
<ide>
<ide> /**
<ide> * Cleanup Grails structure.
<ide> */
<del> Cleanable GRAILS_2 = new Cleanable() {
<del>
<del> // FIXME GG: in progress, make it more dry
<del> @Override
<del> public void clean(final Delete delete, final Path path) {
<del> if (this.match(path)) {
<del> Yconfig yconf = new Yconfig();
<del> yconf.setDeletes(Lists.newArrayList("target", "**/*.log"));
<del> yconf
<del> .filesToDelete(path)
<del> .forEach(delete::file);
<del> }
<del> }
<del>
<del> // FIXME GG: in progress, extract to different method
<del> // and cleanup
<del> @Override
<del> public boolean match(final Path path) {
<add> Cleanable GRAILS_2 = new Definition(
<add> "Grails 2",
<add> path -> {
<ide> boolean success;
<ide> final File file = path
<ide> .resolve("application.properties")
<ide> .readFileToString(file)
<ide> .contains("app.grails.version");
<ide> } catch (IOException ioe) {
<del> Logger.debug(this, "Unable to read %s %[exception]s", file, ioe);
<add> Logger.debug(Cleanable.class, "Unable to read %s %[exception]s", file, ioe);
<ide> success = false;
<ide> }
<ide> return success;
<add> },
<add> (delete, path) -> {
<add> Yconfig yconf = new Yconfig();
<add> yconf.setDeletes(Lists.newArrayList("target", "**/*.log"));
<add> yconf
<add> .filesToDelete(path)
<add> .forEach(delete::file);
<add> }
<add> );
<add>
<add> /**
<add> * Cleanup using yaml configuration file.
<add> */
<add> Cleanable YCLEAN = new Definition(
<add> ".clean.yml",
<add> path -> path.resolve(".clean.yml").toFile().exists(),
<add> (delete, path) -> {
<add> Yconfig
<add> .load(path.resolve(".clean.yml").toFile())
<add> .filesToDelete(path)
<add> .forEach(delete::file);
<add> }
<add> );
<add>
<add> /**
<add> * List of all available cleaners.
<add> */
<add> List<Cleanable> ALL = Lists.newArrayList(
<add> MAVEN,
<add> GRAILS_2,
<add> YCLEAN
<add> );
<add>
<add> final class Definition implements Cleanable {
<add>
<add> /**
<add> * Name of the cleaning definition.
<add> */
<add> private String name;
<add>
<add> /**
<add> * Matching behaviour.
<add> */
<add> private Function<Path, Boolean> matcher;
<add>
<add> /**
<add> * Cleaning behaviour.
<add> */
<add> private BiConsumer<Delete, Path> cleaner;
<add>
<add> /**
<add> * Ctor.
<add> *
<add> * @param cname Name of the cleaner.
<add> * @param cmatcher Matching behaviour.
<add> * @param ccleaner Cleaning behaviour.
<add> */
<add> public Definition(
<add> final String cname,
<add> final Function<Path, Boolean> cmatcher,
<add> final BiConsumer<Delete, Path> ccleaner
<add> ) {
<add> this.name = cname;
<add> this.matcher = cmatcher;
<add> this.cleaner = ccleaner;
<add> }
<add>
<add> @Override
<add> public void clean(final Delete delete, final Path path) {
<add> if(this.match(path)) {
<add> this.cleaner.accept(delete, path);
<add> }
<add> }
<add>
<add> @Override
<add> public boolean match(final Path path) {
<add> return this.matcher.apply(path);
<ide> }
<ide>
<ide> @Override
<ide> public void display(final Path path, final Console console) {
<ide> console.print(
<ide> String.format(
<del> "[Maven]: %s", path
<del> )
<del> );
<del> }
<del> };
<del>
<del> /**
<del> * Cleanup using yaml configuration file.
<del> */
<del> Cleanable YCLEAN = new Cleanable() {
<del>
<del> @Override
<del> public void clean(final Delete delete, final Path path) {
<del> if (this.match(path)) {
<del> Yconfig
<del> .load(file(path))
<del> .filesToDelete(path)
<del> .forEach(delete::file);
<del> }
<del> }
<del>
<del> @Override
<del> public boolean match(final Path path) {
<del> return file(path).exists();
<del> }
<del>
<del> @Override
<del> public void display(final Path path, final Console console) {
<del> console.print(
<del> String.format(
<del> "[.clean.yml]: %s", path
<add> "[%s]: %s", this.name, path
<ide> )
<ide> );
<ide> }
<ide>
<del> /**
<del> * Returns configuration file.
<del> *
<del> * @param path Working directory.
<del> * @return Clean yml file.
<del> */
<del> private File file(final Path path) {
<del> return path.resolve(".clean.yml").toFile();
<del> }
<add> }
<ide>
<del> };
<ide>
<del> List<Cleanable> ALL = Lists.newArrayList(
<del> MAVEN,
<del> GRAILS_2,
<del> YCLEAN
<del> );
<add>
<ide>
<ide> }
|
|
Java
|
lgpl-2.1
|
34c07a91e1568f0417ef99641d047d45ce417b49
| 0 |
KengoTODA/spotbugs,sewe/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs
|
/*
* Bytecode Analysis Framework
* Copyright (C) 2003, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.daveho.ba;
import org.apache.bcel.*;
import org.apache.bcel.generic.*;
/**
* A common base class for frame modeling visitors.
* This class provides a default implementation which copies values
* between frame slots whenever appropriate. For example, its handler
* for the ALOAD bytecode will get the value from the referenced
* local in the frame and push it onto the stack. Bytecodes which
* do something other than copying values are modeled by popping
* values as appropriate, and pushing the "default" value onto the stack
* for each stack slot produced, where the default value is the one
* returned by the getDefaultValue() method.
*
* <p> Subclasses should override the visit methods for any bytecode instructions
* which require special handling.
*
* @see Frame
* @see DataflowAnalysis
* @author David Hovemeyer
*/
public abstract class AbstractFrameModelingVisitor<Value> implements Visitor {
private Frame<Value> frame;
private ConstantPoolGen cpg;
/**
* Constructor.
* @param frame the frame to be transformed
* @param cpg the ConstantPoolGen of the method to be analyzed
*/
public AbstractFrameModelingVisitor(Frame<Value> frame, ConstantPoolGen cpg) {
this.frame = frame;
this.cpg = cpg;
}
/**
* Get the frame.
* @return the Frame object
*/
public Frame<Value> getFrame() { return frame; }
/**
* Produce a "default" value.
* This is what is pushed onto the stack by the
* handleNormalInstruction() method for instructions which produce stack values.
*/
public abstract Value getDefaultValue();
/**
* Get the number of words consumed by given instruction.
*/
public int getNumWordsConsumed(Instruction ins) {
int numWordsConsumed = ins.consumeStack(cpg);
if (numWordsConsumed == Constants.UNPREDICTABLE) throw new IllegalStateException();
return numWordsConsumed;
}
/**
* Get the number of words produced by given instruction.
*/
public int getNumWordsProduced(Instruction ins) {
int numWordsProduced = ins.produceStack(cpg);
if (numWordsProduced == Constants.UNPREDICTABLE) throw new IllegalStateException();
return numWordsProduced;
}
/**
* This is called for illegal bytecodes.
* @throws IllegalStateException
*/
private void illegalBytecode(Instruction ins) {
throw new IllegalStateException("Illegal bytecode: " + ins);
}
/* ----------------------------------------------------------------------
* Empty visit methods
* ---------------------------------------------------------------------- */
public void visitStackInstruction(StackInstruction obj) { }
public void visitLocalVariableInstruction(LocalVariableInstruction obj) { }
public void visitBranchInstruction(BranchInstruction obj) { }
public void visitLoadClass(LoadClass obj) { }
public void visitFieldInstruction(FieldInstruction obj) { }
public void visitIfInstruction(IfInstruction obj) { }
public void visitConversionInstruction(ConversionInstruction obj) { }
public void visitPopInstruction(PopInstruction obj) { }
public void visitJsrInstruction(JsrInstruction obj) { }
public void visitGotoInstruction(GotoInstruction obj) { }
public void visitStoreInstruction(StoreInstruction obj) { }
public void visitTypedInstruction(TypedInstruction obj) { }
public void visitSelect(Select obj) { }
public void visitUnconditionalBranch(UnconditionalBranch obj) { }
public void visitPushInstruction(PushInstruction obj) { }
public void visitArithmeticInstruction(ArithmeticInstruction obj) { }
public void visitCPInstruction(CPInstruction obj) { }
public void visitInvokeInstruction(InvokeInstruction obj) { }
public void visitArrayInstruction(ArrayInstruction obj) { }
public void visitAllocationInstruction(AllocationInstruction obj) { }
public void visitReturnInstruction(ReturnInstruction obj) { }
public void visitFieldOrMethod(FieldOrMethod obj) { }
public void visitConstantPushInstruction(ConstantPushInstruction obj) { }
public void visitExceptionThrower(ExceptionThrower obj) { }
public void visitLoadInstruction(LoadInstruction obj) { }
public void visitVariableLengthInstruction(VariableLengthInstruction obj) { }
public void visitStackProducer(StackProducer obj) { }
public void visitStackConsumer(StackConsumer obj) { }
/* ----------------------------------------------------------------------
* General instruction handlers
* ---------------------------------------------------------------------- */
/**
* Handler for all instructions which pop values from the stack
* and store them in a local variable. Note that two locals
* are stored into for long and double stores.
*/
public void handleStoreInstruction(StoreInstruction obj) {
try {
int numConsumed = obj.consumeStack(cpg);
if (numConsumed == Constants.UNPREDICTABLE) throw new IllegalStateException();
int index = obj.getIndex();
// Store values into consecutive locals corresponding
// to the order in which the values appeared on the stack.
while (numConsumed-- > 0) {
Value value = frame.popValue();
frame.setValue(index++, value);
}
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
/**
* Handler for all instructions which load values from a local variable
* and push them on the stack. Note that two locals are loaded for
* long and double loads.
*/
public void handleLoadInstruction(LoadInstruction obj) {
int numProduced = obj.produceStack(cpg);
if (numProduced == Constants.UNPREDICTABLE) throw new IllegalStateException();
int index = obj.getIndex() + numProduced;
// Load values from locals in reverse order.
// This restores them to the stack in a way consistent
// with visitStoreInstruction().
while (numProduced-- > 0) {
Value value = frame.getValue(--index);
frame.pushValue(value);
}
}
/**
* This is called to handle any instruction which does not simply
* copy values between stack slots.
*/
public void handleNormalInstruction(Instruction ins) {
modelNormalInstruction(ins, getNumWordsConsumed(ins), getNumWordsProduced(ins));
}
/**
* Model the stack for instructions handled by handleNormalInstruction().
* Subclasses may override to provide analysis-specific behavior.
*/
public void modelNormalInstruction(Instruction ins, int numWordsConsumed, int numWordsProduced) {
try {
while (numWordsConsumed-- > 0)
frame.popValue();
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
while (numWordsProduced-- > 0)
frame.pushValue(getDefaultValue());
}
/* ----------------------------------------------------------------------
* Visit methods for scalar STORE instructions
* ---------------------------------------------------------------------- */
public void visitASTORE(ASTORE obj) { handleStoreInstruction(obj); }
public void visitDSTORE(DSTORE obj) { handleStoreInstruction(obj); }
public void visitFSTORE(FSTORE obj) { handleStoreInstruction(obj); }
public void visitISTORE(ISTORE obj) { handleStoreInstruction(obj); }
public void visitLSTORE(LSTORE obj) { handleStoreInstruction(obj); }
/* ----------------------------------------------------------------------
* Visit methods for scalar LOAD instructions
* ---------------------------------------------------------------------- */
public void visitALOAD(ALOAD obj) { handleLoadInstruction(obj); }
public void visitDLOAD(DLOAD obj) { handleLoadInstruction(obj); }
public void visitFLOAD(FLOAD obj) { handleLoadInstruction(obj); }
public void visitILOAD(ILOAD obj) { handleLoadInstruction(obj); }
public void visitLLOAD(LLOAD obj) { handleLoadInstruction(obj); }
/* ----------------------------------------------------------------------
* Visit methods for POP, DUP, and SWAP instructions
* ---------------------------------------------------------------------- */
public void visitPOP(POP obj) { handleNormalInstruction(obj); }
public void visitPOP2(POP2 obj) { handleNormalInstruction(obj); }
public void visitDUP(DUP obj) {
try {
Value value = frame.popValue();
frame.pushValue(value);
frame.pushValue(value);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
public void visitDUP_X1(DUP_X1 obj) {
try {
Value value1 = frame.popValue();
Value value2 = frame.popValue();
frame.pushValue(value1);
frame.pushValue(value2);
frame.pushValue(value1);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
public void visitDUP_X2(DUP_X2 obj) {
try {
Value value1 = frame.popValue();
Value value2 = frame.popValue();
Value value3 = frame.popValue();
frame.pushValue(value1);
frame.pushValue(value3);
frame.pushValue(value2);
frame.pushValue(value1);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
public void visitDUP2(DUP2 obj) {
try {
Value value1 = frame.popValue();
Value value2 = frame.popValue();
frame.pushValue(value2);
frame.pushValue(value1);
frame.pushValue(value2);
frame.pushValue(value1);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
public void visitDUP2_X1(DUP2_X1 obj) {
try {
Value value1 = frame.popValue();
Value value2 = frame.popValue();
Value value3 = frame.popValue();
frame.pushValue(value2);
frame.pushValue(value1);
frame.pushValue(value3);
frame.pushValue(value2);
frame.pushValue(value1);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
public void visitDUP2_X2(DUP2_X2 obj) {
try {
Value value1 = frame.popValue();
Value value2 = frame.popValue();
Value value3 = frame.popValue();
Value value4 = frame.popValue();
frame.pushValue(value2);
frame.pushValue(value1);
frame.pushValue(value4);
frame.pushValue(value3);
frame.pushValue(value2);
frame.pushValue(value1);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
public void visitSWAP(SWAP obj) {
try {
Value value1 = frame.popValue();
Value value2 = frame.popValue();
frame.pushValue(value1);
frame.pushValue(value2);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
/* ----------------------------------------------------------------------
* Illegal bytecodes
* ---------------------------------------------------------------------- */
public void visitIMPDEP1(IMPDEP1 obj) { illegalBytecode(obj); }
public void visitIMPDEP2(IMPDEP2 obj) { illegalBytecode(obj); }
public void visitBREAKPOINT(BREAKPOINT obj) { illegalBytecode(obj); }
/* ----------------------------------------------------------------------
* Bytecodes that have "default" semantics
* ---------------------------------------------------------------------- */
public void visitACONST_NULL(ACONST_NULL obj) { handleNormalInstruction(obj); }
public void visitGETSTATIC(GETSTATIC obj) { handleNormalInstruction(obj); }
public void visitIF_ICMPLT(IF_ICMPLT obj) { handleNormalInstruction(obj); }
public void visitMONITOREXIT(MONITOREXIT obj) { handleNormalInstruction(obj); }
public void visitIFLT(IFLT obj) { handleNormalInstruction(obj); }
public void visitBASTORE(BASTORE obj) { handleNormalInstruction(obj); }
public void visitCHECKCAST(CHECKCAST obj) { handleNormalInstruction(obj); }
public void visitFCMPG(FCMPG obj) { handleNormalInstruction(obj); }
public void visitI2F(I2F obj) { handleNormalInstruction(obj); }
public void visitATHROW(ATHROW obj) { handleNormalInstruction(obj); }
public void visitDCMPL(DCMPL obj) { handleNormalInstruction(obj); }
public void visitARRAYLENGTH(ARRAYLENGTH obj) { handleNormalInstruction(obj); }
public void visitINVOKESTATIC(INVOKESTATIC obj) { handleNormalInstruction(obj); }
public void visitLCONST(LCONST obj) { handleNormalInstruction(obj); }
public void visitDREM(DREM obj) { handleNormalInstruction(obj); }
public void visitIFGE(IFGE obj) { handleNormalInstruction(obj); }
public void visitCALOAD(CALOAD obj) { handleNormalInstruction(obj); }
public void visitLASTORE(LASTORE obj) { handleNormalInstruction(obj); }
public void visitI2D(I2D obj) { handleNormalInstruction(obj); }
public void visitDADD(DADD obj) { handleNormalInstruction(obj); }
public void visitINVOKESPECIAL(INVOKESPECIAL obj) { handleNormalInstruction(obj); }
public void visitIAND(IAND obj) { handleNormalInstruction(obj); }
public void visitPUTFIELD(PUTFIELD obj) { handleNormalInstruction(obj); }
public void visitDCONST(DCONST obj) { handleNormalInstruction(obj); }
public void visitNEW(NEW obj) { handleNormalInstruction(obj); }
public void visitIFNULL(IFNULL obj) { handleNormalInstruction(obj); }
public void visitLSUB(LSUB obj) { handleNormalInstruction(obj); }
public void visitL2I(L2I obj) { handleNormalInstruction(obj); }
public void visitISHR(ISHR obj) { handleNormalInstruction(obj); }
public void visitTABLESWITCH(TABLESWITCH obj) { handleNormalInstruction(obj); }
public void visitIINC(IINC obj) { handleNormalInstruction(obj); }
public void visitDRETURN(DRETURN obj) { handleNormalInstruction(obj); }
public void visitDASTORE(DASTORE obj) { handleNormalInstruction(obj); }
public void visitIALOAD(IALOAD obj) { handleNormalInstruction(obj); }
public void visitDDIV(DDIV obj) { handleNormalInstruction(obj); }
public void visitIF_ICMPGE(IF_ICMPGE obj) { handleNormalInstruction(obj); }
public void visitLAND(LAND obj) { handleNormalInstruction(obj); }
public void visitIDIV(IDIV obj) { handleNormalInstruction(obj); }
public void visitLOR(LOR obj) { handleNormalInstruction(obj); }
public void visitCASTORE(CASTORE obj) { handleNormalInstruction(obj); }
public void visitFREM(FREM obj) { handleNormalInstruction(obj); }
public void visitLDC(LDC obj) { handleNormalInstruction(obj); }
public void visitBIPUSH(BIPUSH obj) { handleNormalInstruction(obj); }
public void visitF2L(F2L obj) { handleNormalInstruction(obj); }
public void visitFMUL(FMUL obj) { handleNormalInstruction(obj); }
public void visitJSR(JSR obj) { handleNormalInstruction(obj); }
public void visitFSUB(FSUB obj) { handleNormalInstruction(obj); }
public void visitSASTORE(SASTORE obj) { handleNormalInstruction(obj); }
public void visitRETURN(RETURN obj) { handleNormalInstruction(obj); }
public void visitDALOAD(DALOAD obj) { handleNormalInstruction(obj); }
public void visitSIPUSH(SIPUSH obj) { handleNormalInstruction(obj); }
public void visitDSUB(DSUB obj) { handleNormalInstruction(obj); }
public void visitL2F(L2F obj) { handleNormalInstruction(obj); }
public void visitIF_ICMPGT(IF_ICMPGT obj) { handleNormalInstruction(obj); }
public void visitF2D(F2D obj) { handleNormalInstruction(obj); }
public void visitI2L(I2L obj) { handleNormalInstruction(obj); }
public void visitIF_ACMPNE(IF_ACMPNE obj) { handleNormalInstruction(obj); }
public void visitI2S(I2S obj) { handleNormalInstruction(obj); }
public void visitIFEQ(IFEQ obj) { handleNormalInstruction(obj); }
public void visitIOR(IOR obj) { handleNormalInstruction(obj); }
public void visitIREM(IREM obj) { handleNormalInstruction(obj); }
public void visitIASTORE(IASTORE obj) { handleNormalInstruction(obj); }
public void visitNEWARRAY(NEWARRAY obj) { handleNormalInstruction(obj); }
public void visitINVOKEINTERFACE(INVOKEINTERFACE obj) { handleNormalInstruction(obj); }
public void visitINEG(INEG obj) { handleNormalInstruction(obj); }
public void visitLCMP(LCMP obj) { handleNormalInstruction(obj); }
public void visitJSR_W(JSR_W obj) { handleNormalInstruction(obj); }
public void visitMULTIANEWARRAY(MULTIANEWARRAY obj) { handleNormalInstruction(obj); }
public void visitSALOAD(SALOAD obj) { handleNormalInstruction(obj); }
public void visitIFNONNULL(IFNONNULL obj) { handleNormalInstruction(obj); }
public void visitDMUL(DMUL obj) { handleNormalInstruction(obj); }
public void visitIFNE(IFNE obj) { handleNormalInstruction(obj); }
public void visitIF_ICMPLE(IF_ICMPLE obj) { handleNormalInstruction(obj); }
public void visitLDC2_W(LDC2_W obj) { handleNormalInstruction(obj); }
public void visitGETFIELD(GETFIELD obj) { handleNormalInstruction(obj); }
public void visitLADD(LADD obj) { handleNormalInstruction(obj); }
public void visitNOP(NOP obj) { handleNormalInstruction(obj); }
public void visitFALOAD(FALOAD obj) { handleNormalInstruction(obj); }
public void visitINSTANCEOF(INSTANCEOF obj) { handleNormalInstruction(obj); }
public void visitIFLE(IFLE obj) { handleNormalInstruction(obj); }
public void visitLXOR(LXOR obj) { handleNormalInstruction(obj); }
public void visitLRETURN(LRETURN obj) { handleNormalInstruction(obj); }
public void visitFCONST(FCONST obj) { handleNormalInstruction(obj); }
public void visitIUSHR(IUSHR obj) { handleNormalInstruction(obj); }
public void visitBALOAD(BALOAD obj) { handleNormalInstruction(obj); }
public void visitIF_ACMPEQ(IF_ACMPEQ obj) { handleNormalInstruction(obj); }
public void visitMONITORENTER(MONITORENTER obj) { handleNormalInstruction(obj); }
public void visitLSHL(LSHL obj) { handleNormalInstruction(obj); }
public void visitDCMPG(DCMPG obj) { handleNormalInstruction(obj); }
public void visitD2L(D2L obj) { handleNormalInstruction(obj); }
public void visitL2D(L2D obj) { handleNormalInstruction(obj); }
public void visitRET(RET obj) { handleNormalInstruction(obj); }
public void visitIFGT(IFGT obj) { handleNormalInstruction(obj); }
public void visitIXOR(IXOR obj) { handleNormalInstruction(obj); }
public void visitINVOKEVIRTUAL(INVOKEVIRTUAL obj) { handleNormalInstruction(obj); }
public void visitFASTORE(FASTORE obj) { handleNormalInstruction(obj); }
public void visitIRETURN(IRETURN obj) { handleNormalInstruction(obj); }
public void visitIF_ICMPNE(IF_ICMPNE obj) { handleNormalInstruction(obj); }
public void visitLDIV(LDIV obj) { handleNormalInstruction(obj); }
public void visitPUTSTATIC(PUTSTATIC obj) { handleNormalInstruction(obj); }
public void visitAALOAD(AALOAD obj) { handleNormalInstruction(obj); }
public void visitD2I(D2I obj) { handleNormalInstruction(obj); }
public void visitIF_ICMPEQ(IF_ICMPEQ obj) { handleNormalInstruction(obj); }
public void visitAASTORE(AASTORE obj) { handleNormalInstruction(obj); }
public void visitARETURN(ARETURN obj) { handleNormalInstruction(obj); }
public void visitFNEG(FNEG obj) { handleNormalInstruction(obj); }
public void visitGOTO_W(GOTO_W obj) { handleNormalInstruction(obj); }
public void visitD2F(D2F obj) { handleNormalInstruction(obj); }
public void visitGOTO(GOTO obj) { handleNormalInstruction(obj); }
public void visitISUB(ISUB obj) { handleNormalInstruction(obj); }
public void visitF2I(F2I obj) { handleNormalInstruction(obj); }
public void visitDNEG(DNEG obj) { handleNormalInstruction(obj); }
public void visitICONST(ICONST obj) { handleNormalInstruction(obj); }
public void visitFDIV(FDIV obj) { handleNormalInstruction(obj); }
public void visitI2B(I2B obj) { handleNormalInstruction(obj); }
public void visitLNEG(LNEG obj) { handleNormalInstruction(obj); }
public void visitLREM(LREM obj) { handleNormalInstruction(obj); }
public void visitIMUL(IMUL obj) { handleNormalInstruction(obj); }
public void visitIADD(IADD obj) { handleNormalInstruction(obj); }
public void visitLSHR(LSHR obj) { handleNormalInstruction(obj); }
public void visitLOOKUPSWITCH(LOOKUPSWITCH obj) { handleNormalInstruction(obj); }
public void visitFCMPL(FCMPL obj) { handleNormalInstruction(obj); }
public void visitI2C(I2C obj) { handleNormalInstruction(obj); }
public void visitLMUL(LMUL obj) { handleNormalInstruction(obj); }
public void visitLUSHR(LUSHR obj) { handleNormalInstruction(obj); }
public void visitISHL(ISHL obj) { handleNormalInstruction(obj); }
public void visitLALOAD(LALOAD obj) { handleNormalInstruction(obj); }
public void visitANEWARRAY(ANEWARRAY obj) { handleNormalInstruction(obj); }
public void visitFRETURN(FRETURN obj) { handleNormalInstruction(obj); }
public void visitFADD(FADD obj) { handleNormalInstruction(obj); }
}
// vim:ts=4
|
findbugs/src/java/edu/umd/cs/findbugs/ba/AbstractFrameModelingVisitor.java
|
/*
* Bytecode Analysis Framework
* Copyright (C) 2003, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.daveho.ba;
import org.apache.bcel.*;
import org.apache.bcel.generic.*;
/**
* A common base class for frame modeling visitors.
* This class provides a default implementation which copies values
* between frame slots whenever appropriate. For example, its handler
* for the ALOAD bytecode will get the value from the referenced
* local in the frame and push it onto the stack. Bytecodes which
* do something other than copying values are modeled by popping
* values as appropriate, and pushing the "default" value onto the stack
* for each stack slot produced, where the default value is the one
* returned by the getDefaultValue() method.
*
* <p> Subclasses should override the visit methods for any bytecode instructions
* which require special handling.
*
* @see Frame
* @see DataflowAnalysis
* @author David Hovemeyer
*/
public abstract class AbstractFrameModelingVisitor<Value> implements Visitor {
private Frame<Value> frame;
private ConstantPoolGen cpg;
/**
* Constructor.
* @param frame the frame to be transformed
* @param cpg the ConstantPoolGen of the method to be analyzed
*/
public AbstractFrameModelingVisitor(Frame<Value> frame, ConstantPoolGen cpg) {
this.frame = frame;
this.cpg = cpg;
}
/**
* Get the frame.
* @return the Frame object
*/
public Frame<Value> getFrame() { return frame; }
/**
* Produce a "default" value.
* This is what is pushed onto the stack by the
* handleNormalInstruction() method for instructions which produce stack values.
*/
public abstract Value getDefaultValue();
/**
* This is called for illegal bytecodes.
* @throws IllegalStateException
*/
private void illegalBytecode(Instruction ins) {
throw new IllegalStateException("Illegal bytecode: " + ins);
}
/* ----------------------------------------------------------------------
* Empty visit methods
* ---------------------------------------------------------------------- */
public void visitStackInstruction(StackInstruction obj) { }
public void visitLocalVariableInstruction(LocalVariableInstruction obj) { }
public void visitBranchInstruction(BranchInstruction obj) { }
public void visitLoadClass(LoadClass obj) { }
public void visitFieldInstruction(FieldInstruction obj) { }
public void visitIfInstruction(IfInstruction obj) { }
public void visitConversionInstruction(ConversionInstruction obj) { }
public void visitPopInstruction(PopInstruction obj) { }
public void visitJsrInstruction(JsrInstruction obj) { }
public void visitGotoInstruction(GotoInstruction obj) { }
public void visitStoreInstruction(StoreInstruction obj) { }
public void visitTypedInstruction(TypedInstruction obj) { }
public void visitSelect(Select obj) { }
public void visitUnconditionalBranch(UnconditionalBranch obj) { }
public void visitPushInstruction(PushInstruction obj) { }
public void visitArithmeticInstruction(ArithmeticInstruction obj) { }
public void visitCPInstruction(CPInstruction obj) { }
public void visitInvokeInstruction(InvokeInstruction obj) { }
public void visitArrayInstruction(ArrayInstruction obj) { }
public void visitAllocationInstruction(AllocationInstruction obj) { }
public void visitReturnInstruction(ReturnInstruction obj) { }
public void visitFieldOrMethod(FieldOrMethod obj) { }
public void visitConstantPushInstruction(ConstantPushInstruction obj) { }
public void visitExceptionThrower(ExceptionThrower obj) { }
public void visitLoadInstruction(LoadInstruction obj) { }
public void visitVariableLengthInstruction(VariableLengthInstruction obj) { }
public void visitStackProducer(StackProducer obj) { }
public void visitStackConsumer(StackConsumer obj) { }
/* ----------------------------------------------------------------------
* General instruction handlers
* ---------------------------------------------------------------------- */
/**
* Handler for all instructions which pop values from the stack
* and store them in a local variable. Note that two locals
* are stored into for long and double stores.
*/
public void handleStoreInstruction(StoreInstruction obj) {
try {
int numConsumed = obj.consumeStack(cpg);
if (numConsumed == Constants.UNPREDICTABLE) throw new IllegalStateException();
int index = obj.getIndex();
// Store values into consecutive locals corresponding
// to the order in which the values appeared on the stack.
while (numConsumed-- > 0) {
Value value = frame.popValue();
frame.setValue(index++, value);
}
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
/**
* Handler for all instructions which load values from a local variable
* and push them on the stack. Note that two locals are loaded for
* long and double loads.
*/
public void handleLoadInstruction(LoadInstruction obj) {
int numProduced = obj.produceStack(cpg);
if (numProduced == Constants.UNPREDICTABLE) throw new IllegalStateException();
int index = obj.getIndex() + numProduced;
// Load values from locals in reverse order.
// This restores them to the stack in a way consistent
// with visitStoreInstruction().
while (numProduced-- > 0) {
Value value = frame.getValue(--index);
frame.pushValue(value);
}
}
/**
* "Normal" handler.
* This models the stack for all instructions which destroy
* any values they consume, and produce only "default" values.
*/
public void handleNormalInstruction(Instruction ins) {
int nwords;
nwords = ins.consumeStack(cpg);
if (nwords == Constants.UNPREDICTABLE) throw new IllegalStateException();
try {
while (nwords-- > 0)
frame.popValue();
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
nwords = ins.produceStack(cpg);
if (nwords == Constants.UNPREDICTABLE) throw new IllegalStateException();
while (nwords-- > 0)
frame.pushValue(getDefaultValue());
}
/* ----------------------------------------------------------------------
* Visit methods for scalar STORE instructions
* ---------------------------------------------------------------------- */
public void visitASTORE(ASTORE obj) { handleStoreInstruction(obj); }
public void visitDSTORE(DSTORE obj) { handleStoreInstruction(obj); }
public void visitFSTORE(FSTORE obj) { handleStoreInstruction(obj); }
public void visitISTORE(ISTORE obj) { handleStoreInstruction(obj); }
public void visitLSTORE(LSTORE obj) { handleStoreInstruction(obj); }
/* ----------------------------------------------------------------------
* Visit methods for scalar LOAD instructions
* ---------------------------------------------------------------------- */
public void visitALOAD(ALOAD obj) { handleLoadInstruction(obj); }
public void visitDLOAD(DLOAD obj) { handleLoadInstruction(obj); }
public void visitFLOAD(FLOAD obj) { handleLoadInstruction(obj); }
public void visitILOAD(ILOAD obj) { handleLoadInstruction(obj); }
public void visitLLOAD(LLOAD obj) { handleLoadInstruction(obj); }
/* ----------------------------------------------------------------------
* Visit methods for POP, DUP, and SWAP instructions
* ---------------------------------------------------------------------- */
public void visitPOP(POP obj) { handleNormalInstruction(obj); }
public void visitPOP2(POP2 obj) { handleNormalInstruction(obj); }
public void visitDUP(DUP obj) {
try {
Value value = frame.popValue();
frame.pushValue(value);
frame.pushValue(value);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
public void visitDUP_X1(DUP_X1 obj) {
try {
Value value1 = frame.popValue();
Value value2 = frame.popValue();
frame.pushValue(value1);
frame.pushValue(value2);
frame.pushValue(value1);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
public void visitDUP_X2(DUP_X2 obj) {
try {
Value value1 = frame.popValue();
Value value2 = frame.popValue();
Value value3 = frame.popValue();
frame.pushValue(value1);
frame.pushValue(value3);
frame.pushValue(value2);
frame.pushValue(value1);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
public void visitDUP2(DUP2 obj) {
try {
Value value1 = frame.popValue();
Value value2 = frame.popValue();
frame.pushValue(value2);
frame.pushValue(value1);
frame.pushValue(value2);
frame.pushValue(value1);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
public void visitDUP2_X1(DUP2_X1 obj) {
try {
Value value1 = frame.popValue();
Value value2 = frame.popValue();
Value value3 = frame.popValue();
frame.pushValue(value2);
frame.pushValue(value1);
frame.pushValue(value3);
frame.pushValue(value2);
frame.pushValue(value1);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
public void visitDUP2_X2(DUP2_X2 obj) {
try {
Value value1 = frame.popValue();
Value value2 = frame.popValue();
Value value3 = frame.popValue();
Value value4 = frame.popValue();
frame.pushValue(value2);
frame.pushValue(value1);
frame.pushValue(value4);
frame.pushValue(value3);
frame.pushValue(value2);
frame.pushValue(value1);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
public void visitSWAP(SWAP obj) {
try {
Value value1 = frame.popValue();
Value value2 = frame.popValue();
frame.pushValue(value1);
frame.pushValue(value2);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException(e.toString());
}
}
/* ----------------------------------------------------------------------
* Illegal bytecodes
* ---------------------------------------------------------------------- */
public void visitIMPDEP1(IMPDEP1 obj) { illegalBytecode(obj); }
public void visitIMPDEP2(IMPDEP2 obj) { illegalBytecode(obj); }
public void visitBREAKPOINT(BREAKPOINT obj) { illegalBytecode(obj); }
/* ----------------------------------------------------------------------
* Bytecodes that have "default" semantics
* ---------------------------------------------------------------------- */
public void visitACONST_NULL(ACONST_NULL obj) { handleNormalInstruction(obj); }
public void visitGETSTATIC(GETSTATIC obj) { handleNormalInstruction(obj); }
public void visitIF_ICMPLT(IF_ICMPLT obj) { handleNormalInstruction(obj); }
public void visitMONITOREXIT(MONITOREXIT obj) { handleNormalInstruction(obj); }
public void visitIFLT(IFLT obj) { handleNormalInstruction(obj); }
public void visitBASTORE(BASTORE obj) { handleNormalInstruction(obj); }
public void visitCHECKCAST(CHECKCAST obj) { handleNormalInstruction(obj); }
public void visitFCMPG(FCMPG obj) { handleNormalInstruction(obj); }
public void visitI2F(I2F obj) { handleNormalInstruction(obj); }
public void visitATHROW(ATHROW obj) { handleNormalInstruction(obj); }
public void visitDCMPL(DCMPL obj) { handleNormalInstruction(obj); }
public void visitARRAYLENGTH(ARRAYLENGTH obj) { handleNormalInstruction(obj); }
public void visitINVOKESTATIC(INVOKESTATIC obj) { handleNormalInstruction(obj); }
public void visitLCONST(LCONST obj) { handleNormalInstruction(obj); }
public void visitDREM(DREM obj) { handleNormalInstruction(obj); }
public void visitIFGE(IFGE obj) { handleNormalInstruction(obj); }
public void visitCALOAD(CALOAD obj) { handleNormalInstruction(obj); }
public void visitLASTORE(LASTORE obj) { handleNormalInstruction(obj); }
public void visitI2D(I2D obj) { handleNormalInstruction(obj); }
public void visitDADD(DADD obj) { handleNormalInstruction(obj); }
public void visitINVOKESPECIAL(INVOKESPECIAL obj) { handleNormalInstruction(obj); }
public void visitIAND(IAND obj) { handleNormalInstruction(obj); }
public void visitPUTFIELD(PUTFIELD obj) { handleNormalInstruction(obj); }
public void visitDCONST(DCONST obj) { handleNormalInstruction(obj); }
public void visitNEW(NEW obj) { handleNormalInstruction(obj); }
public void visitIFNULL(IFNULL obj) { handleNormalInstruction(obj); }
public void visitLSUB(LSUB obj) { handleNormalInstruction(obj); }
public void visitL2I(L2I obj) { handleNormalInstruction(obj); }
public void visitISHR(ISHR obj) { handleNormalInstruction(obj); }
public void visitTABLESWITCH(TABLESWITCH obj) { handleNormalInstruction(obj); }
public void visitIINC(IINC obj) { handleNormalInstruction(obj); }
public void visitDRETURN(DRETURN obj) { handleNormalInstruction(obj); }
public void visitDASTORE(DASTORE obj) { handleNormalInstruction(obj); }
public void visitIALOAD(IALOAD obj) { handleNormalInstruction(obj); }
public void visitDDIV(DDIV obj) { handleNormalInstruction(obj); }
public void visitIF_ICMPGE(IF_ICMPGE obj) { handleNormalInstruction(obj); }
public void visitLAND(LAND obj) { handleNormalInstruction(obj); }
public void visitIDIV(IDIV obj) { handleNormalInstruction(obj); }
public void visitLOR(LOR obj) { handleNormalInstruction(obj); }
public void visitCASTORE(CASTORE obj) { handleNormalInstruction(obj); }
public void visitFREM(FREM obj) { handleNormalInstruction(obj); }
public void visitLDC(LDC obj) { handleNormalInstruction(obj); }
public void visitBIPUSH(BIPUSH obj) { handleNormalInstruction(obj); }
public void visitF2L(F2L obj) { handleNormalInstruction(obj); }
public void visitFMUL(FMUL obj) { handleNormalInstruction(obj); }
public void visitJSR(JSR obj) { handleNormalInstruction(obj); }
public void visitFSUB(FSUB obj) { handleNormalInstruction(obj); }
public void visitSASTORE(SASTORE obj) { handleNormalInstruction(obj); }
public void visitRETURN(RETURN obj) { handleNormalInstruction(obj); }
public void visitDALOAD(DALOAD obj) { handleNormalInstruction(obj); }
public void visitSIPUSH(SIPUSH obj) { handleNormalInstruction(obj); }
public void visitDSUB(DSUB obj) { handleNormalInstruction(obj); }
public void visitL2F(L2F obj) { handleNormalInstruction(obj); }
public void visitIF_ICMPGT(IF_ICMPGT obj) { handleNormalInstruction(obj); }
public void visitF2D(F2D obj) { handleNormalInstruction(obj); }
public void visitI2L(I2L obj) { handleNormalInstruction(obj); }
public void visitIF_ACMPNE(IF_ACMPNE obj) { handleNormalInstruction(obj); }
public void visitI2S(I2S obj) { handleNormalInstruction(obj); }
public void visitIFEQ(IFEQ obj) { handleNormalInstruction(obj); }
public void visitIOR(IOR obj) { handleNormalInstruction(obj); }
public void visitIREM(IREM obj) { handleNormalInstruction(obj); }
public void visitIASTORE(IASTORE obj) { handleNormalInstruction(obj); }
public void visitNEWARRAY(NEWARRAY obj) { handleNormalInstruction(obj); }
public void visitINVOKEINTERFACE(INVOKEINTERFACE obj) { handleNormalInstruction(obj); }
public void visitINEG(INEG obj) { handleNormalInstruction(obj); }
public void visitLCMP(LCMP obj) { handleNormalInstruction(obj); }
public void visitJSR_W(JSR_W obj) { handleNormalInstruction(obj); }
public void visitMULTIANEWARRAY(MULTIANEWARRAY obj) { handleNormalInstruction(obj); }
public void visitSALOAD(SALOAD obj) { handleNormalInstruction(obj); }
public void visitIFNONNULL(IFNONNULL obj) { handleNormalInstruction(obj); }
public void visitDMUL(DMUL obj) { handleNormalInstruction(obj); }
public void visitIFNE(IFNE obj) { handleNormalInstruction(obj); }
public void visitIF_ICMPLE(IF_ICMPLE obj) { handleNormalInstruction(obj); }
public void visitLDC2_W(LDC2_W obj) { handleNormalInstruction(obj); }
public void visitGETFIELD(GETFIELD obj) { handleNormalInstruction(obj); }
public void visitLADD(LADD obj) { handleNormalInstruction(obj); }
public void visitNOP(NOP obj) { handleNormalInstruction(obj); }
public void visitFALOAD(FALOAD obj) { handleNormalInstruction(obj); }
public void visitINSTANCEOF(INSTANCEOF obj) { handleNormalInstruction(obj); }
public void visitIFLE(IFLE obj) { handleNormalInstruction(obj); }
public void visitLXOR(LXOR obj) { handleNormalInstruction(obj); }
public void visitLRETURN(LRETURN obj) { handleNormalInstruction(obj); }
public void visitFCONST(FCONST obj) { handleNormalInstruction(obj); }
public void visitIUSHR(IUSHR obj) { handleNormalInstruction(obj); }
public void visitBALOAD(BALOAD obj) { handleNormalInstruction(obj); }
public void visitIF_ACMPEQ(IF_ACMPEQ obj) { handleNormalInstruction(obj); }
public void visitMONITORENTER(MONITORENTER obj) { handleNormalInstruction(obj); }
public void visitLSHL(LSHL obj) { handleNormalInstruction(obj); }
public void visitDCMPG(DCMPG obj) { handleNormalInstruction(obj); }
public void visitD2L(D2L obj) { handleNormalInstruction(obj); }
public void visitL2D(L2D obj) { handleNormalInstruction(obj); }
public void visitRET(RET obj) { handleNormalInstruction(obj); }
public void visitIFGT(IFGT obj) { handleNormalInstruction(obj); }
public void visitIXOR(IXOR obj) { handleNormalInstruction(obj); }
public void visitINVOKEVIRTUAL(INVOKEVIRTUAL obj) { handleNormalInstruction(obj); }
public void visitFASTORE(FASTORE obj) { handleNormalInstruction(obj); }
public void visitIRETURN(IRETURN obj) { handleNormalInstruction(obj); }
public void visitIF_ICMPNE(IF_ICMPNE obj) { handleNormalInstruction(obj); }
public void visitLDIV(LDIV obj) { handleNormalInstruction(obj); }
public void visitPUTSTATIC(PUTSTATIC obj) { handleNormalInstruction(obj); }
public void visitAALOAD(AALOAD obj) { handleNormalInstruction(obj); }
public void visitD2I(D2I obj) { handleNormalInstruction(obj); }
public void visitIF_ICMPEQ(IF_ICMPEQ obj) { handleNormalInstruction(obj); }
public void visitAASTORE(AASTORE obj) { handleNormalInstruction(obj); }
public void visitARETURN(ARETURN obj) { handleNormalInstruction(obj); }
public void visitFNEG(FNEG obj) { handleNormalInstruction(obj); }
public void visitGOTO_W(GOTO_W obj) { handleNormalInstruction(obj); }
public void visitD2F(D2F obj) { handleNormalInstruction(obj); }
public void visitGOTO(GOTO obj) { handleNormalInstruction(obj); }
public void visitISUB(ISUB obj) { handleNormalInstruction(obj); }
public void visitF2I(F2I obj) { handleNormalInstruction(obj); }
public void visitDNEG(DNEG obj) { handleNormalInstruction(obj); }
public void visitICONST(ICONST obj) { handleNormalInstruction(obj); }
public void visitFDIV(FDIV obj) { handleNormalInstruction(obj); }
public void visitI2B(I2B obj) { handleNormalInstruction(obj); }
public void visitLNEG(LNEG obj) { handleNormalInstruction(obj); }
public void visitLREM(LREM obj) { handleNormalInstruction(obj); }
public void visitIMUL(IMUL obj) { handleNormalInstruction(obj); }
public void visitIADD(IADD obj) { handleNormalInstruction(obj); }
public void visitLSHR(LSHR obj) { handleNormalInstruction(obj); }
public void visitLOOKUPSWITCH(LOOKUPSWITCH obj) { handleNormalInstruction(obj); }
public void visitFCMPL(FCMPL obj) { handleNormalInstruction(obj); }
public void visitI2C(I2C obj) { handleNormalInstruction(obj); }
public void visitLMUL(LMUL obj) { handleNormalInstruction(obj); }
public void visitLUSHR(LUSHR obj) { handleNormalInstruction(obj); }
public void visitISHL(ISHL obj) { handleNormalInstruction(obj); }
public void visitLALOAD(LALOAD obj) { handleNormalInstruction(obj); }
public void visitANEWARRAY(ANEWARRAY obj) { handleNormalInstruction(obj); }
public void visitFRETURN(FRETURN obj) { handleNormalInstruction(obj); }
public void visitFADD(FADD obj) { handleNormalInstruction(obj); }
}
// vim:ts=4
|
Allow more flexible overriding for 'normal' instructions.
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@418 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
|
findbugs/src/java/edu/umd/cs/findbugs/ba/AbstractFrameModelingVisitor.java
|
Allow more flexible overriding for 'normal' instructions.
|
<ide><path>indbugs/src/java/edu/umd/cs/findbugs/ba/AbstractFrameModelingVisitor.java
<ide> * handleNormalInstruction() method for instructions which produce stack values.
<ide> */
<ide> public abstract Value getDefaultValue();
<add>
<add> /**
<add> * Get the number of words consumed by given instruction.
<add> */
<add> public int getNumWordsConsumed(Instruction ins) {
<add> int numWordsConsumed = ins.consumeStack(cpg);
<add> if (numWordsConsumed == Constants.UNPREDICTABLE) throw new IllegalStateException();
<add> return numWordsConsumed;
<add> }
<add>
<add> /**
<add> * Get the number of words produced by given instruction.
<add> */
<add> public int getNumWordsProduced(Instruction ins) {
<add> int numWordsProduced = ins.produceStack(cpg);
<add> if (numWordsProduced == Constants.UNPREDICTABLE) throw new IllegalStateException();
<add> return numWordsProduced;
<add> }
<ide>
<ide> /**
<ide> * This is called for illegal bytecodes.
<ide> }
<ide>
<ide> /**
<del> * "Normal" handler.
<del> * This models the stack for all instructions which destroy
<del> * any values they consume, and produce only "default" values.
<add> * This is called to handle any instruction which does not simply
<add> * copy values between stack slots.
<ide> */
<ide> public void handleNormalInstruction(Instruction ins) {
<del> int nwords;
<del>
<del> nwords = ins.consumeStack(cpg);
<del> if (nwords == Constants.UNPREDICTABLE) throw new IllegalStateException();
<del> try {
<del> while (nwords-- > 0)
<add> modelNormalInstruction(ins, getNumWordsConsumed(ins), getNumWordsProduced(ins));
<add> }
<add>
<add> /**
<add> * Model the stack for instructions handled by handleNormalInstruction().
<add> * Subclasses may override to provide analysis-specific behavior.
<add> */
<add> public void modelNormalInstruction(Instruction ins, int numWordsConsumed, int numWordsProduced) {
<add> try {
<add> while (numWordsConsumed-- > 0)
<ide> frame.popValue();
<ide> } catch (DataflowAnalysisException e) {
<ide> throw new IllegalStateException(e.toString());
<ide> }
<ide>
<del> nwords = ins.produceStack(cpg);
<del> if (nwords == Constants.UNPREDICTABLE) throw new IllegalStateException();
<del> while (nwords-- > 0)
<add> while (numWordsProduced-- > 0)
<ide> frame.pushValue(getDefaultValue());
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
error: pathspec 'integrationtest/src/test/java/org/openengsb/integrationtest/StartIntegrationTestServer.java' did not match any file(s) known to git
|
7dccbad94b38a0f8fcc6163952b86e128d17a187
| 1 |
openengsb/openengsb,openengsb/openengsb,openengsb/openengsb,openengsb/openengsb,openengsb/openengsb,openengsb/openengsb
|
/**
Copyright 2010 OpenEngSB Division, Vienna University of Technology
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openengsb.integrationtest;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openengsb.integrationtest.util.BaseExamConfiguration;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.container.def.options.VMOption;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.ops4j.pax.exam.options.TimeoutOption;
@RunWith(JUnit4TestRunner.class)
public class StartIntegrationTestServer {
@Configuration
public static Option[] configuration() {
List<Option> baseConfiguration = BaseExamConfiguration.getBaseExamOptions("../");
configurePlatform(baseConfiguration);
Option[] options = BaseExamConfiguration.convertOptionListToArray(baseConfiguration);
return CoreOptions.options(options);
}
private static void configurePlatform(List<Option> baseConfiguration) {
BaseExamConfiguration.addEntireOpenEngSBPlatform(baseConfiguration);
baseConfiguration.add(new VMOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"));
baseConfiguration.add(new TimeoutOption(0));
}
@Test
public void testRunServer() throws Exception {
while (true) {
Thread.sleep(10000);
}
}
}
|
integrationtest/src/test/java/org/openengsb/integrationtest/StartIntegrationTestServer.java
|
added possibility to start openengsb from exam test (refs #openengsb-104)
Signed-off-by: Andreas Pieber <[email protected]>
|
integrationtest/src/test/java/org/openengsb/integrationtest/StartIntegrationTestServer.java
|
added possibility to start openengsb from exam test (refs #openengsb-104)
|
<ide><path>ntegrationtest/src/test/java/org/openengsb/integrationtest/StartIntegrationTestServer.java
<add>/**
<add>
<add> Copyright 2010 OpenEngSB Division, Vienna University of Technology
<add>
<add> Licensed under the Apache License, Version 2.0 (the "License");
<add> you may not use this file except in compliance with the License.
<add> You may obtain a copy of the License at
<add>
<add> http://www.apache.org/licenses/LICENSE-2.0
<add>
<add> Unless required by applicable law or agreed to in writing, software
<add> distributed under the License is distributed on an "AS IS" BASIS,
<add> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> See the License for the specific language governing permissions and
<add> limitations under the License.
<add>
<add> */
<add>package org.openengsb.integrationtest;
<add>
<add>import java.util.List;
<add>
<add>import org.junit.Test;
<add>import org.junit.runner.RunWith;
<add>import org.openengsb.integrationtest.util.BaseExamConfiguration;
<add>import org.ops4j.pax.exam.CoreOptions;
<add>import org.ops4j.pax.exam.Option;
<add>import org.ops4j.pax.exam.container.def.options.VMOption;
<add>import org.ops4j.pax.exam.junit.Configuration;
<add>import org.ops4j.pax.exam.junit.JUnit4TestRunner;
<add>import org.ops4j.pax.exam.options.TimeoutOption;
<add>
<add>@RunWith(JUnit4TestRunner.class)
<add>public class StartIntegrationTestServer {
<add>
<add> @Configuration
<add> public static Option[] configuration() {
<add> List<Option> baseConfiguration = BaseExamConfiguration.getBaseExamOptions("../");
<add> configurePlatform(baseConfiguration);
<add> Option[] options = BaseExamConfiguration.convertOptionListToArray(baseConfiguration);
<add> return CoreOptions.options(options);
<add> }
<add>
<add> private static void configurePlatform(List<Option> baseConfiguration) {
<add> BaseExamConfiguration.addEntireOpenEngSBPlatform(baseConfiguration);
<add> baseConfiguration.add(new VMOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"));
<add> baseConfiguration.add(new TimeoutOption(0));
<add> }
<add>
<add> @Test
<add> public void testRunServer() throws Exception {
<add> while (true) {
<add> Thread.sleep(10000);
<add> }
<add> }
<add>}
|
|
Java
|
apache-2.0
|
fa47375bdb479c797e55048c5984787862be21df
| 0 |
tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki
|
/*
JSPWiki - a JSP-based WikiWiki clone.
Copyright (C) 2001-2004 Janne Jalkanen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.ecyrd.jspwiki.auth.acl;
import java.security.Permission;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
/**
* JSPWiki implementation of an Access Control List.
* @author Janne Jalkanen
* @author Andrew Jaquith
* @since 2.3
*/
public class AclImpl implements Acl
{
private final Vector m_entries = new Vector();
/**
* Constructs a new AclImpl instance.
*/
public AclImpl()
{
}
/**
* @see com.ecyrd.jspwiki.auth.acl.Acl#findPrincipals(java.security.Permission)
*/
public Principal[] findPrincipals( Permission permission )
{
Vector principals = new Vector();
Enumeration entries = entries();
while (entries.hasMoreElements())
{
AclEntry entry = (AclEntry)entries.nextElement();
Enumeration permissions = entry.permissions();
while ( permissions.hasMoreElements() )
{
Permission perm = (Permission)permissions.nextElement();
if ( perm.implies( permission ) )
{
principals.add( entry.getPrincipal() );
}
}
}
return (Principal[])principals.toArray( new Principal[principals.size()] );
}
private boolean hasEntry( AclEntry entry )
{
if( entry == null )
{
return false;
}
for( Iterator i = m_entries.iterator(); i.hasNext(); )
{
AclEntry e = (AclEntry) i.next();
Principal ep = e.getPrincipal();
Principal entryp = entry.getPrincipal();
if( ep == null || entryp == null )
{
throw new IllegalArgumentException( "Entry is null; check code, please (entry="+entry+"; e="+e+")" );
}
if( ep.getName().equals( entryp.getName() ) )
{
return true;
}
}
return false;
}
public synchronized boolean addEntry( AclEntry entry )
{
if( entry.getPrincipal() == null )
{
throw new IllegalArgumentException( "Entry principal cannot be null" );
}
if( hasEntry( entry ) )
{
return false;
}
m_entries.add( entry );
return true;
}
public synchronized boolean removeEntry( AclEntry entry )
{
return m_entries.remove( entry );
}
public Enumeration entries()
{
return m_entries.elements();
}
public AclEntry getEntry( Principal principal )
{
for( Enumeration e = m_entries.elements(); e.hasMoreElements(); )
{
AclEntry entry = (AclEntry) e.nextElement();
if( entry.getPrincipal().getName().equals( principal.getName() ) )
{
return entry;
}
}
return null;
}
/**
* Returns a string representation of the contents of this Acl.
*/
public String toString()
{
StringBuffer sb = new StringBuffer();
for( Enumeration myEnum = entries(); myEnum.hasMoreElements(); )
{
AclEntry entry = (AclEntry) myEnum.nextElement();
Principal pal = entry.getPrincipal();
if( pal != null )
sb.append( " user = "+pal.getName()+": " );
else
sb.append( " user = null: " );
sb.append( "(" );
for( Enumeration perms = entry.permissions(); perms.hasMoreElements(); )
{
Permission perm = (Permission) perms.nextElement();
sb.append( perm.toString() );
}
sb.append( ")\n" );
}
return sb.toString();
}
public boolean isEmpty()
{
return m_entries.isEmpty();
}
}
|
src/com/ecyrd/jspwiki/auth/acl/AclImpl.java
|
/*
JSPWiki - a JSP-based WikiWiki clone.
Copyright (C) 2001-2004 Janne Jalkanen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.ecyrd.jspwiki.auth.acl;
import java.security.Permission;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
/**
* JSPWiki implementation of an Access Control List.
* @author Janne Jalkanen
* @author Andrew Jaquith
* @since 2.3
*/
public class AclImpl
implements Acl
{
private Vector m_entries = new Vector();
/**
* Constructs a new AclImpl instance.
*/
public AclImpl()
{
}
/**
* @see com.ecyrd.jspwiki.auth.acl.Acl#findPrincipals(java.security.Permission)
*/
public Principal[] findPrincipals(Permission permission)
{
Vector principals = new Vector();
Enumeration entries = entries();
while (entries.hasMoreElements())
{
AclEntry entry = (AclEntry)entries.nextElement();
Enumeration permissions = entry.permissions();
while (permissions.hasMoreElements())
{
Permission perm = (Permission)permissions.nextElement();
if (perm.implies(permission))
{
principals.add(entry.getPrincipal());
}
}
}
return (Principal[])principals.toArray(new Principal[principals.size()]);
}
private boolean hasEntry( AclEntry entry )
{
if( entry == null )
{
return false;
}
for( Iterator i = m_entries.iterator(); i.hasNext(); )
{
AclEntry e = (AclEntry) i.next();
Principal ep = e.getPrincipal();
Principal entryp = entry.getPrincipal();
if( ep == null || entryp == null )
{
throw new IllegalArgumentException("Entry is null; check code, please (entry="+entry+"; e="+e+")");
}
if( ep.getName().equals( entryp.getName() ))
{
return true;
}
}
return false;
}
public boolean addEntry( AclEntry entry )
{
if( entry.getPrincipal() == null )
{
throw new IllegalArgumentException("Entry principal cannot be null");
}
if( hasEntry( entry ) )
{
return false;
}
m_entries.add( entry );
return true;
}
public boolean removeEntry( AclEntry entry )
{
return m_entries.remove( entry );
}
public Enumeration entries()
{
return m_entries.elements();
}
public AclEntry getEntry( Principal principal )
{
for( Enumeration e = m_entries.elements(); e.hasMoreElements(); )
{
AclEntry entry = (AclEntry) e.nextElement();
if( entry.getPrincipal().getName().equals(principal.getName()) )
{
return entry;
}
}
return null;
}
/**
* Returns a string representation of the contents of this Acl.
*/
public String toString()
{
StringBuffer sb = new StringBuffer();
for( Enumeration myEnum = entries(); myEnum.hasMoreElements(); )
{
AclEntry entry = (AclEntry) myEnum.nextElement();
Principal pal = entry.getPrincipal();
if( pal != null )
sb.append(" user = "+pal.getName()+": ");
else
sb.append(" user = null: ");
sb.append("(");
for( Enumeration perms = entry.permissions(); perms.hasMoreElements(); )
{
Permission perm = (Permission) perms.nextElement();
sb.append( perm.toString() );
}
sb.append(")\n");
}
return sb.toString();
}
public boolean isEmpty()
{
return m_entries.isEmpty();
}
}
|
Synchronized thread-sensitive methods in the AclImpl/AclEntryImpl class.
git-svn-id: 6c0206e3b9edd104850923da33ebd73b435d374d@626297 13f79535-47bb-0310-9956-ffa450edef68
|
src/com/ecyrd/jspwiki/auth/acl/AclImpl.java
|
Synchronized thread-sensitive methods in the AclImpl/AclEntryImpl class.
|
<ide><path>rc/com/ecyrd/jspwiki/auth/acl/AclImpl.java
<ide> * @author Andrew Jaquith
<ide> * @since 2.3
<ide> */
<del>public class AclImpl
<del> implements Acl
<add>public class AclImpl implements Acl
<ide> {
<del> private Vector m_entries = new Vector();
<add> private final Vector m_entries = new Vector();
<ide>
<ide> /**
<ide> * Constructs a new AclImpl instance.
<ide> /**
<ide> * @see com.ecyrd.jspwiki.auth.acl.Acl#findPrincipals(java.security.Permission)
<ide> */
<del> public Principal[] findPrincipals(Permission permission)
<add> public Principal[] findPrincipals( Permission permission )
<ide> {
<ide> Vector principals = new Vector();
<ide> Enumeration entries = entries();
<ide> {
<ide> AclEntry entry = (AclEntry)entries.nextElement();
<ide> Enumeration permissions = entry.permissions();
<del> while (permissions.hasMoreElements())
<add> while ( permissions.hasMoreElements() )
<ide> {
<ide> Permission perm = (Permission)permissions.nextElement();
<del> if (perm.implies(permission))
<add> if ( perm.implies( permission ) )
<ide> {
<del> principals.add(entry.getPrincipal());
<add> principals.add( entry.getPrincipal() );
<ide> }
<ide> }
<ide> }
<del> return (Principal[])principals.toArray(new Principal[principals.size()]);
<add> return (Principal[])principals.toArray( new Principal[principals.size()] );
<ide> }
<ide>
<ide> private boolean hasEntry( AclEntry entry )
<ide>
<ide> if( ep == null || entryp == null )
<ide> {
<del> throw new IllegalArgumentException("Entry is null; check code, please (entry="+entry+"; e="+e+")");
<add> throw new IllegalArgumentException( "Entry is null; check code, please (entry="+entry+"; e="+e+")" );
<ide> }
<ide>
<del> if( ep.getName().equals( entryp.getName() ))
<add> if( ep.getName().equals( entryp.getName() ) )
<ide> {
<ide> return true;
<ide> }
<ide> return false;
<ide> }
<ide>
<del> public boolean addEntry( AclEntry entry )
<add> public synchronized boolean addEntry( AclEntry entry )
<ide> {
<ide> if( entry.getPrincipal() == null )
<ide> {
<del> throw new IllegalArgumentException("Entry principal cannot be null");
<add> throw new IllegalArgumentException( "Entry principal cannot be null" );
<ide> }
<ide>
<ide> if( hasEntry( entry ) )
<ide> return true;
<ide> }
<ide>
<del> public boolean removeEntry( AclEntry entry )
<add> public synchronized boolean removeEntry( AclEntry entry )
<ide> {
<ide> return m_entries.remove( entry );
<ide> }
<ide> {
<ide> AclEntry entry = (AclEntry) e.nextElement();
<ide>
<del> if( entry.getPrincipal().getName().equals(principal.getName()) )
<add> if( entry.getPrincipal().getName().equals( principal.getName() ) )
<ide> {
<ide> return entry;
<ide> }
<ide> Principal pal = entry.getPrincipal();
<ide>
<ide> if( pal != null )
<del> sb.append(" user = "+pal.getName()+": ");
<add> sb.append( " user = "+pal.getName()+": " );
<ide> else
<del> sb.append(" user = null: ");
<add> sb.append( " user = null: " );
<ide>
<del> sb.append("(");
<add> sb.append( "(" );
<ide> for( Enumeration perms = entry.permissions(); perms.hasMoreElements(); )
<ide> {
<ide> Permission perm = (Permission) perms.nextElement();
<ide> sb.append( perm.toString() );
<ide> }
<del> sb.append(")\n");
<add> sb.append( ")\n" );
<ide> }
<ide>
<ide> return sb.toString();
|
|
Java
|
apache-2.0
|
e14a385a8833ce0cde1735af4544a664c4028e40
| 0 |
Techcable/netty,idelpivnitskiy/netty,Apache9/netty,kiril-me/netty,mikkokar/netty,zer0se7en/netty,s-gheldd/netty,mikkokar/netty,mcobrien/netty,Apache9/netty,luyiisme/netty,idelpivnitskiy/netty,johnou/netty,maliqq/netty,fengjiachun/netty,andsel/netty,skyao/netty,gerdriesselmann/netty,golovnin/netty,ejona86/netty,KatsuraKKKK/netty,NiteshKant/netty,ngocdaothanh/netty,artgon/netty,golovnin/netty,Squarespace/netty,Scottmitch/netty,ngocdaothanh/netty,blucas/netty,zer0se7en/netty,Spikhalskiy/netty,doom369/netty,ichaki5748/netty,johnou/netty,artgon/netty,cnoldtree/netty,tbrooks8/netty,bryce-anderson/netty,tbrooks8/netty,kiril-me/netty,andsel/netty,golovnin/netty,netty/netty,Apache9/netty,bryce-anderson/netty,Spikhalskiy/netty,luyiisme/netty,ejona86/netty,Techcable/netty,mcobrien/netty,tbrooks8/netty,luyiisme/netty,idelpivnitskiy/netty,fenik17/netty,skyao/netty,fengjiachun/netty,carl-mastrangelo/netty,fenik17/netty,gerdriesselmann/netty,ichaki5748/netty,zer0se7en/netty,ngocdaothanh/netty,Scottmitch/netty,zer0se7en/netty,ichaki5748/netty,golovnin/netty,KatsuraKKKK/netty,Squarespace/netty,Scottmitch/netty,golovnin/netty,Spikhalskiy/netty,gerdriesselmann/netty,KatsuraKKKK/netty,doom369/netty,Techcable/netty,luyiisme/netty,fengjiachun/netty,jchambers/netty,netty/netty,netty/netty,idelpivnitskiy/netty,fenik17/netty,louxiu/netty,fenik17/netty,netty/netty,maliqq/netty,s-gheldd/netty,carl-mastrangelo/netty,ichaki5748/netty,artgon/netty,ejona86/netty,cnoldtree/netty,s-gheldd/netty,andsel/netty,jchambers/netty,blucas/netty,andsel/netty,cnoldtree/netty,maliqq/netty,mikkokar/netty,maliqq/netty,louxiu/netty,fengjiachun/netty,jchambers/netty,KatsuraKKKK/netty,mikkokar/netty,fenik17/netty,carl-mastrangelo/netty,maliqq/netty,Techcable/netty,kiril-me/netty,Apache9/netty,ichaki5748/netty,louxiu/netty,netty/netty,cnoldtree/netty,mcobrien/netty,skyao/netty,louxiu/netty,NiteshKant/netty,Scottmitch/netty,kiril-me/netty,KatsuraKKKK/netty,Apache9/netty,blucas/netty,jchambers/netty,mcobrien/netty,cnoldtree/netty,gerdriesselmann/netty,tbrooks8/netty,ejona86/netty,tbrooks8/netty,skyao/netty,johnou/netty,carl-mastrangelo/netty,Techcable/netty,idelpivnitskiy/netty,NiteshKant/netty,kiril-me/netty,fengjiachun/netty,Squarespace/netty,Scottmitch/netty,bryce-anderson/netty,artgon/netty,andsel/netty,Spikhalskiy/netty,Spikhalskiy/netty,ngocdaothanh/netty,skyao/netty,Squarespace/netty,bryce-anderson/netty,bryce-anderson/netty,NiteshKant/netty,carl-mastrangelo/netty,artgon/netty,johnou/netty,johnou/netty,doom369/netty,blucas/netty,ngocdaothanh/netty,zer0se7en/netty,doom369/netty,doom369/netty,louxiu/netty,ejona86/netty,mcobrien/netty,NiteshKant/netty,luyiisme/netty,Squarespace/netty,jchambers/netty,s-gheldd/netty,gerdriesselmann/netty,mikkokar/netty,s-gheldd/netty,blucas/netty
|
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.ssl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.InternalThreadLocalMap;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.apache.tomcat.jni.Buffer;
import org.apache.tomcat.jni.SSL;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionBindingEvent;
import javax.net.ssl.SSLSessionBindingListener;
import javax.net.ssl.SSLSessionContext;
import javax.security.cert.X509Certificate;
import static io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior;
import static io.netty.handler.ssl.OpenSsl.memoryAddress;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.FINISHED;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_WRAP;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
import static javax.net.ssl.SSLEngineResult.Status.BUFFER_OVERFLOW;
import static javax.net.ssl.SSLEngineResult.Status.CLOSED;
import static javax.net.ssl.SSLEngineResult.Status.OK;
/**
* Implements a {@link SSLEngine} using
* <a href="https://www.openssl.org/docs/crypto/BIO_s_bio.html#EXAMPLE">OpenSSL BIO abstractions</a>.
*/
public final class OpenSslEngine extends SSLEngine {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(OpenSslEngine.class);
private static final Certificate[] EMPTY_CERTIFICATES = EmptyArrays.EMPTY_CERTIFICATES;
private static final X509Certificate[] EMPTY_X509_CERTIFICATES = EmptyArrays.EMPTY_JAVAX_X509_CERTIFICATES;
private static final SSLException ENGINE_CLOSED = new SSLException("engine closed");
private static final SSLException RENEGOTIATION_UNSUPPORTED = new SSLException("renegotiation unsupported");
private static final SSLException ENCRYPTED_PACKET_OVERSIZED = new SSLException("encrypted packet oversized");
private static final Class<?> SNI_HOSTNAME_CLASS;
private static final Method GET_SERVER_NAMES_METHOD;
private static final Method SET_SERVER_NAMES_METHOD;
private static final Method GET_ASCII_NAME_METHOD;
static {
ENGINE_CLOSED.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);
RENEGOTIATION_UNSUPPORTED.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);
ENCRYPTED_PACKET_OVERSIZED.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);
AtomicIntegerFieldUpdater<OpenSslEngine> destroyedUpdater =
PlatformDependent.newAtomicIntegerFieldUpdater(OpenSslEngine.class, "destroyed");
if (destroyedUpdater == null) {
destroyedUpdater = AtomicIntegerFieldUpdater.newUpdater(OpenSslEngine.class, "destroyed");
}
DESTROYED_UPDATER = destroyedUpdater;
Class<?> sniHostNameClass = null;
Method getAsciiNameMethod = null;
Method getServerNamesMethod = null;
Method setServerNamesMethod = null;
if (PlatformDependent.javaVersion() >= 8) {
try {
sniHostNameClass = Class.forName("javax.net.ssl.SNIHostName", false,
PlatformDependent.getClassLoader(OpenSslEngine.class));
Object sniHostName = sniHostNameClass.getConstructor(String.class).newInstance("netty.io");
getAsciiNameMethod = sniHostNameClass.getDeclaredMethod("getAsciiName");
@SuppressWarnings("unused")
String name = (String) getAsciiNameMethod.invoke(sniHostName);
getServerNamesMethod = SSLParameters.class.getDeclaredMethod("getServerNames");
setServerNamesMethod = SSLParameters.class.getDeclaredMethod("setServerNames", List.class);
SSLParameters parameters = new SSLParameters();
@SuppressWarnings({ "rawtypes", "unused" })
List serverNames = (List) getServerNamesMethod.invoke(parameters);
setServerNamesMethod.invoke(parameters, Collections.emptyList());
} catch (Throwable ingore) {
sniHostNameClass = null;
getAsciiNameMethod = null;
getServerNamesMethod = null;
setServerNamesMethod = null;
}
}
SNI_HOSTNAME_CLASS = sniHostNameClass;
GET_ASCII_NAME_METHOD = getAsciiNameMethod;
GET_SERVER_NAMES_METHOD = getServerNamesMethod;
SET_SERVER_NAMES_METHOD = setServerNamesMethod;
}
private static final int MAX_PLAINTEXT_LENGTH = 16 * 1024; // 2^14
private static final int MAX_COMPRESSED_LENGTH = MAX_PLAINTEXT_LENGTH + 1024;
private static final int MAX_CIPHERTEXT_LENGTH = MAX_COMPRESSED_LENGTH + 1024;
// Protocols
private static final String PROTOCOL_SSL_V2_HELLO = "SSLv2Hello";
private static final String PROTOCOL_SSL_V2 = "SSLv2";
private static final String PROTOCOL_SSL_V3 = "SSLv3";
private static final String PROTOCOL_TLS_V1 = "TLSv1";
private static final String PROTOCOL_TLS_V1_1 = "TLSv1.1";
private static final String PROTOCOL_TLS_V1_2 = "TLSv1.2";
private static final String[] SUPPORTED_PROTOCOLS = {
PROTOCOL_SSL_V2_HELLO,
PROTOCOL_SSL_V2,
PROTOCOL_SSL_V3,
PROTOCOL_TLS_V1,
PROTOCOL_TLS_V1_1,
PROTOCOL_TLS_V1_2
};
private static final Set<String> SUPPORTED_PROTOCOLS_SET = new HashSet<String>(Arrays.asList(SUPPORTED_PROTOCOLS));
// Header (5) + Data (2^14) + Compression (1024) + Encryption (1024) + MAC (20) + Padding (256)
static final int MAX_ENCRYPTED_PACKET_LENGTH = MAX_CIPHERTEXT_LENGTH + 5 + 20 + 256;
static final int MAX_ENCRYPTION_OVERHEAD_LENGTH = MAX_ENCRYPTED_PACKET_LENGTH - MAX_PLAINTEXT_LENGTH;
private static final AtomicIntegerFieldUpdater<OpenSslEngine> DESTROYED_UPDATER;
private static final String INVALID_CIPHER = "SSL_NULL_WITH_NULL_NULL";
private static final long EMPTY_ADDR = Buffer.address(Unpooled.EMPTY_BUFFER.nioBuffer());
private static final SSLEngineResult NEED_UNWRAP_OK = new SSLEngineResult(OK, NEED_UNWRAP, 0, 0);
private static final SSLEngineResult NEED_UNWRAP_CLOSED = new SSLEngineResult(CLOSED, NEED_UNWRAP, 0, 0);
private static final SSLEngineResult NEED_WRAP_OK = new SSLEngineResult(OK, NEED_WRAP, 0, 0);
private static final SSLEngineResult NEED_WRAP_CLOSED = new SSLEngineResult(CLOSED, NEED_WRAP, 0, 0);
private static final SSLEngineResult CLOSED_NOT_HANDSHAKING = new SSLEngineResult(CLOSED, NOT_HANDSHAKING, 0, 0);
// OpenSSL state
private long ssl;
private long networkBIO;
private enum HandshakeState {
/**
* Not started yet.
*/
NOT_STARTED,
/**
* Started via unwrap/wrap.
*/
STARTED_IMPLICITLY,
/**
* Started via {@link #beginHandshake()}.
*/
STARTED_EXPLICITLY,
/**
* Handshake is finished.
*/
FINISHED
}
private HandshakeState handshakeState = HandshakeState.NOT_STARTED;
private boolean receivedShutdown;
private volatile int destroyed;
private volatile ClientAuth clientAuth = ClientAuth.NONE;
private String endPointIdentificationAlgorithm;
// Store as object as AlgorithmConstraints only exists since java 7.
private Object algorithmConstraints;
private List<?> sniHostNames;
// SSL Engine status variables
private boolean isInboundDone;
private boolean isOutboundDone;
private boolean engineClosed;
private final boolean clientMode;
private final ByteBufAllocator alloc;
private final OpenSslEngineMap engineMap;
private final OpenSslApplicationProtocolNegotiator apn;
private final boolean rejectRemoteInitiatedRenegation;
private final OpenSslSession session;
private final Certificate[] localCerts;
private final ByteBuffer[] singleSrcBuffer = new ByteBuffer[1];
private final ByteBuffer[] singleDstBuffer = new ByteBuffer[1];
// This is package-private as we set it from OpenSslContext if an exception is thrown during
// the verification step.
SSLHandshakeException handshakeException;
/**
* Creates a new instance
*
* @param sslCtx an OpenSSL {@code SSL_CTX} object
* @param alloc the {@link ByteBufAllocator} that will be used by this engine
*/
@Deprecated
public OpenSslEngine(long sslCtx, ByteBufAllocator alloc,
@SuppressWarnings("unused") String fallbackApplicationProtocol) {
this(sslCtx, alloc, false, null, OpenSslContext.NONE_PROTOCOL_NEGOTIATOR, OpenSslEngineMap.EMPTY, false,
ClientAuth.NONE);
}
OpenSslEngine(long sslCtx, ByteBufAllocator alloc,
boolean clientMode, OpenSslSessionContext sessionContext,
OpenSslApplicationProtocolNegotiator apn, OpenSslEngineMap engineMap,
boolean rejectRemoteInitiatedRenegation,
ClientAuth clientAuth) {
this(sslCtx, alloc, clientMode, sessionContext, apn, engineMap, rejectRemoteInitiatedRenegation, null, -1,
null, clientAuth);
}
OpenSslEngine(long sslCtx, ByteBufAllocator alloc,
boolean clientMode, OpenSslSessionContext sessionContext,
OpenSslApplicationProtocolNegotiator apn, OpenSslEngineMap engineMap,
boolean rejectRemoteInitiatedRenegation, String peerHost, int peerPort,
Certificate[] localCerts,
ClientAuth clientAuth) {
super(peerHost, peerPort);
OpenSsl.ensureAvailability();
if (sslCtx == 0) {
throw new NullPointerException("sslCtx");
}
this.alloc = checkNotNull(alloc, "alloc");
this.apn = checkNotNull(apn, "apn");
ssl = SSL.newSSL(sslCtx, !clientMode);
session = new OpenSslSession(sessionContext);
networkBIO = SSL.makeNetworkBIO(ssl);
this.clientMode = clientMode;
this.engineMap = engineMap;
this.rejectRemoteInitiatedRenegation = rejectRemoteInitiatedRenegation;
this.localCerts = localCerts;
// Set the client auth mode, this needs to be done via setClientAuth(...) method so we actually call the
// needed JNI methods.
setClientAuth(clientMode ? ClientAuth.NONE : checkNotNull(clientAuth, "clientAuth"));
// Use SNI if peerHost was specified
// See https://github.com/netty/netty/issues/4746
if (clientMode && peerHost != null) {
SSL.setTlsExtHostName(ssl, peerHost);
}
}
@Override
public synchronized SSLSession getHandshakeSession() {
// Javadocs state return value should be:
// null if this instance is not currently handshaking, or if the current handshake has not
// progressed far enough to create a basic SSLSession. Otherwise, this method returns the
// SSLSession currently being negotiated.
switch(handshakeState) {
case NOT_STARTED:
case FINISHED:
return null;
default:
return session;
}
}
/**
* Returns the pointer to the {@code SSL} object for this {@link OpenSslEngine}.
* Be aware that it is freed as soon as the {@link #finalize()} or {@link #shutdown} method is called.
* At this point {@code 0} will be returned.
*/
public synchronized long sslPointer() {
return ssl;
}
/**
* Destroys this engine.
*/
public synchronized void shutdown() {
if (DESTROYED_UPDATER.compareAndSet(this, 0, 1)) {
engineMap.remove(ssl);
SSL.freeSSL(ssl);
SSL.freeBIO(networkBIO);
ssl = networkBIO = 0;
// internal errors can cause shutdown without marking the engine closed
isInboundDone = isOutboundDone = engineClosed = true;
}
// On shutdown clear all errors
SSL.clearError();
}
/**
* Write plaintext data to the OpenSSL internal BIO
*
* Calling this function with src.remaining == 0 is undefined.
*/
private int writePlaintextData(final ByteBuffer src) {
final int pos = src.position();
final int limit = src.limit();
final int len = Math.min(limit - pos, MAX_PLAINTEXT_LENGTH);
final int sslWrote;
if (src.isDirect()) {
final long addr = Buffer.address(src) + pos;
sslWrote = SSL.writeToSSL(ssl, addr, len);
if (sslWrote > 0) {
src.position(pos + sslWrote);
}
} else {
ByteBuf buf = alloc.directBuffer(len);
try {
final long addr = memoryAddress(buf);
src.limit(pos + len);
buf.setBytes(0, src);
src.limit(limit);
sslWrote = SSL.writeToSSL(ssl, addr, len);
if (sslWrote > 0) {
src.position(pos + sslWrote);
} else {
src.position(pos);
}
} finally {
buf.release();
}
}
return sslWrote;
}
/**
* Write encrypted data to the OpenSSL network BIO.
*/
private int writeEncryptedData(final ByteBuffer src) {
final int pos = src.position();
final int len = src.remaining();
final int netWrote;
if (src.isDirect()) {
final long addr = Buffer.address(src) + pos;
netWrote = SSL.writeToBIO(networkBIO, addr, len);
if (netWrote >= 0) {
src.position(pos + netWrote);
}
} else {
final ByteBuf buf = alloc.directBuffer(len);
try {
final long addr = memoryAddress(buf);
buf.setBytes(0, src);
netWrote = SSL.writeToBIO(networkBIO, addr, len);
if (netWrote >= 0) {
src.position(pos + netWrote);
} else {
src.position(pos);
}
} finally {
buf.release();
}
}
return netWrote;
}
/**
* Read plaintext data from the OpenSSL internal BIO
*/
private int readPlaintextData(final ByteBuffer dst) {
final int sslRead;
if (dst.isDirect()) {
final int pos = dst.position();
final long addr = Buffer.address(dst) + pos;
final int len = dst.limit() - pos;
sslRead = SSL.readFromSSL(ssl, addr, len);
if (sslRead > 0) {
dst.position(pos + sslRead);
}
} else {
final int pos = dst.position();
final int limit = dst.limit();
final int len = Math.min(MAX_ENCRYPTED_PACKET_LENGTH, limit - pos);
final ByteBuf buf = alloc.directBuffer(len);
try {
final long addr = memoryAddress(buf);
sslRead = SSL.readFromSSL(ssl, addr, len);
if (sslRead > 0) {
dst.limit(pos + sslRead);
buf.getBytes(0, dst);
dst.limit(limit);
}
} finally {
buf.release();
}
}
return sslRead;
}
/**
* Read encrypted data from the OpenSSL network BIO
*/
private int readEncryptedData(final ByteBuffer dst, final int pending) {
final int bioRead;
if (dst.isDirect() && dst.remaining() >= pending) {
final int pos = dst.position();
final long addr = Buffer.address(dst) + pos;
bioRead = SSL.readFromBIO(networkBIO, addr, pending);
if (bioRead > 0) {
dst.position(pos + bioRead);
return bioRead;
}
} else {
final ByteBuf buf = alloc.directBuffer(pending);
try {
final long addr = memoryAddress(buf);
bioRead = SSL.readFromBIO(networkBIO, addr, pending);
if (bioRead > 0) {
int oldLimit = dst.limit();
dst.limit(dst.position() + bioRead);
buf.getBytes(0, dst);
dst.limit(oldLimit);
return bioRead;
}
} finally {
buf.release();
}
}
return bioRead;
}
private SSLEngineResult readPendingBytesFromBIO(
ByteBuffer dst, int bytesConsumed, int bytesProduced, HandshakeStatus status) throws SSLException {
// Check to see if the engine wrote data into the network BIO
int pendingNet = SSL.pendingWrittenBytesInBIO(networkBIO);
if (pendingNet > 0) {
// Do we have enough room in dst to write encrypted data?
int capacity = dst.remaining();
if (capacity < pendingNet) {
return new SSLEngineResult(BUFFER_OVERFLOW,
mayFinishHandshake(status != FINISHED ? getHandshakeStatus(pendingNet) : status),
bytesConsumed, bytesProduced);
}
// Write the pending data from the network BIO into the dst buffer
int produced = readEncryptedData(dst, pendingNet);
if (produced <= 0) {
// We ignore BIO_* errors here as we use in memory BIO anyway and will do another SSL_* call later
// on in which we will produce an exception in case of an error
SSL.clearError();
} else {
bytesProduced += produced;
pendingNet -= produced;
}
// If isOuboundDone is set, then the data from the network BIO
// was the close_notify message -- we are not required to wait
// for the receipt the peer's close_notify message -- shutdown.
if (isOutboundDone) {
shutdown();
}
return new SSLEngineResult(getEngineStatus(),
mayFinishHandshake(status != FINISHED ? getHandshakeStatus(pendingNet) : status),
bytesConsumed, bytesProduced);
}
return null;
}
@Override
public synchronized SSLEngineResult wrap(
final ByteBuffer[] srcs, final int offset, final int length, final ByteBuffer dst) throws SSLException {
// Check to make sure the engine has not been closed
if (isDestroyed()) {
return CLOSED_NOT_HANDSHAKING;
}
// Throw required runtime exceptions
if (srcs == null) {
throw new IllegalArgumentException("srcs is null");
}
if (dst == null) {
throw new IllegalArgumentException("dst is null");
}
if (offset >= srcs.length || offset + length > srcs.length) {
throw new IndexOutOfBoundsException(
"offset: " + offset + ", length: " + length +
" (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
}
if (dst.isReadOnly()) {
throw new ReadOnlyBufferException();
}
HandshakeStatus status = NOT_HANDSHAKING;
// Prepare OpenSSL to work in server mode and receive handshake
if (handshakeState != HandshakeState.FINISHED) {
if (handshakeState != HandshakeState.STARTED_EXPLICITLY) {
// Update accepted so we know we triggered the handshake via wrap
handshakeState = HandshakeState.STARTED_IMPLICITLY;
}
status = handshake();
if (status == NEED_UNWRAP) {
return NEED_UNWRAP_OK;
}
if (engineClosed) {
return NEED_UNWRAP_CLOSED;
}
}
// There was no pending data in the network BIO -- encrypt any application data
int bytesProduced = 0;
int bytesConsumed = 0;
int endOffset = offset + length;
for (int i = offset; i < endOffset; ++ i) {
final ByteBuffer src = srcs[i];
if (src == null) {
throw new IllegalArgumentException("srcs[" + i + "] is null");
}
while (src.hasRemaining()) {
final SSLEngineResult pendingNetResult;
// Write plaintext application data to the SSL engine
int result = writePlaintextData(src);
if (result > 0) {
bytesConsumed += result;
pendingNetResult = readPendingBytesFromBIO(dst, bytesConsumed, bytesProduced, status);
if (pendingNetResult != null) {
if (pendingNetResult.getStatus() != OK) {
return pendingNetResult;
}
bytesProduced = pendingNetResult.bytesProduced();
}
} else {
int sslError = SSL.getError(ssl, result);
switch (sslError) {
case SSL.SSL_ERROR_ZERO_RETURN:
// This means the connection was shutdown correctly, close inbound and outbound
if (!receivedShutdown) {
closeAll();
}
pendingNetResult = readPendingBytesFromBIO(dst, bytesConsumed, bytesProduced, status);
return pendingNetResult != null ? pendingNetResult : CLOSED_NOT_HANDSHAKING;
case SSL.SSL_ERROR_WANT_READ:
// If there is no pending data to read from BIO we should go back to event loop and try to read
// more data [1]. It is also possible that event loop will detect the socket has been closed.
// [1] https://www.openssl.org/docs/manmaster/ssl/SSL_write.html
pendingNetResult = readPendingBytesFromBIO(dst, bytesConsumed, bytesProduced, status);
return pendingNetResult != null ? pendingNetResult :
new SSLEngineResult(getEngineStatus(), NEED_UNWRAP, bytesConsumed, bytesProduced);
case SSL.SSL_ERROR_WANT_WRITE:
// SSL_ERROR_WANT_WRITE typically means that the underlying transport is not writable and we
// should set the "want write" flag on the selector and try again when the underlying transport
// is writable [1]. However we are not directly writing to the underlying transport and instead
// writing to a BIO buffer. The OpenSsl documentation says we should do the following [1]:
//
// "When using a buffering BIO, like a BIO pair, data must be written into or retrieved out of
// the BIO before being able to continue."
//
// So we attempt to drain the BIO buffer below, but if there is no data this condition is
// undefined and we assume their is a fatal error with the openssl engine and close.
// [1] https://www.openssl.org/docs/manmaster/ssl/SSL_write.html
pendingNetResult = readPendingBytesFromBIO(dst, bytesConsumed, bytesProduced, status);
return pendingNetResult != null ? pendingNetResult : NEED_WRAP_CLOSED;
default:
// Everything else is considered as error
throw shutdownWithError("SSL_write");
}
}
}
}
// We need to check if pendingWrittenBytesInBIO was checked yet, as we may not checked if the srcs was empty,
// or only contained empty buffers.
if (bytesConsumed == 0) {
SSLEngineResult pendingNetResult = readPendingBytesFromBIO(dst, 0, bytesProduced, status);
if (pendingNetResult != null) {
return pendingNetResult;
}
}
return newResult(bytesConsumed, bytesProduced, status);
}
/**
* Log the error, shutdown the engine and throw an exception.
*/
private SSLException shutdownWithError(String operations) {
String err = SSL.getLastError();
return shutdownWithError(operations, err);
}
private SSLException shutdownWithError(String operation, String err) {
if (logger.isDebugEnabled()) {
logger.debug("{} failed: OpenSSL error: {}", operation, err);
}
// There was an internal error -- shutdown
shutdown();
if (handshakeState == HandshakeState.FINISHED) {
return new SSLException(err);
}
return new SSLHandshakeException(err);
}
public synchronized SSLEngineResult unwrap(
final ByteBuffer[] srcs, int srcsOffset, final int srcsLength,
final ByteBuffer[] dsts, final int dstsOffset, final int dstsLength) throws SSLException {
// Check to make sure the engine has not been closed
if (isDestroyed()) {
return CLOSED_NOT_HANDSHAKING;
}
// Throw required runtime exceptions
if (srcs == null) {
throw new NullPointerException("srcs");
}
if (srcsOffset >= srcs.length
|| srcsOffset + srcsLength > srcs.length) {
throw new IndexOutOfBoundsException(
"offset: " + srcsOffset + ", length: " + srcsLength +
" (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
}
if (dsts == null) {
throw new IllegalArgumentException("dsts is null");
}
if (dstsOffset >= dsts.length || dstsOffset + dstsLength > dsts.length) {
throw new IndexOutOfBoundsException(
"offset: " + dstsOffset + ", length: " + dstsLength +
" (expected: offset <= offset + length <= dsts.length (" + dsts.length + "))");
}
long capacity = 0;
final int endOffset = dstsOffset + dstsLength;
for (int i = dstsOffset; i < endOffset; i ++) {
ByteBuffer dst = dsts[i];
if (dst == null) {
throw new IllegalArgumentException("dsts[" + i + "] is null");
}
if (dst.isReadOnly()) {
throw new ReadOnlyBufferException();
}
capacity += dst.remaining();
}
HandshakeStatus status = NOT_HANDSHAKING;
// Prepare OpenSSL to work in server mode and receive handshake
if (handshakeState != HandshakeState.FINISHED) {
if (handshakeState != HandshakeState.STARTED_EXPLICITLY) {
// Update accepted so we know we triggered the handshake via wrap
handshakeState = HandshakeState.STARTED_IMPLICITLY;
}
status = handshake();
if (status == NEED_WRAP) {
return NEED_WRAP_OK;
}
if (engineClosed) {
return NEED_WRAP_CLOSED;
}
}
final int srcsEndOffset = srcsOffset + srcsLength;
long len = 0;
for (int i = srcsOffset; i < srcsEndOffset; i++) {
ByteBuffer src = srcs[i];
if (src == null) {
throw new IllegalArgumentException("srcs[" + i + "] is null");
}
len += src.remaining();
}
// protect against protocol overflow attack vector
if (len > MAX_ENCRYPTED_PACKET_LENGTH) {
isInboundDone = true;
isOutboundDone = true;
engineClosed = true;
shutdown();
throw ENCRYPTED_PACKET_OVERSIZED;
}
// Write encrypted data to network BIO
int bytesConsumed = 0;
if (srcsOffset < srcsEndOffset) {
do {
ByteBuffer src = srcs[srcsOffset];
int remaining = src.remaining();
if (remaining == 0) {
// We must skip empty buffers as BIO_write will return 0 if asked to write something
// with length 0.
srcsOffset ++;
continue;
}
int written = writeEncryptedData(src);
if (written > 0) {
bytesConsumed += written;
if (written == remaining) {
srcsOffset ++;
} else {
// We were not able to write everything into the BIO so break the write loop as otherwise
// we will produce an error on the next write attempt, which will trigger a SSL.clearError()
// later.
break;
}
} else {
// BIO_write returned a negative or zero number, this means we could not complete the write
// operation and should retry later.
// We ignore BIO_* errors here as we use in memory BIO anyway and will do another SSL_* call later
// on in which we will produce an exception in case of an error
SSL.clearError();
break;
}
} while (srcsOffset < srcsEndOffset);
}
// Number of produced bytes
int bytesProduced = 0;
if (capacity > 0) {
// Write decrypted data to dsts buffers
int idx = dstsOffset;
while (idx < endOffset) {
ByteBuffer dst = dsts[idx];
if (!dst.hasRemaining()) {
idx ++;
continue;
}
int bytesRead = readPlaintextData(dst);
// TODO: We may want to consider if we move this check and only do it in a less often called place at
// the price of not being 100% accurate, like for example when calling SSL.getError(...).
rejectRemoteInitiatedRenegation();
if (bytesRead > 0) {
bytesProduced += bytesRead;
if (!dst.hasRemaining()) {
idx ++;
} else {
// We read everything return now.
return newResult(bytesConsumed, bytesProduced, status);
}
} else {
int sslError = SSL.getError(ssl, bytesRead);
switch (sslError) {
case SSL.SSL_ERROR_ZERO_RETURN:
// This means the connection was shutdown correctly, close inbound and outbound
if (!receivedShutdown) {
closeAll();
}
// fall-trough!
case SSL.SSL_ERROR_WANT_READ:
case SSL.SSL_ERROR_WANT_WRITE:
// break to the outer loop
return newResult(bytesConsumed, bytesProduced, status);
default:
return sslReadErrorResult(SSL.getLastErrorNumber(), bytesConsumed, bytesProduced);
}
}
}
} else {
// If the capacity of all destination buffers is 0 we need to trigger a SSL_read anyway to ensure
// everything is flushed in the BIO pair and so we can detect it in the pendingAppData() call.
if (SSL.readFromSSL(ssl, EMPTY_ADDR, 0) <= 0) {
// We do not check SSL_get_error as we are not interested in any error that is not fatal.
int err = SSL.getLastErrorNumber();
if (OpenSsl.isError(err)) {
return sslReadErrorResult(err, bytesConsumed, bytesProduced);
}
}
}
if (pendingAppData() > 0) {
// We filled all buffers but there is still some data pending in the BIO buffer, return BUFFER_OVERFLOW.
return new SSLEngineResult(
BUFFER_OVERFLOW, mayFinishHandshake(status != FINISHED ? getHandshakeStatus(): status),
bytesConsumed, bytesProduced);
}
// Check to see if we received a close_notify message from the peer.
if (!receivedShutdown && (SSL.getShutdown(ssl) & SSL.SSL_RECEIVED_SHUTDOWN) == SSL.SSL_RECEIVED_SHUTDOWN) {
closeAll();
}
return newResult(bytesConsumed, bytesProduced, status);
}
private SSLEngineResult sslReadErrorResult(int err, int bytesConsumed, int bytesProduced) throws SSLException {
String errStr = SSL.getErrorString(err);
// Check if we have a pending handshakeException and if so see if we need to consume all pending data from the
// BIO first or can just shutdown and throw it now.
// This is needed so we ensure close_notify etc is correctly send to the remote peer.
// See https://github.com/netty/netty/issues/3900
if (SSL.pendingWrittenBytesInBIO(networkBIO) > 0) {
if (handshakeException == null && handshakeState != HandshakeState.FINISHED) {
// we seems to have data left that needs to be transfered and so the user needs
// call wrap(...). Store the error so we can pick it up later.
handshakeException = new SSLHandshakeException(errStr);
}
return new SSLEngineResult(OK, NEED_WRAP, bytesConsumed, bytesProduced);
}
throw shutdownWithError("SSL_read", errStr);
}
private int pendingAppData() {
// There won't be any application data until we're done handshaking.
// We first check handshakeFinished to eliminate the overhead of extra JNI call if possible.
return handshakeState == HandshakeState.FINISHED ? SSL.pendingReadableBytesInSSL(ssl) : 0;
}
private SSLEngineResult newResult(
int bytesConsumed, int bytesProduced, HandshakeStatus status) throws SSLException {
return new SSLEngineResult(
getEngineStatus(), mayFinishHandshake(status != FINISHED ? getHandshakeStatus() : status)
, bytesConsumed, bytesProduced);
}
private void closeAll() throws SSLException {
receivedShutdown = true;
closeOutbound();
closeInbound();
}
private void rejectRemoteInitiatedRenegation() throws SSLHandshakeException {
if (rejectRemoteInitiatedRenegation && SSL.getHandshakeCount(ssl) > 1) {
// TODO: In future versions me may also want to send a fatal_alert to the client and so notify it
// that the renegotiation failed.
shutdown();
throw new SSLHandshakeException("remote-initiated renegotation not allowed");
}
}
public SSLEngineResult unwrap(final ByteBuffer[] srcs, final ByteBuffer[] dsts) throws SSLException {
return unwrap(srcs, 0, srcs.length, dsts, 0, dsts.length);
}
private ByteBuffer[] singleSrcBuffer(ByteBuffer src) {
singleSrcBuffer[0] = src;
return singleSrcBuffer;
}
private void resetSingleSrcBuffer() {
singleSrcBuffer[0] = null;
}
private ByteBuffer[] singleDstBuffer(ByteBuffer src) {
singleDstBuffer[0] = src;
return singleDstBuffer;
}
private void resetSingleDstBuffer() {
singleDstBuffer[0] = null;
}
@Override
public synchronized SSLEngineResult unwrap(
final ByteBuffer src, final ByteBuffer[] dsts, final int offset, final int length) throws SSLException {
try {
return unwrap(singleSrcBuffer(src), 0, 1, dsts, offset, length);
} finally {
resetSingleSrcBuffer();
}
}
@Override
public synchronized SSLEngineResult wrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
try {
return wrap(singleSrcBuffer(src), dst);
} finally {
resetSingleSrcBuffer();
}
}
@Override
public synchronized SSLEngineResult unwrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
try {
return unwrap(singleSrcBuffer(src), singleDstBuffer(dst));
} finally {
resetSingleSrcBuffer();
resetSingleDstBuffer();
}
}
@Override
public synchronized SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts) throws SSLException {
try {
return unwrap(singleSrcBuffer(src), dsts);
} finally {
resetSingleSrcBuffer();
}
}
@Override
public Runnable getDelegatedTask() {
// Currently, we do not delegate SSL computation tasks
// TODO: in the future, possibly create tasks to do encrypt / decrypt async
return null;
}
@Override
public synchronized void closeInbound() throws SSLException {
if (isInboundDone) {
return;
}
isInboundDone = true;
engineClosed = true;
shutdown();
if (handshakeState != HandshakeState.NOT_STARTED && !receivedShutdown) {
throw new SSLException(
"Inbound closed before receiving peer's close_notify: possible truncation attack?");
}
}
@Override
public synchronized boolean isInboundDone() {
return isInboundDone || engineClosed;
}
@Override
public synchronized void closeOutbound() {
if (isOutboundDone) {
return;
}
isOutboundDone = true;
engineClosed = true;
if (handshakeState != HandshakeState.NOT_STARTED && !isDestroyed()) {
int mode = SSL.getShutdown(ssl);
if ((mode & SSL.SSL_SENT_SHUTDOWN) != SSL.SSL_SENT_SHUTDOWN) {
int err = SSL.shutdownSSL(ssl);
if (err < 0) {
int sslErr = SSL.getError(ssl, err);
switch (sslErr) {
case SSL.SSL_ERROR_NONE:
case SSL.SSL_ERROR_WANT_ACCEPT:
case SSL.SSL_ERROR_WANT_CONNECT:
case SSL.SSL_ERROR_WANT_WRITE:
case SSL.SSL_ERROR_WANT_READ:
case SSL.SSL_ERROR_WANT_X509_LOOKUP:
case SSL.SSL_ERROR_ZERO_RETURN:
// Nothing to do here
break;
case SSL.SSL_ERROR_SYSCALL:
case SSL.SSL_ERROR_SSL:
if (logger.isDebugEnabled()) {
logger.debug("SSL_shutdown failed: OpenSSL error: {}", SSL.getLastError());
}
// There was an internal error -- shutdown
shutdown();
break;
default:
SSL.clearError();
break;
}
}
}
} else {
// engine closing before initial handshake
shutdown();
}
}
@Override
public synchronized boolean isOutboundDone() {
return isOutboundDone;
}
@Override
public String[] getSupportedCipherSuites() {
Set<String> availableCipherSuites = OpenSsl.availableCipherSuites();
return availableCipherSuites.toArray(new String[availableCipherSuites.size()]);
}
@Override
public String[] getEnabledCipherSuites() {
final String[] enabled;
synchronized (this) {
if (!isDestroyed()) {
enabled = SSL.getCiphers(ssl);
} else {
return EmptyArrays.EMPTY_STRINGS;
}
}
if (enabled == null) {
return EmptyArrays.EMPTY_STRINGS;
} else {
for (int i = 0; i < enabled.length; i++) {
String mapped = toJavaCipherSuite(enabled[i]);
if (mapped != null) {
enabled[i] = mapped;
}
}
return enabled;
}
}
@Override
public void setEnabledCipherSuites(String[] cipherSuites) {
checkNotNull(cipherSuites, "cipherSuites");
final StringBuilder buf = new StringBuilder();
for (String c: cipherSuites) {
if (c == null) {
break;
}
String converted = CipherSuiteConverter.toOpenSsl(c);
if (converted == null) {
converted = c;
}
if (!OpenSsl.isCipherSuiteAvailable(converted)) {
throw new IllegalArgumentException("unsupported cipher suite: " + c + '(' + converted + ')');
}
buf.append(converted);
buf.append(':');
}
if (buf.length() == 0) {
throw new IllegalArgumentException("empty cipher suites");
}
buf.setLength(buf.length() - 1);
final String cipherSuiteSpec = buf.toString();
synchronized (this) {
if (!isDestroyed()) {
try {
SSL.setCipherSuites(ssl, cipherSuiteSpec);
} catch (Exception e) {
throw new IllegalStateException("failed to enable cipher suites: " + cipherSuiteSpec, e);
}
} else {
throw new IllegalStateException("failed to enable cipher suites: " + cipherSuiteSpec);
}
}
}
@Override
public String[] getSupportedProtocols() {
return SUPPORTED_PROTOCOLS.clone();
}
@Override
public String[] getEnabledProtocols() {
List<String> enabled = InternalThreadLocalMap.get().arrayList();
// Seems like there is no way to explict disable SSLv2Hello in openssl so it is always enabled
enabled.add(PROTOCOL_SSL_V2_HELLO);
int opts;
synchronized (this) {
if (!isDestroyed()) {
opts = SSL.getOptions(ssl);
} else {
return enabled.toArray(new String[1]);
}
}
if ((opts & SSL.SSL_OP_NO_TLSv1) == 0) {
enabled.add(PROTOCOL_TLS_V1);
}
if ((opts & SSL.SSL_OP_NO_TLSv1_1) == 0) {
enabled.add(PROTOCOL_TLS_V1_1);
}
if ((opts & SSL.SSL_OP_NO_TLSv1_2) == 0) {
enabled.add(PROTOCOL_TLS_V1_2);
}
if ((opts & SSL.SSL_OP_NO_SSLv2) == 0) {
enabled.add(PROTOCOL_SSL_V2);
}
if ((opts & SSL.SSL_OP_NO_SSLv3) == 0) {
enabled.add(PROTOCOL_SSL_V3);
}
return enabled.toArray(new String[enabled.size()]);
}
@Override
public void setEnabledProtocols(String[] protocols) {
if (protocols == null) {
// This is correct from the API docs
throw new IllegalArgumentException();
}
boolean sslv2 = false;
boolean sslv3 = false;
boolean tlsv1 = false;
boolean tlsv1_1 = false;
boolean tlsv1_2 = false;
for (String p: protocols) {
if (!SUPPORTED_PROTOCOLS_SET.contains(p)) {
throw new IllegalArgumentException("Protocol " + p + " is not supported.");
}
if (p.equals(PROTOCOL_SSL_V2)) {
sslv2 = true;
} else if (p.equals(PROTOCOL_SSL_V3)) {
sslv3 = true;
} else if (p.equals(PROTOCOL_TLS_V1)) {
tlsv1 = true;
} else if (p.equals(PROTOCOL_TLS_V1_1)) {
tlsv1_1 = true;
} else if (p.equals(PROTOCOL_TLS_V1_2)) {
tlsv1_2 = true;
}
}
synchronized (this) {
if (!isDestroyed()) {
// Enable all and then disable what we not want
SSL.setOptions(ssl, SSL.SSL_OP_ALL);
// Clear out options which disable protocols
SSL.clearOptions(ssl, SSL.SSL_OP_NO_SSLv2 | SSL.SSL_OP_NO_SSLv3 | SSL.SSL_OP_NO_TLSv1 |
SSL.SSL_OP_NO_TLSv1_1 | SSL.SSL_OP_NO_TLSv1_2);
int opts = 0;
if (!sslv2) {
opts |= SSL.SSL_OP_NO_SSLv2;
}
if (!sslv3) {
opts |= SSL.SSL_OP_NO_SSLv3;
}
if (!tlsv1) {
opts |= SSL.SSL_OP_NO_TLSv1;
}
if (!tlsv1_1) {
opts |= SSL.SSL_OP_NO_TLSv1_1;
}
if (!tlsv1_2) {
opts |= SSL.SSL_OP_NO_TLSv1_2;
}
// Disable protocols we do not want
SSL.setOptions(ssl, opts);
} else {
throw new IllegalStateException("failed to enable protocols: " + Arrays.asList(protocols));
}
}
}
@Override
public SSLSession getSession() {
return session;
}
@Override
public synchronized void beginHandshake() throws SSLException {
switch (handshakeState) {
case STARTED_IMPLICITLY:
checkEngineClosed();
// A user did not start handshake by calling this method by him/herself,
// but handshake has been started already by wrap() or unwrap() implicitly.
// Because it's the user's first time to call this method, it is unfair to
// raise an exception. From the user's standpoint, he or she never asked
// for renegotiation.
handshakeState = HandshakeState.STARTED_EXPLICITLY; // Next time this method is invoked by the user,
// we should raise an exception.
break;
case STARTED_EXPLICITLY:
// Nothing to do as the handshake is not done yet.
break;
case FINISHED:
if (clientMode) {
// Only supported for server mode at the moment.
throw RENEGOTIATION_UNSUPPORTED;
}
// For renegotiate on the server side we need to issue the following command sequence with openssl:
//
// SSL_renegotiate(ssl)
// SSL_do_handshake(ssl)
// ssl->state = SSL_ST_ACCEPT
// SSL_do_handshake(ssl)
//
// Bcause of this we fall-through to call handshake() after setting the state, as this will also take
// care of updating the internal OpenSslSession object.
//
// See also:
// https://github.com/apache/httpd/blob/2.4.16/modules/ssl/ssl_engine_kernel.c#L812
// http://h71000.www7.hp.com/doc/83final/ba554_90007/ch04s03.html
if (SSL.renegotiate(ssl) != 1 || SSL.doHandshake(ssl) != 1) {
throw shutdownWithError("renegotiation failed");
}
SSL.setState(ssl, SSL.SSL_ST_ACCEPT);
// fall-through
case NOT_STARTED:
handshakeState = HandshakeState.STARTED_EXPLICITLY;
handshake();
break;
default:
throw new Error();
}
}
private void checkEngineClosed() throws SSLException {
if (engineClosed || isDestroyed()) {
throw ENGINE_CLOSED;
}
}
private static HandshakeStatus pendingStatus(int pendingStatus) {
// Depending on if there is something left in the BIO we need to WRAP or UNWRAP
return pendingStatus > 0 ? NEED_WRAP : NEED_UNWRAP;
}
private HandshakeStatus handshake() throws SSLException {
if (handshakeState == HandshakeState.FINISHED) {
return FINISHED;
}
checkEngineClosed();
// Check if we have a pending handshakeException and if so see if we need to consume all pending data from the
// BIO first or can just shutdown and throw it now.
// This is needed so we ensure close_notify etc is correctly send to the remote peer.
// See https://github.com/netty/netty/issues/3900
SSLHandshakeException exception = handshakeException;
if (exception != null) {
if (SSL.pendingWrittenBytesInBIO(networkBIO) > 0) {
// There is something pending, we need to consume it first via a WRAP so we not loose anything.
return NEED_WRAP;
}
// No more data left to send to the remote peer, so null out the exception field, shutdown and throw
// the exception.
handshakeException = null;
shutdown();
throw exception;
}
// Adding the OpenSslEngine to the OpenSslEngineMap so it can be used in the AbstractCertificateVerifier.
engineMap.add(this);
int code = SSL.doHandshake(ssl);
if (code <= 0) {
// Check if we have a pending exception that was created during the handshake and if so throw it after
// shutdown the connection.
if (handshakeException != null) {
exception = handshakeException;
handshakeException = null;
shutdown();
throw exception;
}
int sslError = SSL.getError(ssl, code);
switch (sslError) {
case SSL.SSL_ERROR_WANT_READ:
case SSL.SSL_ERROR_WANT_WRITE:
return pendingStatus(SSL.pendingWrittenBytesInBIO(networkBIO));
default:
// Everything else is considered as error
throw shutdownWithError("SSL_do_handshake");
}
}
// if SSL_do_handshake returns > 0 or sslError == SSL.SSL_ERROR_NAME it means the handshake was finished.
session.handshakeFinished();
return FINISHED;
}
private Status getEngineStatus() {
return engineClosed? CLOSED : OK;
}
private SSLEngineResult.HandshakeStatus mayFinishHandshake(SSLEngineResult.HandshakeStatus status)
throws SSLException {
if (status == NOT_HANDSHAKING && handshakeState != HandshakeState.FINISHED) {
// If the status was NOT_HANDSHAKING and we not finished the handshake we need to call
// SSL_do_handshake() again
return handshake();
}
return status;
}
@Override
public synchronized SSLEngineResult.HandshakeStatus getHandshakeStatus() {
// Check if we are in the initial handshake phase or shutdown phase
return needPendingStatus() ? pendingStatus(SSL.pendingWrittenBytesInBIO(networkBIO)) : NOT_HANDSHAKING;
}
private SSLEngineResult.HandshakeStatus getHandshakeStatus(int pending) {
// Check if we are in the initial handshake phase or shutdown phase
return needPendingStatus() ? pendingStatus(pending) : NOT_HANDSHAKING;
}
private boolean needPendingStatus() {
return handshakeState != HandshakeState.NOT_STARTED && !isDestroyed()
&& (handshakeState != HandshakeState.FINISHED || engineClosed);
}
/**
* Converts the specified OpenSSL cipher suite to the Java cipher suite.
*/
private String toJavaCipherSuite(String openSslCipherSuite) {
if (openSslCipherSuite == null) {
return null;
}
String prefix = toJavaCipherSuitePrefix(SSL.getVersion(ssl));
return CipherSuiteConverter.toJava(openSslCipherSuite, prefix);
}
/**
* Converts the protocol version string returned by {@link SSL#getVersion(long)} to protocol family string.
*/
private static String toJavaCipherSuitePrefix(String protocolVersion) {
final char c;
if (protocolVersion == null || protocolVersion.length() == 0) {
c = 0;
} else {
c = protocolVersion.charAt(0);
}
switch (c) {
case 'T':
return "TLS";
case 'S':
return "SSL";
default:
return "UNKNOWN";
}
}
@Override
public void setUseClientMode(boolean clientMode) {
if (clientMode != this.clientMode) {
throw new UnsupportedOperationException();
}
}
@Override
public boolean getUseClientMode() {
return clientMode;
}
@Override
public void setNeedClientAuth(boolean b) {
setClientAuth(b ? ClientAuth.REQUIRE : ClientAuth.NONE);
}
@Override
public boolean getNeedClientAuth() {
return clientAuth == ClientAuth.REQUIRE;
}
@Override
public void setWantClientAuth(boolean b) {
setClientAuth(b ? ClientAuth.OPTIONAL : ClientAuth.NONE);
}
@Override
public boolean getWantClientAuth() {
return clientAuth == ClientAuth.OPTIONAL;
}
private void setClientAuth(ClientAuth mode) {
if (clientMode) {
return;
}
synchronized (this) {
if (clientAuth == mode) {
// No need to issue any JNI calls if the mode is the same
return;
}
switch (mode) {
case NONE:
SSL.setVerify(ssl, SSL.SSL_CVERIFY_NONE, OpenSslContext.VERIFY_DEPTH);
break;
case REQUIRE:
SSL.setVerify(ssl, SSL.SSL_CVERIFY_REQUIRE, OpenSslContext.VERIFY_DEPTH);
break;
case OPTIONAL:
SSL.setVerify(ssl, SSL.SSL_CVERIFY_OPTIONAL, OpenSslContext.VERIFY_DEPTH);
break;
}
clientAuth = mode;
}
}
@Override
public void setEnableSessionCreation(boolean b) {
if (b) {
throw new UnsupportedOperationException();
}
}
@Override
public boolean getEnableSessionCreation() {
return false;
}
@Override
public synchronized SSLParameters getSSLParameters() {
SSLParameters sslParameters = super.getSSLParameters();
int version = PlatformDependent.javaVersion();
if (version >= 7) {
sslParameters.setEndpointIdentificationAlgorithm(endPointIdentificationAlgorithm);
SslParametersUtils.setAlgorithmConstraints(sslParameters, algorithmConstraints);
if (version >= 8 && SET_SERVER_NAMES_METHOD != null && sniHostNames != null) {
try {
SET_SERVER_NAMES_METHOD.invoke(sslParameters, sniHostNames);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw new Error(e);
}
}
}
return sslParameters;
}
@Override
public synchronized void setSSLParameters(SSLParameters sslParameters) {
super.setSSLParameters(sslParameters);
int version = PlatformDependent.javaVersion();
if (version >= 7) {
endPointIdentificationAlgorithm = sslParameters.getEndpointIdentificationAlgorithm();
algorithmConstraints = sslParameters.getAlgorithmConstraints();
if (version >= 8 && SNI_HOSTNAME_CLASS != null && clientMode && !isDestroyed()) {
assert GET_SERVER_NAMES_METHOD != null;
assert GET_ASCII_NAME_METHOD != null;
try {
List<?> servernames = (List<?>) GET_SERVER_NAMES_METHOD.invoke(sslParameters);
for (Object serverName : servernames) {
if (SNI_HOSTNAME_CLASS.isInstance(serverName)) {
SSL.setTlsExtHostName(ssl, (String) GET_ASCII_NAME_METHOD.invoke(serverName));
} else {
throw new IllegalArgumentException("Only " + SNI_HOSTNAME_CLASS.getName()
+ " instances are supported, but found: " + serverName);
}
}
sniHostNames = servernames;
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw new Error(e);
}
}
}
}
@Override
@SuppressWarnings("FinalizeDeclaration")
protected void finalize() throws Throwable {
super.finalize();
// Call shutdown as the user may have created the OpenSslEngine and not used it at all.
shutdown();
}
private boolean isDestroyed() {
return destroyed != 0;
}
private final class OpenSslSession implements SSLSession, ApplicationProtocolAccessor {
private final OpenSslSessionContext sessionContext;
// These are guarded by synchronized(OpenSslEngine.this) as handshakeFinished() may be triggered by any
// thread.
private X509Certificate[] x509PeerCerts;
private String protocol;
private String applicationProtocol;
private Certificate[] peerCerts;
private String cipher;
private byte[] id;
private long creationTime;
// lazy init for memory reasons
private Map<String, Object> values;
OpenSslSession(OpenSslSessionContext sessionContext) {
this.sessionContext = sessionContext;
}
@Override
public byte[] getId() {
synchronized (OpenSslEngine.this) {
if (id == null) {
return EmptyArrays.EMPTY_BYTES;
}
return id.clone();
}
}
@Override
public SSLSessionContext getSessionContext() {
return sessionContext;
}
@Override
public long getCreationTime() {
synchronized (OpenSslEngine.this) {
if (creationTime == 0 && !isDestroyed()) {
creationTime = SSL.getTime(ssl) * 1000L;
}
}
return creationTime;
}
@Override
public long getLastAccessedTime() {
// TODO: Add proper implementation
return getCreationTime();
}
@Override
public void invalidate() {
synchronized (OpenSslEngine.this) {
if (!isDestroyed()) {
SSL.setTimeout(ssl, 0);
}
}
}
@Override
public boolean isValid() {
synchronized (OpenSslEngine.this) {
if (!isDestroyed()) {
return System.currentTimeMillis() - (SSL.getTimeout(ssl) * 1000L) < (SSL.getTime(ssl) * 1000L);
}
}
return false;
}
@Override
public void putValue(String name, Object value) {
if (name == null) {
throw new NullPointerException("name");
}
if (value == null) {
throw new NullPointerException("value");
}
Map<String, Object> values = this.values;
if (values == null) {
// Use size of 2 to keep the memory overhead small
values = this.values = new HashMap<String, Object>(2);
}
Object old = values.put(name, value);
if (value instanceof SSLSessionBindingListener) {
((SSLSessionBindingListener) value).valueBound(new SSLSessionBindingEvent(this, name));
}
notifyUnbound(old, name);
}
@Override
public Object getValue(String name) {
if (name == null) {
throw new NullPointerException("name");
}
if (values == null) {
return null;
}
return values.get(name);
}
@Override
public void removeValue(String name) {
if (name == null) {
throw new NullPointerException("name");
}
Map<String, Object> values = this.values;
if (values == null) {
return;
}
Object old = values.remove(name);
notifyUnbound(old, name);
}
@Override
public String[] getValueNames() {
Map<String, Object> values = this.values;
if (values == null || values.isEmpty()) {
return EmptyArrays.EMPTY_STRINGS;
}
return values.keySet().toArray(new String[values.size()]);
}
private void notifyUnbound(Object value, String name) {
if (value instanceof SSLSessionBindingListener) {
((SSLSessionBindingListener) value).valueUnbound(new SSLSessionBindingEvent(this, name));
}
}
/**
* Finish the handshake and so init everything in the {@link OpenSslSession} that should be accessable by
* the user.
*/
void handshakeFinished() throws SSLException {
synchronized (OpenSslEngine.this) {
if (!isDestroyed()) {
id = SSL.getSessionId(ssl);
cipher = toJavaCipherSuite(SSL.getCipherForSSL(ssl));
protocol = SSL.getVersion(ssl);
initPeerCerts();
selectApplicationProtocol();
handshakeState = HandshakeState.FINISHED;
} else {
throw new SSLException("Already closed");
}
}
}
/**
* Init peer certificates that can be obtained via {@link #getPeerCertificateChain()}
* and {@link #getPeerCertificates()}.
*/
private void initPeerCerts() {
// Return the full chain from the JNI layer.
byte[][] chain = SSL.getPeerCertChain(ssl);
final byte[] clientCert;
if (!clientMode) {
// if used on the server side SSL_get_peer_cert_chain(...) will not include the remote peer
// certificate. We use SSL_get_peer_certificate to get it in this case and add it to our
// array later.
//
// See https://www.openssl.org/docs/ssl/SSL_get_peer_cert_chain.html
clientCert = SSL.getPeerCertificate(ssl);
} else {
clientCert = null;
}
if (chain == null && clientCert == null) {
peerCerts = EMPTY_CERTIFICATES;
x509PeerCerts = EMPTY_X509_CERTIFICATES;
} else {
int len = chain != null ? chain.length : 0;
int i = 0;
Certificate[] peerCerts;
if (clientCert != null) {
len++;
peerCerts = new Certificate[len];
peerCerts[i++] = new OpenSslX509Certificate(clientCert);
} else {
peerCerts = new Certificate[len];
}
if (chain != null) {
X509Certificate[] pCerts = new X509Certificate[chain.length];
for (int a = 0; a < pCerts.length; ++i, ++a) {
byte[] bytes = chain[a];
pCerts[a] = new OpenSslJavaxX509Certificate(bytes);
peerCerts[i] = new OpenSslX509Certificate(bytes);
}
x509PeerCerts = pCerts;
} else {
x509PeerCerts = EMPTY_X509_CERTIFICATES;
}
this.peerCerts = peerCerts;
}
}
/**
* Select the application protocol used.
*/
private void selectApplicationProtocol() throws SSLException {
SelectedListenerFailureBehavior behavior = apn.selectedListenerFailureBehavior();
List<String> protocols = apn.protocols();
String applicationProtocol;
switch (apn.protocol()) {
case NONE:
break;
// We always need to check for applicationProtocol == null as the remote peer may not support
// the TLS extension or may have returned an empty selection.
case ALPN:
applicationProtocol = SSL.getAlpnSelected(ssl);
if (applicationProtocol != null) {
this.applicationProtocol = selectApplicationProtocol(
protocols, behavior, applicationProtocol);
}
break;
case NPN:
applicationProtocol = SSL.getNextProtoNegotiated(ssl);
if (applicationProtocol != null) {
this.applicationProtocol = selectApplicationProtocol(
protocols, behavior, applicationProtocol);
}
break;
case NPN_AND_ALPN:
applicationProtocol = SSL.getAlpnSelected(ssl);
if (applicationProtocol == null) {
applicationProtocol = SSL.getNextProtoNegotiated(ssl);
}
if (applicationProtocol != null) {
this.applicationProtocol = selectApplicationProtocol(
protocols, behavior, applicationProtocol);
}
break;
default:
throw new Error();
}
}
private String selectApplicationProtocol(List<String> protocols,
SelectedListenerFailureBehavior behavior,
String applicationProtocol) throws SSLException {
if (behavior == SelectedListenerFailureBehavior.ACCEPT) {
return applicationProtocol;
} else {
int size = protocols.size();
assert size > 0;
if (protocols.contains(applicationProtocol)) {
return applicationProtocol;
} else {
if (behavior == SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL) {
return protocols.get(size - 1);
} else {
throw new SSLException("unknown protocol " + applicationProtocol);
}
}
}
}
@Override
public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
synchronized (OpenSslEngine.this) {
if (peerCerts == null || peerCerts.length == 0) {
throw new SSLPeerUnverifiedException("peer not verified");
}
return peerCerts;
}
}
@Override
public Certificate[] getLocalCertificates() {
if (localCerts == null) {
return null;
}
return localCerts.clone();
}
@Override
public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
synchronized (OpenSslEngine.this) {
if (x509PeerCerts == null || x509PeerCerts.length == 0) {
throw new SSLPeerUnverifiedException("peer not verified");
}
return x509PeerCerts;
}
}
@Override
public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
Certificate[] peer = getPeerCertificates();
// No need for null or length > 0 is needed as this is done in getPeerCertificates()
// already.
return ((java.security.cert.X509Certificate) peer[0]).getSubjectX500Principal();
}
@Override
public Principal getLocalPrincipal() {
Certificate[] local = localCerts;
if (local == null || local.length == 0) {
return null;
}
return ((java.security.cert.X509Certificate) local[0]).getIssuerX500Principal();
}
@Override
public String getCipherSuite() {
synchronized (OpenSslEngine.this) {
if (cipher == null) {
return INVALID_CIPHER;
}
return cipher;
}
}
@Override
public String getProtocol() {
String protocol = this.protocol;
if (protocol == null) {
synchronized (OpenSslEngine.this) {
if (!isDestroyed()) {
protocol = SSL.getVersion(ssl);
} else {
protocol = StringUtil.EMPTY_STRING;
}
}
}
return protocol;
}
@Override
public String getApplicationProtocol() {
synchronized (OpenSslEngine.this) {
return applicationProtocol;
}
}
@Override
public String getPeerHost() {
return OpenSslEngine.this.getPeerHost();
}
@Override
public int getPeerPort() {
return OpenSslEngine.this.getPeerPort();
}
@Override
public int getPacketBufferSize() {
return MAX_ENCRYPTED_PACKET_LENGTH;
}
@Override
public int getApplicationBufferSize() {
return MAX_PLAINTEXT_LENGTH;
}
}
}
|
handler/src/main/java/io/netty/handler/ssl/OpenSslEngine.java
|
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.ssl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.InternalThreadLocalMap;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.apache.tomcat.jni.Buffer;
import org.apache.tomcat.jni.SSL;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionBindingEvent;
import javax.net.ssl.SSLSessionBindingListener;
import javax.net.ssl.SSLSessionContext;
import javax.security.cert.X509Certificate;
import static io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior;
import static io.netty.handler.ssl.OpenSsl.memoryAddress;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.FINISHED;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_WRAP;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
import static javax.net.ssl.SSLEngineResult.Status.BUFFER_OVERFLOW;
import static javax.net.ssl.SSLEngineResult.Status.CLOSED;
import static javax.net.ssl.SSLEngineResult.Status.OK;
/**
* Implements a {@link SSLEngine} using
* <a href="https://www.openssl.org/docs/crypto/BIO_s_bio.html#EXAMPLE">OpenSSL BIO abstractions</a>.
*/
public final class OpenSslEngine extends SSLEngine {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(OpenSslEngine.class);
private static final Certificate[] EMPTY_CERTIFICATES = EmptyArrays.EMPTY_CERTIFICATES;
private static final X509Certificate[] EMPTY_X509_CERTIFICATES = EmptyArrays.EMPTY_JAVAX_X509_CERTIFICATES;
private static final SSLException ENGINE_CLOSED = new SSLException("engine closed");
private static final SSLException RENEGOTIATION_UNSUPPORTED = new SSLException("renegotiation unsupported");
private static final SSLException ENCRYPTED_PACKET_OVERSIZED = new SSLException("encrypted packet oversized");
static {
ENGINE_CLOSED.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);
RENEGOTIATION_UNSUPPORTED.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);
ENCRYPTED_PACKET_OVERSIZED.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);
AtomicIntegerFieldUpdater<OpenSslEngine> destroyedUpdater =
PlatformDependent.newAtomicIntegerFieldUpdater(OpenSslEngine.class, "destroyed");
if (destroyedUpdater == null) {
destroyedUpdater = AtomicIntegerFieldUpdater.newUpdater(OpenSslEngine.class, "destroyed");
}
DESTROYED_UPDATER = destroyedUpdater;
}
private static final int MAX_PLAINTEXT_LENGTH = 16 * 1024; // 2^14
private static final int MAX_COMPRESSED_LENGTH = MAX_PLAINTEXT_LENGTH + 1024;
private static final int MAX_CIPHERTEXT_LENGTH = MAX_COMPRESSED_LENGTH + 1024;
// Protocols
private static final String PROTOCOL_SSL_V2_HELLO = "SSLv2Hello";
private static final String PROTOCOL_SSL_V2 = "SSLv2";
private static final String PROTOCOL_SSL_V3 = "SSLv3";
private static final String PROTOCOL_TLS_V1 = "TLSv1";
private static final String PROTOCOL_TLS_V1_1 = "TLSv1.1";
private static final String PROTOCOL_TLS_V1_2 = "TLSv1.2";
private static final String[] SUPPORTED_PROTOCOLS = {
PROTOCOL_SSL_V2_HELLO,
PROTOCOL_SSL_V2,
PROTOCOL_SSL_V3,
PROTOCOL_TLS_V1,
PROTOCOL_TLS_V1_1,
PROTOCOL_TLS_V1_2
};
private static final Set<String> SUPPORTED_PROTOCOLS_SET = new HashSet<String>(Arrays.asList(SUPPORTED_PROTOCOLS));
// Header (5) + Data (2^14) + Compression (1024) + Encryption (1024) + MAC (20) + Padding (256)
static final int MAX_ENCRYPTED_PACKET_LENGTH = MAX_CIPHERTEXT_LENGTH + 5 + 20 + 256;
static final int MAX_ENCRYPTION_OVERHEAD_LENGTH = MAX_ENCRYPTED_PACKET_LENGTH - MAX_PLAINTEXT_LENGTH;
private static final AtomicIntegerFieldUpdater<OpenSslEngine> DESTROYED_UPDATER;
private static final String INVALID_CIPHER = "SSL_NULL_WITH_NULL_NULL";
private static final long EMPTY_ADDR = Buffer.address(Unpooled.EMPTY_BUFFER.nioBuffer());
private static final SSLEngineResult NEED_UNWRAP_OK = new SSLEngineResult(OK, NEED_UNWRAP, 0, 0);
private static final SSLEngineResult NEED_UNWRAP_CLOSED = new SSLEngineResult(CLOSED, NEED_UNWRAP, 0, 0);
private static final SSLEngineResult NEED_WRAP_OK = new SSLEngineResult(OK, NEED_WRAP, 0, 0);
private static final SSLEngineResult NEED_WRAP_CLOSED = new SSLEngineResult(CLOSED, NEED_WRAP, 0, 0);
private static final SSLEngineResult CLOSED_NOT_HANDSHAKING = new SSLEngineResult(CLOSED, NOT_HANDSHAKING, 0, 0);
// OpenSSL state
private long ssl;
private long networkBIO;
private enum HandshakeState {
/**
* Not started yet.
*/
NOT_STARTED,
/**
* Started via unwrap/wrap.
*/
STARTED_IMPLICITLY,
/**
* Started via {@link #beginHandshake()}.
*/
STARTED_EXPLICITLY,
/**
* Handshake is finished.
*/
FINISHED
}
private HandshakeState handshakeState = HandshakeState.NOT_STARTED;
private boolean receivedShutdown;
private volatile int destroyed;
private volatile ClientAuth clientAuth = ClientAuth.NONE;
private volatile String endPointIdentificationAlgorithm;
// Store as object as AlgorithmConstraints only exists since java 7.
private volatile Object algorithmConstraints;
// SSL Engine status variables
private boolean isInboundDone;
private boolean isOutboundDone;
private boolean engineClosed;
private final boolean clientMode;
private final ByteBufAllocator alloc;
private final OpenSslEngineMap engineMap;
private final OpenSslApplicationProtocolNegotiator apn;
private final boolean rejectRemoteInitiatedRenegation;
private final OpenSslSession session;
private final Certificate[] localCerts;
private final ByteBuffer[] singleSrcBuffer = new ByteBuffer[1];
private final ByteBuffer[] singleDstBuffer = new ByteBuffer[1];
// This is package-private as we set it from OpenSslContext if an exception is thrown during
// the verification step.
SSLHandshakeException handshakeException;
/**
* Creates a new instance
*
* @param sslCtx an OpenSSL {@code SSL_CTX} object
* @param alloc the {@link ByteBufAllocator} that will be used by this engine
*/
@Deprecated
public OpenSslEngine(long sslCtx, ByteBufAllocator alloc,
@SuppressWarnings("unused") String fallbackApplicationProtocol) {
this(sslCtx, alloc, false, null, OpenSslContext.NONE_PROTOCOL_NEGOTIATOR, OpenSslEngineMap.EMPTY, false,
ClientAuth.NONE);
}
OpenSslEngine(long sslCtx, ByteBufAllocator alloc,
boolean clientMode, OpenSslSessionContext sessionContext,
OpenSslApplicationProtocolNegotiator apn, OpenSslEngineMap engineMap,
boolean rejectRemoteInitiatedRenegation,
ClientAuth clientAuth) {
this(sslCtx, alloc, clientMode, sessionContext, apn, engineMap, rejectRemoteInitiatedRenegation, null, -1,
null, clientAuth);
}
OpenSslEngine(long sslCtx, ByteBufAllocator alloc,
boolean clientMode, OpenSslSessionContext sessionContext,
OpenSslApplicationProtocolNegotiator apn, OpenSslEngineMap engineMap,
boolean rejectRemoteInitiatedRenegation, String peerHost, int peerPort,
Certificate[] localCerts,
ClientAuth clientAuth) {
super(peerHost, peerPort);
OpenSsl.ensureAvailability();
if (sslCtx == 0) {
throw new NullPointerException("sslCtx");
}
this.alloc = checkNotNull(alloc, "alloc");
this.apn = checkNotNull(apn, "apn");
ssl = SSL.newSSL(sslCtx, !clientMode);
session = new OpenSslSession(sessionContext);
networkBIO = SSL.makeNetworkBIO(ssl);
this.clientMode = clientMode;
this.engineMap = engineMap;
this.rejectRemoteInitiatedRenegation = rejectRemoteInitiatedRenegation;
this.localCerts = localCerts;
// Set the client auth mode, this needs to be done via setClientAuth(...) method so we actually call the
// needed JNI methods.
setClientAuth(clientMode ? ClientAuth.NONE : checkNotNull(clientAuth, "clientAuth"));
// Use SNI if peerHost was specified
// See https://github.com/netty/netty/issues/4746
if (clientMode && peerHost != null) {
SSL.setTlsExtHostName(ssl, peerHost);
}
}
@Override
public synchronized SSLSession getHandshakeSession() {
// Javadocs state return value should be:
// null if this instance is not currently handshaking, or if the current handshake has not
// progressed far enough to create a basic SSLSession. Otherwise, this method returns the
// SSLSession currently being negotiated.
switch(handshakeState) {
case NOT_STARTED:
case FINISHED:
return null;
default:
return session;
}
}
/**
* Returns the pointer to the {@code SSL} object for this {@link OpenSslEngine}.
* Be aware that it is freed as soon as the {@link #finalize()} or {@link #shutdown} method is called.
* At this point {@code 0} will be returned.
*/
public synchronized long sslPointer() {
return ssl;
}
/**
* Destroys this engine.
*/
public synchronized void shutdown() {
if (DESTROYED_UPDATER.compareAndSet(this, 0, 1)) {
engineMap.remove(ssl);
SSL.freeSSL(ssl);
SSL.freeBIO(networkBIO);
ssl = networkBIO = 0;
// internal errors can cause shutdown without marking the engine closed
isInboundDone = isOutboundDone = engineClosed = true;
}
// On shutdown clear all errors
SSL.clearError();
}
/**
* Write plaintext data to the OpenSSL internal BIO
*
* Calling this function with src.remaining == 0 is undefined.
*/
private int writePlaintextData(final ByteBuffer src) {
final int pos = src.position();
final int limit = src.limit();
final int len = Math.min(limit - pos, MAX_PLAINTEXT_LENGTH);
final int sslWrote;
if (src.isDirect()) {
final long addr = Buffer.address(src) + pos;
sslWrote = SSL.writeToSSL(ssl, addr, len);
if (sslWrote > 0) {
src.position(pos + sslWrote);
}
} else {
ByteBuf buf = alloc.directBuffer(len);
try {
final long addr = memoryAddress(buf);
src.limit(pos + len);
buf.setBytes(0, src);
src.limit(limit);
sslWrote = SSL.writeToSSL(ssl, addr, len);
if (sslWrote > 0) {
src.position(pos + sslWrote);
} else {
src.position(pos);
}
} finally {
buf.release();
}
}
return sslWrote;
}
/**
* Write encrypted data to the OpenSSL network BIO.
*/
private int writeEncryptedData(final ByteBuffer src) {
final int pos = src.position();
final int len = src.remaining();
final int netWrote;
if (src.isDirect()) {
final long addr = Buffer.address(src) + pos;
netWrote = SSL.writeToBIO(networkBIO, addr, len);
if (netWrote >= 0) {
src.position(pos + netWrote);
}
} else {
final ByteBuf buf = alloc.directBuffer(len);
try {
final long addr = memoryAddress(buf);
buf.setBytes(0, src);
netWrote = SSL.writeToBIO(networkBIO, addr, len);
if (netWrote >= 0) {
src.position(pos + netWrote);
} else {
src.position(pos);
}
} finally {
buf.release();
}
}
return netWrote;
}
/**
* Read plaintext data from the OpenSSL internal BIO
*/
private int readPlaintextData(final ByteBuffer dst) {
final int sslRead;
if (dst.isDirect()) {
final int pos = dst.position();
final long addr = Buffer.address(dst) + pos;
final int len = dst.limit() - pos;
sslRead = SSL.readFromSSL(ssl, addr, len);
if (sslRead > 0) {
dst.position(pos + sslRead);
}
} else {
final int pos = dst.position();
final int limit = dst.limit();
final int len = Math.min(MAX_ENCRYPTED_PACKET_LENGTH, limit - pos);
final ByteBuf buf = alloc.directBuffer(len);
try {
final long addr = memoryAddress(buf);
sslRead = SSL.readFromSSL(ssl, addr, len);
if (sslRead > 0) {
dst.limit(pos + sslRead);
buf.getBytes(0, dst);
dst.limit(limit);
}
} finally {
buf.release();
}
}
return sslRead;
}
/**
* Read encrypted data from the OpenSSL network BIO
*/
private int readEncryptedData(final ByteBuffer dst, final int pending) {
final int bioRead;
if (dst.isDirect() && dst.remaining() >= pending) {
final int pos = dst.position();
final long addr = Buffer.address(dst) + pos;
bioRead = SSL.readFromBIO(networkBIO, addr, pending);
if (bioRead > 0) {
dst.position(pos + bioRead);
return bioRead;
}
} else {
final ByteBuf buf = alloc.directBuffer(pending);
try {
final long addr = memoryAddress(buf);
bioRead = SSL.readFromBIO(networkBIO, addr, pending);
if (bioRead > 0) {
int oldLimit = dst.limit();
dst.limit(dst.position() + bioRead);
buf.getBytes(0, dst);
dst.limit(oldLimit);
return bioRead;
}
} finally {
buf.release();
}
}
return bioRead;
}
private SSLEngineResult readPendingBytesFromBIO(
ByteBuffer dst, int bytesConsumed, int bytesProduced, HandshakeStatus status) throws SSLException {
// Check to see if the engine wrote data into the network BIO
int pendingNet = SSL.pendingWrittenBytesInBIO(networkBIO);
if (pendingNet > 0) {
// Do we have enough room in dst to write encrypted data?
int capacity = dst.remaining();
if (capacity < pendingNet) {
return new SSLEngineResult(BUFFER_OVERFLOW,
mayFinishHandshake(status != FINISHED ? getHandshakeStatus(pendingNet) : status),
bytesConsumed, bytesProduced);
}
// Write the pending data from the network BIO into the dst buffer
int produced = readEncryptedData(dst, pendingNet);
if (produced <= 0) {
// We ignore BIO_* errors here as we use in memory BIO anyway and will do another SSL_* call later
// on in which we will produce an exception in case of an error
SSL.clearError();
} else {
bytesProduced += produced;
pendingNet -= produced;
}
// If isOuboundDone is set, then the data from the network BIO
// was the close_notify message -- we are not required to wait
// for the receipt the peer's close_notify message -- shutdown.
if (isOutboundDone) {
shutdown();
}
return new SSLEngineResult(getEngineStatus(),
mayFinishHandshake(status != FINISHED ? getHandshakeStatus(pendingNet) : status),
bytesConsumed, bytesProduced);
}
return null;
}
@Override
public synchronized SSLEngineResult wrap(
final ByteBuffer[] srcs, final int offset, final int length, final ByteBuffer dst) throws SSLException {
// Check to make sure the engine has not been closed
if (isDestroyed()) {
return CLOSED_NOT_HANDSHAKING;
}
// Throw required runtime exceptions
if (srcs == null) {
throw new IllegalArgumentException("srcs is null");
}
if (dst == null) {
throw new IllegalArgumentException("dst is null");
}
if (offset >= srcs.length || offset + length > srcs.length) {
throw new IndexOutOfBoundsException(
"offset: " + offset + ", length: " + length +
" (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
}
if (dst.isReadOnly()) {
throw new ReadOnlyBufferException();
}
HandshakeStatus status = NOT_HANDSHAKING;
// Prepare OpenSSL to work in server mode and receive handshake
if (handshakeState != HandshakeState.FINISHED) {
if (handshakeState != HandshakeState.STARTED_EXPLICITLY) {
// Update accepted so we know we triggered the handshake via wrap
handshakeState = HandshakeState.STARTED_IMPLICITLY;
}
status = handshake();
if (status == NEED_UNWRAP) {
return NEED_UNWRAP_OK;
}
if (engineClosed) {
return NEED_UNWRAP_CLOSED;
}
}
// There was no pending data in the network BIO -- encrypt any application data
int bytesProduced = 0;
int bytesConsumed = 0;
int endOffset = offset + length;
for (int i = offset; i < endOffset; ++ i) {
final ByteBuffer src = srcs[i];
if (src == null) {
throw new IllegalArgumentException("srcs[" + i + "] is null");
}
while (src.hasRemaining()) {
final SSLEngineResult pendingNetResult;
// Write plaintext application data to the SSL engine
int result = writePlaintextData(src);
if (result > 0) {
bytesConsumed += result;
pendingNetResult = readPendingBytesFromBIO(dst, bytesConsumed, bytesProduced, status);
if (pendingNetResult != null) {
if (pendingNetResult.getStatus() != OK) {
return pendingNetResult;
}
bytesProduced = pendingNetResult.bytesProduced();
}
} else {
int sslError = SSL.getError(ssl, result);
switch (sslError) {
case SSL.SSL_ERROR_ZERO_RETURN:
// This means the connection was shutdown correctly, close inbound and outbound
if (!receivedShutdown) {
closeAll();
}
pendingNetResult = readPendingBytesFromBIO(dst, bytesConsumed, bytesProduced, status);
return pendingNetResult != null ? pendingNetResult : CLOSED_NOT_HANDSHAKING;
case SSL.SSL_ERROR_WANT_READ:
// If there is no pending data to read from BIO we should go back to event loop and try to read
// more data [1]. It is also possible that event loop will detect the socket has been closed.
// [1] https://www.openssl.org/docs/manmaster/ssl/SSL_write.html
pendingNetResult = readPendingBytesFromBIO(dst, bytesConsumed, bytesProduced, status);
return pendingNetResult != null ? pendingNetResult :
new SSLEngineResult(getEngineStatus(), NEED_UNWRAP, bytesConsumed, bytesProduced);
case SSL.SSL_ERROR_WANT_WRITE:
// SSL_ERROR_WANT_WRITE typically means that the underlying transport is not writable and we
// should set the "want write" flag on the selector and try again when the underlying transport
// is writable [1]. However we are not directly writing to the underlying transport and instead
// writing to a BIO buffer. The OpenSsl documentation says we should do the following [1]:
//
// "When using a buffering BIO, like a BIO pair, data must be written into or retrieved out of
// the BIO before being able to continue."
//
// So we attempt to drain the BIO buffer below, but if there is no data this condition is
// undefined and we assume their is a fatal error with the openssl engine and close.
// [1] https://www.openssl.org/docs/manmaster/ssl/SSL_write.html
pendingNetResult = readPendingBytesFromBIO(dst, bytesConsumed, bytesProduced, status);
return pendingNetResult != null ? pendingNetResult : NEED_WRAP_CLOSED;
default:
// Everything else is considered as error
throw shutdownWithError("SSL_write");
}
}
}
}
// We need to check if pendingWrittenBytesInBIO was checked yet, as we may not checked if the srcs was empty,
// or only contained empty buffers.
if (bytesConsumed == 0) {
SSLEngineResult pendingNetResult = readPendingBytesFromBIO(dst, 0, bytesProduced, status);
if (pendingNetResult != null) {
return pendingNetResult;
}
}
return newResult(bytesConsumed, bytesProduced, status);
}
/**
* Log the error, shutdown the engine and throw an exception.
*/
private SSLException shutdownWithError(String operations) {
String err = SSL.getLastError();
return shutdownWithError(operations, err);
}
private SSLException shutdownWithError(String operation, String err) {
if (logger.isDebugEnabled()) {
logger.debug("{} failed: OpenSSL error: {}", operation, err);
}
// There was an internal error -- shutdown
shutdown();
if (handshakeState == HandshakeState.FINISHED) {
return new SSLException(err);
}
return new SSLHandshakeException(err);
}
public synchronized SSLEngineResult unwrap(
final ByteBuffer[] srcs, int srcsOffset, final int srcsLength,
final ByteBuffer[] dsts, final int dstsOffset, final int dstsLength) throws SSLException {
// Check to make sure the engine has not been closed
if (isDestroyed()) {
return CLOSED_NOT_HANDSHAKING;
}
// Throw required runtime exceptions
if (srcs == null) {
throw new NullPointerException("srcs");
}
if (srcsOffset >= srcs.length
|| srcsOffset + srcsLength > srcs.length) {
throw new IndexOutOfBoundsException(
"offset: " + srcsOffset + ", length: " + srcsLength +
" (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
}
if (dsts == null) {
throw new IllegalArgumentException("dsts is null");
}
if (dstsOffset >= dsts.length || dstsOffset + dstsLength > dsts.length) {
throw new IndexOutOfBoundsException(
"offset: " + dstsOffset + ", length: " + dstsLength +
" (expected: offset <= offset + length <= dsts.length (" + dsts.length + "))");
}
long capacity = 0;
final int endOffset = dstsOffset + dstsLength;
for (int i = dstsOffset; i < endOffset; i ++) {
ByteBuffer dst = dsts[i];
if (dst == null) {
throw new IllegalArgumentException("dsts[" + i + "] is null");
}
if (dst.isReadOnly()) {
throw new ReadOnlyBufferException();
}
capacity += dst.remaining();
}
HandshakeStatus status = NOT_HANDSHAKING;
// Prepare OpenSSL to work in server mode and receive handshake
if (handshakeState != HandshakeState.FINISHED) {
if (handshakeState != HandshakeState.STARTED_EXPLICITLY) {
// Update accepted so we know we triggered the handshake via wrap
handshakeState = HandshakeState.STARTED_IMPLICITLY;
}
status = handshake();
if (status == NEED_WRAP) {
return NEED_WRAP_OK;
}
if (engineClosed) {
return NEED_WRAP_CLOSED;
}
}
final int srcsEndOffset = srcsOffset + srcsLength;
long len = 0;
for (int i = srcsOffset; i < srcsEndOffset; i++) {
ByteBuffer src = srcs[i];
if (src == null) {
throw new IllegalArgumentException("srcs[" + i + "] is null");
}
len += src.remaining();
}
// protect against protocol overflow attack vector
if (len > MAX_ENCRYPTED_PACKET_LENGTH) {
isInboundDone = true;
isOutboundDone = true;
engineClosed = true;
shutdown();
throw ENCRYPTED_PACKET_OVERSIZED;
}
// Write encrypted data to network BIO
int bytesConsumed = 0;
if (srcsOffset < srcsEndOffset) {
do {
ByteBuffer src = srcs[srcsOffset];
int remaining = src.remaining();
if (remaining == 0) {
// We must skip empty buffers as BIO_write will return 0 if asked to write something
// with length 0.
srcsOffset ++;
continue;
}
int written = writeEncryptedData(src);
if (written > 0) {
bytesConsumed += written;
if (written == remaining) {
srcsOffset ++;
} else {
// We were not able to write everything into the BIO so break the write loop as otherwise
// we will produce an error on the next write attempt, which will trigger a SSL.clearError()
// later.
break;
}
} else {
// BIO_write returned a negative or zero number, this means we could not complete the write
// operation and should retry later.
// We ignore BIO_* errors here as we use in memory BIO anyway and will do another SSL_* call later
// on in which we will produce an exception in case of an error
SSL.clearError();
break;
}
} while (srcsOffset < srcsEndOffset);
}
// Number of produced bytes
int bytesProduced = 0;
if (capacity > 0) {
// Write decrypted data to dsts buffers
int idx = dstsOffset;
while (idx < endOffset) {
ByteBuffer dst = dsts[idx];
if (!dst.hasRemaining()) {
idx ++;
continue;
}
int bytesRead = readPlaintextData(dst);
// TODO: We may want to consider if we move this check and only do it in a less often called place at
// the price of not being 100% accurate, like for example when calling SSL.getError(...).
rejectRemoteInitiatedRenegation();
if (bytesRead > 0) {
bytesProduced += bytesRead;
if (!dst.hasRemaining()) {
idx ++;
} else {
// We read everything return now.
return newResult(bytesConsumed, bytesProduced, status);
}
} else {
int sslError = SSL.getError(ssl, bytesRead);
switch (sslError) {
case SSL.SSL_ERROR_ZERO_RETURN:
// This means the connection was shutdown correctly, close inbound and outbound
if (!receivedShutdown) {
closeAll();
}
// fall-trough!
case SSL.SSL_ERROR_WANT_READ:
case SSL.SSL_ERROR_WANT_WRITE:
// break to the outer loop
return newResult(bytesConsumed, bytesProduced, status);
default:
return sslReadErrorResult(SSL.getLastErrorNumber(), bytesConsumed, bytesProduced);
}
}
}
} else {
// If the capacity of all destination buffers is 0 we need to trigger a SSL_read anyway to ensure
// everything is flushed in the BIO pair and so we can detect it in the pendingAppData() call.
if (SSL.readFromSSL(ssl, EMPTY_ADDR, 0) <= 0) {
// We do not check SSL_get_error as we are not interested in any error that is not fatal.
int err = SSL.getLastErrorNumber();
if (OpenSsl.isError(err)) {
return sslReadErrorResult(err, bytesConsumed, bytesProduced);
}
}
}
if (pendingAppData() > 0) {
// We filled all buffers but there is still some data pending in the BIO buffer, return BUFFER_OVERFLOW.
return new SSLEngineResult(
BUFFER_OVERFLOW, mayFinishHandshake(status != FINISHED ? getHandshakeStatus(): status),
bytesConsumed, bytesProduced);
}
// Check to see if we received a close_notify message from the peer.
if (!receivedShutdown && (SSL.getShutdown(ssl) & SSL.SSL_RECEIVED_SHUTDOWN) == SSL.SSL_RECEIVED_SHUTDOWN) {
closeAll();
}
return newResult(bytesConsumed, bytesProduced, status);
}
private SSLEngineResult sslReadErrorResult(int err, int bytesConsumed, int bytesProduced) throws SSLException {
String errStr = SSL.getErrorString(err);
// Check if we have a pending handshakeException and if so see if we need to consume all pending data from the
// BIO first or can just shutdown and throw it now.
// This is needed so we ensure close_notify etc is correctly send to the remote peer.
// See https://github.com/netty/netty/issues/3900
if (SSL.pendingWrittenBytesInBIO(networkBIO) > 0) {
if (handshakeException == null && handshakeState != HandshakeState.FINISHED) {
// we seems to have data left that needs to be transfered and so the user needs
// call wrap(...). Store the error so we can pick it up later.
handshakeException = new SSLHandshakeException(errStr);
}
return new SSLEngineResult(OK, NEED_WRAP, bytesConsumed, bytesProduced);
}
throw shutdownWithError("SSL_read", errStr);
}
private int pendingAppData() {
// There won't be any application data until we're done handshaking.
// We first check handshakeFinished to eliminate the overhead of extra JNI call if possible.
return handshakeState == HandshakeState.FINISHED ? SSL.pendingReadableBytesInSSL(ssl) : 0;
}
private SSLEngineResult newResult(
int bytesConsumed, int bytesProduced, HandshakeStatus status) throws SSLException {
return new SSLEngineResult(
getEngineStatus(), mayFinishHandshake(status != FINISHED ? getHandshakeStatus() : status)
, bytesConsumed, bytesProduced);
}
private void closeAll() throws SSLException {
receivedShutdown = true;
closeOutbound();
closeInbound();
}
private void rejectRemoteInitiatedRenegation() throws SSLHandshakeException {
if (rejectRemoteInitiatedRenegation && SSL.getHandshakeCount(ssl) > 1) {
// TODO: In future versions me may also want to send a fatal_alert to the client and so notify it
// that the renegotiation failed.
shutdown();
throw new SSLHandshakeException("remote-initiated renegotation not allowed");
}
}
public SSLEngineResult unwrap(final ByteBuffer[] srcs, final ByteBuffer[] dsts) throws SSLException {
return unwrap(srcs, 0, srcs.length, dsts, 0, dsts.length);
}
private ByteBuffer[] singleSrcBuffer(ByteBuffer src) {
singleSrcBuffer[0] = src;
return singleSrcBuffer;
}
private void resetSingleSrcBuffer() {
singleSrcBuffer[0] = null;
}
private ByteBuffer[] singleDstBuffer(ByteBuffer src) {
singleDstBuffer[0] = src;
return singleDstBuffer;
}
private void resetSingleDstBuffer() {
singleDstBuffer[0] = null;
}
@Override
public synchronized SSLEngineResult unwrap(
final ByteBuffer src, final ByteBuffer[] dsts, final int offset, final int length) throws SSLException {
try {
return unwrap(singleSrcBuffer(src), 0, 1, dsts, offset, length);
} finally {
resetSingleSrcBuffer();
}
}
@Override
public synchronized SSLEngineResult wrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
try {
return wrap(singleSrcBuffer(src), dst);
} finally {
resetSingleSrcBuffer();
}
}
@Override
public synchronized SSLEngineResult unwrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
try {
return unwrap(singleSrcBuffer(src), singleDstBuffer(dst));
} finally {
resetSingleSrcBuffer();
resetSingleDstBuffer();
}
}
@Override
public synchronized SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts) throws SSLException {
try {
return unwrap(singleSrcBuffer(src), dsts);
} finally {
resetSingleSrcBuffer();
}
}
@Override
public Runnable getDelegatedTask() {
// Currently, we do not delegate SSL computation tasks
// TODO: in the future, possibly create tasks to do encrypt / decrypt async
return null;
}
@Override
public synchronized void closeInbound() throws SSLException {
if (isInboundDone) {
return;
}
isInboundDone = true;
engineClosed = true;
shutdown();
if (handshakeState != HandshakeState.NOT_STARTED && !receivedShutdown) {
throw new SSLException(
"Inbound closed before receiving peer's close_notify: possible truncation attack?");
}
}
@Override
public synchronized boolean isInboundDone() {
return isInboundDone || engineClosed;
}
@Override
public synchronized void closeOutbound() {
if (isOutboundDone) {
return;
}
isOutboundDone = true;
engineClosed = true;
if (handshakeState != HandshakeState.NOT_STARTED && !isDestroyed()) {
int mode = SSL.getShutdown(ssl);
if ((mode & SSL.SSL_SENT_SHUTDOWN) != SSL.SSL_SENT_SHUTDOWN) {
int err = SSL.shutdownSSL(ssl);
if (err < 0) {
int sslErr = SSL.getError(ssl, err);
switch (sslErr) {
case SSL.SSL_ERROR_NONE:
case SSL.SSL_ERROR_WANT_ACCEPT:
case SSL.SSL_ERROR_WANT_CONNECT:
case SSL.SSL_ERROR_WANT_WRITE:
case SSL.SSL_ERROR_WANT_READ:
case SSL.SSL_ERROR_WANT_X509_LOOKUP:
case SSL.SSL_ERROR_ZERO_RETURN:
// Nothing to do here
break;
case SSL.SSL_ERROR_SYSCALL:
case SSL.SSL_ERROR_SSL:
if (logger.isDebugEnabled()) {
logger.debug("SSL_shutdown failed: OpenSSL error: {}", SSL.getLastError());
}
// There was an internal error -- shutdown
shutdown();
break;
default:
SSL.clearError();
break;
}
}
}
} else {
// engine closing before initial handshake
shutdown();
}
}
@Override
public synchronized boolean isOutboundDone() {
return isOutboundDone;
}
@Override
public String[] getSupportedCipherSuites() {
Set<String> availableCipherSuites = OpenSsl.availableCipherSuites();
return availableCipherSuites.toArray(new String[availableCipherSuites.size()]);
}
@Override
public String[] getEnabledCipherSuites() {
final String[] enabled;
synchronized (this) {
if (!isDestroyed()) {
enabled = SSL.getCiphers(ssl);
} else {
return EmptyArrays.EMPTY_STRINGS;
}
}
if (enabled == null) {
return EmptyArrays.EMPTY_STRINGS;
} else {
for (int i = 0; i < enabled.length; i++) {
String mapped = toJavaCipherSuite(enabled[i]);
if (mapped != null) {
enabled[i] = mapped;
}
}
return enabled;
}
}
@Override
public void setEnabledCipherSuites(String[] cipherSuites) {
checkNotNull(cipherSuites, "cipherSuites");
final StringBuilder buf = new StringBuilder();
for (String c: cipherSuites) {
if (c == null) {
break;
}
String converted = CipherSuiteConverter.toOpenSsl(c);
if (converted == null) {
converted = c;
}
if (!OpenSsl.isCipherSuiteAvailable(converted)) {
throw new IllegalArgumentException("unsupported cipher suite: " + c + '(' + converted + ')');
}
buf.append(converted);
buf.append(':');
}
if (buf.length() == 0) {
throw new IllegalArgumentException("empty cipher suites");
}
buf.setLength(buf.length() - 1);
final String cipherSuiteSpec = buf.toString();
synchronized (this) {
if (!isDestroyed()) {
try {
SSL.setCipherSuites(ssl, cipherSuiteSpec);
} catch (Exception e) {
throw new IllegalStateException("failed to enable cipher suites: " + cipherSuiteSpec, e);
}
} else {
throw new IllegalStateException("failed to enable cipher suites: " + cipherSuiteSpec);
}
}
}
@Override
public String[] getSupportedProtocols() {
return SUPPORTED_PROTOCOLS.clone();
}
@Override
public String[] getEnabledProtocols() {
List<String> enabled = InternalThreadLocalMap.get().arrayList();
// Seems like there is no way to explict disable SSLv2Hello in openssl so it is always enabled
enabled.add(PROTOCOL_SSL_V2_HELLO);
int opts;
synchronized (this) {
if (!isDestroyed()) {
opts = SSL.getOptions(ssl);
} else {
return enabled.toArray(new String[1]);
}
}
if ((opts & SSL.SSL_OP_NO_TLSv1) == 0) {
enabled.add(PROTOCOL_TLS_V1);
}
if ((opts & SSL.SSL_OP_NO_TLSv1_1) == 0) {
enabled.add(PROTOCOL_TLS_V1_1);
}
if ((opts & SSL.SSL_OP_NO_TLSv1_2) == 0) {
enabled.add(PROTOCOL_TLS_V1_2);
}
if ((opts & SSL.SSL_OP_NO_SSLv2) == 0) {
enabled.add(PROTOCOL_SSL_V2);
}
if ((opts & SSL.SSL_OP_NO_SSLv3) == 0) {
enabled.add(PROTOCOL_SSL_V3);
}
return enabled.toArray(new String[enabled.size()]);
}
@Override
public void setEnabledProtocols(String[] protocols) {
if (protocols == null) {
// This is correct from the API docs
throw new IllegalArgumentException();
}
boolean sslv2 = false;
boolean sslv3 = false;
boolean tlsv1 = false;
boolean tlsv1_1 = false;
boolean tlsv1_2 = false;
for (String p: protocols) {
if (!SUPPORTED_PROTOCOLS_SET.contains(p)) {
throw new IllegalArgumentException("Protocol " + p + " is not supported.");
}
if (p.equals(PROTOCOL_SSL_V2)) {
sslv2 = true;
} else if (p.equals(PROTOCOL_SSL_V3)) {
sslv3 = true;
} else if (p.equals(PROTOCOL_TLS_V1)) {
tlsv1 = true;
} else if (p.equals(PROTOCOL_TLS_V1_1)) {
tlsv1_1 = true;
} else if (p.equals(PROTOCOL_TLS_V1_2)) {
tlsv1_2 = true;
}
}
synchronized (this) {
if (!isDestroyed()) {
// Enable all and then disable what we not want
SSL.setOptions(ssl, SSL.SSL_OP_ALL);
// Clear out options which disable protocols
SSL.clearOptions(ssl, SSL.SSL_OP_NO_SSLv2 | SSL.SSL_OP_NO_SSLv3 | SSL.SSL_OP_NO_TLSv1 |
SSL.SSL_OP_NO_TLSv1_1 | SSL.SSL_OP_NO_TLSv1_2);
int opts = 0;
if (!sslv2) {
opts |= SSL.SSL_OP_NO_SSLv2;
}
if (!sslv3) {
opts |= SSL.SSL_OP_NO_SSLv3;
}
if (!tlsv1) {
opts |= SSL.SSL_OP_NO_TLSv1;
}
if (!tlsv1_1) {
opts |= SSL.SSL_OP_NO_TLSv1_1;
}
if (!tlsv1_2) {
opts |= SSL.SSL_OP_NO_TLSv1_2;
}
// Disable protocols we do not want
SSL.setOptions(ssl, opts);
} else {
throw new IllegalStateException("failed to enable protocols: " + Arrays.asList(protocols));
}
}
}
@Override
public SSLSession getSession() {
return session;
}
@Override
public synchronized void beginHandshake() throws SSLException {
switch (handshakeState) {
case STARTED_IMPLICITLY:
checkEngineClosed();
// A user did not start handshake by calling this method by him/herself,
// but handshake has been started already by wrap() or unwrap() implicitly.
// Because it's the user's first time to call this method, it is unfair to
// raise an exception. From the user's standpoint, he or she never asked
// for renegotiation.
handshakeState = HandshakeState.STARTED_EXPLICITLY; // Next time this method is invoked by the user,
// we should raise an exception.
break;
case STARTED_EXPLICITLY:
// Nothing to do as the handshake is not done yet.
break;
case FINISHED:
if (clientMode) {
// Only supported for server mode at the moment.
throw RENEGOTIATION_UNSUPPORTED;
}
// For renegotiate on the server side we need to issue the following command sequence with openssl:
//
// SSL_renegotiate(ssl)
// SSL_do_handshake(ssl)
// ssl->state = SSL_ST_ACCEPT
// SSL_do_handshake(ssl)
//
// Bcause of this we fall-through to call handshake() after setting the state, as this will also take
// care of updating the internal OpenSslSession object.
//
// See also:
// https://github.com/apache/httpd/blob/2.4.16/modules/ssl/ssl_engine_kernel.c#L812
// http://h71000.www7.hp.com/doc/83final/ba554_90007/ch04s03.html
if (SSL.renegotiate(ssl) != 1 || SSL.doHandshake(ssl) != 1) {
throw shutdownWithError("renegotiation failed");
}
SSL.setState(ssl, SSL.SSL_ST_ACCEPT);
// fall-through
case NOT_STARTED:
handshakeState = HandshakeState.STARTED_EXPLICITLY;
handshake();
break;
default:
throw new Error();
}
}
private void checkEngineClosed() throws SSLException {
if (engineClosed || isDestroyed()) {
throw ENGINE_CLOSED;
}
}
private static HandshakeStatus pendingStatus(int pendingStatus) {
// Depending on if there is something left in the BIO we need to WRAP or UNWRAP
return pendingStatus > 0 ? NEED_WRAP : NEED_UNWRAP;
}
private HandshakeStatus handshake() throws SSLException {
if (handshakeState == HandshakeState.FINISHED) {
return FINISHED;
}
checkEngineClosed();
// Check if we have a pending handshakeException and if so see if we need to consume all pending data from the
// BIO first or can just shutdown and throw it now.
// This is needed so we ensure close_notify etc is correctly send to the remote peer.
// See https://github.com/netty/netty/issues/3900
SSLHandshakeException exception = handshakeException;
if (exception != null) {
if (SSL.pendingWrittenBytesInBIO(networkBIO) > 0) {
// There is something pending, we need to consume it first via a WRAP so we not loose anything.
return NEED_WRAP;
}
// No more data left to send to the remote peer, so null out the exception field, shutdown and throw
// the exception.
handshakeException = null;
shutdown();
throw exception;
}
// Adding the OpenSslEngine to the OpenSslEngineMap so it can be used in the AbstractCertificateVerifier.
engineMap.add(this);
int code = SSL.doHandshake(ssl);
if (code <= 0) {
// Check if we have a pending exception that was created during the handshake and if so throw it after
// shutdown the connection.
if (handshakeException != null) {
exception = handshakeException;
handshakeException = null;
shutdown();
throw exception;
}
int sslError = SSL.getError(ssl, code);
switch (sslError) {
case SSL.SSL_ERROR_WANT_READ:
case SSL.SSL_ERROR_WANT_WRITE:
return pendingStatus(SSL.pendingWrittenBytesInBIO(networkBIO));
default:
// Everything else is considered as error
throw shutdownWithError("SSL_do_handshake");
}
}
// if SSL_do_handshake returns > 0 or sslError == SSL.SSL_ERROR_NAME it means the handshake was finished.
session.handshakeFinished();
return FINISHED;
}
private Status getEngineStatus() {
return engineClosed? CLOSED : OK;
}
private SSLEngineResult.HandshakeStatus mayFinishHandshake(SSLEngineResult.HandshakeStatus status)
throws SSLException {
if (status == NOT_HANDSHAKING && handshakeState != HandshakeState.FINISHED) {
// If the status was NOT_HANDSHAKING and we not finished the handshake we need to call
// SSL_do_handshake() again
return handshake();
}
return status;
}
@Override
public synchronized SSLEngineResult.HandshakeStatus getHandshakeStatus() {
// Check if we are in the initial handshake phase or shutdown phase
return needPendingStatus() ? pendingStatus(SSL.pendingWrittenBytesInBIO(networkBIO)) : NOT_HANDSHAKING;
}
private SSLEngineResult.HandshakeStatus getHandshakeStatus(int pending) {
// Check if we are in the initial handshake phase or shutdown phase
return needPendingStatus() ? pendingStatus(pending) : NOT_HANDSHAKING;
}
private boolean needPendingStatus() {
return handshakeState != HandshakeState.NOT_STARTED && !isDestroyed()
&& (handshakeState != HandshakeState.FINISHED || engineClosed);
}
/**
* Converts the specified OpenSSL cipher suite to the Java cipher suite.
*/
private String toJavaCipherSuite(String openSslCipherSuite) {
if (openSslCipherSuite == null) {
return null;
}
String prefix = toJavaCipherSuitePrefix(SSL.getVersion(ssl));
return CipherSuiteConverter.toJava(openSslCipherSuite, prefix);
}
/**
* Converts the protocol version string returned by {@link SSL#getVersion(long)} to protocol family string.
*/
private static String toJavaCipherSuitePrefix(String protocolVersion) {
final char c;
if (protocolVersion == null || protocolVersion.length() == 0) {
c = 0;
} else {
c = protocolVersion.charAt(0);
}
switch (c) {
case 'T':
return "TLS";
case 'S':
return "SSL";
default:
return "UNKNOWN";
}
}
@Override
public void setUseClientMode(boolean clientMode) {
if (clientMode != this.clientMode) {
throw new UnsupportedOperationException();
}
}
@Override
public boolean getUseClientMode() {
return clientMode;
}
@Override
public void setNeedClientAuth(boolean b) {
setClientAuth(b ? ClientAuth.REQUIRE : ClientAuth.NONE);
}
@Override
public boolean getNeedClientAuth() {
return clientAuth == ClientAuth.REQUIRE;
}
@Override
public void setWantClientAuth(boolean b) {
setClientAuth(b ? ClientAuth.OPTIONAL : ClientAuth.NONE);
}
@Override
public boolean getWantClientAuth() {
return clientAuth == ClientAuth.OPTIONAL;
}
private void setClientAuth(ClientAuth mode) {
if (clientMode) {
return;
}
synchronized (this) {
if (clientAuth == mode) {
// No need to issue any JNI calls if the mode is the same
return;
}
switch (mode) {
case NONE:
SSL.setVerify(ssl, SSL.SSL_CVERIFY_NONE, OpenSslContext.VERIFY_DEPTH);
break;
case REQUIRE:
SSL.setVerify(ssl, SSL.SSL_CVERIFY_REQUIRE, OpenSslContext.VERIFY_DEPTH);
break;
case OPTIONAL:
SSL.setVerify(ssl, SSL.SSL_CVERIFY_OPTIONAL, OpenSslContext.VERIFY_DEPTH);
break;
}
clientAuth = mode;
}
}
@Override
public void setEnableSessionCreation(boolean b) {
if (b) {
throw new UnsupportedOperationException();
}
}
@Override
public boolean getEnableSessionCreation() {
return false;
}
@Override
public SSLParameters getSSLParameters() {
SSLParameters sslParameters = super.getSSLParameters();
if (PlatformDependent.javaVersion() >= 7) {
sslParameters.setEndpointIdentificationAlgorithm(endPointIdentificationAlgorithm);
SslParametersUtils.setAlgorithmConstraints(sslParameters, algorithmConstraints);
}
return sslParameters;
}
@Override
public void setSSLParameters(SSLParameters sslParameters) {
super.setSSLParameters(sslParameters);
if (PlatformDependent.javaVersion() >= 7) {
endPointIdentificationAlgorithm = sslParameters.getEndpointIdentificationAlgorithm();
algorithmConstraints = sslParameters.getAlgorithmConstraints();
}
}
@Override
@SuppressWarnings("FinalizeDeclaration")
protected void finalize() throws Throwable {
super.finalize();
// Call shutdown as the user may have created the OpenSslEngine and not used it at all.
shutdown();
}
private boolean isDestroyed() {
return destroyed != 0;
}
private final class OpenSslSession implements SSLSession, ApplicationProtocolAccessor {
private final OpenSslSessionContext sessionContext;
// These are guarded by synchronized(OpenSslEngine.this) as handshakeFinished() may be triggered by any
// thread.
private X509Certificate[] x509PeerCerts;
private String protocol;
private String applicationProtocol;
private Certificate[] peerCerts;
private String cipher;
private byte[] id;
private long creationTime;
// lazy init for memory reasons
private Map<String, Object> values;
OpenSslSession(OpenSslSessionContext sessionContext) {
this.sessionContext = sessionContext;
}
@Override
public byte[] getId() {
synchronized (OpenSslEngine.this) {
if (id == null) {
return EmptyArrays.EMPTY_BYTES;
}
return id.clone();
}
}
@Override
public SSLSessionContext getSessionContext() {
return sessionContext;
}
@Override
public long getCreationTime() {
synchronized (OpenSslEngine.this) {
if (creationTime == 0 && !isDestroyed()) {
creationTime = SSL.getTime(ssl) * 1000L;
}
}
return creationTime;
}
@Override
public long getLastAccessedTime() {
// TODO: Add proper implementation
return getCreationTime();
}
@Override
public void invalidate() {
synchronized (OpenSslEngine.this) {
if (!isDestroyed()) {
SSL.setTimeout(ssl, 0);
}
}
}
@Override
public boolean isValid() {
synchronized (OpenSslEngine.this) {
if (!isDestroyed()) {
return System.currentTimeMillis() - (SSL.getTimeout(ssl) * 1000L) < (SSL.getTime(ssl) * 1000L);
}
}
return false;
}
@Override
public void putValue(String name, Object value) {
if (name == null) {
throw new NullPointerException("name");
}
if (value == null) {
throw new NullPointerException("value");
}
Map<String, Object> values = this.values;
if (values == null) {
// Use size of 2 to keep the memory overhead small
values = this.values = new HashMap<String, Object>(2);
}
Object old = values.put(name, value);
if (value instanceof SSLSessionBindingListener) {
((SSLSessionBindingListener) value).valueBound(new SSLSessionBindingEvent(this, name));
}
notifyUnbound(old, name);
}
@Override
public Object getValue(String name) {
if (name == null) {
throw new NullPointerException("name");
}
if (values == null) {
return null;
}
return values.get(name);
}
@Override
public void removeValue(String name) {
if (name == null) {
throw new NullPointerException("name");
}
Map<String, Object> values = this.values;
if (values == null) {
return;
}
Object old = values.remove(name);
notifyUnbound(old, name);
}
@Override
public String[] getValueNames() {
Map<String, Object> values = this.values;
if (values == null || values.isEmpty()) {
return EmptyArrays.EMPTY_STRINGS;
}
return values.keySet().toArray(new String[values.size()]);
}
private void notifyUnbound(Object value, String name) {
if (value instanceof SSLSessionBindingListener) {
((SSLSessionBindingListener) value).valueUnbound(new SSLSessionBindingEvent(this, name));
}
}
/**
* Finish the handshake and so init everything in the {@link OpenSslSession} that should be accessable by
* the user.
*/
void handshakeFinished() throws SSLException {
synchronized (OpenSslEngine.this) {
if (!isDestroyed()) {
id = SSL.getSessionId(ssl);
cipher = toJavaCipherSuite(SSL.getCipherForSSL(ssl));
protocol = SSL.getVersion(ssl);
initPeerCerts();
selectApplicationProtocol();
handshakeState = HandshakeState.FINISHED;
} else {
throw new SSLException("Already closed");
}
}
}
/**
* Init peer certificates that can be obtained via {@link #getPeerCertificateChain()}
* and {@link #getPeerCertificates()}.
*/
private void initPeerCerts() {
// Return the full chain from the JNI layer.
byte[][] chain = SSL.getPeerCertChain(ssl);
final byte[] clientCert;
if (!clientMode) {
// if used on the server side SSL_get_peer_cert_chain(...) will not include the remote peer
// certificate. We use SSL_get_peer_certificate to get it in this case and add it to our
// array later.
//
// See https://www.openssl.org/docs/ssl/SSL_get_peer_cert_chain.html
clientCert = SSL.getPeerCertificate(ssl);
} else {
clientCert = null;
}
if (chain == null && clientCert == null) {
peerCerts = EMPTY_CERTIFICATES;
x509PeerCerts = EMPTY_X509_CERTIFICATES;
} else {
int len = chain != null ? chain.length : 0;
int i = 0;
Certificate[] peerCerts;
if (clientCert != null) {
len++;
peerCerts = new Certificate[len];
peerCerts[i++] = new OpenSslX509Certificate(clientCert);
} else {
peerCerts = new Certificate[len];
}
if (chain != null) {
X509Certificate[] pCerts = new X509Certificate[chain.length];
for (int a = 0; a < pCerts.length; ++i, ++a) {
byte[] bytes = chain[a];
pCerts[a] = new OpenSslJavaxX509Certificate(bytes);
peerCerts[i] = new OpenSslX509Certificate(bytes);
}
x509PeerCerts = pCerts;
} else {
x509PeerCerts = EMPTY_X509_CERTIFICATES;
}
this.peerCerts = peerCerts;
}
}
/**
* Select the application protocol used.
*/
private void selectApplicationProtocol() throws SSLException {
SelectedListenerFailureBehavior behavior = apn.selectedListenerFailureBehavior();
List<String> protocols = apn.protocols();
String applicationProtocol;
switch (apn.protocol()) {
case NONE:
break;
// We always need to check for applicationProtocol == null as the remote peer may not support
// the TLS extension or may have returned an empty selection.
case ALPN:
applicationProtocol = SSL.getAlpnSelected(ssl);
if (applicationProtocol != null) {
this.applicationProtocol = selectApplicationProtocol(
protocols, behavior, applicationProtocol);
}
break;
case NPN:
applicationProtocol = SSL.getNextProtoNegotiated(ssl);
if (applicationProtocol != null) {
this.applicationProtocol = selectApplicationProtocol(
protocols, behavior, applicationProtocol);
}
break;
case NPN_AND_ALPN:
applicationProtocol = SSL.getAlpnSelected(ssl);
if (applicationProtocol == null) {
applicationProtocol = SSL.getNextProtoNegotiated(ssl);
}
if (applicationProtocol != null) {
this.applicationProtocol = selectApplicationProtocol(
protocols, behavior, applicationProtocol);
}
break;
default:
throw new Error();
}
}
private String selectApplicationProtocol(List<String> protocols,
SelectedListenerFailureBehavior behavior,
String applicationProtocol) throws SSLException {
if (behavior == SelectedListenerFailureBehavior.ACCEPT) {
return applicationProtocol;
} else {
int size = protocols.size();
assert size > 0;
if (protocols.contains(applicationProtocol)) {
return applicationProtocol;
} else {
if (behavior == SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL) {
return protocols.get(size - 1);
} else {
throw new SSLException("unknown protocol " + applicationProtocol);
}
}
}
}
@Override
public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
synchronized (OpenSslEngine.this) {
if (peerCerts == null || peerCerts.length == 0) {
throw new SSLPeerUnverifiedException("peer not verified");
}
return peerCerts;
}
}
@Override
public Certificate[] getLocalCertificates() {
if (localCerts == null) {
return null;
}
return localCerts.clone();
}
@Override
public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
synchronized (OpenSslEngine.this) {
if (x509PeerCerts == null || x509PeerCerts.length == 0) {
throw new SSLPeerUnverifiedException("peer not verified");
}
return x509PeerCerts;
}
}
@Override
public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
Certificate[] peer = getPeerCertificates();
// No need for null or length > 0 is needed as this is done in getPeerCertificates()
// already.
return ((java.security.cert.X509Certificate) peer[0]).getSubjectX500Principal();
}
@Override
public Principal getLocalPrincipal() {
Certificate[] local = localCerts;
if (local == null || local.length == 0) {
return null;
}
return ((java.security.cert.X509Certificate) local[0]).getIssuerX500Principal();
}
@Override
public String getCipherSuite() {
synchronized (OpenSslEngine.this) {
if (cipher == null) {
return INVALID_CIPHER;
}
return cipher;
}
}
@Override
public String getProtocol() {
String protocol = this.protocol;
if (protocol == null) {
synchronized (OpenSslEngine.this) {
if (!isDestroyed()) {
protocol = SSL.getVersion(ssl);
} else {
protocol = StringUtil.EMPTY_STRING;
}
}
}
return protocol;
}
@Override
public String getApplicationProtocol() {
synchronized (OpenSslEngine.this) {
return applicationProtocol;
}
}
@Override
public String getPeerHost() {
return OpenSslEngine.this.getPeerHost();
}
@Override
public int getPeerPort() {
return OpenSslEngine.this.getPeerPort();
}
@Override
public int getPacketBufferSize() {
return MAX_ENCRYPTED_PACKET_LENGTH;
}
@Override
public int getApplicationBufferSize() {
return MAX_PLAINTEXT_LENGTH;
}
}
}
|
Add support for SNIHostName when using Java8+
Motivation:
Java8 added support for using SNIHostName with SSLParameters. We currently ignore it in OpenSslEngine.
Modifications:
Use reflection to support SNIHostName.
Result:
People using Java8 can use SNIHostName even when OpenSslEngine is used.
|
handler/src/main/java/io/netty/handler/ssl/OpenSslEngine.java
|
Add support for SNIHostName when using Java8+
|
<ide><path>andler/src/main/java/io/netty/handler/ssl/OpenSslEngine.java
<ide> import org.apache.tomcat.jni.Buffer;
<ide> import org.apache.tomcat.jni.SSL;
<ide>
<add>import java.lang.reflect.InvocationTargetException;
<add>import java.lang.reflect.Method;
<ide> import java.nio.ByteBuffer;
<ide> import java.nio.ReadOnlyBufferException;
<ide> import java.security.Principal;
<ide> import java.security.cert.Certificate;
<ide> import java.util.Arrays;
<add>import java.util.Collections;
<ide> import java.util.HashMap;
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide> private static final SSLException ENGINE_CLOSED = new SSLException("engine closed");
<ide> private static final SSLException RENEGOTIATION_UNSUPPORTED = new SSLException("renegotiation unsupported");
<ide> private static final SSLException ENCRYPTED_PACKET_OVERSIZED = new SSLException("encrypted packet oversized");
<add> private static final Class<?> SNI_HOSTNAME_CLASS;
<add> private static final Method GET_SERVER_NAMES_METHOD;
<add> private static final Method SET_SERVER_NAMES_METHOD;
<add> private static final Method GET_ASCII_NAME_METHOD;
<add>
<ide> static {
<ide> ENGINE_CLOSED.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);
<ide> RENEGOTIATION_UNSUPPORTED.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);
<ide> destroyedUpdater = AtomicIntegerFieldUpdater.newUpdater(OpenSslEngine.class, "destroyed");
<ide> }
<ide> DESTROYED_UPDATER = destroyedUpdater;
<add>
<add> Class<?> sniHostNameClass = null;
<add> Method getAsciiNameMethod = null;
<add> Method getServerNamesMethod = null;
<add> Method setServerNamesMethod = null;
<add> if (PlatformDependent.javaVersion() >= 8) {
<add> try {
<add> sniHostNameClass = Class.forName("javax.net.ssl.SNIHostName", false,
<add> PlatformDependent.getClassLoader(OpenSslEngine.class));
<add> Object sniHostName = sniHostNameClass.getConstructor(String.class).newInstance("netty.io");
<add> getAsciiNameMethod = sniHostNameClass.getDeclaredMethod("getAsciiName");
<add> @SuppressWarnings("unused")
<add> String name = (String) getAsciiNameMethod.invoke(sniHostName);
<add>
<add> getServerNamesMethod = SSLParameters.class.getDeclaredMethod("getServerNames");
<add> setServerNamesMethod = SSLParameters.class.getDeclaredMethod("setServerNames", List.class);
<add> SSLParameters parameters = new SSLParameters();
<add> @SuppressWarnings({ "rawtypes", "unused" })
<add> List serverNames = (List) getServerNamesMethod.invoke(parameters);
<add> setServerNamesMethod.invoke(parameters, Collections.emptyList());
<add> } catch (Throwable ingore) {
<add> sniHostNameClass = null;
<add> getAsciiNameMethod = null;
<add> getServerNamesMethod = null;
<add> setServerNamesMethod = null;
<add> }
<add> }
<add> SNI_HOSTNAME_CLASS = sniHostNameClass;
<add> GET_ASCII_NAME_METHOD = getAsciiNameMethod;
<add> GET_SERVER_NAMES_METHOD = getServerNamesMethod;
<add> SET_SERVER_NAMES_METHOD = setServerNamesMethod;
<ide> }
<ide>
<ide> private static final int MAX_PLAINTEXT_LENGTH = 16 * 1024; // 2^14
<ide>
<ide> private volatile ClientAuth clientAuth = ClientAuth.NONE;
<ide>
<del> private volatile String endPointIdentificationAlgorithm;
<add> private String endPointIdentificationAlgorithm;
<ide> // Store as object as AlgorithmConstraints only exists since java 7.
<del> private volatile Object algorithmConstraints;
<add> private Object algorithmConstraints;
<add> private List<?> sniHostNames;
<ide>
<ide> // SSL Engine status variables
<ide> private boolean isInboundDone;
<ide> }
<ide>
<ide> @Override
<del> public SSLParameters getSSLParameters() {
<add> public synchronized SSLParameters getSSLParameters() {
<ide> SSLParameters sslParameters = super.getSSLParameters();
<ide>
<del> if (PlatformDependent.javaVersion() >= 7) {
<add> int version = PlatformDependent.javaVersion();
<add> if (version >= 7) {
<ide> sslParameters.setEndpointIdentificationAlgorithm(endPointIdentificationAlgorithm);
<ide> SslParametersUtils.setAlgorithmConstraints(sslParameters, algorithmConstraints);
<add> if (version >= 8 && SET_SERVER_NAMES_METHOD != null && sniHostNames != null) {
<add> try {
<add> SET_SERVER_NAMES_METHOD.invoke(sslParameters, sniHostNames);
<add> } catch (IllegalAccessException e) {
<add> throw new Error(e);
<add> } catch (InvocationTargetException e) {
<add> throw new Error(e);
<add> }
<add> }
<ide> }
<ide> return sslParameters;
<ide> }
<ide>
<ide> @Override
<del> public void setSSLParameters(SSLParameters sslParameters) {
<add> public synchronized void setSSLParameters(SSLParameters sslParameters) {
<ide> super.setSSLParameters(sslParameters);
<ide>
<del> if (PlatformDependent.javaVersion() >= 7) {
<add> int version = PlatformDependent.javaVersion();
<add> if (version >= 7) {
<ide> endPointIdentificationAlgorithm = sslParameters.getEndpointIdentificationAlgorithm();
<ide> algorithmConstraints = sslParameters.getAlgorithmConstraints();
<add>
<add> if (version >= 8 && SNI_HOSTNAME_CLASS != null && clientMode && !isDestroyed()) {
<add> assert GET_SERVER_NAMES_METHOD != null;
<add> assert GET_ASCII_NAME_METHOD != null;
<add> try {
<add> List<?> servernames = (List<?>) GET_SERVER_NAMES_METHOD.invoke(sslParameters);
<add> for (Object serverName : servernames) {
<add> if (SNI_HOSTNAME_CLASS.isInstance(serverName)) {
<add> SSL.setTlsExtHostName(ssl, (String) GET_ASCII_NAME_METHOD.invoke(serverName));
<add> } else {
<add> throw new IllegalArgumentException("Only " + SNI_HOSTNAME_CLASS.getName()
<add> + " instances are supported, but found: " + serverName);
<add> }
<add> }
<add> sniHostNames = servernames;
<add> } catch (IllegalAccessException e) {
<add> throw new Error(e);
<add> } catch (InvocationTargetException e) {
<add> throw new Error(e);
<add> }
<add> }
<ide> }
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
16a200d1a508e30223e95e9a2a2bfec06591040d
| 0 |
jlfex/hermes,fuhongliang/hermes,fuhongliang/hermes,fuhongliang/hermes,jlfex/hermes,jlfex/hermes
|
package com.jlfex.hermes.console;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.jlfex.hermes.common.App;
import com.jlfex.hermes.common.Result;
import com.jlfex.hermes.common.utils.Files;
import com.jlfex.hermes.common.utils.Images;
import com.jlfex.hermes.model.Properties;
import com.jlfex.hermes.model.Text;
import com.jlfex.hermes.service.PropertiesService;
import com.jlfex.hermes.service.TextService;
/**
* 系统控制器
*
* @author ultrafrog
* @version 1.0, 2013-11-29
* @since 1.0
*/
@Controller
@RequestMapping("/system")
public class SystemController {
/** 系统属性业务接口 */
@Autowired
private PropertiesService propertiesService;
@Autowired
private TextService textService;
/**
* 系统属性
*
* @return
*/
@RequestMapping("/properties")
public String properties(Model model) {
Properties properties = propertiesService.findByCode("app.logo");
model.addAttribute("logo", textService.loadById(properties.getValue()).getText());
return "system/properties";
}
/**
* 查询系统属性
*
* @param name
* @param code
* @param page
* @return
*/
@RequestMapping("/properties/search")
@ResponseBody
public Page<Properties> searchProperties(String name, String code, Integer page) {
return propertiesService.findByNameAndCode(name, code, page, null);
}
/**
* 保存系统属性
*
* @param id
* @param name
* @param code
* @param value
* @return
*/
@RequestMapping("/properties/save")
@ResponseBody
public Result saveProperties(MultipartHttpServletRequest request) {
MultipartFile file = request.getFile("logo");
Result<String> result = new Result<String>();
try {
propertiesService.saveConfigurableProperties(
Images.toBase64(Files.getMimeType(file.getOriginalFilename()), file.getBytes()),
request.getParameter("operationName"), request.getParameter("operationNickname"),
request.getParameter("website"), request.getParameter("copyright"), request.getParameter("icp"),
request.getParameter("serviceTel"), request.getParameter("serviceTime"),
request.getParameter("companyName"), request.getParameter("companyAddress"),
request.getParameter("companyCity"), request.getParameter("smtpHost"),
request.getParameter("smtpPort"), request.getParameter("smtpUsername"),
request.getParameter("smtpPassword"), request.getParameter("mailFrom"),
request.getParameter("serviceEmail"), request.getParameter("jobNoticeEmail"),
request.getParameter("indexLoanSize"), request.getParameter("emailExpire"),
request.getParameter("smsExpire"), request.getParameter("realnameSwitch"),
request.getParameter("cellphoneSwitch"));
} catch (IOException e) {
result.setType(com.jlfex.hermes.common.Result.Type.FAILURE);
result.addMessage(e.getMessage());
}
result.setType(com.jlfex.hermes.common.Result.Type.SUCCESS);
result.addMessage(App.message("app.config.save.ok"));
return result;
}
/**
* 读取系统属性
*
* @param id
* @return
*/
@RequestMapping("/properties/load")
@ResponseBody
public Properties loadProperties(String id) {
return propertiesService.findById(id);
}
/**
* 读取系统logo属性
*
* @param id
* @return
*/
@RequestMapping("/properties/logo")
@ResponseBody
public Text loadLogo() {
Properties properties = propertiesService.findByCode("app.logo");
return textService.loadById(properties.getValue());
}
}
|
hermes-console/src/main/java/com/jlfex/hermes/console/SystemController.java
|
package com.jlfex.hermes.console;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.jlfex.hermes.common.App;
import com.jlfex.hermes.common.Result;
import com.jlfex.hermes.common.utils.Files;
import com.jlfex.hermes.common.utils.Images;
import com.jlfex.hermes.model.Properties;
import com.jlfex.hermes.model.Text;
import com.jlfex.hermes.service.PropertiesService;
import com.jlfex.hermes.service.TextService;
/**
* 系统控制器
*
* @author ultrafrog
* @version 1.0, 2013-11-29
* @since 1.0
*/
@Controller
@RequestMapping("/system")
public class SystemController {
/** 系统属性业务接口 */
@Autowired
private PropertiesService propertiesService;
@Autowired
private TextService textService;
/**
* 系统属性
*
* @return
*/
@RequestMapping("/properties")
public String properties(Model model) {
Properties properties = propertiesService.findByCode("app.logo");
model.addAttribute("logo", textService.loadById(properties.getValue()).getText());
return "system/properties";
}
/**
* 查询系统属性
*
* @param name
* @param code
* @param page
* @return
*/
@RequestMapping("/properties/search")
@ResponseBody
public Page<Properties> searchProperties(String name, String code, Integer page) {
return propertiesService.findByNameAndCode(name, code, page, null);
}
/**
* 保存系统属性
*
* @param id
* @param name
* @param code
* @param value
* @return
*/
@RequestMapping("/properties/save")
@ResponseBody
public Result saveProperties(MultipartHttpServletRequest request) {
MultipartFile file = request.getFile("logo");
Result<String> result = new Result<String>();
try {
propertiesService.saveConfigurableProperties(
Images.toBase64(Files.getMimeType(file.getOriginalFilename()), file.getBytes()),
request.getParameter("operationName"), request.getParameter("operationNickname"),
request.getParameter("website"), request.getParameter("copyright"), request.getParameter("icp"),
request.getParameter("serviceTel"), request.getParameter("serviceTel"),
request.getParameter("companyName"), request.getParameter("companyAddress"),
request.getParameter("companyCity"), request.getParameter("smtpHost"),
request.getParameter("smtpPort"), request.getParameter("smtpUsername"),
request.getParameter("smtpPassword"), request.getParameter("mailFrom"),
request.getParameter("serviceEmail"), request.getParameter("jobNoticeEmail"),
request.getParameter("indexLoanSize"), request.getParameter("emailExpire"),
request.getParameter("smsExpire"), request.getParameter("realnameSwitch"),
request.getParameter("cellphoneSwitch"));
} catch (IOException e) {
result.setType(com.jlfex.hermes.common.Result.Type.FAILURE);
result.addMessage(e.getMessage());
}
result.setType(com.jlfex.hermes.common.Result.Type.SUCCESS);
result.addMessage(App.message("app.config.save.ok"));
return result;
}
/**
* 读取系统属性
*
* @param id
* @return
*/
@RequestMapping("/properties/load")
@ResponseBody
public Properties loadProperties(String id) {
return propertiesService.findById(id);
}
/**
* 读取系统logo属性
*
* @param id
* @return
*/
@RequestMapping("/properties/logo")
@ResponseBody
public Text loadLogo() {
Properties properties = propertiesService.findByCode("app.logo");
return textService.loadById(properties.getValue());
}
}
|
修复配置错误
|
hermes-console/src/main/java/com/jlfex/hermes/console/SystemController.java
|
修复配置错误
|
<ide><path>ermes-console/src/main/java/com/jlfex/hermes/console/SystemController.java
<ide> Images.toBase64(Files.getMimeType(file.getOriginalFilename()), file.getBytes()),
<ide> request.getParameter("operationName"), request.getParameter("operationNickname"),
<ide> request.getParameter("website"), request.getParameter("copyright"), request.getParameter("icp"),
<del> request.getParameter("serviceTel"), request.getParameter("serviceTel"),
<add> request.getParameter("serviceTel"), request.getParameter("serviceTime"),
<ide> request.getParameter("companyName"), request.getParameter("companyAddress"),
<ide> request.getParameter("companyCity"), request.getParameter("smtpHost"),
<ide> request.getParameter("smtpPort"), request.getParameter("smtpUsername"),
|
|
Java
|
epl-1.0
|
743614bc5928f5e39ed436c8c0d430bf666072af
| 0 |
ELTE-Soft/xUML-RT-Executor
|
package hu.eltesoft.modelexecution.runtime.library;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import com.google.common.collect.HashMultiset;
/**
* Implements standard collection operations used by the runtime.
*/
public final class CollectionOperations {
private static final String CLASS_PREFIX = CollectionOperations.class.getCanonicalName() + ".";
public static final String SEQUENCE_LITERAL = CLASS_PREFIX + "sequenceLiteral";
public static final String SET_LITERAL = CLASS_PREFIX + "setLiteral";
public static final String BAG_LITERAL = CLASS_PREFIX + "bagLiteral";
public static final String IS_EMPTY = CLASS_PREFIX + "isEmpty";
public static final String SIZE = CLASS_PREFIX + "size";
public static final String ONE = CLASS_PREFIX + "one";
public static final String FILTER = CLASS_PREFIX + "filter";
public static final String ADD = "add";
public static final String ADD_ALL = "addAll";
public static final String GET = "get";
public static final String ADD_AT = "addAt";
@SafeVarargs
public static <E> ArrayList<E> sequenceLiteral(E... items) {
return new ArrayList<E>(Arrays.asList(items));
}
@SafeVarargs
public static <E> HashSet<E> setLiteral(E... items) {
return new HashSet<E>(Arrays.asList(items));
}
@SafeVarargs
public static <E> HashMultiset<E> bagLiteral(E... items) {
return HashMultiset.create(Arrays.asList(items));
}
public static ArrayList<Boolean> isEmpty(Collection<?> collection) {
return PrimitiveOperations.wrap(collection.isEmpty());
}
public static ArrayList<BigInteger> size(Collection<?> collection) {
return PrimitiveOperations.wrap(BigInteger.valueOf(collection.size()));
}
/**
* Currently it always extracts the first item of the collection.
*/
public static <E> ArrayList<E> one(Collection<E> collection) {
if (collection.isEmpty()) {
return PrimitiveOperations.nullValue();
}
return PrimitiveOperations.wrap(collection.iterator().next());
}
/**
* Returns filtered elements while preserving the container type. The
* predicate works on wrapped values.
*/
public static <E, C extends Collection<E>> C filter(C collection, Predicate<ArrayList<E>> predicate) {
return collection.stream().filter(e -> predicate.test(PrimitiveOperations.wrap(e)))
.collect(Collectors.toCollection(factoryOf(collection)));
}
@SuppressWarnings("unchecked")
public static <E, C extends Collection<E>> Supplier<C> factoryOf(C collection) {
if (collection instanceof ArrayList<?>) {
return () -> (C) new ArrayList<E>();
} else if (collection instanceof HashSet<?>) {
return () -> (C) new HashSet<E>();
} else if (collection instanceof HashMultiset<?>) {
return () -> (C) HashMultiset.create();
}
return null;
}
public static <E, C extends Collection<?>> Supplier<? extends Collection<E>> factoryOf(C collection,
Class<E> newItemType) {
if (collection instanceof ArrayList<?>) {
return ArrayList::new;
} else if (collection instanceof HashSet<?>) {
return HashSet::new;
} else if (collection instanceof HashMultiset<?>) {
return HashMultiset::create;
}
return null;
}
public static <E, C extends Collection<E>> ArrayList<Boolean> add(C collection, ArrayList<E> newItem) {
return PrimitiveOperations.wrap(collection.add(PrimitiveOperations.unwrap(newItem)));
}
public static <E, C extends Collection<E>, C2 extends Collection<E>> ArrayList<Boolean> addAll(C collection,
C2 newItems) {
return PrimitiveOperations.wrap(collection.addAll(newItems));
}
public static <E> ArrayList<E> get(ArrayList<E> collection, ArrayList<BigInteger> index) {
return PrimitiveOperations.wrap(collection.get(PrimitiveOperations.unwrap(index).intValue()));
}
public static <E> void addAt(ArrayList<E> collection, ArrayList<BigInteger> index,
ArrayList<E> newItem) {
collection.add(PrimitiveOperations.unwrap(index).intValue(), PrimitiveOperations.unwrap(newItem));
}
}
|
plugins/hu.eltesoft.modelexecution.runtime/src/hu/eltesoft/modelexecution/runtime/library/CollectionOperations.java
|
package hu.eltesoft.modelexecution.runtime.library;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import com.google.common.collect.HashMultiset;
/**
* Implements standard collection operations used by the runtime.
*/
public final class CollectionOperations {
private static final String CLASS_PREFIX = CollectionOperations.class.getCanonicalName() + ".";
public static final String SEQUENCE_LITERAL = CLASS_PREFIX + "sequenceLiteral";
public static final String SET_LITERAL = CLASS_PREFIX + "setLiteral";
public static final String BAG_LITERAL = CLASS_PREFIX + "bagLiteral";
public static final String IS_EMPTY = CLASS_PREFIX + "isEmpty";
public static final String SIZE = CLASS_PREFIX + "size";
public static final String ONE = CLASS_PREFIX + "one";
public static final String FILTER = CLASS_PREFIX + "filter";
public static final String ADD = "add";
public static final String ADD_ALL = "addAll";
public static final String GET = "get";
public static final String ADD_AT = "addAt";
@SafeVarargs
public static <E> ArrayList<E> sequenceLiteral(E... items) {
return new ArrayList<E>(Arrays.asList(items));
}
@SafeVarargs
public static <E> HashSet<E> setLiteral(E... items) {
return new HashSet<E>(Arrays.asList(items));
}
@SafeVarargs
public static <E> HashMultiset<E> bagLiteral(E... items) {
return HashMultiset.create(Arrays.asList(items));
}
public static ArrayList<Boolean> isEmpty(Collection<?> collection) {
return PrimitiveOperations.wrap(collection.isEmpty());
}
public static ArrayList<BigInteger> size(Collection<?> collection) {
return PrimitiveOperations.wrap(BigInteger.valueOf(collection.size()));
}
/**
* Currently it always extracts the first item of the collection.
*/
public static <E> ArrayList<E> one(Collection<E> collection) {
return PrimitiveOperations.wrap(collection.iterator().next());
}
/**
* Returns filtered elements while preserving the container type. The
* predicate works on wrapped values.
*/
public static <E, C extends Collection<E>> C filter(C collection, Predicate<ArrayList<E>> predicate) {
return collection.stream().filter(e -> predicate.test(PrimitiveOperations.wrap(e)))
.collect(Collectors.toCollection(factoryOf(collection)));
}
@SuppressWarnings("unchecked")
public static <E, C extends Collection<E>> Supplier<C> factoryOf(C collection) {
if (collection instanceof ArrayList<?>) {
return () -> (C) new ArrayList<E>();
} else if (collection instanceof HashSet<?>) {
return () -> (C) new HashSet<E>();
} else if (collection instanceof HashMultiset<?>) {
return () -> (C) HashMultiset.create();
}
return null;
}
public static <E, C extends Collection<?>> Supplier<? extends Collection<E>> factoryOf(C collection,
Class<E> newItemType) {
if (collection instanceof ArrayList<?>) {
return ArrayList::new;
} else if (collection instanceof HashSet<?>) {
return HashSet::new;
} else if (collection instanceof HashMultiset<?>) {
return HashMultiset::create;
}
return null;
}
public static <E, C extends Collection<E>> ArrayList<Boolean> add(C collection, ArrayList<E> newItem) {
return PrimitiveOperations.wrap(collection.add(PrimitiveOperations.unwrap(newItem)));
}
public static <E, C extends Collection<E>, C2 extends Collection<E>> ArrayList<Boolean> addAll(C collection,
C2 newItems) {
return PrimitiveOperations.wrap(collection.addAll(newItems));
}
public static <E> ArrayList<E> get(ArrayList<E> collection, ArrayList<BigInteger> index) {
return PrimitiveOperations.wrap(collection.get(PrimitiveOperations.unwrap(index).intValue()));
}
// FIXME: what is the meaning of the return value here?
public static <E> ArrayList<Boolean> addAt(ArrayList<E> collection, ArrayList<BigInteger> index,
ArrayList<E> newItem) {
collection.add(PrimitiveOperations.unwrap(index).intValue(), PrimitiveOperations.unwrap(newItem));
return PrimitiveOperations.booleanLiteral(true);
}
}
|
actionCode-sept: fixing collection operations
|
plugins/hu.eltesoft.modelexecution.runtime/src/hu/eltesoft/modelexecution/runtime/library/CollectionOperations.java
|
actionCode-sept: fixing collection operations
|
<ide><path>lugins/hu.eltesoft.modelexecution.runtime/src/hu/eltesoft/modelexecution/runtime/library/CollectionOperations.java
<ide> * Currently it always extracts the first item of the collection.
<ide> */
<ide> public static <E> ArrayList<E> one(Collection<E> collection) {
<add> if (collection.isEmpty()) {
<add> return PrimitiveOperations.nullValue();
<add> }
<ide> return PrimitiveOperations.wrap(collection.iterator().next());
<ide> }
<ide>
<ide> return PrimitiveOperations.wrap(collection.get(PrimitiveOperations.unwrap(index).intValue()));
<ide> }
<ide>
<del> // FIXME: what is the meaning of the return value here?
<del> public static <E> ArrayList<Boolean> addAt(ArrayList<E> collection, ArrayList<BigInteger> index,
<add> public static <E> void addAt(ArrayList<E> collection, ArrayList<BigInteger> index,
<ide> ArrayList<E> newItem) {
<ide> collection.add(PrimitiveOperations.unwrap(index).intValue(), PrimitiveOperations.unwrap(newItem));
<del> return PrimitiveOperations.booleanLiteral(true);
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
da803fb7260d07212600473b4a9e9f0298f820c8
| 0 |
YUKAI/konashi-android-sdk,kiryuxxu/konashi-android-sdk,YUKAI/konashi-android-sdk
|
package com.uxxu.konashi.lib.ui;
import android.app.Activity;
import android.os.Bundle;
import com.uxxu.konashi.lib.KonashiManager;
/**
* konashiを簡単に使うためのActivity
*
* @author monakaz, YUKAI Engineering
* http://konashi.ux-xu.com
* ========================================================================
* Copyright 2014 Yukai Engineering Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
public class KonashiActivity extends Activity {
/**
* konashiマネージャ
*/
private KonashiManager mKonashiManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize konashi manager
mKonashiManager = new KonashiManager();
mKonashiManager.initialize(getApplicationContext());
}
@Override
protected void onDestroy() {
if(mKonashiManager!=null){
mKonashiManager.disconnect();
mKonashiManager = null;
}
super.onDestroy();
}
/**
* konashiマネージャのgetter
* @return konashiマネージャのオブジェクト
*/
public KonashiManager getKonashiManager(){
return mKonashiManager;
}
}
|
konashi-android-sdk/src/main/java/com/uxxu/konashi/lib/ui/KonashiActivity.java
|
package com.uxxu.konashi.lib.ui;
import android.app.Activity;
import android.os.Bundle;
import com.uxxu.konashi.lib.KonashiManager;
/**
* konashiを簡単に使うためのActivity
*
* @author monakaz, YUKAI Engineering
* http://konashi.ux-xu.com
* ========================================================================
* Copyright 2014 Yukai Engineering Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
public class KonashiActivity extends Activity {
/**
* konashiマネージャ
*/
private KonashiManager mKonashiManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize konashi manager
mKonashiManager = new KonashiManager();
mKonashiManager.initialize(getApplicationContext());
}
@Override
protected void onDestroy() {
if(mKonashiManager!=null){
mKonashiManager.disconnect();
mKonashiManager.close();
mKonashiManager = null;
}
super.onDestroy();
}
/**
* konashiマネージャのgetter
* @return konashiマネージャのオブジェクト
*/
public KonashiManager getKonashiManager(){
return mKonashiManager;
}
}
|
Fix KonashiActivity
|
konashi-android-sdk/src/main/java/com/uxxu/konashi/lib/ui/KonashiActivity.java
|
Fix KonashiActivity
|
<ide><path>onashi-android-sdk/src/main/java/com/uxxu/konashi/lib/ui/KonashiActivity.java
<ide> protected void onDestroy() {
<ide> if(mKonashiManager!=null){
<ide> mKonashiManager.disconnect();
<del> mKonashiManager.close();
<ide> mKonashiManager = null;
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
7e39b4b39a3fdba19832bc3a5b47c3a9d0b7a8a5
| 0 |
Ooppa/iot-industrial-internet,Ooppa/iot-industrial-internet,Ooppa/iot-industrial-internet,Ooppa/iot-industrial-internet
|
/*
* IoT - Industrial Internet Framework
* Apache License Version 2.0, January 2004
* Released as a part of Helsinki University
* Software Engineering Lab in summer 2015
*/
package fi.iot.iiframework.services;
import fi.iot.iiframework.application.TestConfig;
import fi.iot.iiframework.dataobject.DataSourceObject;
import fi.iot.iiframework.dataobject.Device;
import fi.iot.iiframework.dataobject.Sensor;
import fi.iot.iiframework.services.dataobject.DeviceService;
import java.io.Serializable;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestConfig.class})
public class DeviceServiceTest implements Serializable {
Device d1;
Device d2;
@Autowired
private DeviceService service;
@Before
public void setUp() {
d1 = new Device();
d1.setId("ssds");
d1.setDeviceid("ss");
}
@Test
public void anEntityCanBeSavedAndRetrievedFromDatabase() {
service.save(d1);
Device d2 = service.get(d1.getId());
assertEquals(d1.getId(), d2.getId());
assertEquals(d1.getDeviceid(), d2.getDeviceid());
}
}
|
iot-industrial-internet/src/test/java/fi/iot/iiframework/services/DeviceServiceTest.java
|
/*
* IoT - Industrial Internet Framework
* Apache License Version 2.0, January 2004
* Released as a part of Helsinki University
* Software Engineering Lab in summer 2015
*/
package fi.iot.iiframework.services;
import fi.iot.iiframework.application.TestConfig;
import fi.iot.iiframework.dataobject.DataSourceObject;
import fi.iot.iiframework.dataobject.Device;
import fi.iot.iiframework.dataobject.Sensor;
import fi.iot.iiframework.services.dataobject.DeviceService;
import java.io.Serializable;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@Ignore
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestConfig.class})
public class DeviceServiceTest implements Serializable {
Device d1;
Device d2;
@Autowired
private DeviceService service;
@Before
public void setUp() {
d1 = new Device();
d1.setId("ssds");
}
@Test
public void anEntityCanBeSavedAndRetrievedFromDatabase() {
service.save(d1);
Device d2 = service.get(d1.getId());
d2.setId("ssds");
assertEquals(d1.getId(), d2.getId());
assertEquals(d1.getDeviceid(), d2.getDeviceid());
assertEquals(d1.getSensors(), d2.getSensors());
assertEquals(d1.getDataSourceObject(), d2.getDataSourceObject());
}
}
|
deviceservicetest now functional...
|
iot-industrial-internet/src/test/java/fi/iot/iiframework/services/DeviceServiceTest.java
|
deviceservicetest now functional...
|
<ide><path>ot-industrial-internet/src/test/java/fi/iot/iiframework/services/DeviceServiceTest.java
<ide> import org.springframework.boot.test.SpringApplicationConfiguration;
<ide> import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<ide>
<del>@Ignore
<ide> @RunWith(SpringJUnit4ClassRunner.class)
<ide> @SpringApplicationConfiguration(classes = {TestConfig.class})
<ide> public class DeviceServiceTest implements Serializable {
<ide> public void setUp() {
<ide> d1 = new Device();
<ide> d1.setId("ssds");
<add> d1.setDeviceid("ss");
<ide> }
<ide>
<ide> @Test
<ide> public void anEntityCanBeSavedAndRetrievedFromDatabase() {
<ide> service.save(d1);
<ide> Device d2 = service.get(d1.getId());
<del> d2.setId("ssds");
<ide> assertEquals(d1.getId(), d2.getId());
<ide> assertEquals(d1.getDeviceid(), d2.getDeviceid());
<del> assertEquals(d1.getSensors(), d2.getSensors());
<del> assertEquals(d1.getDataSourceObject(), d2.getDataSourceObject());
<ide> }
<ide>
<ide> }
|
|
JavaScript
|
mit
|
a57c5e4a172c4c110d2635088b2cf529308dc3aa
| 0 |
ssilab/computed-style-to-inline-style
|
(function(root, factory) {
if (typeof define === "function" && define.amd) {
define([], factory); // AMD.
} else if (typeof module === 'object' && module.exports) {
module.exports = factory(); // CommonJS.
} else {
root.computedStyleToInlineStyle = factory(); // Browser.
}
}(this, function() {
return function computedStyleToInlineStyle(element, recursive) {
if (!element) {
throw new Error("No element specified.");
}
if (recursive) {
Array.prototype.forEach.call(element.children, function(child) {
computedStyleToInlineStyle(child, recursive);
});
}
var computedStyle = getComputedStyle(element);
for (var i = 0; i < computedStyle.length; i++) {
var property = computedStyle.item(i);
var value = computedStyle.getPropertyValue(property);
element.style[property] = value;
}
};
}));
|
index.js
|
(function(root, factory) {
if (typeof define === "function" && define.amd) {
define([], factory); // AMD.
} else if (typeof module === 'object' && module.exports) {
module.exports = factory(); // CommonJS.
} else {
root.computedStyleToInlineStyle = factory(); // Browser.
}
}(this, function() {
return function computedStyleToInlineStyle(element, recursive) {
if (!element) {
throw new Error("No element specified.");
}
if (!(element instanceof Element)) {
throw new Error("Specified element is not an instance of Element.");
}
if (recursive) {
Array.prototype.forEach.call(element.children, function(child) {
computedStyleToInlineStyle(child, recursive);
});
}
var computedStyle = getComputedStyle(element);
for (var i = 0; i < computedStyle.length; i++) {
var property = computedStyle.item(i);
var value = computedStyle.getPropertyValue(property);
element.style[property] = value;
}
};
}));
|
Drop instanceof check
|
index.js
|
Drop instanceof check
|
<ide><path>ndex.js
<ide> return function computedStyleToInlineStyle(element, recursive) {
<ide> if (!element) {
<ide> throw new Error("No element specified.");
<del> }
<del>
<del> if (!(element instanceof Element)) {
<del> throw new Error("Specified element is not an instance of Element.");
<ide> }
<ide>
<ide> if (recursive) {
|
|
Java
|
apache-2.0
|
24ffa9350df9d32b35e3cf746bbcfb9b3d9dc517
| 0 |
GerritCodeReview/gerrit,WANdisco/gerrit,gerrit-review/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,WANdisco/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit
|
// Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.acceptance.git;
import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.acceptance.GitUtil.deleteRef;
import static org.eclipse.jgit.lib.Constants.HEAD;
import static org.eclipse.jgit.transport.RemoteRefUpdate.Status.OK;
import static org.eclipse.jgit.transport.RemoteRefUpdate.Status.REJECTED_OTHER_REASON;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.NoHttpd;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.common.data.Permission;
import com.google.gerrit.extensions.api.projects.BranchInput;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.transport.PushResult;
import org.eclipse.jgit.transport.RemoteRefUpdate;
import org.junit.Test;
@NoHttpd
public class ForcePushIT extends AbstractDaemonTest {
@Test
public void forcePushNotAllowed() throws Exception {
ObjectId initial = repo().exactRef(HEAD).getLeaf().getObjectId();
PushOneCommit push1 =
pushFactory.create(db, admin.getIdent(), testRepo, "change1", "a.txt", "content");
PushOneCommit.Result r1 = push1.to("refs/heads/master");
r1.assertOkStatus();
// Reset HEAD to initial so the new change is a non-fast forward
RefUpdate ru = repo().updateRef(HEAD);
ru.setNewObjectId(initial);
assertThat(ru.forceUpdate()).isEqualTo(RefUpdate.Result.FORCED);
PushOneCommit push2 =
pushFactory.create(db, admin.getIdent(), testRepo, "change2", "b.txt", "content");
push2.setForce(true);
PushOneCommit.Result r2 = push2.to("refs/heads/master");
r2.assertErrorStatus("non-fast forward");
}
@Test
public void forcePushAllowed() throws Exception {
ObjectId initial = repo().exactRef(HEAD).getLeaf().getObjectId();
grant(Permission.PUSH, project, "refs/*", true);
PushOneCommit push1 =
pushFactory.create(db, admin.getIdent(), testRepo, "change1", "a.txt", "content");
PushOneCommit.Result r1 = push1.to("refs/heads/master");
r1.assertOkStatus();
// Reset HEAD to initial so the new change is a non-fast forward
RefUpdate ru = repo().updateRef(HEAD);
ru.setNewObjectId(initial);
assertThat(ru.forceUpdate()).isEqualTo(RefUpdate.Result.FORCED);
PushOneCommit push2 =
pushFactory.create(db, admin.getIdent(), testRepo, "change2", "b.txt", "content");
push2.setForce(true);
PushOneCommit.Result r2 = push2.to("refs/heads/master");
r2.assertOkStatus();
}
@Test
public void deleteNotAllowed() throws Exception {
assertDeleteRef(REJECTED_OTHER_REASON);
}
@Test
public void deleteNotAllowedWithOnlyPushPermission() throws Exception {
grant(Permission.PUSH, project, "refs/*", false);
assertDeleteRef(REJECTED_OTHER_REASON);
}
@Test
public void deleteAllowedWithForcePushPermission() throws Exception {
grant(Permission.PUSH, project, "refs/*", true);
assertDeleteRef(OK);
}
@Test
public void deleteAllowedWithDeletePermission() throws Exception {
grant(Permission.DELETE, project, "refs/*", true);
assertDeleteRef(OK);
}
private void assertDeleteRef(RemoteRefUpdate.Status expectedStatus) throws Exception {
BranchInput in = new BranchInput();
in.ref = "refs/heads/test";
gApi.projects().name(project.get()).branch(in.ref).create(in);
PushResult result = deleteRef(testRepo, in.ref);
RemoteRefUpdate refUpdate = result.getRemoteUpdate(in.ref);
assertThat(refUpdate.getStatus()).isEqualTo(expectedStatus);
}
}
|
gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/git/ForcePushIT.java
|
// Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.acceptance.git;
import static com.google.common.truth.Truth.assertThat;
import static org.eclipse.jgit.lib.Constants.HEAD;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.common.data.Permission;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.RefUpdate;
import org.junit.Test;
public class ForcePushIT extends AbstractDaemonTest {
@Test
public void forcePushNotAllowed() throws Exception {
ObjectId initial = repo().exactRef(HEAD).getLeaf().getObjectId();
PushOneCommit push1 =
pushFactory.create(db, admin.getIdent(), testRepo, "change1", "a.txt", "content");
PushOneCommit.Result r1 = push1.to("refs/heads/master");
r1.assertOkStatus();
// Reset HEAD to initial so the new change is a non-fast forward
RefUpdate ru = repo().updateRef(HEAD);
ru.setNewObjectId(initial);
assertThat(ru.forceUpdate()).isEqualTo(RefUpdate.Result.FORCED);
PushOneCommit push2 =
pushFactory.create(db, admin.getIdent(), testRepo, "change2", "b.txt", "content");
push2.setForce(true);
PushOneCommit.Result r2 = push2.to("refs/heads/master");
r2.assertErrorStatus("non-fast forward");
}
@Test
public void forcePushAllowed() throws Exception {
ObjectId initial = repo().exactRef(HEAD).getLeaf().getObjectId();
grant(Permission.PUSH, project, "refs/*", true);
PushOneCommit push1 =
pushFactory.create(db, admin.getIdent(), testRepo, "change1", "a.txt", "content");
PushOneCommit.Result r1 = push1.to("refs/heads/master");
r1.assertOkStatus();
// Reset HEAD to initial so the new change is a non-fast forward
RefUpdate ru = repo().updateRef(HEAD);
ru.setNewObjectId(initial);
assertThat(ru.forceUpdate()).isEqualTo(RefUpdate.Result.FORCED);
PushOneCommit push2 =
pushFactory.create(db, admin.getIdent(), testRepo, "change2", "b.txt", "content");
push2.setForce(true);
PushOneCommit.Result r2 = push2.to("refs/heads/master");
r2.assertOkStatus();
}
}
|
ForcePushIT: Add tests for deleting branch by push
Test that a branch can be deleted by pushing to ":refs/heads/branch-name",
while having the "PUSH" permission with the force option, or the "DELETE"
permission. Test that it is not possible to delete without either of the
permissions, or when having the "PUSH" permission without force option.
Bug: Issue 7490
Change-Id: I4861871a3bc01e4dae7268914d8d68d7b559e62b
|
gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/git/ForcePushIT.java
|
ForcePushIT: Add tests for deleting branch by push
|
<ide><path>errit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/git/ForcePushIT.java
<ide> package com.google.gerrit.acceptance.git;
<ide>
<ide> import static com.google.common.truth.Truth.assertThat;
<add>import static com.google.gerrit.acceptance.GitUtil.deleteRef;
<ide> import static org.eclipse.jgit.lib.Constants.HEAD;
<add>import static org.eclipse.jgit.transport.RemoteRefUpdate.Status.OK;
<add>import static org.eclipse.jgit.transport.RemoteRefUpdate.Status.REJECTED_OTHER_REASON;
<ide>
<ide> import com.google.gerrit.acceptance.AbstractDaemonTest;
<add>import com.google.gerrit.acceptance.NoHttpd;
<ide> import com.google.gerrit.acceptance.PushOneCommit;
<ide> import com.google.gerrit.common.data.Permission;
<add>import com.google.gerrit.extensions.api.projects.BranchInput;
<ide> import org.eclipse.jgit.lib.ObjectId;
<ide> import org.eclipse.jgit.lib.RefUpdate;
<add>import org.eclipse.jgit.transport.PushResult;
<add>import org.eclipse.jgit.transport.RemoteRefUpdate;
<ide> import org.junit.Test;
<ide>
<add>@NoHttpd
<ide> public class ForcePushIT extends AbstractDaemonTest {
<ide>
<ide> @Test
<ide> PushOneCommit.Result r2 = push2.to("refs/heads/master");
<ide> r2.assertOkStatus();
<ide> }
<add>
<add> @Test
<add> public void deleteNotAllowed() throws Exception {
<add> assertDeleteRef(REJECTED_OTHER_REASON);
<add> }
<add>
<add> @Test
<add> public void deleteNotAllowedWithOnlyPushPermission() throws Exception {
<add> grant(Permission.PUSH, project, "refs/*", false);
<add> assertDeleteRef(REJECTED_OTHER_REASON);
<add> }
<add>
<add> @Test
<add> public void deleteAllowedWithForcePushPermission() throws Exception {
<add> grant(Permission.PUSH, project, "refs/*", true);
<add> assertDeleteRef(OK);
<add> }
<add>
<add> @Test
<add> public void deleteAllowedWithDeletePermission() throws Exception {
<add> grant(Permission.DELETE, project, "refs/*", true);
<add> assertDeleteRef(OK);
<add> }
<add>
<add> private void assertDeleteRef(RemoteRefUpdate.Status expectedStatus) throws Exception {
<add> BranchInput in = new BranchInput();
<add> in.ref = "refs/heads/test";
<add> gApi.projects().name(project.get()).branch(in.ref).create(in);
<add> PushResult result = deleteRef(testRepo, in.ref);
<add> RemoteRefUpdate refUpdate = result.getRemoteUpdate(in.ref);
<add> assertThat(refUpdate.getStatus()).isEqualTo(expectedStatus);
<add> }
<ide> }
|
|
JavaScript
|
mit
|
ca96812a2377ee17f4183f9c7d445013c5d41a78
| 0 |
christophior/spotify-web-api-node,thelinmichael/spotify-web-api-node,jlewallen/spotify-web-api-node,UnbounDev/spotify-web-api-node,JMPerez/spotify-web-api-node,erezny/spotify-web-api-node
|
var SpotifyWebApi = require('../src/spotify-web-api'),
should = require('should')
fs = require('fs');
'use strict';
describe('Spotify Web API', function() {
this.timeout(5000);
it('should set clientId, clientSecret and redirectUri', function() {
var credentials = {
clientId : 'someClientId',
clientSecret : 'someClientSecret',
redirectUri : 'myRedirectUri',
accessToken :'mySuperNiceAccessToken',
refreshToken :'iCanEvenSaveMyAccessToken'
};
var api = new SpotifyWebApi(credentials);
api.getCredentials().clientId.should.equal(credentials.clientId);
api.getCredentials().clientSecret.should.equal(credentials.clientSecret);
api.getCredentials().redirectUri.should.equal(credentials.redirectUri);
api.getCredentials().accessToken.should.equal(credentials.accessToken);
api.getCredentials().refreshToken.should.equal(credentials.refreshToken);
});
it("should retrieve track metadata", function(done) {
var api = new SpotifyWebApi();
api.getTrack('3Qm86XLflmIXVm1wcwkgDK')
.then(function(data) {
done();
}, function(err) {
done(err);
});
});
it.skip("should fail for non existing track id", function(done) {
var api = new SpotifyWebApi();
api.getTrack('idontexist')
.then(function(data) {
done(new Error('Should have failed'));
}, function(err) {
'non existing id'.should.equal(err.message);
done();
});
});
it('should fail for empty track id', function(done) {
var api = new SpotifyWebApi();
api.getTrack()
.then(function(data) {
done(new Error('Should have failed'));
}, function(err) {
done();
});
});
it("should retrieve metadata for several tracks", function(done) {
var api = new SpotifyWebApi();
api.getTracks(['0eGsygTp906u18L0Oimnem', '1lDWb6b6ieDQ2xT7ewTC3G'])
.then(function(data) {
done();
}, function(err) {
done(err);
});
});
it("should retrieve metadata for an album", function(done) {
var api = new SpotifyWebApi();
api.getAlbum('0sNOF9WDwhWunNAHPD3Baj')
.then(function(data) {
('spotify:album:0sNOF9WDwhWunNAHPD3Baj').should.equal(data.uri);
done();
}, function(err) {
done(err);
});
});
it("should retrieve metadata for several albums", function(done) {
var api = new SpotifyWebApi();
api.getAlbums(['41MnTivkwTO3UUJ8DrqEJJ', '6JWc4iAiJ9FjyK0B59ABb4'])
.then(function(data) {
'spotify:album:41MnTivkwTO3UUJ8DrqEJJ'.should.equal(data.albums[0].uri);
'spotify:album:6JWc4iAiJ9FjyK0B59ABb4'.should.equal(data.albums[1].uri);
done();
}, function(err) {
done(err);
});
});
it("should retrive metadata for an artist", function(done) {
var api = new SpotifyWebApi();
api.getArtist('0LcJLqbBmaGUft1e9Mm8HV')
.then(function(data) {
('spotify:artist:0LcJLqbBmaGUft1e9Mm8HV').should.equal(data.uri);
done();
}, function(err) {
done(err);
});
});
it("should retrieve metadata for several artists", function(done) {
var api = new SpotifyWebApi();
api.getArtists(['0oSGxfWSnnOXhD2fKuz2Gy', '3dBVyJ7JuOMt4GE9607Qin'])
.then(function(data) {
'spotify:artist:0oSGxfWSnnOXhD2fKuz2Gy'.should.equal(data.artists[0].uri);
'spotify:artist:3dBVyJ7JuOMt4GE9607Qin'.should.equal(data.artists[1].uri);
done();
}, function(err) {
done(err);
});
});
it("should search for an album using limit and offset", function(done) {
var api = new SpotifyWebApi();
api.searchAlbums('The Best of Keane', { limit : 3, offset : 2 })
.then(function(data) {
'https://api.spotify.com/v1/search?query=The+Best+of+Keane&offset=2&limit=3&type=album'.should.equal(data.albums.href);
done();
}, function(err) {
console.log(err);
done(err);
});
});
it("should search for an artist using limit and offset", function(done) {
var api = new SpotifyWebApi();
api.searchArtists('David Bowie', { limit : 5, offset : 1 })
.then(function(data) {
'https://api.spotify.com/v1/search?query=David+Bowie&offset=1&limit=5&type=artist'.should.equal(data.artists.href);
done();
}, function(err) {
done(err);
});
});
it("should search for a track using limit and offset", function(done) {
var api = new SpotifyWebApi();
api.searchTracks('Mr. Brightside', { limit : 3, offset : 2 })
.then(function(data) {
'https://api.spotify.com/v1/search?query=Mr.+Brightside&offset=2&limit=3&type=track'.should.equal(data.tracks.href);
done();
}, function(err) {
console.log(err);
done(err);
});
});
it("should get artists albums", function(done) {
var api = new SpotifyWebApi();
api.getArtistAlbums('0oSGxfWSnnOXhD2fKuz2Gy', { album_type : 'album', country : 'GB', limit : 2, offset : 5 })
.then(function(data) {
'https://api.spotify.com/v1/artists/0oSGxfWSnnOXhD2fKuz2Gy/albums?offset=5&limit=2&album_type=album&market=GB'.should.equal(data.href);
done();
}, function(err) {
console.log(err);
done(err);
});
});
it("should get tracks from album", function(done) {
var api = new SpotifyWebApi();
api.getAlbumTracks('41MnTivkwTO3UUJ8DrqEJJ', { limit : 5, offset : 1 })
.then(function(data) {
'https://api.spotify.com/v1/albums/41MnTivkwTO3UUJ8DrqEJJ/tracks?offset=1&limit=5'.should.equal(data.href);
done();
}, function(err) {
done(err);
});
});
it("should get top tracks for artist", function(done) {
var api = new SpotifyWebApi();
api.getArtistTopTracks('0oSGxfWSnnOXhD2fKuz2Gy', 'GB')
.then(function(data) {
done();
}, function(err) {
done(err);
});
});
it("should get similar artists", function(done) {
var api = new SpotifyWebApi();
api.getArtistRelatedArtists('0qeei9KQnptjwb8MgkqEoy')
.then(function(data) {
should.exist(data.artists);
done();
}, function(err) {
done(err);
});
});
it("should get a user", function(done) {
var api = new SpotifyWebApi();
api.getUser('petteralexis')
.then(function(data) {
'spotify:user:petteralexis'.should.equal(data.uri);
done();
}, function(err) {
done(err);
});
});
it.skip("should get the authenticated user's information", function(done) {
var api = new SpotifyWebApi({
accessToken : 'someAccessToken'
});
api.getMe()
.then(function(data) {
'spotify:user:thelinmichael'.should.equal(data.uri);
done();
}, function(err) {
done(err);
});
});
it.skip("should get the authenticated user's information with accesstoken set on the api object", function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('someAccessToken');
api.getMe()
.then(function(data) {
'spotify:user:thelinmichael'.should.equal(data.uri);
done();
}, function(err) {
done(err);
});
});
it('should fail if no token is provided for a request that requires an access token', function(done) {
var api = new SpotifyWebApi();
api.getMe()
.then(function(data) {
done(new Error('Should have failed!'));
}, function(err) {
done();
});
});
it.skip('should get a users playlists', function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('myVeryLongAccessToken');
api.getUserPlaylists('thelinmichael')
.then(function(data) {
done();
},function(err) {
done(err);
});
});
it.skip('should get a playlist', function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('myVeryVeryLongAccessToken');
api.getPlaylist('thelinmichael', '5ieJqeLJjjI8iJWaxeBLuK')
.then(function(data) {
'spotify:user:thelinmichael:playlist:5ieJqeLJjjI8iJWaxeBLuK'.should.equal(data.uri);
done();
}, function(err) {
done(err);
});
});
it.skip('should create a playlist', function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('long-access-token');
api.createPlaylist('thelinmichael', 'My Cool Playlist', { 'public' : true })
.then(function(data) {
done();
}, function(err) {
console.log(err.error);
done(err);
});
});
it.skip('should change playlist details', function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('long-access-token');
api.changePlaylistDetails('thelinmichael', '5ieJqeLJjjI8iJWaxeBLuK', {
name: 'This is a new name for my Cool Playlist, and will become private',
'public' : false
}).then(function(data) {
done();
}, function(err) {
console.log(err.error);
done(err);
});
});
it.skip('should add tracks to playlist', function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('long-access-token');
api.addTracksToPlaylist('thelinmichael', '5ieJqeLJjjI8iJWaxeBLuK', ["spotify:track:4iV5W9uYEdYUVa79Axb7Rh", "spotify:track:1301WleyT98MSxVHPZCA6M"])
.then(function(data) {
done();
}, function(err) {
console.log(err.error);
done(err);
});
});
it.skip('should add tracks to playlist with specified index', function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('<insert valid access token>');
api.addTracksToPlaylist('thelinmichael', '5ieJqeLJjjI8iJWaxeBLuK', ["spotify:track:4iV5W9uYEdYUVa79Axb7Rh", "spotify:track:1301WleyT98MSxVHPZCA6M"],
{
position : 10
})
.then(function(data) {
done();
}, function(err) {
console.log(err.error);
done(err);
});
});
it.skip("should retrieve an access token using the client credentials flow", function(done) {
var clientId = 'someClientId',
clientSecret = 'someClientSecret';
var api = new SpotifyWebApi({
clientId : clientId,
clientSecret : clientSecret
});
api.clientCredentialsGrant()
.then(function(data) {
'Bearer'.should.equal(data['token_type']);
(3600).should.equal(data['expires_in']);
should.exist(data['access_token']);
done();
}, function(err) {
done(err);
});
});
it.skip("should retrieve an access token with scopes", function(done) {
var clientId = 'fcecfc79122e4cd299473677a17cbd4d',
clientSecret = 'f6338737c9bb4bc9a71924cb2940adss';
var api = new SpotifyWebApi({
clientId : clientId,
clientSecret : clientSecret
});
var scopes = ['playlist-read'];
api.clientCredentialsGrant({
'scope' : scopes
})
.then(function(data) {
console.log(data);
'Bearer'.should.equal(data['token_type']);
(3600).should.equal(data['expires_in']);
should.exist(data['access_token']);
done();
}, function(err) {
done(err);
});
});
it.skip("should retrieve an access token using the authorization code flow", function(done) {
var credentials = {
clientId : 'someClientId',
clientSecret : 'someClientSecret',
redirectUri : 'http://www.michaelthelin.se/test-callback'
};
var api = new SpotifyWebApi(credentials);
api.authorizationCodeGrant('mySuperLongCode')
.then(function(data) {
'Bearer'.should.equal(data['token_type']);
(3600).should.equal(data['expires_in']);
should.exist(data['access_token']);
should.exist(data['refresh_token']);
done();
}, function(err) {
console.log(err);
done(err);
});
});
it.skip('should refresh an access token', function(done) {
var clientId = 'someClientId';
var clientSecret = 'someClientSecret';
var refreshToken = 'someLongRefreshToken';
var api = new SpotifyWebApi({
clientId : clientId,
clientSecret : clientSecret,
refreshToken : refreshToken
});
api.refreshAccessToken()
.then(function(data) {
done();
}, function(err) {
done(err);
});
});
it('should create authorization URL', function() {
var scopes = ['user-read-private', 'user-read-email'],
redirectUri = 'https://example.com/callback',
clientId = '5fe01282e44241328a84e7c5cc169165',
state = 'some-state-of-my-choice';
var api = new SpotifyWebApi({
clientId : clientId,
redirectUri : redirectUri
});
var authorizeURL = api.createAuthorizeURL(scopes, state);
'https://accounts.spotify.com:443/authorize?client_id=5fe01282e44241328a84e7c5cc169165&response_type=code&redirect_uri=https://example.com/callback&scope=user-read-private%20user-read-email&state=some-state-of-my-choice'.should.equal(authorizeURL);
});
it('should set, get and reset credentials successfully', function() {
var api = new SpotifyWebApi({
clientId : 'myClientId'
});
api.getClientId().should.equal('myClientId');
api.resetClientId();
should.not.exist(api.getClientId());
api.setClientId('woopwoop');
api.getClientId().should.equal('woopwoop');
});
it.skip('should get tracks in a playlist', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.getPlaylistTracks('thelinmichael', '3ktAYNcRHpazJ9qecm3ptn')
.then(function(data) {
'https://api.spotify.com/v1/users/thelinmichael/playlists/3ktAYNcRHpazJ9qecm3ptn/tracks'.should.equal(data.href);
done();
}, function(err) {
console.log(err);
done(err);
});
});
it.skip('should get tracks in a playlist with fields option', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.getPlaylistTracks('thelinmichael', '3ktAYNcRHpazJ9qecm3ptn', { 'fields' : 'items' })
.then(function(data) {
should.exist(data.items);
should.not.exist(data.href);
done();
}, function(err) {
console.log(err);
done(err);
});
});
/* Run this test with a valid access token with the user-library-read scope */
it.skip('should get tracks in the users library', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.getMySavedTracks({
limit : 2,
offset: 1
})
.then(function(data) {
data.href.should.equal("https://api.spotify.com/v1/me/tracks?offset=1&limit=2");
done();
}, function(err) {
console.log(err);
done(err);
});
});
/* Run this test with a valid access token with the user-library-read scope */
it.skip('should determine if a track is in the users library', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.containsMySavedTracks(["5ybJm6GczjQOgTqmJ0BomP"])
.then(function(data) {
Object.prototype.toString.call(data).should.equal('[object Array]');
data.length.should.equal(1);
data[0].should.equal(false);
done();
}, function(err) {
console.log(err);
done(err);
});
});
/* Run this test with a valid access token with the user-library-modify scope */
it.skip('should remove tracks in the users library', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.removeFromMySavedTracks(["3VNWq8rTnQG6fM1eldSpZ0"])
.then(function(data) {
done();
}, function(err) {
console.log(err);
done(err);
});
});
/* Run this test with a valid access token with the user-library-modify scope */
it.skip('should add tracks to the users library', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.addToMySavedTracks(["3VNWq8rTnQG6fM1eldSpZ0"])
.then(function(data) {
done();
}, function(err) {
console.log(err);
done(err);
});
});
it('handles expired tokens', function(done) {
var accessToken = "BQAGn9m9tRK96oUcc7962erAWydSShZ-geyZ1mcHSmDSfsoRKmhsz_g2ZZwBDlbRuKTUAb4RjGFFybDm0Kvv-7UNR608ff7nk0u9YU4nM6f9HeRhYXprgmZXQHhBKFfyxaVetvNnPMCBctf05vJcHbpiZBL3-WLQhScTrMExceyrfQ7g";
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.addToMySavedTracks(['3VNWq8rTnQG6fM1eldSpZ0'])
.then(function(data) {
console.log(data);
done(new Error('should have failed'));
}, function(err) {
err.message.should.equal('The access token expired');
done();
});
})
/* Run this test with a valid access token */
it.skip('should get new releases', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.getNewReleases({
limit : 5,
offset: 0,
country: 'SE'
})
.then(function(data) {
data.albums.href.should.equal('https://api.spotify.com/v1/browse/new-releases?country=SE&offset=0&limit=5')
data.albums.items.length.should.equal(5);
done();
}, function(err) {
console.log(err);
done(err);
});
});
/* Run this test with a valid access token */
it.skip('should get featured playlists', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.getFeaturedPlaylists({
limit : 3,
offset: 1,
country: 'SE',
locale: 'sv_SE',
timestamp:'2014-10-23T09:00:00'
})
.then(function(data) {
data.playlists.href.should.equal('https://api.spotify.com/v1/browse/featured-playlists?country=SE&locale=sv_SE×tamp=2014-10-23T09:00:00&offset=1&limit=3')
data.playlists.items.length.should.equal(3);
done();
}, function(err) {
console.log(err);
done(err);
});
});
});
|
test/spotify-web-api.js
|
var SpotifyWebApi = require('../src/spotify-web-api'),
should = require('should')
fs = require('fs');
'use strict';
describe('Spotify Web API', function() {
this.timeout(5000);
it('should set clientId, clientSecret and redirectUri', function() {
var credentials = {
clientId : 'someClientId',
clientSecret : 'someClientSecret',
redirectUri : 'myRedirectUri',
accessToken :'mySuperNiceAccessToken',
refreshToken :'iCanEvenSaveMyAccessToken'
};
var api = new SpotifyWebApi(credentials);
api.getCredentials().clientId.should.equal(credentials.clientId);
api.getCredentials().clientSecret.should.equal(credentials.clientSecret);
api.getCredentials().redirectUri.should.equal(credentials.redirectUri);
api.getCredentials().accessToken.should.equal(credentials.accessToken);
api.getCredentials().refreshToken.should.equal(credentials.refreshToken);
});
it("should retrieve track metadata", function(done) {
var api = new SpotifyWebApi();
api.getTrack('3Qm86XLflmIXVm1wcwkgDK')
.then(function(data) {
done();
}, function(err) {
done(err);
});
});
it.skip("should fail for non existing track id", function(done) {
var api = new SpotifyWebApi();
api.getTrack('idontexist')
.then(function(data) {
done(new Error('Should have failed'));
}, function(err) {
'non existing id'.should.equal(err.message);
done();
});
});
it('should fail for empty track id', function(done) {
var api = new SpotifyWebApi();
api.getTrack()
.then(function(data) {
done(new Error('Should have failed'));
}, function(err) {
done();
});
});
it("should retrieve metadata for several tracks", function(done) {
var api = new SpotifyWebApi();
api.getTracks(['0eGsygTp906u18L0Oimnem', '1lDWb6b6ieDQ2xT7ewTC3G'])
.then(function(data) {
done();
}, function(err) {
done(err);
});
});
it("should retrieve metadata for an album", function(done) {
var api = new SpotifyWebApi();
api.getAlbum('0sNOF9WDwhWunNAHPD3Baj')
.then(function(data) {
('spotify:album:0sNOF9WDwhWunNAHPD3Baj').should.equal(data.uri);
done();
}, function(err) {
done(err);
});
});
it("should retrieve metadata for several albums", function(done) {
var api = new SpotifyWebApi();
api.getAlbums(['41MnTivkwTO3UUJ8DrqEJJ', '6JWc4iAiJ9FjyK0B59ABb4'])
.then(function(data) {
'spotify:album:41MnTivkwTO3UUJ8DrqEJJ'.should.equal(data.albums[0].uri);
'spotify:album:6JWc4iAiJ9FjyK0B59ABb4'.should.equal(data.albums[1].uri);
done();
}, function(err) {
done(err);
});
});
it("should retrive metadata for an artist", function(done) {
var api = new SpotifyWebApi();
api.getArtist('0LcJLqbBmaGUft1e9Mm8HV')
.then(function(data) {
('spotify:artist:0LcJLqbBmaGUft1e9Mm8HV').should.equal(data.uri);
done();
}, function(err) {
done(err);
});
});
it("should retrieve metadata for several artists", function(done) {
var api = new SpotifyWebApi();
api.getArtists(['0oSGxfWSnnOXhD2fKuz2Gy', '3dBVyJ7JuOMt4GE9607Qin'])
.then(function(data) {
'spotify:artist:0oSGxfWSnnOXhD2fKuz2Gy'.should.equal(data.artists[0].uri);
'spotify:artist:3dBVyJ7JuOMt4GE9607Qin'.should.equal(data.artists[1].uri);
done();
}, function(err) {
done(err);
});
});
it("should search for an album using limit and offset", function(done) {
var api = new SpotifyWebApi();
api.searchAlbums('The Best of Keane', { limit : 3, offset : 2 })
.then(function(data) {
'https://api.spotify.com/v1/search?query=The+Best+of+Keane&offset=2&limit=3&type=album'.should.equal(data.albums.href);
done();
}, function(err) {
console.log(err);
done(err);
});
});
it("should search for an artist using limit and offset", function(done) {
var api = new SpotifyWebApi();
api.searchArtists('David Bowie', { limit : 5, offset : 1 })
.then(function(data) {
'https://api.spotify.com/v1/search?query=David+Bowie&offset=1&limit=5&type=artist'.should.equal(data.artists.href);
done();
}, function(err) {
done(err);
});
});
it("should search for a track using limit and offset", function(done) {
var api = new SpotifyWebApi();
api.searchTracks('Mr. Brightside', { limit : 3, offset : 2 })
.then(function(data) {
'https://api.spotify.com/v1/search?query=Mr.+Brightside&offset=2&limit=3&type=track'.should.equal(data.tracks.href);
done();
}, function(err) {
done(err);
});
});
it("should get artists albums", function(done) {
var api = new SpotifyWebApi();
api.getArtistAlbums('0oSGxfWSnnOXhD2fKuz2Gy', { album_type : 'album', country : 'GB', limit : 2, offset : 5 })
.then(function(data) {
'https://api.spotify.com/v1/artists/0oSGxfWSnnOXhD2fKuz2Gy/albums?offset=5&limit=2&album_type=album'.should.equal(data.href);
done();
}, function(err) {
done(err);
});
});
it("should get tracks from album", function(done) {
var api = new SpotifyWebApi();
api.getAlbumTracks('41MnTivkwTO3UUJ8DrqEJJ', { limit : 5, offset : 1 })
.then(function(data) {
'https://api.spotify.com/v1/albums/41MnTivkwTO3UUJ8DrqEJJ/tracks?offset=1&limit=5'.should.equal(data.href);
done();
}, function(err) {
done(err);
});
});
it("should get top tracks for artist", function(done) {
var api = new SpotifyWebApi();
api.getArtistTopTracks('0oSGxfWSnnOXhD2fKuz2Gy', 'GB')
.then(function(data) {
done();
}, function(err) {
done(err);
});
});
it("should get similar artists", function(done) {
var api = new SpotifyWebApi();
api.getArtistRelatedArtists('0qeei9KQnptjwb8MgkqEoy')
.then(function(data) {
should.exist(data.artists);
done();
}, function(err) {
done(err);
});
});
it("should get a user", function(done) {
var api = new SpotifyWebApi();
api.getUser('petteralexis')
.then(function(data) {
'spotify:user:petteralexis'.should.equal(data.uri);
done();
}, function(err) {
done(err);
});
});
it.skip("should get the authenticated user's information", function(done) {
var api = new SpotifyWebApi({
accessToken : 'someAccessToken'
});
api.getMe()
.then(function(data) {
'spotify:user:thelinmichael'.should.equal(data.uri);
done();
}, function(err) {
done(err);
});
});
it.skip("should get the authenticated user's information with accesstoken set on the api object", function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('someAccessToken');
api.getMe()
.then(function(data) {
'spotify:user:thelinmichael'.should.equal(data.uri);
done();
}, function(err) {
done(err);
});
});
it('should fail if no token is provided for a request that requires an access token', function(done) {
var api = new SpotifyWebApi();
api.getMe()
.then(function(data) {
done(new Error('Should have failed!'));
}, function(err) {
done();
});
});
it.skip('should get a users playlists', function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('myVeryLongAccessToken');
api.getUserPlaylists('thelinmichael')
.then(function(data) {
done();
},function(err) {
done(err);
});
});
it.skip('should get a playlist', function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('myVeryVeryLongAccessToken');
api.getPlaylist('thelinmichael', '5ieJqeLJjjI8iJWaxeBLuK')
.then(function(data) {
'spotify:user:thelinmichael:playlist:5ieJqeLJjjI8iJWaxeBLuK'.should.equal(data.uri);
done();
}, function(err) {
done(err);
});
});
it.skip('should create a playlist', function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('long-access-token');
api.createPlaylist('thelinmichael', 'My Cool Playlist', { 'public' : true })
.then(function(data) {
done();
}, function(err) {
console.log(err.error);
done(err);
});
});
it.skip('should change playlist details', function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('long-access-token');
api.changePlaylistDetails('thelinmichael', '5ieJqeLJjjI8iJWaxeBLuK', {
name: 'This is a new name for my Cool Playlist, and will become private',
'public' : false
}).then(function(data) {
done();
}, function(err) {
console.log(err.error);
done(err);
});
});
it.skip('should add tracks to playlist', function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('long-access-token');
api.addTracksToPlaylist('thelinmichael', '5ieJqeLJjjI8iJWaxeBLuK', ["spotify:track:4iV5W9uYEdYUVa79Axb7Rh", "spotify:track:1301WleyT98MSxVHPZCA6M"])
.then(function(data) {
done();
}, function(err) {
console.log(err.error);
done(err);
});
});
it.skip('should add tracks to playlist with specified index', function(done) {
var api = new SpotifyWebApi();
api.setAccessToken('<insert valid access token>');
api.addTracksToPlaylist('thelinmichael', '5ieJqeLJjjI8iJWaxeBLuK', ["spotify:track:4iV5W9uYEdYUVa79Axb7Rh", "spotify:track:1301WleyT98MSxVHPZCA6M"],
{
position : 10
})
.then(function(data) {
done();
}, function(err) {
console.log(err.error);
done(err);
});
});
it.skip("should retrieve an access token using the client credentials flow", function(done) {
var clientId = 'someClientId',
clientSecret = 'someClientSecret';
var api = new SpotifyWebApi({
clientId : clientId,
clientSecret : clientSecret
});
api.clientCredentialsGrant()
.then(function(data) {
'Bearer'.should.equal(data['token_type']);
(3600).should.equal(data['expires_in']);
should.exist(data['access_token']);
done();
}, function(err) {
done(err);
});
});
it.skip("should retrieve an access token with scopes", function(done) {
var clientId = 'fcecfc79122e4cd299473677a17cbd4d',
clientSecret = 'f6338737c9bb4bc9a71924cb2940adss';
var api = new SpotifyWebApi({
clientId : clientId,
clientSecret : clientSecret
});
var scopes = ['playlist-read'];
api.clientCredentialsGrant({
'scope' : scopes
})
.then(function(data) {
console.log(data);
'Bearer'.should.equal(data['token_type']);
(3600).should.equal(data['expires_in']);
should.exist(data['access_token']);
done();
}, function(err) {
done(err);
});
});
it.skip("should retrieve an access token using the authorization code flow", function(done) {
var credentials = {
clientId : 'someClientId',
clientSecret : 'someClientSecret',
redirectUri : 'http://www.michaelthelin.se/test-callback'
};
var api = new SpotifyWebApi(credentials);
api.authorizationCodeGrant('mySuperLongCode')
.then(function(data) {
'Bearer'.should.equal(data['token_type']);
(3600).should.equal(data['expires_in']);
should.exist(data['access_token']);
should.exist(data['refresh_token']);
done();
}, function(err) {
console.log(err);
done(err);
});
});
it.skip('should refresh an access token', function(done) {
var clientId = 'someClientId';
var clientSecret = 'someClientSecret';
var refreshToken = 'someLongRefreshToken';
var api = new SpotifyWebApi({
clientId : clientId,
clientSecret : clientSecret,
refreshToken : refreshToken
});
api.refreshAccessToken()
.then(function(data) {
done();
}, function(err) {
done(err);
});
});
it('should create authorization URL', function() {
var scopes = ['user-read-private', 'user-read-email'],
redirectUri = 'https://example.com/callback',
clientId = '5fe01282e44241328a84e7c5cc169165',
state = 'some-state-of-my-choice';
var api = new SpotifyWebApi({
clientId : clientId,
redirectUri : redirectUri
});
var authorizeURL = api.createAuthorizeURL(scopes, state);
'https://accounts.spotify.com:443/authorize?client_id=5fe01282e44241328a84e7c5cc169165&response_type=code&redirect_uri=https://example.com/callback&scope=user-read-private%20user-read-email&state=some-state-of-my-choice'.should.equal(authorizeURL);
});
it('should set, get and reset credentials successfully', function() {
var api = new SpotifyWebApi({
clientId : 'myClientId'
});
api.getClientId().should.equal('myClientId');
api.resetClientId();
should.not.exist(api.getClientId());
api.setClientId('woopwoop');
api.getClientId().should.equal('woopwoop');
});
it.skip('should get tracks in a playlist', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.getPlaylistTracks('thelinmichael', '3ktAYNcRHpazJ9qecm3ptn')
.then(function(data) {
'https://api.spotify.com/v1/users/thelinmichael/playlists/3ktAYNcRHpazJ9qecm3ptn/tracks'.should.equal(data.href);
done();
}, function(err) {
console.log(err);
done(err);
});
});
it.skip('should get tracks in a playlist with fields option', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.getPlaylistTracks('thelinmichael', '3ktAYNcRHpazJ9qecm3ptn', { 'fields' : 'items' })
.then(function(data) {
should.exist(data.items);
should.not.exist(data.href);
done();
}, function(err) {
console.log(err);
done(err);
});
});
/* Run this test with a valid access token with the user-library-read scope */
it.skip('should get tracks in the users library', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.getMySavedTracks({
limit : 2,
offset: 1
})
.then(function(data) {
data.href.should.equal("https://api.spotify.com/v1/me/tracks?offset=1&limit=2");
done();
}, function(err) {
console.log(err);
done(err);
});
});
/* Run this test with a valid access token with the user-library-read scope */
it.skip('should determine if a track is in the users library', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.containsMySavedTracks(["5ybJm6GczjQOgTqmJ0BomP"])
.then(function(data) {
Object.prototype.toString.call(data).should.equal('[object Array]');
data.length.should.equal(1);
data[0].should.equal(false);
done();
}, function(err) {
console.log(err);
done(err);
});
});
/* Run this test with a valid access token with the user-library-modify scope */
it.skip('should remove tracks in the users library', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.removeFromMySavedTracks(["3VNWq8rTnQG6fM1eldSpZ0"])
.then(function(data) {
done();
}, function(err) {
console.log(err);
done(err);
});
});
/* Run this test with a valid access token with the user-library-modify scope */
it.skip('should add tracks to the users library', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.addToMySavedTracks(["3VNWq8rTnQG6fM1eldSpZ0"])
.then(function(data) {
done();
}, function(err) {
console.log(err);
done(err);
});
});
it.only('handles expired tokens', function(done) {
var accessToken = "BQAGn9m9tRK96oUcc7962erAWydSShZ-geyZ1mcHSmDSfsoRKmhsz_g2ZZwBDlbRuKTUAb4RjGFFybDm0Kvv-7UNR608ff7nk0u9YU4nM6f9HeRhYXprgmZXQHhBKFfyxaVetvNnPMCBctf05vJcHbpiZBL3-WLQhScTrMExceyrfQ7g";
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.addToMySavedTracks(['3VNWq8rTnQG6fM1eldSpZ0'])
.then(function(data) {
console.log(data);
done(new Error('should have failed'));
}, function(err) {
err.message.should.equal('The access token expired');
done();
});
})
/* Run this test with a valid access token */
it.skip('should get new releases', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.getNewReleases({
limit : 5,
offset: 0,
country: 'SE'
})
.then(function(data) {
data.albums.href.should.equal('https://api.spotify.com/v1/browse/new-releases?country=SE&offset=0&limit=5')
data.albums.items.length.should.equal(5);
done();
}, function(err) {
console.log(err);
done(err);
});
});
/* Run this test with a valid access token */
it.skip('should get featured playlists', function(done) {
var accessToken = 'myAccessToken';
var api = new SpotifyWebApi({
accessToken : accessToken
});
api.getFeaturedPlaylists({
limit : 3,
offset: 1,
country: 'SE',
locale: 'sv_SE',
timestamp:'2014-10-23T09:00:00'
})
.then(function(data) {
data.playlists.href.should.equal('https://api.spotify.com/v1/browse/featured-playlists?country=SE&locale=sv_SE×tamp=2014-10-23T09:00:00&offset=1&limit=3')
data.playlists.items.length.should.equal(3);
done();
}, function(err) {
console.log(err);
done(err);
});
});
});
|
Fix artists albums test
|
test/spotify-web-api.js
|
Fix artists albums test
|
<ide><path>est/spotify-web-api.js
<ide> 'https://api.spotify.com/v1/search?query=Mr.+Brightside&offset=2&limit=3&type=track'.should.equal(data.tracks.href);
<ide> done();
<ide> }, function(err) {
<add> console.log(err);
<ide> done(err);
<ide> });
<ide> });
<ide> var api = new SpotifyWebApi();
<ide> api.getArtistAlbums('0oSGxfWSnnOXhD2fKuz2Gy', { album_type : 'album', country : 'GB', limit : 2, offset : 5 })
<ide> .then(function(data) {
<del> 'https://api.spotify.com/v1/artists/0oSGxfWSnnOXhD2fKuz2Gy/albums?offset=5&limit=2&album_type=album'.should.equal(data.href);
<del> done();
<del> }, function(err) {
<add> 'https://api.spotify.com/v1/artists/0oSGxfWSnnOXhD2fKuz2Gy/albums?offset=5&limit=2&album_type=album&market=GB'.should.equal(data.href);
<add> done();
<add> }, function(err) {
<add> console.log(err);
<ide> done(err);
<ide> });
<ide> });
<ide> });
<ide> });
<ide>
<del> it.only('handles expired tokens', function(done) {
<add> it('handles expired tokens', function(done) {
<ide> var accessToken = "BQAGn9m9tRK96oUcc7962erAWydSShZ-geyZ1mcHSmDSfsoRKmhsz_g2ZZwBDlbRuKTUAb4RjGFFybDm0Kvv-7UNR608ff7nk0u9YU4nM6f9HeRhYXprgmZXQHhBKFfyxaVetvNnPMCBctf05vJcHbpiZBL3-WLQhScTrMExceyrfQ7g";
<ide> var api = new SpotifyWebApi({
<ide> accessToken : accessToken
|
|
Java
|
apache-2.0
|
6343dfe1daf84c39c6244a814905f98eb5af6adb
| 0 |
ferney95/karaoke_1
|
package interfaz;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import logica.Autor;
import logica.Genero;
public class PanelIzquierda extends JPanel {
private static final long serialVersionUID = 1L;
private JComboBox<Genero> jcGenero;
private JComboBox<Autor> jcAutor;
private JLabel lbMostrarCanciones;
private JButton jbBuscar;
public PanelIzquierda() {
setSize(600,100);
jcGenero = new JComboBox<Genero>();
jcGenero.setSize(30, 100);
jcGenero.setBackground(Color.WHITE);
add(jcGenero);
jcAutor = new JComboBox<Autor>();
jcAutor.setSize(30, 100);
jcAutor.setBackground(Color.WHITE);
add(jcAutor);
lbMostrarCanciones = new JLabel();
lbMostrarCanciones.setSize(500,100);
lbMostrarCanciones.setBackground(Color.RED);
add(lbMostrarCanciones);
jbBuscar = new JButton("Buscar");
jbBuscar.setSize(40,100);
add(jbBuscar);
}
}
|
karaoke/src/interfaz/PanelIzquierda.java
|
package interfaz;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import logica.Autor;
import logica.Genero;
public class PanelIzquierda extends JPanel {
private static final long serialVersionUID = 1L;
private JComboBox<Genero> jcGenero;
private JComboBox<Autor> jcAutor;
private JLabel lbMostrarCanciones;
private JButton jbBuscar;
public PanelIzquierda() {
setSize(500,510);
setBackground(Color.RED);
jcGenero = new JComboBox<Genero>();
jcGenero.setSize(20, 78);
jcGenero.setBackground(Color.WHITE);
add(jcGenero);
jcAutor = new JComboBox<Autor>();
jcAutor.setSize(20, 78);
jcAutor.setBackground(Color.WHITE);
add(jcAutor);
lbMostrarCanciones = new JLabel();
add(lbMostrarCanciones);
jbBuscar = new JButton("Buscar");
add(jbBuscar);
}
}
|
Agregar componentes alpanel ycorregir unos errores
|
karaoke/src/interfaz/PanelIzquierda.java
|
Agregar componentes alpanel ycorregir unos errores
|
<ide><path>araoke/src/interfaz/PanelIzquierda.java
<ide>
<ide> public PanelIzquierda() {
<ide>
<del> setSize(500,510);
<del> setBackground(Color.RED);
<add> setSize(600,100);
<add>
<ide>
<ide> jcGenero = new JComboBox<Genero>();
<del> jcGenero.setSize(20, 78);
<add> jcGenero.setSize(30, 100);
<ide> jcGenero.setBackground(Color.WHITE);
<ide> add(jcGenero);
<ide>
<ide> jcAutor = new JComboBox<Autor>();
<del> jcAutor.setSize(20, 78);
<add> jcAutor.setSize(30, 100);
<ide> jcAutor.setBackground(Color.WHITE);
<ide> add(jcAutor);
<ide>
<ide> lbMostrarCanciones = new JLabel();
<del>
<add> lbMostrarCanciones.setSize(500,100);
<add> lbMostrarCanciones.setBackground(Color.RED);
<ide> add(lbMostrarCanciones);
<ide>
<ide> jbBuscar = new JButton("Buscar");
<add> jbBuscar.setSize(40,100);
<ide> add(jbBuscar);
<ide> }
<ide>
|
|
Java
|
lgpl-2.1
|
87383d1a754c67d92d924e2b3b54206945227356
| 0 |
levants/lightmare
|
package org.lightmare.deploy;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.lightmare.cache.MetaContainer;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
/**
* Manager class for application deployment
*
* @author levan
*
*/
public class LoaderPoolManager {
// Amount of deployment thread pool
private static final int LOADER_POOL_SIZE = 5;
// Name prefix of deployment threads
private static final String LOADER_THREAD_NAME = "Ejb-Loader-Thread-";
// Lock for pool reopening
private static final Lock LOCK = new ReentrantLock();
/**
* Tries to lock Lock object or waits while locks
*
* @return <code>boolean</code>
*/
private static boolean tryLock() {
boolean locked = LOCK.tryLock();
while (ObjectUtils.notTrue(locked)) {
locked = LOCK.tryLock();
}
return locked;
}
/**
* Gets class loader for existing {@link org.lightmare.deploy.MetaCreator}
* instance
*
* @return {@link ClassLoader}
*/
protected static ClassLoader getCurrent() {
ClassLoader current;
MetaCreator creator = MetaContainer.getCreator();
ClassLoader creatorLoader;
if (ObjectUtils.notNull(creator)) {
// Gets class loader for this deployment
creatorLoader = creator.getCurrent();
if (ObjectUtils.notNull(creatorLoader)) {
current = creatorLoader;
} else {
// Gets default, context class loader for current thread
current = LibraryLoader.getContextClassLoader();
}
} else {
// Gets default, context class loader for current thread
current = LibraryLoader.getContextClassLoader();
}
return current;
}
/**
* Implementation of {@link ThreadFactory} interface for application loading
*
* @author levan
*
*/
private static final class LoaderThreadFactory implements ThreadFactory {
/**
* Constructs and sets thread name
*
* @param thread
*/
private void nameThread(Thread thread) {
String name = StringUtils
.concat(LOADER_THREAD_NAME, thread.getId());
thread.setName(name);
}
/**
* Sets priority of {@link Thread} instance
*
* @param thread
*/
private void setPriority(Thread thread) {
thread.setPriority(Thread.MAX_PRIORITY);
}
/**
* Sets {@link ClassLoader} to passed {@link Thread} instance
*
* @param thread
*/
private void setContextClassLoader(Thread thread) {
ClassLoader parent = getCurrent();
thread.setContextClassLoader(parent);
}
/**
* Configures (sets name, priority and {@link ClassLoader}) passed
* {@link Thread} instance
*
* @param thread
*/
private void configureThread(Thread thread) {
nameThread(thread);
setPriority(thread);
setContextClassLoader(thread);
}
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
configureThread(thread);
return thread;
}
}
// Thread pool for deploying and removal of beans and temporal resources
private static ExecutorService LOADER_POOL;
/**
* Checks if loader {@link ExecutorService} is null or is shut down or is
* terminated
*
* @return <code>boolean</code>
*/
private static boolean invalid() {
return LOADER_POOL == null || LOADER_POOL.isShutdown()
|| LOADER_POOL.isTerminated();
}
private static void initLoaderPool() {
if (invalid()) {
LOADER_POOL = Executors.newFixedThreadPool(LOADER_POOL_SIZE,
new LoaderThreadFactory());
}
}
/**
* Checks and if not valid reopens deploy {@link ExecutorService} instance
*
* @return {@link ExecutorService}
*/
protected static ExecutorService getLoaderPool() {
if (invalid()) {
boolean locked = tryLock();
if (locked) {
try {
initLoaderPool();
} finally {
LOCK.unlock();
}
}
}
return LOADER_POOL;
}
/**
* Submit passed {@link Runnable} implementation in loader pool
*
* @param runnable
*/
public static void submit(Runnable runnable) {
getLoaderPool().submit(runnable);
}
/**
* Submits passed {@link Callable} implementation in loader pool
*
* @param callable
* @return {@link Future}<code><T></code>
*/
public static <T> Future<T> submit(Callable<T> callable) {
Future<T> future = getLoaderPool().submit(callable);
return future;
}
/**
* Clears existing {@link ExecutorService}s from loader threads
*/
public static void reload() {
boolean locked = tryLock();
if (locked) {
try {
if (ObjectUtils.notNull(LOADER_POOL)) {
LOADER_POOL.shutdown();
LOADER_POOL = null;
}
} finally {
LOCK.unlock();
}
}
getLoaderPool();
}
}
|
src/main/java/org/lightmare/deploy/LoaderPoolManager.java
|
package org.lightmare.deploy;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.lightmare.cache.MetaContainer;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
/**
* Manager class for application deployment
*
* @author levan
*
*/
public class LoaderPoolManager {
// Amount of deployment thread pool
private static final int LOADER_POOL_SIZE = 5;
// Name prefix of deployment threads
private static final String LOADER_THREAD_NAME = "Ejb-Loader-Thread-";
// Lock for pool reopening
private static final Lock LOCK = new ReentrantLock();
/**
* Tries to lock Lock object if it it not locked else runs loop while Lock
* releases and locks it again
*
* @return <code>boolean</code>
*/
private static boolean tryLock() {
boolean locked = LOCK.tryLock();
while (ObjectUtils.notTrue(locked)) {
locked = LOCK.tryLock();
}
return locked;
}
/**
* Gets class loader for existing {@link org.lightmare.deploy.MetaCreator}
* instance
*
* @return {@link ClassLoader}
*/
protected static ClassLoader getCurrent() {
ClassLoader current;
MetaCreator creator = MetaContainer.getCreator();
ClassLoader creatorLoader;
if (ObjectUtils.notNull(creator)) {
// Gets class loader for this deployment
creatorLoader = creator.getCurrent();
if (ObjectUtils.notNull(creatorLoader)) {
current = creatorLoader;
} else {
// Gets default, context class loader for current thread
current = LibraryLoader.getContextClassLoader();
}
} else {
// Gets default, context class loader for current thread
current = LibraryLoader.getContextClassLoader();
}
return current;
}
/**
* Implementation of {@link ThreadFactory} interface for application loading
*
* @author levan
*
*/
private static final class LoaderThreadFactory implements ThreadFactory {
/**
* Constructs and sets thread name
*
* @param thread
*/
private void nameThread(Thread thread) {
String name = StringUtils
.concat(LOADER_THREAD_NAME, thread.getId());
thread.setName(name);
}
/**
* Sets priority of {@link Thread} instance
*
* @param thread
*/
private void setPriority(Thread thread) {
thread.setPriority(Thread.MAX_PRIORITY);
}
/**
* Sets {@link ClassLoader} to passed {@link Thread} instance
*
* @param thread
*/
private void setContextClassLoader(Thread thread) {
ClassLoader parent = getCurrent();
thread.setContextClassLoader(parent);
}
/**
* Configures (sets name, priority and {@link ClassLoader}) passed
* {@link Thread} instance
*
* @param thread
*/
private void configureThread(Thread thread) {
nameThread(thread);
setPriority(thread);
setContextClassLoader(thread);
}
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
configureThread(thread);
return thread;
}
}
// Thread pool for deploying and removal of beans and temporal resources
private static ExecutorService LOADER_POOL;
/**
* Checks if loader {@link ExecutorService} is null or is shut down or is
* terminated
*
* @return <code>boolean</code>
*/
private static boolean invalid() {
return (LOADER_POOL == null || LOADER_POOL.isShutdown() || LOADER_POOL
.isTerminated());
}
private static void initLoaderPool() {
LOADER_POOL = Executors.newFixedThreadPool(LOADER_POOL_SIZE,
new LoaderThreadFactory());
}
/**
* Checks and if not valid reopens deploy {@link ExecutorService} instance
*
* @return {@link ExecutorService}
*/
protected static ExecutorService getLoaderPool() {
boolean locked = tryLock();
if (locked && invalid()) {
try {
initLoaderPool();
} finally {
LOCK.unlock();
}
}
return LOADER_POOL;
}
/**
* Submit passed {@link Runnable} implementation in loader pool
*
* @param runnable
*/
public static void submit(Runnable runnable) {
getLoaderPool().submit(runnable);
}
/**
* Submits passed {@link Callable} implementation in loader pool
*
* @param callable
* @return {@link Future}<code><T></code>
*/
public static <T> Future<T> submit(Callable<T> callable) {
Future<T> future = getLoaderPool().submit(callable);
return future;
}
/**
* Clears existing {@link ExecutorService}s from loader threads
*/
public static void reload() {
boolean locked = tryLock();
if (locked) {
try {
if (ObjectUtils.notNull(LOADER_POOL)) {
LOADER_POOL.shutdown();
LOADER_POOL = null;
}
} finally {
LOCK.unlock();
}
}
}
}
|
improved ShutDown class method
|
src/main/java/org/lightmare/deploy/LoaderPoolManager.java
|
improved ShutDown class method
|
<ide><path>rc/main/java/org/lightmare/deploy/LoaderPoolManager.java
<ide> private static final Lock LOCK = new ReentrantLock();
<ide>
<ide> /**
<del> * Tries to lock Lock object if it it not locked else runs loop while Lock
<del> * releases and locks it again
<add> * Tries to lock Lock object or waits while locks
<ide> *
<ide> * @return <code>boolean</code>
<ide> */
<ide> */
<ide> private static boolean invalid() {
<ide>
<del> return (LOADER_POOL == null || LOADER_POOL.isShutdown() || LOADER_POOL
<del> .isTerminated());
<add> return LOADER_POOL == null || LOADER_POOL.isShutdown()
<add> || LOADER_POOL.isTerminated();
<ide> }
<ide>
<ide> private static void initLoaderPool() {
<ide>
<del> LOADER_POOL = Executors.newFixedThreadPool(LOADER_POOL_SIZE,
<del> new LoaderThreadFactory());
<add> if (invalid()) {
<add> LOADER_POOL = Executors.newFixedThreadPool(LOADER_POOL_SIZE,
<add> new LoaderThreadFactory());
<add> }
<ide> }
<ide>
<ide> /**
<ide> */
<ide> protected static ExecutorService getLoaderPool() {
<ide>
<del> boolean locked = tryLock();
<del> if (locked && invalid()) {
<del> try {
<del> initLoaderPool();
<del> } finally {
<del> LOCK.unlock();
<add> if (invalid()) {
<add> boolean locked = tryLock();
<add> if (locked) {
<add> try {
<add> initLoaderPool();
<add> } finally {
<add> LOCK.unlock();
<add> }
<ide> }
<ide> }
<ide>
<ide>
<ide> if (locked) {
<ide> try {
<del>
<ide> if (ObjectUtils.notNull(LOADER_POOL)) {
<ide> LOADER_POOL.shutdown();
<ide> LOADER_POOL = null;
<ide> }
<del>
<ide> } finally {
<ide> LOCK.unlock();
<ide> }
<ide> }
<add>
<add> getLoaderPool();
<ide> }
<ide> }
|
|
Java
|
agpl-3.0
|
389529501000075eda05693f7d0c8b0fbe0ee164
| 0 |
Asqatasun/Asqatasun,Tanaguru/Tanaguru,Tanaguru/Tanaguru,Tanaguru/Tanaguru,medsob/Tanaguru,dzc34/Asqatasun,Tanaguru/Tanaguru,Asqatasun/Asqatasun,dzc34/Asqatasun,dzc34/Asqatasun,Asqatasun/Asqatasun,dzc34/Asqatasun,medsob/Tanaguru,medsob/Tanaguru,Asqatasun/Asqatasun,dzc34/Asqatasun,Asqatasun/Asqatasun,medsob/Tanaguru
|
/*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2011 Open-S Company
*
* This file is part of Tanaguru.
*
* Tanaguru is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: open-s AT open-s DOT com
*/
package org.opens.tgol.command.factory;
import java.io.Serializable;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import org.opens.tgol.command.CreateContractCommand;
import org.opens.tgol.entity.contract.Contract;
import org.opens.tgol.entity.functionality.Functionality;
import org.opens.tgol.entity.option.Option;
import org.opens.tgol.entity.option.OptionElement;
import org.opens.tgol.entity.referential.Referential;
import org.opens.tgol.entity.service.functionality.FunctionalityDataService;
import org.opens.tgol.entity.service.option.OptionDataService;
import org.opens.tgol.entity.service.option.OptionElementDataService;
import org.opens.tgol.entity.service.referential.ReferentialDataService;
/**
*
* @author jkowalczyk
*/
public class CreateContractCommandFactory implements Serializable {
private static final String DOMAIN_OPTION_CODE = "DOMAIN";
private static CreateContractCommandFactory createContractCommandFactory;
private Collection<Referential> referentialList;
private Collection<Functionality> functionalityList;
private Collection<Option> optionList = new HashSet<Option>();
public void setReferentialDataService (ReferentialDataService referentialDataService) {
referentialList = referentialDataService.findAll();
}
public void setFunctionalityDataService (FunctionalityDataService funcitonalityDataService) {
functionalityList = funcitonalityDataService.findAll();
}
private Option contractUrlOption;
public void setOptionDataService (OptionDataService optionDataService) {
for (Option option : optionDataService.findAll()) {
if (optionNameList.contains(option.getCode())){
if (option.getCode().equals(DOMAIN_OPTION_CODE)){
contractUrlOption = option;
} else {
optionList.add(option);
}
}
}
}
private OptionElementDataService optionElementDataService;
public void setOptionElementDataService (OptionElementDataService optionElementDataService) {
this.optionElementDataService = optionElementDataService;
}
private Collection<String> optionNameList;
public void setOptionNameList (Collection<String> optionNameList) {
this.optionNameList = optionNameList;
}
/**
* Factory has default constructor
*/
private CreateContractCommandFactory(){}
public static synchronized CreateContractCommandFactory getInstance() {
if (createContractCommandFactory == null) {
createContractCommandFactory = new CreateContractCommandFactory();
}
return createContractCommandFactory;
}
/**
*
* @param contract
* @return
*/
public CreateContractCommand getInitialisedCreateContractCommand(Contract contract) {
CreateContractCommand createContractCommand = new CreateContractCommand();
createContractCommand.setLabel(contract.getLabel());
createContractCommand.setBeginDate(contract.getBeginDate());
createContractCommand.setEndDate(contract.getEndDate());
addFunctionalityToCommand(createContractCommand, contract);
addReferentialToCommand(createContractCommand, contract);
addOptionToCommand(createContractCommand,contract);
addContractUrlToCommand(createContractCommand,contract);
return createContractCommand;
}
/**
*
* @param createContractCommand
* @return
*/
public CreateContractCommand getInitialisedCreateContractCommand(
CreateContractCommand createContractCommand) {
addFunctionalityToExistingCommand(createContractCommand);
addReferentialToExistingCommand(createContractCommand);
return createContractCommand;
}
/**
*
* @return
*/
public CreateContractCommand getNewCreateContractCommand() {
CreateContractCommand createContractCommand = getCreateContractCommand();
Calendar cal = Calendar.getInstance();
createContractCommand.setBeginDate(cal.getTime());
cal.add(Calendar.YEAR,1);
createContractCommand.setEndDate(cal.getTime());
return createContractCommand;
}
/**
*
* @return
*/
private CreateContractCommand getCreateContractCommand() {
CreateContractCommand createContractCommand = new CreateContractCommand();
addNewFunctionalityToCommand(createContractCommand);
addNewReferentialToCommand(createContractCommand);
addNewOptionsToCommand(createContractCommand);
return createContractCommand;
}
/**
*
*/
private void addFunctionalityToCommand(CreateContractCommand ccc, Contract contract) {
Map<String,Boolean> functMap = new LinkedHashMap<String,Boolean>();
for (Functionality funct : this.functionalityList){
if (contract.getFunctionalitySet().contains(funct)) {
functMap.put(funct.getCode(),Boolean.TRUE);
} else {
functMap.put(funct.getCode(),Boolean.FALSE);
}
}
ccc.setFunctionalityMap(functMap);
}
/**
*
*/
private void addFunctionalityToExistingCommand(CreateContractCommand ccc) {
Map<String,Boolean> functMap = new LinkedHashMap<String,Boolean>();
for (Map.Entry<String,Boolean> entry : ccc.getFunctionalityMap().entrySet()){
if (entry.getValue() == null) {
functMap.put(entry.getKey(),Boolean.FALSE);
} else {
functMap.put(entry.getKey(),Boolean.TRUE);
}
}
ccc.setFunctionalityMap(functMap);
}
/**
*
* @param ccc
*/
private void addNewFunctionalityToCommand(CreateContractCommand ccc) {
Map<String,Boolean> functMap = new LinkedHashMap<String,Boolean>();
for (Functionality funct : this.functionalityList){
functMap.put(funct.getCode(),Boolean.FALSE);
}
ccc.setFunctionalityMap(functMap);
}
/**
*
* @param ccc
* @param contract
*/
private void addReferentialToCommand(CreateContractCommand ccc, Contract contract) {
Map<String,Boolean> refMap = new LinkedHashMap<String,Boolean>();
for (Referential ref : referentialList){
if (contract.getReferentialSet().contains(ref)) {
refMap.put(ref.getCode(),Boolean.TRUE);
} else {
refMap.put(ref.getCode(),Boolean.FALSE);
}
}
ccc.setReferentialMap(refMap);
}
/**
*
* @param ccc
* @param contract
*/
private void addReferentialToExistingCommand(CreateContractCommand ccc) {
Map<String,Boolean> refMap = new LinkedHashMap<String,Boolean>();
for (Map.Entry<String,Boolean> entry : ccc.getReferentialMap().entrySet()){
if (entry.getValue() == null) {
refMap.put(entry.getKey(),Boolean.FALSE);
} else {
refMap.put(entry.getKey(),Boolean.TRUE);
}
}
ccc.setReferentialMap(refMap);
}
/**
*
* @param ccc
*/
private void addNewReferentialToCommand(CreateContractCommand ccc) {
Map<String,Boolean> refMap = new LinkedHashMap<String,Boolean>();
for (Referential ref : referentialList){
refMap.put(ref.getCode(),Boolean.FALSE);
}
ccc.setReferentialMap(refMap);
}
/**
*
* @param ccc
* @param contract
*/
private void addOptionToCommand(CreateContractCommand ccc, Contract contract) {
Map<String,String> optionMap = new LinkedHashMap<String, String>();
for (Option option : optionList){
optionMap.put(
option.getCode(),
getValueFromOptionElementCollection(contract.getOptionElementSet(),option));
}
ccc.setOptionMap(optionMap);
}
/**
*
* @param ccc
* @param contract
*/
private void addContractUrlToCommand(CreateContractCommand ccc, Contract contract) {
for (OptionElement optionElement : contract.getOptionElementSet()){
if (optionElement.getOption().equals(contractUrlOption)) {
ccc.setContractUrl(optionElement.getValue());
}
}
}
/**
*
* @param ccc
* @param contract
*/
private void addNewOptionsToCommand(CreateContractCommand ccc) {
Map<String,String> optionMap = new LinkedHashMap<String,String>();
for (Option option : optionList) {
if (!option.getCode().equals(DOMAIN_OPTION_CODE)) {
optionMap.put(option.getCode(),"");
}
}
ccc.setOptionMap(optionMap);
}
/**
* Retrieve the option value from a collection of option elements.
*
* @param optionElementCollection
* @param option
* @return
*/
private String getValueFromOptionElementCollection(
Collection<OptionElement> optionElementCollection,
Option option) {
for (OptionElement optionElement : optionElementCollection) {
if (optionElement.getOption().getCode().equals(option.getCode())) {
return optionElement.getValue();
}
}
return "";
}
/**
*
* @param createContractCommand
* @param contract
* @return
*/
public Contract updateContractFromCommand(
CreateContractCommand ccc,
Contract contract) {
Set<Functionality> functSet = new HashSet<Functionality>();
Set<Referential> refSet = new HashSet<Referential>();
Set<OptionElement> optionElementSet = new HashSet<OptionElement>();
for (Map.Entry<String,Boolean> entry : ccc.getFunctionalityMap().entrySet()) {
if (entry.getValue() != null && entry.getValue()) {
functSet.add(getFunctionalityFromCode(entry.getKey()));
}
}
for (Map.Entry<String,Boolean> entry : ccc.getReferentialMap().entrySet()) {
if (entry.getValue() != null && entry.getValue()) {
refSet.add(getReferentialFromCode(entry.getKey()));
}
}
for (Map.Entry<String,String> entry : ccc.getOptionMap().entrySet()) {
if (!StringUtils.isEmpty(entry.getValue())) {
optionElementSet.add(getOptionElementFromOptionAndValue(entry.getKey(), entry.getValue()));
}
}
if (!StringUtils.isEmpty(ccc.getContractUrl()) && !ccc.getContractUrl().equalsIgnoreCase("http://")) {
optionElementSet.add(addUrlToContract(ccc.getContractUrl()));
}
contract.addAllFunctionality(functSet);
contract.addAllReferential(refSet);
contract.addAllOptionElement(optionElementSet);
contract.setBeginDate(ccc.getBeginDate());
Calendar cal = Calendar.getInstance();
cal.setTime(ccc.getEndDate());
// the end contract date is added without the hour/minute/second info
// we force the end of the filled-in day before we persist.
cal.add(Calendar.MINUTE, 59);
cal.add(Calendar.HOUR_OF_DAY, 23);
cal.add(Calendar.SECOND, 59);
contract.setEndDate(cal.getTime());
contract.setLabel(ccc.getLabel());
return contract;
}
/**
*
* @param url
* @return
*/
private OptionElement addUrlToContract(String url) {
return createOptionElement(contractUrlOption, url);
}
/**
* @param value
* @param optionCode
* @return
*/
private OptionElement getOptionElementFromOptionAndValue(String optionCode, String value) {
Option option = getOptionFromCode(optionCode);
return createOptionElement(option, value);
}
/**
*
* @param value
* @param option
* @return
*/
private OptionElement createOptionElement(Option option, String value) {
OptionElement optionElement = optionElementDataService.getOptionElementFromValueAndOption(value, option);
if (optionElement != null) {
return optionElement;
}
optionElement = optionElementDataService.create();
optionElement.setValue(value);
optionElement.setOption(option);
optionElementDataService.saveOrUpdate(optionElement);
return optionElement;
}
/**
* Retrieve a referential from its code regarding the local referential list.
*
* @param refCode
* @return
*/
private Referential getReferentialFromCode(String refCode) {
for (Referential ref : referentialList) {
if (ref.getCode().equalsIgnoreCase(refCode)) {
return ref;
}
}
return null;
}
/**
* Retrieve a functionality from its code regarding the local functionality
* list.
*
* @param functCode
* @return
*/
private Functionality getFunctionalityFromCode(String functCode) {
for (Functionality funct : functionalityList) {
if (funct.getCode().equalsIgnoreCase(functCode)) {
return funct;
}
}
return null;
}
/**
* Retrieve an option from its code regarding the local option list
*
* @param optionCode
* @return
*/
private Option getOptionFromCode(String optionCode) {
for (Option option : optionList) {
if (option.getCode().equalsIgnoreCase(optionCode)) {
return option;
}
}
return null;
}
}
|
web-app/tgol-web-app/src/main/java/org/opens/tgol/command/factory/CreateContractCommandFactory.java
|
/*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2011 Open-S Company
*
* This file is part of Tanaguru.
*
* Tanaguru is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: open-s AT open-s DOT com
*/
package org.opens.tgol.command.factory;
import java.io.Serializable;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.opens.tgol.command.CreateContractCommand;
import org.opens.tgol.entity.contract.Contract;
import org.opens.tgol.entity.functionality.Functionality;
import org.opens.tgol.entity.option.Option;
import org.opens.tgol.entity.option.OptionElement;
import org.opens.tgol.entity.referential.Referential;
import org.opens.tgol.entity.service.functionality.FunctionalityDataService;
import org.opens.tgol.entity.service.option.OptionDataService;
import org.opens.tgol.entity.service.option.OptionElementDataService;
import org.opens.tgol.entity.service.referential.ReferentialDataService;
/**
*
* @author jkowalczyk
*/
public class CreateContractCommandFactory implements Serializable {
private static final String DOMAIN_OPTION_CODE = "DOMAIN";
private static CreateContractCommandFactory createContractCommandFactory;
private Collection<Referential> referentialList;
private Collection<Functionality> functionalityList;
private Collection<Option> optionList = new HashSet<Option>();
public void setReferentialDataService (ReferentialDataService referentialDataService) {
referentialList = referentialDataService.findAll();
for (Referential ref : referentialList) {
Logger.getLogger(this.getClass()).error(ref.getCode());
}
}
public void setFunctionalityDataService (FunctionalityDataService funcitonalityDataService) {
functionalityList = funcitonalityDataService.findAll();
}
private Option contractUrlOption;
public void setOptionDataService (OptionDataService optionDataService) {
for (Option option : optionDataService.findAll()) {
if (optionNameList.contains(option.getCode())){
if (option.getCode().equals(DOMAIN_OPTION_CODE)){
contractUrlOption = option;
} else {
optionList.add(option);
}
}
}
}
private OptionElementDataService optionElementDataService;
public void setOptionElementDataService (OptionElementDataService optionElementDataService) {
this.optionElementDataService = optionElementDataService;
}
private Collection<String> optionNameList;
public void setOptionNameList (Collection<String> optionNameList) {
this.optionNameList = optionNameList;
}
/**
* Factory has default constructor
*/
private CreateContractCommandFactory(){}
public static synchronized CreateContractCommandFactory getInstance() {
if (createContractCommandFactory == null) {
createContractCommandFactory = new CreateContractCommandFactory();
}
return createContractCommandFactory;
}
/**
*
* @param contract
* @return
*/
public CreateContractCommand getInitialisedCreateContractCommand(Contract contract) {
CreateContractCommand createContractCommand = new CreateContractCommand();
createContractCommand.setLabel(contract.getLabel());
createContractCommand.setBeginDate(contract.getBeginDate());
createContractCommand.setEndDate(contract.getEndDate());
addFunctionalityToCommand(createContractCommand, contract);
addReferentialToCommand(createContractCommand, contract);
addOptionToCommand(createContractCommand,contract);
addContractUrlToCommand(createContractCommand,contract);
return createContractCommand;
}
/**
*
* @param createContractCommand
* @return
*/
public CreateContractCommand getInitialisedCreateContractCommand(
CreateContractCommand createContractCommand) {
addFunctionalityToExistingCommand(createContractCommand);
addReferentialToExistingCommand(createContractCommand);
return createContractCommand;
}
/**
*
* @return
*/
public CreateContractCommand getNewCreateContractCommand() {
CreateContractCommand createContractCommand = getCreateContractCommand();
Calendar cal = Calendar.getInstance();
createContractCommand.setBeginDate(cal.getTime());
cal.add(Calendar.YEAR,1);
createContractCommand.setEndDate(cal.getTime());
return createContractCommand;
}
/**
*
* @return
*/
private CreateContractCommand getCreateContractCommand() {
CreateContractCommand createContractCommand = new CreateContractCommand();
addNewFunctionalityToCommand(createContractCommand);
addNewReferentialToCommand(createContractCommand);
addNewOptionsToCommand(createContractCommand);
return createContractCommand;
}
/**
*
*/
private void addFunctionalityToCommand(CreateContractCommand ccc, Contract contract) {
Map<String,Boolean> functMap = new LinkedHashMap<String,Boolean>();
for (Functionality funct : this.functionalityList){
if (contract.getFunctionalitySet().contains(funct)) {
functMap.put(funct.getCode(),Boolean.TRUE);
} else {
functMap.put(funct.getCode(),Boolean.FALSE);
}
}
ccc.setFunctionalityMap(functMap);
}
/**
*
*/
private void addFunctionalityToExistingCommand(CreateContractCommand ccc) {
Map<String,Boolean> functMap = new LinkedHashMap<String,Boolean>();
for (Map.Entry<String,Boolean> entry : ccc.getFunctionalityMap().entrySet()){
if (entry.getValue() == null) {
functMap.put(entry.getKey(),Boolean.FALSE);
} else {
functMap.put(entry.getKey(),Boolean.TRUE);
}
}
ccc.setFunctionalityMap(functMap);
}
/**
*
* @param ccc
*/
private void addNewFunctionalityToCommand(CreateContractCommand ccc) {
Map<String,Boolean> functMap = new LinkedHashMap<String,Boolean>();
for (Functionality funct : this.functionalityList){
functMap.put(funct.getCode(),Boolean.FALSE);
}
ccc.setFunctionalityMap(functMap);
}
/**
*
* @param ccc
* @param contract
*/
private void addReferentialToCommand(CreateContractCommand ccc, Contract contract) {
Map<String,Boolean> refMap = new LinkedHashMap<String,Boolean>();
for (Referential ref : referentialList){
if (contract.getReferentialSet().contains(ref)) {
refMap.put(ref.getCode(),Boolean.TRUE);
} else {
refMap.put(ref.getCode(),Boolean.FALSE);
}
}
ccc.setReferentialMap(refMap);
}
/**
*
* @param ccc
* @param contract
*/
private void addReferentialToExistingCommand(CreateContractCommand ccc) {
Map<String,Boolean> refMap = new LinkedHashMap<String,Boolean>();
for (Map.Entry<String,Boolean> entry : ccc.getReferentialMap().entrySet()){
if (entry.getValue() == null) {
refMap.put(entry.getKey(),Boolean.FALSE);
} else {
refMap.put(entry.getKey(),Boolean.TRUE);
}
}
ccc.setReferentialMap(refMap);
}
/**
*
* @param ccc
*/
private void addNewReferentialToCommand(CreateContractCommand ccc) {
Map<String,Boolean> refMap = new LinkedHashMap<String,Boolean>();
for (Referential ref : referentialList){
refMap.put(ref.getCode(),Boolean.FALSE);
}
ccc.setReferentialMap(refMap);
}
/**
*
* @param ccc
* @param contract
*/
private void addOptionToCommand(CreateContractCommand ccc, Contract contract) {
Map<String,String> optionMap = new LinkedHashMap<String, String>();
for (Option option : optionList){
optionMap.put(
option.getCode(),
getValueFromOptionElementCollection(contract.getOptionElementSet(),option));
}
ccc.setOptionMap(optionMap);
}
/**
*
* @param ccc
* @param contract
*/
private void addContractUrlToCommand(CreateContractCommand ccc, Contract contract) {
for (OptionElement optionElement : contract.getOptionElementSet()){
if (optionElement.getOption().equals(contractUrlOption)) {
ccc.setContractUrl(optionElement.getValue());
}
}
}
/**
*
* @param ccc
* @param contract
*/
private void addNewOptionsToCommand(CreateContractCommand ccc) {
Map<String,String> optionMap = new LinkedHashMap<String,String>();
for (Option option : optionList) {
if (!option.getCode().equals(DOMAIN_OPTION_CODE)) {
optionMap.put(option.getCode(),"");
}
}
ccc.setOptionMap(optionMap);
}
/**
* Retrieve the option value from a collection of option elements.
*
* @param optionElementCollection
* @param option
* @return
*/
private String getValueFromOptionElementCollection(
Collection<OptionElement> optionElementCollection,
Option option) {
for (OptionElement optionElement : optionElementCollection) {
if (optionElement.getOption().getCode().equals(option.getCode())) {
return optionElement.getValue();
}
}
return "";
}
/**
*
* @param createContractCommand
* @param contract
* @return
*/
public Contract updateContractFromCommand(
CreateContractCommand ccc,
Contract contract) {
Set<Functionality> functSet = new HashSet<Functionality>();
Set<Referential> refSet = new HashSet<Referential>();
Set<OptionElement> optionElementSet = new HashSet<OptionElement>();
for (Map.Entry<String,Boolean> entry : ccc.getFunctionalityMap().entrySet()) {
if (entry.getValue() != null && entry.getValue()) {
functSet.add(getFunctionalityFromCode(entry.getKey()));
}
}
for (Map.Entry<String,Boolean> entry : ccc.getReferentialMap().entrySet()) {
if (entry.getValue() != null && entry.getValue()) {
refSet.add(getReferentialFromCode(entry.getKey()));
}
}
for (Map.Entry<String,String> entry : ccc.getOptionMap().entrySet()) {
if (!StringUtils.isEmpty(entry.getValue())) {
optionElementSet.add(getOptionElementFromOptionAndValue(entry.getKey(), entry.getValue()));
}
}
if (!StringUtils.isEmpty(ccc.getContractUrl()) && !ccc.getContractUrl().equalsIgnoreCase("http://")) {
optionElementSet.add(addUrlToContract(ccc.getContractUrl()));
}
contract.addAllFunctionality(functSet);
contract.addAllReferential(refSet);
contract.addAllOptionElement(optionElementSet);
contract.setBeginDate(ccc.getBeginDate());
Calendar cal = Calendar.getInstance();
cal.setTime(ccc.getEndDate());
// the end contract date is added without the hour/minute/second info
// we force the end of the filled-in day before we persist.
cal.add(Calendar.MINUTE, 59);
cal.add(Calendar.HOUR_OF_DAY, 23);
cal.add(Calendar.SECOND, 59);
contract.setEndDate(cal.getTime());
contract.setLabel(ccc.getLabel());
return contract;
}
/**
*
* @param url
* @return
*/
private OptionElement addUrlToContract(String url) {
return createOptionElement(contractUrlOption, url);
}
/**
* @param value
* @param optionCode
* @return
*/
private OptionElement getOptionElementFromOptionAndValue(String optionCode, String value) {
Option option = getOptionFromCode(optionCode);
return createOptionElement(option, value);
}
/**
*
* @param value
* @param option
* @return
*/
private OptionElement createOptionElement(Option option, String value) {
OptionElement optionElement = optionElementDataService.getOptionElementFromValueAndOption(value, option);
if (optionElement != null) {
return optionElement;
}
optionElement = optionElementDataService.create();
optionElement.setValue(value);
optionElement.setOption(option);
optionElementDataService.saveOrUpdate(optionElement);
return optionElement;
}
/**
* Retrieve a referential from its code regarding the local referential list.
*
* @param refCode
* @return
*/
private Referential getReferentialFromCode(String refCode) {
for (Referential ref : referentialList) {
if (ref.getCode().equalsIgnoreCase(refCode)) {
return ref;
}
}
return null;
}
/**
* Retrieve a functionality from its code regarding the local functionality
* list.
*
* @param functCode
* @return
*/
private Functionality getFunctionalityFromCode(String functCode) {
for (Functionality funct : functionalityList) {
if (funct.getCode().equalsIgnoreCase(functCode)) {
return funct;
}
}
return null;
}
/**
* Retrieve an option from its code regarding the local option list
*
* @param optionCode
* @return
*/
private Option getOptionFromCode(String optionCode) {
for (Option option : optionList) {
if (option.getCode().equalsIgnoreCase(optionCode)) {
return option;
}
}
return null;
}
}
|
remove debug log
|
web-app/tgol-web-app/src/main/java/org/opens/tgol/command/factory/CreateContractCommandFactory.java
|
remove debug log
|
<ide><path>eb-app/tgol-web-app/src/main/java/org/opens/tgol/command/factory/CreateContractCommandFactory.java
<ide> import java.io.Serializable;
<ide> import java.util.*;
<ide> import org.apache.commons.lang.StringUtils;
<del>import org.apache.log4j.Logger;
<ide> import org.opens.tgol.command.CreateContractCommand;
<ide> import org.opens.tgol.entity.contract.Contract;
<ide> import org.opens.tgol.entity.functionality.Functionality;
<ide>
<ide> public void setReferentialDataService (ReferentialDataService referentialDataService) {
<ide> referentialList = referentialDataService.findAll();
<del> for (Referential ref : referentialList) {
<del> Logger.getLogger(this.getClass()).error(ref.getCode());
<del> }
<ide> }
<ide>
<ide> public void setFunctionalityDataService (FunctionalityDataService funcitonalityDataService) {
|
|
Java
|
apache-2.0
|
e13959208c6a1a1d643e2a4ff672c3ecbfac60c5
| 0 |
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
|
/*
* JaamSim Discrete Event Simulation
* Copyright (C) 2014 Ausenco Engineering Canada Inc.
* Copyright (C) 2016 JaamSim Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jaamsim.input;
import java.util.ArrayList;
import com.jaamsim.basicsim.ObjectType;
import com.jaamsim.units.AngleUnit;
import com.jaamsim.units.DimensionlessUnit;
import com.jaamsim.units.Unit;
public class ExpParser {
public interface UnOpFunc {
public void checkTypeAndUnits(ParseContext context, ExpResult val, String source, int pos) throws ExpError;
public ExpResult apply(ParseContext context, ExpResult val) throws ExpError;
public ExpValResult validate(ParseContext context, ExpValResult val, String source, int pos);
}
public interface BinOpFunc {
public void checkTypeAndUnits(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError;
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError;
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos);
}
public interface CallableFunc {
public void checkUnits(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError;
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError;
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos);
}
public static class UnitData {
double scaleFactor;
Class<? extends Unit> unitType;
}
public interface OutputResolver {
public ExpResult resolve(EvalContext ec, ExpResult ent) throws ExpError;
public ExpValResult validate(ExpValResult entValRes);
}
public interface Assigner {
public void assign(ExpResult ent, ExpResult index, ExpResult val) throws ExpError;
}
public interface ParseContext {
public UnitData getUnitByName(String name);
public Class<? extends Unit> multUnitTypes(Class<? extends Unit> a, Class<? extends Unit> b);
public Class<? extends Unit> divUnitTypes(Class<? extends Unit> num, Class<? extends Unit> denom);
public ExpResult getValFromName(String name, String source, int pos) throws ExpError;
public OutputResolver getOutputResolver(String name) throws ExpError;
public OutputResolver getConstOutputResolver(ExpResult constEnt, String name) throws ExpError;
public Assigner getAssigner(String attribName) throws ExpError;
public Assigner getConstAssigner(ExpResult constEnt, String attribName) throws ExpError;
}
public interface EvalContext {
}
private interface ExpressionWalker {
public void visit(ExpNode exp) throws ExpError;
public ExpNode updateRef(ExpNode exp) throws ExpError;
}
////////////////////////////////////////////////////////////////////
// Expression types
public static class Expression {
public final String source;
public ExpValResult validationResult;
protected final ArrayList<Thread> executingThreads = new ArrayList<>();
private ExpNode rootNode;
public Expression(String source) {
this.source = source;
}
public ExpResult evaluate(EvalContext ec) throws ExpError {
synchronized(executingThreads) {
if (executingThreads.contains(Thread.currentThread())) {
throw new ExpError(null, 0, "Expression recursion detected for expression: %s", source);
}
executingThreads.add(Thread.currentThread());
}
ExpResult res = null;
try {
res = rootNode.evaluate(ec);
} finally {
synchronized(executingThreads) {
executingThreads.remove(Thread.currentThread());
}
}
return res;
}
void setRootNode(ExpNode node) {
rootNode = node;
}
@Override
public String toString() {
return source;
}
}
public static class Assignment extends Expression {
public ExpNode entExp;
public ExpNode attribIndex;
public ExpNode valueExp;
public Assigner assigner;
public Assignment(String source) {
super(source);
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
synchronized(executingThreads) {
if (executingThreads.contains(Thread.currentThread())) {
throw new ExpError(null, 0, "Expression recursion detected for expression: %s", source);
}
executingThreads.add(Thread.currentThread());
}
try {
ExpResult ent = entExp.evaluate(ec);
ExpResult value = valueExp.evaluate(ec);
ExpResult index = null;
if (attribIndex != null) {
index = attribIndex.evaluate(ec);
}
assigner.assign(ent, index, value);
return value;
} finally {
synchronized(executingThreads) {
executingThreads.remove(Thread.currentThread());
}
}
}
}
private abstract static class ExpNode {
public final ParseContext context;
public final Expression exp;
public final int tokenPos;
public abstract ExpResult evaluate(EvalContext ec) throws ExpError;
public abstract ExpValResult validate();
public ExpNode(ParseContext context, Expression exp, int pos) {
this.context = context;
this.tokenPos = pos;
this.exp = exp;
}
abstract void walk(ExpressionWalker w) throws ExpError;
// Get a version of this node that skips runtime checks if safe to do so,
// otherwise return null
public ExpNode getNoCheckVer() {
return null;
}
}
private static class Constant extends ExpNode {
public ExpResult val;
public Constant(ParseContext context, ExpResult val, Expression exp, int pos) {
super(context, exp, pos);
this.val = val;
}
@Override
public ExpResult evaluate(EvalContext ec) {
return val;
}
@Override
public ExpValResult validate() {
return ExpValResult.makeValidRes(val.type, val.unitType);
}
@Override
void walk(ExpressionWalker w) throws ExpError {
w.visit(this);
}
}
private static class ResolveOutput extends ExpNode {
public ExpNode entNode;
public String outputName;
private final OutputResolver resolver;
public ResolveOutput(ParseContext context, String outputName, ExpNode entNode, Expression exp, int pos) throws ExpError {
super(context, exp, pos);
this.entNode = entNode;
this.outputName = outputName;
try {
if (entNode instanceof Constant) {
this.resolver = context.getConstOutputResolver(entNode.evaluate(null), outputName);
} else {
this.resolver = context.getOutputResolver(outputName);
}
} catch (ExpError ex) {
throw (fixError(ex, exp.source, pos));
}
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
try {
ExpResult ent = entNode.evaluate(ec);
return resolver.resolve(ec, ent);
} catch (ExpError ex) {
throw fixError(ex, exp.source, tokenPos);
}
}
@Override
public ExpValResult validate() {
ExpValResult entValRes = entNode.validate();
if ( entValRes.state == ExpValResult.State.ERROR ||
entValRes.state == ExpValResult.State.UNDECIDABLE) {
fixValidationErrors(entValRes, exp.source, tokenPos);
return entValRes;
}
ExpValResult res = resolver.validate(entValRes);
fixValidationErrors(res, exp.source, tokenPos);
return res;
}
@Override
void walk(ExpressionWalker w) throws ExpError {
entNode.walk(w);
entNode = w.updateRef(entNode);
w.visit(this);
}
}
private static class IndexCollection extends ExpNode {
public ExpNode collection;
public ExpNode index;
public IndexCollection(ParseContext context, ExpNode collection, ExpNode index, Expression exp, int pos) throws ExpError {
super(context, exp, pos);
this.collection = collection;
this.index = index;
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
try {
ExpResult colRes = collection.evaluate(ec);
ExpResult indRes = index.evaluate(ec);
if (colRes.type != ExpResType.COLLECTION) {
throw new ExpError(exp.source, tokenPos, "Expression does not evaluate to a collection type.");
}
return colRes.colVal.index(indRes);
} catch (ExpError ex) {
throw fixError(ex, exp.source, tokenPos);
}
}
@Override
public ExpValResult validate() {
ExpValResult colValRes = collection.validate();
ExpValResult indValRes = index.validate();
if (colValRes.state == ExpValResult.State.ERROR) {
fixValidationErrors(colValRes, exp.source, tokenPos);
return colValRes;
}
if (indValRes.state == ExpValResult.State.ERROR) {
fixValidationErrors(indValRes, exp.source, tokenPos);
return indValRes;
}
if (colValRes.state == ExpValResult.State.UNDECIDABLE) {
return colValRes;
}
if (indValRes.state == ExpValResult.State.UNDECIDABLE) {
return indValRes;
}
if (colValRes.type != ExpResType.COLLECTION) {
return ExpValResult.makeErrorRes(new ExpError(exp.source, tokenPos, "Expression does not evaluate to a collection type."));
}
// TODO: validate collection types
return ExpValResult.makeUndecidableRes();
}
@Override
void walk(ExpressionWalker w) throws ExpError {
collection.walk(w);
collection = w.updateRef(collection);
index.walk(w);
index = w.updateRef(index);
w.visit(this);
}
}
private static class BuildArray extends ExpNode {
public ArrayList<ExpNode> values;
public BuildArray(ParseContext context, ArrayList<ExpNode> valueExps, Expression exp, int pos) throws ExpError {
super(context, exp, pos);
this.values = valueExps;
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
try {
ArrayList<ExpResult> res = new ArrayList<>();
for (ExpNode e : values) {
res.add(e.evaluate(ec));
}
return ExpCollections.makeExpressionCollection(res);
} catch (ExpError ex) {
throw fixError(ex, exp.source, tokenPos);
}
}
@Override
public ExpValResult validate() {
for (ExpNode val : values) {
ExpValResult valRes = val.validate();
if ( valRes.state == ExpValResult.State.ERROR ||
valRes.state == ExpValResult.State.UNDECIDABLE) {
fixValidationErrors(valRes, exp.source, tokenPos);
return valRes;
}
}
return ExpValResult.makeValidRes(ExpResType.COLLECTION, DimensionlessUnit.class);
}
@Override
void walk(ExpressionWalker w) throws ExpError {
for (int i = 0; i < values.size(); ++i) {
values.get(i).walk(w);
values.set(i, w.updateRef(values.get(i)));
}
w.visit(this);
}
}
private static class UnaryOp extends ExpNode {
public ExpNode subExp;
protected final UnOpFunc func;
public String name;
public boolean canSkipRuntimeChecks = false;
UnaryOp(String name, ParseContext context, ExpNode subExp, UnOpFunc func, Expression exp, int pos) {
super(context, exp, pos);
this.subExp = subExp;
this.func = func;
this.name = name;
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult subExpVal = subExp.evaluate(ec);
func.checkTypeAndUnits(context, subExpVal, exp.source, tokenPos);
return func.apply(context, subExpVal);
}
@Override
public ExpValResult validate() {
ExpValResult res = func.validate(context, subExp.validate(), exp.source, tokenPos);
if (res.state == ExpValResult.State.VALID)
canSkipRuntimeChecks = true;
return res;
}
@Override
void walk(ExpressionWalker w) throws ExpError {
subExp.walk(w);
subExp = w.updateRef(subExp);
w.visit(this);
}
@Override
public ExpNode getNoCheckVer() {
if (canSkipRuntimeChecks)
return new UnaryOpNoChecks(this);
else
return null;
}
@Override
public String toString() {
return "UnaryOp: " + name;
}
}
private static class UnaryOpNoChecks extends UnaryOp {
UnaryOpNoChecks(UnaryOp uo) {
super(uo.name, uo.context, uo.subExp, uo.func, uo.exp, uo.tokenPos);
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult subExpVal = subExp.evaluate(ec);
return func.apply(context, subExpVal);
}
}
private static class BinaryOp extends ExpNode {
public ExpNode lSubExp;
public ExpNode rSubExp;
public boolean canSkipRuntimeChecks = false;
public String name;
protected final BinOpFunc func;
BinaryOp(String name, ParseContext context, ExpNode lSubExp, ExpNode rSubExp, BinOpFunc func, Expression exp, int pos) {
super(context, exp, pos);
this.lSubExp = lSubExp;
this.rSubExp = rSubExp;
this.func = func;
this.name = name;
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult lRes = lSubExp.evaluate(ec);
ExpResult rRes = rSubExp.evaluate(ec);
func.checkTypeAndUnits(context, lRes, rRes, exp.source, tokenPos);
return func.apply(context, lRes, rRes, exp.source, tokenPos);
}
@Override
public ExpValResult validate() {
ExpValResult lRes = lSubExp.validate();
ExpValResult rRes = rSubExp.validate();
ExpValResult res = func.validate(context, lRes, rRes, exp.source, tokenPos);
if (res.state == ExpValResult.State.VALID)
canSkipRuntimeChecks = true;
return res;
}
@Override
void walk(ExpressionWalker w) throws ExpError {
lSubExp.walk(w);
rSubExp.walk(w);
lSubExp = w.updateRef(lSubExp);
rSubExp = w.updateRef(rSubExp);
w.visit(this);
}
@Override
public ExpNode getNoCheckVer() {
if (canSkipRuntimeChecks)
return new BinaryOpNoChecks(this);
else
return null;
}
@Override
public String toString() {
return "BinaryOp: " + name;
}
}
private static class BinaryOpNoChecks extends BinaryOp {
BinaryOpNoChecks(BinaryOp bo) {
super(bo.name, bo.context, bo.lSubExp, bo.rSubExp, bo.func, bo.exp, bo.tokenPos);
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult lRes = lSubExp.evaluate(ec);
ExpResult rRes = rSubExp.evaluate(ec);
return func.apply(context, lRes, rRes, exp.source, tokenPos);
}
}
private static class Conditional extends ExpNode {
private ExpNode condExp;
private ExpNode trueExp;
private ExpNode falseExp;
public Conditional(ParseContext context, ExpNode c, ExpNode t, ExpNode f, Expression exp, int pos) {
super(context, exp, pos);
condExp = c;
trueExp = t;
falseExp =f;
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult condRes = condExp.evaluate(ec); //constCondRes != null ? constCondRes : condExp.evaluate(ec);
if (condRes.value == 0)
return falseExp.evaluate(ec);
else
return trueExp.evaluate(ec);
}
@Override
public ExpValResult validate() {
ExpValResult condRes = condExp.validate();
ExpValResult trueRes = trueExp.validate();
ExpValResult falseRes = falseExp.validate();
if ( condRes.state == ExpValResult.State.ERROR ||
trueRes.state == ExpValResult.State.ERROR ||
falseRes.state == ExpValResult.State.ERROR) {
// Error state, merge all returned errors
ArrayList<ExpError> errors = new ArrayList<>();
if (condRes.errors != null)
errors.addAll(condRes.errors);
if (trueRes.errors != null)
errors.addAll(trueRes.errors);
if (falseRes.errors != null)
errors.addAll(falseRes.errors);
return ExpValResult.makeErrorRes(errors);
}
else if ( condRes.state == ExpValResult.State.UNDECIDABLE ||
trueRes.state == ExpValResult.State.UNDECIDABLE ||
falseRes.state == ExpValResult.State.UNDECIDABLE) {
return ExpValResult.makeUndecidableRes();
}
// All valid case
// Check that both sides of the branch return the same type
if (trueRes.type != falseRes.type) {
ExpError typeError = new ExpError(exp.source, tokenPos,
"Type mismatch in conditional. True branch is %s, false branch is %s",
trueRes.type.toString(), falseRes.type.toString());
return ExpValResult.makeErrorRes(typeError);
}
// Check that both sides of the branch return the same unit types, for numerical types
if (trueRes.type == ExpResType.NUMBER && trueRes.unitType != falseRes.unitType) {
ExpError unitError = new ExpError(exp.source, tokenPos,
"Unit mismatch in conditional. True branch is %s, false branch is %s",
trueRes.unitType.getSimpleName(), falseRes.unitType.getSimpleName());
return ExpValResult.makeErrorRes(unitError);
}
return ExpValResult.makeValidRes(trueRes.type, trueRes.unitType);
}
@Override
void walk(ExpressionWalker w) throws ExpError {
condExp.walk(w);
trueExp.walk(w);
falseExp.walk(w);
condExp = w.updateRef(condExp);
trueExp = w.updateRef(trueExp);
falseExp = w.updateRef(falseExp);
w.visit(this);
}
@Override
public String toString() {
return "Conditional";
}
}
private static class FuncCall extends ExpNode {
protected final ArrayList<ExpNode> args;
protected final CallableFunc function;
private boolean canSkipRuntimeChecks = false;
private final String name;
public FuncCall(String name, ParseContext context, CallableFunc function, ArrayList<ExpNode> args, Expression exp, int pos) {
super(context, exp, pos);
this.function = function;
this.args = args;
this.name = name;
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult[] argVals = new ExpResult[args.size()];
for (int i = 0; i < args.size(); ++i) {
argVals[i] = args.get(i).evaluate(ec);
}
function.checkUnits(context, argVals, exp.source, tokenPos);
return function.call(context, argVals, exp.source, tokenPos);
}
@Override
public ExpValResult validate() {
ExpValResult[] argVals = new ExpValResult[args.size()];
for (int i = 0; i < args.size(); ++i) {
argVals[i] = args.get(i).validate();
}
ExpValResult res = function.validate(context, argVals, exp.source, tokenPos);
if (res.state == ExpValResult.State.VALID)
canSkipRuntimeChecks = true;
return res;
}
@Override
void walk(ExpressionWalker w) throws ExpError {
for (int i = 0; i < args.size(); ++i) {
args.get(i).walk(w);
}
for (int i = 0; i < args.size(); ++i) {
args.set(i, w.updateRef(args.get(i)));
}
w.visit(this);
}
@Override
public ExpNode getNoCheckVer() {
if (canSkipRuntimeChecks)
return new FuncCallNoChecks(this);
else
return null;
}
@Override
public String toString() {
return "Function: " + name;
}
}
private static class FuncCallNoChecks extends FuncCall {
FuncCallNoChecks(FuncCall fc) {
super(fc.name, fc.context, fc.function, fc.args, fc.exp, fc.tokenPos);
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult[] argVals = new ExpResult[args.size()];
for (int i = 0; i < args.size(); ++i) {
argVals[i] = args.get(i).evaluate(ec);
}
return function.call(context, argVals, exp.source, tokenPos);
}
}
// Some errors can be throw without a known source or position, update such errors with the given info
private static ExpError fixError(ExpError ex, String source, int pos) {
ExpError exFixed = ex;
if (ex.source == null) {
exFixed = new ExpError(source, pos, ex.getMessage());
}
return exFixed;
}
private static void fixValidationErrors(ExpValResult res, String source, int pos) {
if (res.state == ExpValResult.State.ERROR ) {
for (int i = 0; i < res.errors.size(); ++i) {
res.errors.set(i, fixError(res.errors.get(i), source, pos));
}
}
}
///////////////////////////////////////////////////////////
// Entries for user definable operators and functions
private static class UnaryOpEntry {
public String symbol;
public UnOpFunc function;
public double bindingPower;
}
private static class BinaryOpEntry {
public String symbol;
public BinOpFunc function;
public double bindingPower;
public boolean rAssoc;
}
private static class FunctionEntry {
public String name;
public CallableFunc function;
public int numMinArgs;
public int numMaxArgs;
}
private static ArrayList<UnaryOpEntry> unaryOps = new ArrayList<>();
private static ArrayList<BinaryOpEntry> binaryOps = new ArrayList<>();
private static ArrayList<FunctionEntry> functions = new ArrayList<>();
private static void addUnaryOp(String symbol, double bindPower, UnOpFunc func) {
UnaryOpEntry oe = new UnaryOpEntry();
oe.symbol = symbol;
oe.function = func;
oe.bindingPower = bindPower;
unaryOps.add(oe);
}
private static void addBinaryOp(String symbol, double bindPower, boolean rAssoc, BinOpFunc func) {
BinaryOpEntry oe = new BinaryOpEntry();
oe.symbol = symbol;
oe.function = func;
oe.bindingPower = bindPower;
oe.rAssoc = rAssoc;
binaryOps.add(oe);
}
private static void addFunction(String name, int numMinArgs, int numMaxArgs, CallableFunc func) {
FunctionEntry fe = new FunctionEntry();
fe.name = name;
fe.function = func;
fe.numMinArgs = numMinArgs;
fe.numMaxArgs = numMaxArgs;
functions.add(fe);
}
private static UnaryOpEntry getUnaryOp(String symbol) {
for (UnaryOpEntry oe: unaryOps) {
if (oe.symbol.equals(symbol))
return oe;
}
return null;
}
private static BinaryOpEntry getBinaryOp(String symbol) {
for (BinaryOpEntry oe: binaryOps) {
if (oe.symbol.equals(symbol))
return oe;
}
return null;
}
private static FunctionEntry getFunctionEntry(String funcName) {
for (FunctionEntry fe : functions) {
if (fe.name.equals(funcName)){
return fe;
}
}
return null;
}
///////////////////////////////////////////////////
// Operator Utility Functions
// See if there are any existing errors, or this branch is undecidable
private static ExpValResult mergeBinaryErrors(ExpValResult lval, ExpValResult rval) {
if ( lval.state == ExpValResult.State.ERROR ||
rval.state == ExpValResult.State.ERROR) {
// Propagate the error, no further checking
ArrayList<ExpError> errors = new ArrayList<>();
if (lval.errors != null)
errors.addAll(lval.errors);
if (rval.errors != null)
errors.addAll(rval.errors);
return ExpValResult.makeErrorRes(errors);
}
if ( lval.state == ExpValResult.State.UNDECIDABLE ||
rval.state == ExpValResult.State.UNDECIDABLE) {
return ExpValResult.makeUndecidableRes();
}
return null;
}
private static ExpValResult mergeMultipleErrors(ExpValResult[] args) {
for (ExpValResult val : args) {
if (val.state == ExpValResult.State.ERROR) {
// We have an error, merge all error results and return
ArrayList<ExpError> errors = new ArrayList<>();
for (ExpValResult errVal : args) {
if (errVal.errors != null)
errors.addAll(errVal.errors);
}
return ExpValResult.makeErrorRes(errors);
}
}
for (ExpValResult val : args) {
if (val.state == ExpValResult.State.UNDECIDABLE) {
// At least one value in undecidable, propagate it
return ExpValResult.makeUndecidableRes();
}
}
return null;
}
private static void checkBothNumbers(ExpResult lval, ExpResult rval, String source, int pos)
throws ExpError {
if (lval.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Left operand must be a number");
}
if (rval.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Right operand must be a number");
}
}
private static ExpValResult validateBothNumbers(ExpValResult lval, ExpValResult rval, String source, int pos) {
if (lval.type != ExpResType.NUMBER) {
ExpError error = new ExpError(source, pos, "Left operand must be a number");
return ExpValResult.makeErrorRes(error);
}
if (rval.type != ExpResType.NUMBER) {
ExpError error = new ExpError(source, pos, "Right operand must be a number");
return ExpValResult.makeErrorRes(error);
}
return null;
}
private static ExpValResult validateComparison(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
// Require both values to be the same unit type and return a dimensionless unit
// Propagate errors
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null) {
return mergedErrors;
}
ExpValResult numRes = validateBothNumbers(lval, rval, source, pos);
if (numRes != null) {
return numRes;
}
// Both sub values should be valid here
if (lval.unitType != rval.unitType) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
private static void checkTypedComparison(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
// Check that the types are the same
if (lval.type != rval.type) {
throw new ExpError(source, pos, "Can not compare different types. LHS: %s, RHS: %s",
ExpValResult.typeString(lval.type),
ExpValResult.typeString(rval.type));
}
if (lval.type == ExpResType.NUMBER) {
// Also check that the unit types are the same
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, "Can not compare different unit types. LHS: %s, RHS: %s",
lval.unitType.getSimpleName(),
rval.unitType.getSimpleName());
}
}
}
private static boolean evaluteTypedEquality(ExpResult lval, ExpResult rval) {
boolean equal;
switch(lval.type) {
case ENTITY:
equal = lval.entVal == rval.entVal;
break;
case STRING:
equal = lval.stringVal.equals(rval.stringVal);
break;
case NUMBER:
equal = lval.value == rval.value;
break;
default:
assert(false);
equal = false;
}
return equal;
}
private static ExpValResult validateTypedComparison(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
// Propagate errors
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null) {
return mergedErrors;
}
// Otherwise, check that the types are the same
if (lval.type != rval.type) {
ExpError err = new ExpError(source, pos, "Can not compare different types. LHS: %s, RHS: %s",
ExpValResult.typeString(lval.type),
ExpValResult.typeString(rval.type));
return ExpValResult.makeErrorRes(err);
}
if (lval.type == ExpResType.NUMBER) {
// Also check that the unit types are the same
if (lval.unitType != rval.unitType) {
ExpError err = new ExpError(source, pos, "Can not compare different unit types. LHS: %s, RHS: %s",
lval.unitType.getSimpleName(),
rval.unitType.getSimpleName());
return ExpValResult.makeErrorRes(err);
}
}
return ExpValResult.makeValidRes(lval.type, DimensionlessUnit.class);
}
// Validate with all args using the same units, and a new result returning 'newType' unit type
private static ExpValResult validateSameUnits(ParseContext context, ExpValResult[] args, String source, int pos, Class<? extends Unit> newType) {
ExpValResult mergedErrors = mergeMultipleErrors(args);
if (mergedErrors != null)
return mergedErrors;
for (int i = 1; i < args.length; ++ i) {
if (args[i].type != ExpResType.NUMBER) {
ExpError error = new ExpError(source, pos, String.format("Argument %d must be a number", i+1));
return ExpValResult.makeErrorRes(error);
}
if (args[0].unitType != args[i].unitType) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(args[0].unitType, args[i].unitType));
return ExpValResult.makeErrorRes(error);
}
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, newType);
}
// Make sure the single argument is a collection
private static ExpValResult validateCollection(ParseContext context, ExpValResult[] args, String source, int pos) {
if ( args[0].state == ExpValResult.State.ERROR ||
args[0].state == ExpValResult.State.UNDECIDABLE) {
return args[0];
}
// Check that the argument is a collection
if (args[0].type != ExpResType.COLLECTION) {
ExpError error = new ExpError(source, pos, "Expected Collection type argument");
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeUndecidableRes();
}
// Check that a single argument is not an error and is a dimensionless unit
private static ExpValResult validateSingleArgDimensionless(ParseContext context, ExpValResult arg, String source, int pos) {
if ( arg.state == ExpValResult.State.ERROR ||
arg.state == ExpValResult.State.UNDECIDABLE)
return arg;
if (arg.type != ExpResType.NUMBER) {
ExpError error = new ExpError(source, pos, "Argument must be a number");
return ExpValResult.makeErrorRes(error);
}
if (arg.unitType != DimensionlessUnit.class) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(arg.unitType, DimensionlessUnit.class));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
// Check that a single argument is not an error and is a dimensionless unit or angle unit
private static ExpValResult validateTrigFunction(ParseContext context, ExpValResult arg, String source, int pos) {
if ( arg.state == ExpValResult.State.ERROR ||
arg.state == ExpValResult.State.UNDECIDABLE)
return arg;
if (arg.type != ExpResType.NUMBER) {
ExpError error = new ExpError(source, pos, "Argument must be a number");
return ExpValResult.makeErrorRes(error);
}
if (arg.unitType != DimensionlessUnit.class && arg.unitType != AngleUnit.class) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(arg.unitType, DimensionlessUnit.class));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
////////////////////////////////////////////////////////
// Statically initialize the operators and functions
static {
///////////////////////////////////////////////////
// Unary Operators
addUnaryOp("-", 50, new UnOpFunc() {
@Override
public ExpResult apply(ParseContext context, ExpResult val){
return ExpResult.makeNumResult(-val.value, val.unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult val, String source, int pos) {
if (val.state == ExpValResult.State.VALID && val.type != ExpResType.NUMBER) {
ExpError err = new ExpError(source, pos, "Unary negation only applies to numbers");
return ExpValResult.makeErrorRes(err);
}
return val;
}
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult val, String source, int pos)
throws ExpError {
if (val.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Unary negation only applies to numbers");
}
}
});
addUnaryOp("+", 50, new UnOpFunc() {
@Override
public ExpResult apply(ParseContext context, ExpResult val){
return ExpResult.makeNumResult(val.value, val.unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult val, String source, int pos) {
if (val.state == ExpValResult.State.VALID && val.type != ExpResType.NUMBER) {
ExpError err = new ExpError(source, pos, "Unary positive only applies to numbers");
return ExpValResult.makeErrorRes(err);
}
return val;
}
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult val, String source, int pos)
throws ExpError {
if (val.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Unary positive only applies to numbers");
}
}
});
addUnaryOp("!", 50, new UnOpFunc() {
@Override
public ExpResult apply(ParseContext context, ExpResult val){
return ExpResult.makeNumResult(val.value == 0 ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult val, String source, int pos) {
// If the sub expression result was valid, make it dimensionless, otherwise return the sub expression result
if (val.state == ExpValResult.State.VALID) {
if (val.type == ExpResType.NUMBER)
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
// The expression is valid, but not a number
ExpError error = new ExpError(source, pos, "Argument must be a number");
return ExpValResult.makeErrorRes(error);
} else {
return val;
}
}
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult val, String source, int pos)
throws ExpError {
if (val.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Unary not only applies to numbers");
}
}
});
///////////////////////////////////////////////////
// Binary operators
addBinaryOp("+", 20, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
boolean bothNumbers = (lval.type==ExpResType.NUMBER) && (rval.type==ExpResType.NUMBER);
boolean bothStrings = (lval.type==ExpResType.STRING) && (rval.type==ExpResType.STRING);
if (!bothNumbers && !bothStrings) {
throw new ExpError(source, pos, "Operator '+' requires two numbers or two strings");
}
if (bothNumbers && lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
if (lval.type == ExpResType.STRING && rval.type == ExpResType.STRING) {
return ExpResult.makeStringResult(lval.stringVal.concat(rval.stringVal));
}
return ExpResult.makeNumResult(lval.value + rval.value, lval.unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null)
return mergedErrors;
boolean bothNumbers = (lval.type==ExpResType.NUMBER) && (rval.type==ExpResType.NUMBER);
boolean bothStrings = (lval.type==ExpResType.STRING) && (rval.type==ExpResType.STRING);
if (!bothNumbers && !bothStrings) {
ExpError err = new ExpError(source, pos, "Operator '+' requires two numbers or two strings");
return ExpValResult.makeErrorRes(err);
}
if (bothStrings) {
return ExpValResult.makeValidRes(ExpResType.STRING, DimensionlessUnit.class);
}
// Both numbers
if (lval.unitType != rval.unitType) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, lval.unitType);
}
});
addBinaryOp("-", 20, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source,int pos) throws ExpError {
return ExpResult.makeNumResult(lval.value - rval.value, lval.unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null)
return mergedErrors;
ExpValResult numRes = validateBothNumbers(lval, rval, source, pos);
if (numRes != null) {
return numRes;
}
if (lval.unitType != rval.unitType) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, lval.unitType);
}
});
addBinaryOp("*", 30, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
Class<? extends Unit> newType = context.multUnitTypes(lval.unitType, rval.unitType);
if (newType == null) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
Class<? extends Unit> newType = context.multUnitTypes(lval.unitType, rval.unitType);
return ExpResult.makeNumResult(lval.value * rval.value, newType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null)
return mergedErrors;
ExpValResult numRes = validateBothNumbers(lval, rval, source, pos);
if (numRes != null) {
return numRes;
}
Class<? extends Unit> newType = context.multUnitTypes(lval.unitType, rval.unitType);
if (newType == null) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, newType);
}
});
addBinaryOp("/", 30, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
Class<? extends Unit> newType = context.divUnitTypes(lval.unitType, rval.unitType);
if (newType == null) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
Class<? extends Unit> newType = context.divUnitTypes(lval.unitType, rval.unitType);
return ExpResult.makeNumResult(lval.value / rval.value, newType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null)
return mergedErrors;
ExpValResult numRes = validateBothNumbers(lval, rval, source, pos);
if (numRes != null) {
return numRes;
}
Class<? extends Unit> newType = context.divUnitTypes(lval.unitType, rval.unitType);
if (newType == null) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, newType);
}
});
addBinaryOp("^", 40, true, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != DimensionlessUnit.class ||
rval.unitType != DimensionlessUnit.class) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.pow(lval.value, rval.value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null)
return mergedErrors;
ExpValResult numRes = validateBothNumbers(lval, rval, source, pos);
if (numRes != null) {
return numRes;
}
if ( lval.unitType != DimensionlessUnit.class ||
rval.unitType != DimensionlessUnit.class) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
});
addBinaryOp("%", 30, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(lval.value % rval.value, lval.unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null)
return mergedErrors;
ExpValResult numRes = validateBothNumbers(lval, rval, source, pos);
if (numRes != null) {
return numRes;
}
if (lval.unitType != rval.unitType) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, lval.unitType);
}
});
addBinaryOp("==", 10, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkTypedComparison(context, lval, rval, source, pos);
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
boolean equal = evaluteTypedEquality(lval, rval);
return ExpResult.makeNumResult(equal ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateTypedComparison(context, lval, rval, source, pos);
}
});
addBinaryOp("!=", 10, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkTypedComparison(context, lval, rval, source, pos);
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
boolean equal = evaluteTypedEquality(lval, rval);
return ExpResult.makeNumResult(!equal ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateTypedComparison(context, lval, rval, source, pos);
}
});
addBinaryOp("&&", 8, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos){
return ExpResult.makeNumResult((lval.value!=0) && (rval.value!=0) ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateComparison(context, lval, rval, source, pos);
}
});
addBinaryOp("||", 6, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos){
return ExpResult.makeNumResult((lval.value!=0) || (rval.value!=0) ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateComparison(context, lval, rval, source, pos);
}
});
addBinaryOp("<", 12, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(lval.value < rval.value ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateComparison(context, lval, rval, source, pos);
}
});
addBinaryOp("<=", 12, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(lval.value <= rval.value ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateComparison(context, lval, rval, source, pos);
}
});
addBinaryOp(">", 12, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(lval.value > rval.value ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateComparison(context, lval, rval, source, pos);
}
});
addBinaryOp(">=", 12, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(lval.value >= rval.value ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateComparison(context, lval, rval, source, pos);
}
});
////////////////////////////////////////////////////
// Functions
addFunction("max", 2, -1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
for (int i = 1; i < args.length; ++ i) {
if (args[0].unitType != args[i].unitType)
throw new ExpError(source, pos, getUnitMismatchString(args[0].unitType, args[i].unitType));
}
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
ExpResult res = args[0];
for (int i = 1; i < args.length; ++ i) {
if (args[i].value > res.value)
res = args[i];
}
return res;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSameUnits(context, args, source, pos, args[0].unitType);
}
});
addFunction("min", 2, -1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
for (int i = 1; i < args.length; ++ i) {
if (args[0].unitType != args[i].unitType)
throw new ExpError(source, pos, getUnitMismatchString(args[0].unitType, args[i].unitType));
}
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
ExpResult res = args[0];
for (int i = 1; i < args.length; ++ i) {
if (args[i].value < res.value)
res = args[i];
}
return res;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSameUnits(context, args, source, pos, args[0].unitType);
}
});
addFunction("maxCol", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
if (args[0].type != ExpResType.COLLECTION) {
throw new ExpError(source, pos, "Expected Collection type argument");
}
ExpResult.Collection col = args[0].colVal;
ExpResult.Iterator it = col.getIter();
if (!it.hasNext()) {
throw new ExpError(source, pos, "Can not get max of empty collection");
}
ExpResult ret = col.index(it.nextKey());
Class<? extends Unit> ut = ret.unitType;
if (ret.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take max of non-numeric type in collection");
}
while (it.hasNext()) {
ExpResult comp = col.index(it.nextKey());
if (comp.unitType != ut) {
throw new ExpError(source, pos, "Unmatched Unit types in collection: %s, %s",
ut.getSimpleName(), comp.unitType.getSimpleName());
}
if (comp.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take max of non-numeric type in collection");
}
if (comp.value > ret.value) {
ret = comp;
}
}
return ret;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateCollection(context, args, source, pos);
}
});
addFunction("minCol", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
if (args[0].type != ExpResType.COLLECTION) {
throw new ExpError(source, pos, "Expected Collection type argument");
}
ExpResult.Collection col = args[0].colVal;
ExpResult.Iterator it = col.getIter();
if (!it.hasNext()) {
throw new ExpError(source, pos, "Can not get min of empty collection");
}
ExpResult ret = col.index(it.nextKey());
Class<? extends Unit> ut = ret.unitType;
if (ret.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take min of non-numeric type in collection");
}
while (it.hasNext()) {
ExpResult comp = col.index(it.nextKey());
if (comp.unitType != ut) {
throw new ExpError(source, pos, "Unmatched Unit types in collection: %s, %s",
ut.getSimpleName(), comp.unitType.getSimpleName());
}
if (comp.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take min of non-numeric type in collection");
}
if (comp.value < ret.value) {
ret = comp;
}
}
return ret;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateCollection(context, args, source, pos);
}
});
addFunction("abs", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
// N/A
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) {
return ExpResult.makeNumResult(Math.abs(args[0].value), args[0].unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return args[0];
}
});
addFunction("ceil", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
// N/A
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) {
return ExpResult.makeNumResult(Math.ceil(args[0].value), args[0].unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return args[0];
}
});
addFunction("floor", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
// N/A
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) {
return ExpResult.makeNumResult(Math.floor(args[0].value), args[0].unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return args[0];
}
});
addFunction("signum", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
// N/A
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) {
return ExpResult.makeNumResult(Math.signum(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
if (args[0].state == ExpValResult.State.VALID) {
if (args[0].type == ExpResType.NUMBER) {
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
ExpError err = new ExpError(source, pos, "First parameter must be a number");
return ExpValResult.makeErrorRes(err);
} else {
return args[0];
}
}
});
addFunction("sqrt", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.sqrt(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("cbrt", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.cbrt(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("indexOfMin", 2, -1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
for (int i = 1; i < args.length; ++ i) {
if (args[0].unitType != args[i].unitType)
throw new ExpError(source, pos, getUnitMismatchString(args[0].unitType, args[i].unitType));
}
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
ExpResult res = args[0];
int index = 0;
for (int i = 1; i < args.length; ++ i) {
if (args[i].value < res.value) {
res = args[i];
index = i;
}
}
return ExpResult.makeNumResult(index + 1, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSameUnits(context, args, source, pos, DimensionlessUnit.class);
}
});
addFunction("indexOfMax", 2, -1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
for (int i = 1; i < args.length; ++ i) {
if (args[0].unitType != args[i].unitType)
throw new ExpError(source, pos, getUnitMismatchString(args[0].unitType, args[i].unitType));
}
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
ExpResult res = args[0];
int index = 0;
for (int i = 1; i < args.length; ++ i) {
if (args[i].value > res.value) {
res = args[i];
index = i;
}
}
return ExpResult.makeNumResult(index + 1, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSameUnits(context, args, source, pos, DimensionlessUnit.class);
}
});
addFunction("indexOfMaxCol", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
if (args[0].type != ExpResType.COLLECTION) {
throw new ExpError(source, pos, "Expected Collection type argument");
}
ExpResult.Collection col = args[0].colVal;
ExpResult.Iterator it = col.getIter();
if (!it.hasNext()) {
throw new ExpError(source, pos, "Can not get max of empty collection");
}
ExpResult retKey = it.nextKey();
ExpResult ret = col.index(retKey);
Class<? extends Unit> ut = ret.unitType;
if (ret.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take max of non-numeric type in collection");
}
while (it.hasNext()) {
ExpResult compKey = it.nextKey();
ExpResult comp = col.index(compKey);
if (comp.unitType != ut) {
throw new ExpError(source, pos, "Unmatched Unit types in collection: %s, %s",
ut.getSimpleName(), comp.unitType.getSimpleName());
}
if (comp.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take max of non-numeric type in collection");
}
if (comp.value > ret.value) {
ret = comp;
retKey = compKey;
}
}
return retKey;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateCollection(context, args, source, pos);
}
});
addFunction("indexOfMinCol", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
if (args[0].type != ExpResType.COLLECTION) {
throw new ExpError(source, pos, "Expected Collection type argument");
}
ExpResult.Collection col = args[0].colVal;
ExpResult.Iterator it = col.getIter();
if (!it.hasNext()) {
throw new ExpError(source, pos, "Can not get min of empty collection");
}
ExpResult retKey = it.nextKey();
ExpResult ret = col.index(retKey);
Class<? extends Unit> ut = ret.unitType;
if (ret.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take min of non-numeric type in collection");
}
while (it.hasNext()) {
ExpResult compKey = it.nextKey();
ExpResult comp = col.index(compKey);
if (comp.unitType != ut) {
throw new ExpError(source, pos, "Unmatched Unit types in collection: %s, %s",
ut.getSimpleName(), comp.unitType.getSimpleName());
}
if (comp.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take min of non-numeric type in collection");
}
if (comp.value < ret.value) {
ret = comp;
retKey = compKey;
}
}
return retKey;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateCollection(context, args, source, pos);
}
});
addFunction("indexOfNearest", 2, 2, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
if (args[0].type != ExpResType.COLLECTION) {
throw new ExpError(source, pos, "Expected Collection type argument as first argument.");
}
if (args[1].type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Expected numerical argument as second argument.");
}
ExpResult.Collection col = args[0].colVal;
ExpResult nearPoint = args[1];
ExpResult.Iterator it = col.getIter();
if (!it.hasNext()) {
throw new ExpError(source, pos, "Can not get nearest value of empty collection.");
}
double nearestDist = Double.MAX_VALUE;
ExpResult retKey = null;
while (it.hasNext()) {
ExpResult compKey = it.nextKey();
ExpResult comp = col.index(compKey);
if (comp.unitType != nearPoint.unitType) {
throw new ExpError(source, pos, "Unmatched Unit types when finding nearest: %s, %s",
nearPoint.unitType.getSimpleName(), comp.unitType.getSimpleName());
}
if (comp.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not find nearest value of non-numeric type in collection.");
}
double dist = Math.abs(comp.value - nearPoint.value);
if (dist < nearestDist) {
nearestDist = dist;
retKey = compKey;
}
}
return retKey;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
if (args[1].state == ExpValResult.State.ERROR || args[1].state == ExpValResult.State.UNDECIDABLE) {
return args[1];
}
if (args[1].type != ExpResType.NUMBER) {
return ExpValResult.makeErrorRes(new ExpError(source, pos, "Second argument to 'indexOfNearest' must be a number."));
}
return validateCollection(context, args, source, pos);
}
});
addFunction("size", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
if (args[0].type != ExpResType.COLLECTION) {
throw new ExpError(source, pos, "Expected Collection type argument");
}
ExpResult.Collection col = args[0].colVal;
return ExpResult.makeNumResult(col.getSize(), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateCollection(context, args, source, pos);
}
});
addFunction("choose", 2, -1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
for (int i = 2; i < args.length; ++ i) {
if (args[1].unitType != args[i].unitType)
throw new ExpError(source, pos, getUnitMismatchString(args[1].unitType, args[i].unitType));
}
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
int k = (int) args[0].value;
if (k < 1 || k >= args.length)
throw new ExpError(source, pos,
String.format("Invalid index: %s. Index must be between 1 and %s.", k, args.length-1));
return args[k];
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
ExpValResult mergedErrors = mergeMultipleErrors(args);
if (mergedErrors != null)
return mergedErrors;
if (args[0].type != ExpResType.NUMBER) {
ExpError error = new ExpError(source, pos, "Parameter must be a number");
return ExpValResult.makeErrorRes(error);
}
if (args[0].unitType != DimensionlessUnit.class) {
ExpError error = new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
return ExpValResult.makeErrorRes(error);
}
if (args.length < 2) {
ExpError error = new ExpError(source, pos, "'choose' function must take at least 2 parameters.");
return ExpValResult.makeErrorRes(error);
}
ExpResType valType = args[1].type;
Class<? extends Unit> valUnitType = args[1].unitType;
for (int i = 2; i < args.length; ++ i) {
if (args[i].type != valType) {
ExpError error = new ExpError(source, pos, "All parameter types to 'choose' must be the same type");
return ExpValResult.makeErrorRes(error);
}
if (valType == ExpResType.NUMBER && valUnitType != args[i].unitType) {
ExpError error = new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
return ExpValResult.makeErrorRes(error);
}
}
return ExpValResult.makeValidRes(valType, valUnitType);
}
});
///////////////////////////////////////////////////
// Mathematical Constants
addFunction("E", 0, 0, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
// N/A
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.E, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
});
addFunction("PI", 0, 0, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
// N/A
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.PI, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
});
///////////////////////////////////////////////////
// Trigonometric Functions
addFunction("sin", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class && args[0].unitType != AngleUnit.class)
throw new ExpError(source, pos, getInvalidTrigUnitString(args[0].unitType));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.sin(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateTrigFunction(context, args[0], source, pos);
}
});
addFunction("cos", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class && args[0].unitType != AngleUnit.class)
throw new ExpError(source, pos, getInvalidTrigUnitString(args[0].unitType));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.cos(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateTrigFunction(context, args[0], source, pos);
}
});
addFunction("tan", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class && args[0].unitType != AngleUnit.class)
throw new ExpError(source, pos, getInvalidTrigUnitString(args[0].unitType));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.tan(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateTrigFunction(context, args[0], source, pos);
}
});
///////////////////////////////////////////////////
// Inverse Trigonometric Functions
addFunction("asin", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.asin(args[0].value), AngleUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("acos", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.acos(args[0].value), AngleUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("atan", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.atan(args[0].value), AngleUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("atan2", 2, 2, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
if (args[1].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[1].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.atan2(args[0].value, args[1].value), AngleUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
ExpValResult mergedErrors = mergeMultipleErrors(args);
if (mergedErrors != null)
return mergedErrors;
if (args[0].type != ExpResType.NUMBER || args[1].type != ExpResType.NUMBER ) {
ExpError error = new ExpError(source, pos, "Both parameters must be numbers");
return ExpValResult.makeErrorRes(error);
}
if (args[0].unitType != DimensionlessUnit.class) {
ExpError error = new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
return ExpValResult.makeErrorRes(error);
}
if (args[1].unitType != DimensionlessUnit.class) {
ExpError error = new ExpError(source, pos, getInvalidUnitString(args[1].unitType, DimensionlessUnit.class));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
});
///////////////////////////////////////////////////
// Exponential Functions
addFunction("exp", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.exp(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("ln", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.log(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("log", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.log10(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("notNull", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].type != ExpResType.ENTITY) {
throw new ExpError(source, pos, "notNull requires entity as argument");
}
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(args[0].entVal == null ? 0 : 1, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
if ( args[0].state == ExpValResult.State.ERROR ||
args[0].state == ExpValResult.State.UNDECIDABLE)
return args[0];
if (args[0].type != ExpResType.ENTITY) {
ExpError error = new ExpError(source, pos, "Argument must be an entity");
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
});
}
private static String unitToString(Class<? extends Unit> unit) {
ObjectType type = ObjectType.getObjectTypeForClass(unit);
if (type == null)
return "Unknown Unit";
return type.getName();
}
private static String getUnitMismatchString(Class<? extends Unit> u0, Class<? extends Unit> u1) {
String s0 = unitToString(u0);
String s1 = unitToString(u1);
return String.format("Unit mismatch: '%s' and '%s' are not compatible", s0, s1);
}
private static String getInvalidTrigUnitString(Class<? extends Unit> u0) {
String s0 = unitToString(u0);
return String.format("Invalid unit: %s. The input to a trigonometric function must be dimensionless or an angle.", s0);
}
private static String getInvalidUnitString(Class<? extends Unit> u0, Class<? extends Unit> u1) {
String s0 = unitToString(u0);
String s1 = unitToString(u1);
if (u1 == DimensionlessUnit.class)
return String.format("Invalid unit: %s. A dimensionless number is required.", s0);
return String.format("Invalid unit: %s. Units of %s are required.", s0, s1);
}
/**
* A utility class to make dealing with a list of tokens easier
*
*/
private static class TokenList {
private final ArrayList<ExpTokenizer.Token> tokens;
private int pos;
public TokenList(ArrayList<ExpTokenizer.Token> tokens) {
this.tokens = tokens;
this.pos = 0;
}
public void expect(int type, String val, String source) throws ExpError {
if (pos == tokens.size()) {
throw new ExpError(source, source.length(), String.format("Expected \"%s\", past the end of input", val));
}
ExpTokenizer.Token nextTok = tokens.get(pos);
if (nextTok.type != type || !nextTok.value.equals(val)) {
throw new ExpError(source, nextTok.pos, String.format("Expected \"%s\", got \"%s\"", val, nextTok.value));
}
pos++;
}
public ExpTokenizer.Token next() {
if (pos >= tokens.size()) {
return null;
}
return tokens.get(pos++);
}
public ExpTokenizer.Token peek() {
if (pos >= tokens.size()) {
return null;
}
return tokens.get(pos);
}
}
private static class ConstOptimizer implements ExpressionWalker {
@Override
public void visit(ExpNode exp) throws ExpError {
// N/A
}
/**
* Give a node a chance to swap itself out with a different subtree.
*/
@Override
public ExpNode updateRef(ExpNode origNode) throws ExpError {
// Note: Below we are passing 'null' as an EvalContext, this is not typically
// acceptable, but is 'safe enough' when we know the expression is a constant
if (origNode instanceof UnaryOp) {
UnaryOp uo = (UnaryOp)origNode;
if (uo.subExp instanceof Constant) {
// This is an unary operation on a constant, we can replace it with a constant
ExpResult val = uo.evaluate(null);
return new Constant(uo.context, val, origNode.exp, uo.tokenPos);
}
}
if (origNode instanceof BinaryOp) {
BinaryOp bo = (BinaryOp)origNode;
if ((bo.lSubExp instanceof Constant) && (bo.rSubExp instanceof Constant)) {
// both sub expressions are constants, so replace the binop with a constant
ExpResult val = bo.evaluate(null);
return new Constant(bo.context, val, origNode.exp, bo.tokenPos);
}
}
if (origNode instanceof FuncCall) {
FuncCall fc = (FuncCall)origNode;
boolean constArgs = true;
for (int i = 0; i < fc.args.size(); ++i) {
if (!(fc.args.get(i) instanceof Constant)) {
constArgs = false;
}
}
if (constArgs) {
ExpResult val = fc.evaluate(null);
return new Constant(fc.context, val, origNode.exp, fc.tokenPos);
}
}
if (origNode instanceof BuildArray) {
BuildArray ba = (BuildArray)origNode;
boolean constArgs = true;
for (ExpNode val : ba.values) {
if (!(val instanceof Constant))
constArgs = false;
}
if (constArgs) {
ExpResult val = ba.evaluate(null);
return new Constant(ba.context, val, origNode.exp, ba.tokenPos);
}
}
return origNode;
}
}
private static ConstOptimizer CONST_OP = new ConstOptimizer();
private static class RuntimeCheckOptimizer implements ExpressionWalker {
@Override
public void visit(ExpNode exp) throws ExpError {
// N/A
}
@Override
public ExpNode updateRef(ExpNode exp) throws ExpError {
ExpNode noCheckVer = exp.getNoCheckVer();
if (noCheckVer != null)
return noCheckVer;
else
return exp;
}
}
private static RuntimeCheckOptimizer RTC_OP = new RuntimeCheckOptimizer();
private static ExpNode optimizeAndValidateExpression(String input, ExpNode expNode, Expression exp) throws ExpError {
expNode.walk(CONST_OP);
expNode = CONST_OP.updateRef(expNode); // Finally, give the entire expression a chance to optimize itself into a constant
// Run the validation
ExpValResult valRes = expNode.validate();
if (valRes.state == ExpValResult.State.ERROR) {
if (valRes.errors.size() == 0) {
throw new ExpError(input, 0, "An unknown expression error occurred. This is probably a bug. Please inform the developers.");
}
// We received at least one error while validating.
throw valRes.errors.get(0);
}
// Now that validation is complete, we can run the optimizer that removes runtime checks on validated nodes
expNode.walk(RTC_OP);
expNode = RTC_OP.updateRef(expNode); // Give the top level node a chance to optimize
exp.validationResult = valRes;
return expNode;
}
/**
* The main entry point to the expression parsing system, will either return a valid
* expression that can be evaluated, or throw an error.
*/
public static Expression parseExpression(ParseContext context, String input) throws ExpError {
ArrayList<ExpTokenizer.Token> ts;
ts = ExpTokenizer.tokenize(input);
TokenList tokens = new TokenList(ts);
Expression ret = new Expression(input);
ExpNode expNode = parseExp(context, tokens, 0, ret);
// Make sure we've parsed all the tokens
ExpTokenizer.Token peeked = tokens.peek();
if (peeked != null) {
throw new ExpError(input, peeked.pos, "Unexpected additional values");
}
expNode = optimizeAndValidateExpression(input, expNode, ret);
ret.setRootNode(expNode);
return ret;
}
private static ExpNode parseExp(ParseContext context, TokenList tokens, double bindPower, Expression exp) throws ExpError {
ExpNode lhs = parseOpeningExp(context, tokens, bindPower, exp);
// Parse as many indices as are present
while (true) {
ExpTokenizer.Token peeked = tokens.peek();
if (peeked == null || peeked.type != ExpTokenizer.SYM_TYPE) {
break;
}
if (peeked.value.equals(".")) {
tokens.next(); // consume
ExpTokenizer.Token outputName = tokens.next();
if (outputName == null || outputName.type != ExpTokenizer.VAR_TYPE) {
throw new ExpError(exp.source, peeked.pos, "Expected Identifier after '.'");
}
lhs = new ResolveOutput(context, outputName.value, lhs, exp, peeked.pos);
continue;
}
if (peeked.value.equals("(")) {
tokens.next(); // consume
ExpNode indexExp = parseExp(context, tokens, 0, exp);
tokens.expect(ExpTokenizer.SYM_TYPE, ")", exp.source);
lhs = new IndexCollection(context, lhs, indexExp, exp, peeked.pos);
continue;
}
// Not an index or output. Move on
break;
}
// Now peek for a binary op to modify this expression
while (true) {
ExpTokenizer.Token peeked = tokens.peek();
if (peeked == null || peeked.type != ExpTokenizer.SYM_TYPE) {
break;
}
BinaryOpEntry binOp = getBinaryOp(peeked.value);
if (binOp != null && binOp.bindingPower > bindPower) {
// The next token is a binary op and powerful enough to bind us
lhs = handleBinOp(context, tokens, lhs, binOp, exp, peeked.pos);
continue;
}
// Specific check for binding the conditional (?:) operator
if (peeked.value.equals("?") && bindPower == 0) {
lhs = handleConditional(context, tokens, lhs, exp, peeked.pos);
continue;
}
break;
}
// We have bound as many operators as we can, return it
return lhs;
}
private static ExpNode handleBinOp(ParseContext context, TokenList tokens, ExpNode lhs, BinaryOpEntry binOp, Expression exp, int pos) throws ExpError {
tokens.next(); // Consume the operator
// For right associative operators, we weaken the binding power a bit at application time (but not testing time)
double assocMod = binOp.rAssoc ? -0.5 : 0;
ExpNode rhs = parseExp(context, tokens, binOp.bindingPower + assocMod, exp);
//currentPower = oe.bindingPower;
return new BinaryOp(binOp.symbol, context, lhs, rhs, binOp.function, exp, pos);
}
private static ExpNode handleConditional(ParseContext context, TokenList tokens, ExpNode lhs, Expression exp, int pos) throws ExpError {
tokens.next(); // Consume the '?'
ExpNode trueExp = parseExp(context, tokens, 0, exp);
tokens.expect(ExpTokenizer.SYM_TYPE, ":", exp.source);
ExpNode falseExp = parseExp(context, tokens , 0, exp);
return new Conditional(context, lhs, trueExp, falseExp, exp, pos);
}
public static Assignment parseAssignment(ParseContext context, String input) throws ExpError {
ArrayList<ExpTokenizer.Token> ts;
ts = ExpTokenizer.tokenize(input);
TokenList tokens = new TokenList(ts);
Assignment ret = new Assignment(input);
ExpNode lhsNode = parseExp(context, tokens, 0, ret);
tokens.expect(ExpTokenizer.SYM_TYPE, "=", input);
ExpNode rhsNode = parseExp(context, tokens, 0, ret);
// Make sure we've parsed all the tokens
ExpTokenizer.Token peeked = tokens.peek();
if (peeked != null) {
throw new ExpError(input, peeked.pos, "Unexpected additional values");
}
rhsNode = optimizeAndValidateExpression(input, rhsNode, ret);
ret.valueExp = rhsNode;
// Parsing is done, now we need to unwind the lhs expression to get the necessary components
ExpNode indexExp = null;
// Check for an optional index at the end
if (lhsNode instanceof IndexCollection) {
// the lhs ended with an index, split that off
IndexCollection ind = (IndexCollection)lhsNode;
indexExp = ind.index;
lhsNode = ind.collection;
indexExp = optimizeAndValidateExpression(input, indexExp, ret);
}
ret.attribIndex = indexExp;
// Now make sure the last node of the lhs ends with a output resolve
if (!(lhsNode instanceof ResolveOutput)) {
throw new ExpError(input, lhsNode.tokenPos, "Assignment left side must end with an output");
}
ResolveOutput lhsResolve = (ResolveOutput)lhsNode;
ExpNode entNode = lhsResolve.entNode;
entNode = optimizeAndValidateExpression(input, entNode, ret);
ret.entExp = entNode;
if (ret.entExp instanceof Constant) {
ExpResult ent = ret.entExp.evaluate(null);
ret.assigner = context.getConstAssigner(ent, lhsResolve.outputName);
} else {
ret.assigner = context.getAssigner(lhsResolve.outputName);
}
return ret;
}
// The first half of expression parsing, parse a simple expression based on the next token
private static ExpNode parseOpeningExp(ParseContext context, TokenList tokens, double bindPower, Expression exp) throws ExpError{
ExpTokenizer.Token nextTok = tokens.next(); // consume the first token
if (nextTok == null) {
throw new ExpError(exp.source, exp.source.length(), "Unexpected end of string");
}
if (nextTok.type == ExpTokenizer.NUM_TYPE) {
return parseConstant(context, nextTok.value, tokens, exp, nextTok.pos);
}
if (nextTok.type == ExpTokenizer.STRING_TYPE) {
// Return a literal string constant
return new Constant(context, ExpResult.makeStringResult(nextTok.value), exp, nextTok.pos);
}
if (nextTok.type == ExpTokenizer.VAR_TYPE &&
!nextTok.value.equals("this")) {
return parseFuncCall(context, nextTok.value, tokens, exp, nextTok.pos);
}
if (nextTok.type == ExpTokenizer.SQ_TYPE ||
nextTok.value.equals("this")) {
ExpResult namedVal = context.getValFromName(nextTok.value, exp.source, nextTok.pos);
return new Constant(context, namedVal, exp, nextTok.pos);
}
// The next token must be a symbol
if (nextTok.value.equals("{")) {
boolean foundComma = true;
ArrayList<ExpNode> exps = new ArrayList<>();
while(true) {
// Parse an array
ExpTokenizer.Token peeked = tokens.peek();
if (peeked != null && peeked.value.equals("}")) {
tokens.next(); // consume
break;
}
if (!foundComma) {
throw new ExpError(exp.source, peeked.pos, "Expected ',' or '}' in literal array.");
}
foundComma = false;
exps.add(parseExp(context, tokens, 0, exp));
peeked = tokens.peek();
if (peeked != null && peeked.value.equals(",")) {
tokens.next();
foundComma = true;
}
}
return new BuildArray(context, exps, exp, nextTok.pos);
}
// handle parenthesis
if (nextTok.value.equals("(")) {
ExpNode expNode = parseExp(context, tokens, 0, exp);
tokens.expect(ExpTokenizer.SYM_TYPE, ")", exp.source); // Expect the closing paren
return expNode;
}
UnaryOpEntry oe = getUnaryOp(nextTok.value);
if (oe != null) {
ExpNode expNode = parseExp(context, tokens, oe.bindingPower, exp);
return new UnaryOp(oe.symbol, context, expNode, oe.function, exp, nextTok.pos);
}
// We're all out of tricks here, this is an unknown expression
throw new ExpError(exp.source, nextTok.pos, "Can not parse expression");
}
private static ExpNode parseConstant(ParseContext context, String constant, TokenList tokens, Expression exp, int pos) throws ExpError {
double mult = 1;
Class<? extends Unit> ut = DimensionlessUnit.class;
ExpTokenizer.Token peeked = tokens.peek();
if (peeked != null && peeked.type == ExpTokenizer.SQ_TYPE) {
// This constant is followed by a square quoted token, it must be the unit
tokens.next(); // Consume unit token
UnitData unit = context.getUnitByName(peeked.value);
if (unit == null) {
throw new ExpError(exp.source, peeked.pos, "Unknown unit: %s", peeked.value);
}
mult = unit.scaleFactor;
ut = unit.unitType;
}
return new Constant(context, ExpResult.makeNumResult(Double.parseDouble(constant)*mult, ut), exp, pos);
}
private static ExpNode parseFuncCall(ParseContext context, String funcName, TokenList tokens, Expression exp, int pos) throws ExpError {
tokens.expect(ExpTokenizer.SYM_TYPE, "(", exp.source);
ArrayList<ExpNode> arguments = new ArrayList<>();
ExpTokenizer.Token peeked = tokens.peek();
if (peeked == null) {
throw new ExpError(exp.source, exp.source.length(), "Unexpected end of input in argument list");
}
boolean isEmpty = false;
if (peeked.value.equals(")")) {
// Special case with empty argument list
isEmpty = true;
tokens.next(); // Consume closing parens
}
while (!isEmpty) {
ExpNode nextArg = parseExp(context, tokens, 0, exp);
arguments.add(nextArg);
ExpTokenizer.Token nextTok = tokens.next();
if (nextTok == null) {
throw new ExpError(exp.source, exp.source.length(), "Unexpected end of input in argument list.");
}
if (nextTok.value.equals(")")) {
break;
}
if (nextTok.value.equals(",")) {
continue;
}
// Unexpected token
throw new ExpError(exp.source, nextTok.pos, "Unexpected token in arguement list");
}
FunctionEntry fe = getFunctionEntry(funcName);
if (fe == null) {
throw new ExpError(exp.source, pos, "Uknown function: \"%s\"", funcName);
}
if (fe.numMinArgs >= 0 && arguments.size() < fe.numMinArgs){
throw new ExpError(exp.source, pos, "Function \"%s\" expects at least %d arguments. %d provided.",
funcName, fe.numMinArgs, arguments.size());
}
if (fe.numMaxArgs >= 0 && arguments.size() > fe.numMaxArgs){
throw new ExpError(exp.source, pos, "Function \"%s\" expects at most %d arguments. %d provided.",
funcName, fe.numMaxArgs, arguments.size());
}
return new FuncCall(fe.name, context, fe.function, arguments, exp, pos);
}
}
|
src/main/java/com/jaamsim/input/ExpParser.java
|
/*
* JaamSim Discrete Event Simulation
* Copyright (C) 2014 Ausenco Engineering Canada Inc.
* Copyright (C) 2016 JaamSim Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jaamsim.input;
import java.util.ArrayList;
import com.jaamsim.basicsim.ObjectType;
import com.jaamsim.units.AngleUnit;
import com.jaamsim.units.DimensionlessUnit;
import com.jaamsim.units.Unit;
public class ExpParser {
public interface UnOpFunc {
public void checkTypeAndUnits(ParseContext context, ExpResult val, String source, int pos) throws ExpError;
public ExpResult apply(ParseContext context, ExpResult val) throws ExpError;
public ExpValResult validate(ParseContext context, ExpValResult val, String source, int pos);
}
public interface BinOpFunc {
public void checkTypeAndUnits(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError;
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError;
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos);
}
public interface CallableFunc {
public void checkUnits(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError;
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError;
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos);
}
public static class UnitData {
double scaleFactor;
Class<? extends Unit> unitType;
}
public interface OutputResolver {
public ExpResult resolve(EvalContext ec, ExpResult ent) throws ExpError;
public ExpValResult validate(ExpValResult entValRes);
}
public interface Assigner {
public void assign(ExpResult ent, ExpResult index, ExpResult val) throws ExpError;
}
public interface ParseContext {
public UnitData getUnitByName(String name);
public Class<? extends Unit> multUnitTypes(Class<? extends Unit> a, Class<? extends Unit> b);
public Class<? extends Unit> divUnitTypes(Class<? extends Unit> num, Class<? extends Unit> denom);
public ExpResult getValFromName(String name, String source, int pos) throws ExpError;
public OutputResolver getOutputResolver(String name) throws ExpError;
public OutputResolver getConstOutputResolver(ExpResult constEnt, String name) throws ExpError;
public Assigner getAssigner(String attribName) throws ExpError;
public Assigner getConstAssigner(ExpResult constEnt, String attribName) throws ExpError;
}
public interface EvalContext {
//public ExpResult getVariableValue(String[] names, ExpResult[] indices) throws ExpError;
//public boolean eagerEval();
}
// public interface ValContext {
//
// }
private interface ExpressionWalker {
public void visit(ExpNode exp) throws ExpError;
public ExpNode updateRef(ExpNode exp) throws ExpError;
}
////////////////////////////////////////////////////////////////////
// Expression types
public static class Expression {
public final String source;
public ExpValResult validationResult;
protected final ArrayList<Thread> executingThreads = new ArrayList<>();
private ExpNode rootNode;
public Expression(String source) {
this.source = source;
}
public ExpResult evaluate(EvalContext ec) throws ExpError {
synchronized(executingThreads) {
if (executingThreads.contains(Thread.currentThread())) {
throw new ExpError(null, 0, "Expression recursion detected for expression: %s", source);
}
executingThreads.add(Thread.currentThread());
}
ExpResult res = null;
try {
res = rootNode.evaluate(ec);
} finally {
synchronized(executingThreads) {
executingThreads.remove(Thread.currentThread());
}
}
return res;
}
void setRootNode(ExpNode node) {
rootNode = node;
}
@Override
public String toString() {
return source;
}
}
public static class Assignment extends Expression {
public ExpNode entExp;
public ExpNode attribIndex;
public ExpNode valueExp;
public Assigner assigner;
public Assignment(String source) {
super(source);
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
synchronized(executingThreads) {
if (executingThreads.contains(Thread.currentThread())) {
throw new ExpError(null, 0, "Expression recursion detected for expression: %s", source);
}
executingThreads.add(Thread.currentThread());
}
try {
ExpResult ent = entExp.evaluate(ec);
ExpResult value = valueExp.evaluate(ec);
ExpResult index = null;
if (attribIndex != null) {
index = attribIndex.evaluate(ec);
}
assigner.assign(ent, index, value);
return value;
} finally {
synchronized(executingThreads) {
executingThreads.remove(Thread.currentThread());
}
}
}
}
private abstract static class ExpNode {
public final ParseContext context;
public final Expression exp;
public final int tokenPos;
public abstract ExpResult evaluate(EvalContext ec) throws ExpError;
public abstract ExpValResult validate();
public ExpNode(ParseContext context, Expression exp, int pos) {
this.context = context;
this.tokenPos = pos;
this.exp = exp;
}
abstract void walk(ExpressionWalker w) throws ExpError;
// Get a version of this node that skips runtime checks if safe to do so,
// otherwise return null
public ExpNode getNoCheckVer() {
return null;
}
}
private static class Constant extends ExpNode {
public ExpResult val;
public Constant(ParseContext context, ExpResult val, Expression exp, int pos) {
super(context, exp, pos);
this.val = val;
}
@Override
public ExpResult evaluate(EvalContext ec) {
return val;
}
@Override
public ExpValResult validate() {
return ExpValResult.makeValidRes(val.type, val.unitType);
}
@Override
void walk(ExpressionWalker w) throws ExpError {
w.visit(this);
}
}
private static class ResolveOutput extends ExpNode {
public ExpNode entNode;
public String outputName;
private final OutputResolver resolver;
public ResolveOutput(ParseContext context, String outputName, ExpNode entNode, Expression exp, int pos) throws ExpError {
super(context, exp, pos);
this.entNode = entNode;
this.outputName = outputName;
try {
if (entNode instanceof Constant) {
this.resolver = context.getConstOutputResolver(entNode.evaluate(null), outputName);
} else {
this.resolver = context.getOutputResolver(outputName);
}
} catch (ExpError ex) {
throw (fixError(ex, exp.source, pos));
}
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
try {
ExpResult ent = entNode.evaluate(ec);
return resolver.resolve(ec, ent);
} catch (ExpError ex) {
throw fixError(ex, exp.source, tokenPos);
}
}
@Override
public ExpValResult validate() {
ExpValResult entValRes = entNode.validate();
if ( entValRes.state == ExpValResult.State.ERROR ||
entValRes.state == ExpValResult.State.UNDECIDABLE) {
fixValidationErrors(entValRes, exp.source, tokenPos);
return entValRes;
}
ExpValResult res = resolver.validate(entValRes);
fixValidationErrors(res, exp.source, tokenPos);
return res;
}
@Override
void walk(ExpressionWalker w) throws ExpError {
entNode.walk(w);
entNode = w.updateRef(entNode);
w.visit(this);
}
}
private static class IndexCollection extends ExpNode {
public ExpNode collection;
public ExpNode index;
public IndexCollection(ParseContext context, ExpNode collection, ExpNode index, Expression exp, int pos) throws ExpError {
super(context, exp, pos);
this.collection = collection;
this.index = index;
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
try {
ExpResult colRes = collection.evaluate(ec);
ExpResult indRes = index.evaluate(ec);
if (colRes.type != ExpResType.COLLECTION) {
throw new ExpError(exp.source, tokenPos, "Expression does not evaluate to a collection type.");
}
return colRes.colVal.index(indRes);
} catch (ExpError ex) {
throw fixError(ex, exp.source, tokenPos);
}
}
@Override
public ExpValResult validate() {
ExpValResult colValRes = collection.validate();
ExpValResult indValRes = index.validate();
if (colValRes.state == ExpValResult.State.ERROR) {
fixValidationErrors(colValRes, exp.source, tokenPos);
return colValRes;
}
if (indValRes.state == ExpValResult.State.ERROR) {
fixValidationErrors(indValRes, exp.source, tokenPos);
return indValRes;
}
if (colValRes.state == ExpValResult.State.UNDECIDABLE) {
return colValRes;
}
if (indValRes.state == ExpValResult.State.UNDECIDABLE) {
return indValRes;
}
if (colValRes.type != ExpResType.COLLECTION) {
return ExpValResult.makeErrorRes(new ExpError(exp.source, tokenPos, "Expression does not evaluate to a collection type."));
}
// TODO: validate collection types
return ExpValResult.makeUndecidableRes();
}
@Override
void walk(ExpressionWalker w) throws ExpError {
collection.walk(w);
collection = w.updateRef(collection);
index.walk(w);
index = w.updateRef(index);
w.visit(this);
}
}
private static class BuildArray extends ExpNode {
public ArrayList<ExpNode> values;
public BuildArray(ParseContext context, ArrayList<ExpNode> valueExps, Expression exp, int pos) throws ExpError {
super(context, exp, pos);
this.values = valueExps;
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
try {
ArrayList<ExpResult> res = new ArrayList<>();
for (ExpNode e : values) {
res.add(e.evaluate(ec));
}
return ExpCollections.makeExpressionCollection(res);
} catch (ExpError ex) {
throw fixError(ex, exp.source, tokenPos);
}
}
@Override
public ExpValResult validate() {
for (ExpNode val : values) {
ExpValResult valRes = val.validate();
if ( valRes.state == ExpValResult.State.ERROR ||
valRes.state == ExpValResult.State.UNDECIDABLE) {
fixValidationErrors(valRes, exp.source, tokenPos);
return valRes;
}
}
return ExpValResult.makeValidRes(ExpResType.COLLECTION, DimensionlessUnit.class);
}
@Override
void walk(ExpressionWalker w) throws ExpError {
for (int i = 0; i < values.size(); ++i) {
values.get(i).walk(w);
values.set(i, w.updateRef(values.get(i)));
}
w.visit(this);
}
}
private static class UnaryOp extends ExpNode {
public ExpNode subExp;
protected final UnOpFunc func;
public String name;
public boolean canSkipRuntimeChecks = false;
UnaryOp(String name, ParseContext context, ExpNode subExp, UnOpFunc func, Expression exp, int pos) {
super(context, exp, pos);
this.subExp = subExp;
this.func = func;
this.name = name;
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult subExpVal = subExp.evaluate(ec);
func.checkTypeAndUnits(context, subExpVal, exp.source, tokenPos);
return func.apply(context, subExpVal);
}
@Override
public ExpValResult validate() {
ExpValResult res = func.validate(context, subExp.validate(), exp.source, tokenPos);
if (res.state == ExpValResult.State.VALID)
canSkipRuntimeChecks = true;
return res;
}
@Override
void walk(ExpressionWalker w) throws ExpError {
subExp.walk(w);
subExp = w.updateRef(subExp);
w.visit(this);
}
@Override
public ExpNode getNoCheckVer() {
if (canSkipRuntimeChecks)
return new UnaryOpNoChecks(this);
else
return null;
}
@Override
public String toString() {
return "UnaryOp: " + name;
}
}
private static class UnaryOpNoChecks extends UnaryOp {
UnaryOpNoChecks(UnaryOp uo) {
super(uo.name, uo.context, uo.subExp, uo.func, uo.exp, uo.tokenPos);
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult subExpVal = subExp.evaluate(ec);
return func.apply(context, subExpVal);
}
}
private static class BinaryOp extends ExpNode {
public ExpNode lSubExp;
public ExpNode rSubExp;
public boolean canSkipRuntimeChecks = false;
public String name;
protected final BinOpFunc func;
BinaryOp(String name, ParseContext context, ExpNode lSubExp, ExpNode rSubExp, BinOpFunc func, Expression exp, int pos) {
super(context, exp, pos);
this.lSubExp = lSubExp;
this.rSubExp = rSubExp;
this.func = func;
this.name = name;
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult lRes = lSubExp.evaluate(ec);
ExpResult rRes = rSubExp.evaluate(ec);
func.checkTypeAndUnits(context, lRes, rRes, exp.source, tokenPos);
return func.apply(context, lRes, rRes, exp.source, tokenPos);
}
@Override
public ExpValResult validate() {
ExpValResult lRes = lSubExp.validate();
ExpValResult rRes = rSubExp.validate();
ExpValResult res = func.validate(context, lRes, rRes, exp.source, tokenPos);
if (res.state == ExpValResult.State.VALID)
canSkipRuntimeChecks = true;
return res;
}
@Override
void walk(ExpressionWalker w) throws ExpError {
lSubExp.walk(w);
rSubExp.walk(w);
lSubExp = w.updateRef(lSubExp);
rSubExp = w.updateRef(rSubExp);
w.visit(this);
}
@Override
public ExpNode getNoCheckVer() {
if (canSkipRuntimeChecks)
return new BinaryOpNoChecks(this);
else
return null;
}
@Override
public String toString() {
return "BinaryOp: " + name;
}
}
private static class BinaryOpNoChecks extends BinaryOp {
BinaryOpNoChecks(BinaryOp bo) {
super(bo.name, bo.context, bo.lSubExp, bo.rSubExp, bo.func, bo.exp, bo.tokenPos);
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult lRes = lSubExp.evaluate(ec);
ExpResult rRes = rSubExp.evaluate(ec);
return func.apply(context, lRes, rRes, exp.source, tokenPos);
}
}
private static class Conditional extends ExpNode {
private ExpNode condExp;
private ExpNode trueExp;
private ExpNode falseExp;
public Conditional(ParseContext context, ExpNode c, ExpNode t, ExpNode f, Expression exp, int pos) {
super(context, exp, pos);
condExp = c;
trueExp = t;
falseExp =f;
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult condRes = condExp.evaluate(ec); //constCondRes != null ? constCondRes : condExp.evaluate(ec);
if (condRes.value == 0)
return falseExp.evaluate(ec);
else
return trueExp.evaluate(ec);
}
@Override
public ExpValResult validate() {
ExpValResult condRes = condExp.validate();
ExpValResult trueRes = trueExp.validate();
ExpValResult falseRes = falseExp.validate();
if ( condRes.state == ExpValResult.State.ERROR ||
trueRes.state == ExpValResult.State.ERROR ||
falseRes.state == ExpValResult.State.ERROR) {
// Error state, merge all returned errors
ArrayList<ExpError> errors = new ArrayList<>();
if (condRes.errors != null)
errors.addAll(condRes.errors);
if (trueRes.errors != null)
errors.addAll(trueRes.errors);
if (falseRes.errors != null)
errors.addAll(falseRes.errors);
return ExpValResult.makeErrorRes(errors);
}
else if ( condRes.state == ExpValResult.State.UNDECIDABLE ||
trueRes.state == ExpValResult.State.UNDECIDABLE ||
falseRes.state == ExpValResult.State.UNDECIDABLE) {
return ExpValResult.makeUndecidableRes();
}
// All valid case
// Check that both sides of the branch return the same type
if (trueRes.type != falseRes.type) {
ExpError typeError = new ExpError(exp.source, tokenPos,
"Type mismatch in conditional. True branch is %s, false branch is %s",
trueRes.type.toString(), falseRes.type.toString());
return ExpValResult.makeErrorRes(typeError);
}
// Check that both sides of the branch return the same unit types, for numerical types
if (trueRes.type == ExpResType.NUMBER && trueRes.unitType != falseRes.unitType) {
ExpError unitError = new ExpError(exp.source, tokenPos,
"Unit mismatch in conditional. True branch is %s, false branch is %s",
trueRes.unitType.getSimpleName(), falseRes.unitType.getSimpleName());
return ExpValResult.makeErrorRes(unitError);
}
return ExpValResult.makeValidRes(trueRes.type, trueRes.unitType);
}
@Override
void walk(ExpressionWalker w) throws ExpError {
condExp.walk(w);
trueExp.walk(w);
falseExp.walk(w);
condExp = w.updateRef(condExp);
trueExp = w.updateRef(trueExp);
falseExp = w.updateRef(falseExp);
w.visit(this);
}
@Override
public String toString() {
return "Conditional";
}
}
private static class FuncCall extends ExpNode {
protected final ArrayList<ExpNode> args;
protected final CallableFunc function;
private boolean canSkipRuntimeChecks = false;
private final String name;
public FuncCall(String name, ParseContext context, CallableFunc function, ArrayList<ExpNode> args, Expression exp, int pos) {
super(context, exp, pos);
this.function = function;
this.args = args;
this.name = name;
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult[] argVals = new ExpResult[args.size()];
for (int i = 0; i < args.size(); ++i) {
argVals[i] = args.get(i).evaluate(ec);
}
function.checkUnits(context, argVals, exp.source, tokenPos);
return function.call(context, argVals, exp.source, tokenPos);
}
@Override
public ExpValResult validate() {
ExpValResult[] argVals = new ExpValResult[args.size()];
for (int i = 0; i < args.size(); ++i) {
argVals[i] = args.get(i).validate();
}
ExpValResult res = function.validate(context, argVals, exp.source, tokenPos);
if (res.state == ExpValResult.State.VALID)
canSkipRuntimeChecks = true;
return res;
}
@Override
void walk(ExpressionWalker w) throws ExpError {
for (int i = 0; i < args.size(); ++i) {
args.get(i).walk(w);
}
for (int i = 0; i < args.size(); ++i) {
args.set(i, w.updateRef(args.get(i)));
}
w.visit(this);
}
@Override
public ExpNode getNoCheckVer() {
if (canSkipRuntimeChecks)
return new FuncCallNoChecks(this);
else
return null;
}
@Override
public String toString() {
return "Function: " + name;
}
}
private static class FuncCallNoChecks extends FuncCall {
FuncCallNoChecks(FuncCall fc) {
super(fc.name, fc.context, fc.function, fc.args, fc.exp, fc.tokenPos);
}
@Override
public ExpResult evaluate(EvalContext ec) throws ExpError {
ExpResult[] argVals = new ExpResult[args.size()];
for (int i = 0; i < args.size(); ++i) {
argVals[i] = args.get(i).evaluate(ec);
}
return function.call(context, argVals, exp.source, tokenPos);
}
}
// Some errors can be throw without a known source or position, update such errors with the given info
private static ExpError fixError(ExpError ex, String source, int pos) {
ExpError exFixed = ex;
if (ex.source == null) {
exFixed = new ExpError(source, pos, ex.getMessage());
}
return exFixed;
}
private static void fixValidationErrors(ExpValResult res, String source, int pos) {
if (res.state == ExpValResult.State.ERROR ) {
for (int i = 0; i < res.errors.size(); ++i) {
res.errors.set(i, fixError(res.errors.get(i), source, pos));
}
}
}
///////////////////////////////////////////////////////////
// Entries for user definable operators and functions
private static class UnaryOpEntry {
public String symbol;
public UnOpFunc function;
public double bindingPower;
}
private static class BinaryOpEntry {
public String symbol;
public BinOpFunc function;
public double bindingPower;
public boolean rAssoc;
}
private static class FunctionEntry {
public String name;
public CallableFunc function;
public int numMinArgs;
public int numMaxArgs;
}
private static ArrayList<UnaryOpEntry> unaryOps = new ArrayList<>();
private static ArrayList<BinaryOpEntry> binaryOps = new ArrayList<>();
private static ArrayList<FunctionEntry> functions = new ArrayList<>();
private static void addUnaryOp(String symbol, double bindPower, UnOpFunc func) {
UnaryOpEntry oe = new UnaryOpEntry();
oe.symbol = symbol;
oe.function = func;
oe.bindingPower = bindPower;
unaryOps.add(oe);
}
private static void addBinaryOp(String symbol, double bindPower, boolean rAssoc, BinOpFunc func) {
BinaryOpEntry oe = new BinaryOpEntry();
oe.symbol = symbol;
oe.function = func;
oe.bindingPower = bindPower;
oe.rAssoc = rAssoc;
binaryOps.add(oe);
}
private static void addFunction(String name, int numMinArgs, int numMaxArgs, CallableFunc func) {
FunctionEntry fe = new FunctionEntry();
fe.name = name;
fe.function = func;
fe.numMinArgs = numMinArgs;
fe.numMaxArgs = numMaxArgs;
functions.add(fe);
}
private static UnaryOpEntry getUnaryOp(String symbol) {
for (UnaryOpEntry oe: unaryOps) {
if (oe.symbol.equals(symbol))
return oe;
}
return null;
}
private static BinaryOpEntry getBinaryOp(String symbol) {
for (BinaryOpEntry oe: binaryOps) {
if (oe.symbol.equals(symbol))
return oe;
}
return null;
}
private static FunctionEntry getFunctionEntry(String funcName) {
for (FunctionEntry fe : functions) {
if (fe.name.equals(funcName)){
return fe;
}
}
return null;
}
///////////////////////////////////////////////////
// Operator Utility Functions
// See if there are any existing errors, or this branch is undecidable
private static ExpValResult mergeBinaryErrors(ExpValResult lval, ExpValResult rval) {
if ( lval.state == ExpValResult.State.ERROR ||
rval.state == ExpValResult.State.ERROR) {
// Propagate the error, no further checking
ArrayList<ExpError> errors = new ArrayList<>();
if (lval.errors != null)
errors.addAll(lval.errors);
if (rval.errors != null)
errors.addAll(rval.errors);
return ExpValResult.makeErrorRes(errors);
}
if ( lval.state == ExpValResult.State.UNDECIDABLE ||
rval.state == ExpValResult.State.UNDECIDABLE) {
return ExpValResult.makeUndecidableRes();
}
return null;
}
private static ExpValResult mergeMultipleErrors(ExpValResult[] args) {
for (ExpValResult val : args) {
if (val.state == ExpValResult.State.ERROR) {
// We have an error, merge all error results and return
ArrayList<ExpError> errors = new ArrayList<>();
for (ExpValResult errVal : args) {
if (errVal.errors != null)
errors.addAll(errVal.errors);
}
return ExpValResult.makeErrorRes(errors);
}
}
for (ExpValResult val : args) {
if (val.state == ExpValResult.State.UNDECIDABLE) {
// At least one value in undecidable, propagate it
return ExpValResult.makeUndecidableRes();
}
}
return null;
}
private static void checkBothNumbers(ExpResult lval, ExpResult rval, String source, int pos)
throws ExpError {
if (lval.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Left operand must be a number");
}
if (rval.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Right operand must be a number");
}
}
private static ExpValResult validateBothNumbers(ExpValResult lval, ExpValResult rval, String source, int pos) {
if (lval.type != ExpResType.NUMBER) {
ExpError error = new ExpError(source, pos, "Left operand must be a number");
return ExpValResult.makeErrorRes(error);
}
if (rval.type != ExpResType.NUMBER) {
ExpError error = new ExpError(source, pos, "Right operand must be a number");
return ExpValResult.makeErrorRes(error);
}
return null;
}
private static ExpValResult validateComparison(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
// Require both values to be the same unit type and return a dimensionless unit
// Propagate errors
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null) {
return mergedErrors;
}
ExpValResult numRes = validateBothNumbers(lval, rval, source, pos);
if (numRes != null) {
return numRes;
}
// Both sub values should be valid here
if (lval.unitType != rval.unitType) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
private static void checkTypedComparison(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
// Check that the types are the same
if (lval.type != rval.type) {
throw new ExpError(source, pos, "Can not compare different types. LHS: %s, RHS: %s",
ExpValResult.typeString(lval.type),
ExpValResult.typeString(rval.type));
}
if (lval.type == ExpResType.NUMBER) {
// Also check that the unit types are the same
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, "Can not compare different unit types. LHS: %s, RHS: %s",
lval.unitType.getSimpleName(),
rval.unitType.getSimpleName());
}
}
}
private static boolean evaluteTypedEquality(ExpResult lval, ExpResult rval) {
boolean equal;
switch(lval.type) {
case ENTITY:
equal = lval.entVal == rval.entVal;
break;
case STRING:
equal = lval.stringVal.equals(rval.stringVal);
break;
case NUMBER:
equal = lval.value == rval.value;
break;
default:
assert(false);
equal = false;
}
return equal;
}
private static ExpValResult validateTypedComparison(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
// Propagate errors
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null) {
return mergedErrors;
}
// Otherwise, check that the types are the same
if (lval.type != rval.type) {
ExpError err = new ExpError(source, pos, "Can not compare different types. LHS: %s, RHS: %s",
ExpValResult.typeString(lval.type),
ExpValResult.typeString(rval.type));
return ExpValResult.makeErrorRes(err);
}
if (lval.type == ExpResType.NUMBER) {
// Also check that the unit types are the same
if (lval.unitType != rval.unitType) {
ExpError err = new ExpError(source, pos, "Can not compare different unit types. LHS: %s, RHS: %s",
lval.unitType.getSimpleName(),
rval.unitType.getSimpleName());
return ExpValResult.makeErrorRes(err);
}
}
return ExpValResult.makeValidRes(lval.type, DimensionlessUnit.class);
}
// Validate with all args using the same units, and a new result returning 'newType' unit type
private static ExpValResult validateSameUnits(ParseContext context, ExpValResult[] args, String source, int pos, Class<? extends Unit> newType) {
ExpValResult mergedErrors = mergeMultipleErrors(args);
if (mergedErrors != null)
return mergedErrors;
for (int i = 1; i < args.length; ++ i) {
if (args[i].type != ExpResType.NUMBER) {
ExpError error = new ExpError(source, pos, String.format("Argument %d must be a number", i+1));
return ExpValResult.makeErrorRes(error);
}
if (args[0].unitType != args[i].unitType) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(args[0].unitType, args[i].unitType));
return ExpValResult.makeErrorRes(error);
}
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, newType);
}
// Make sure the single argument is a collection
private static ExpValResult validateCollection(ParseContext context, ExpValResult[] args, String source, int pos) {
if ( args[0].state == ExpValResult.State.ERROR ||
args[0].state == ExpValResult.State.UNDECIDABLE) {
return args[0];
}
// Check that the argument is a collection
if (args[0].type != ExpResType.COLLECTION) {
ExpError error = new ExpError(source, pos, "Expected Collection type argument");
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeUndecidableRes();
}
// Check that a single argument is not an error and is a dimensionless unit
private static ExpValResult validateSingleArgDimensionless(ParseContext context, ExpValResult arg, String source, int pos) {
if ( arg.state == ExpValResult.State.ERROR ||
arg.state == ExpValResult.State.UNDECIDABLE)
return arg;
if (arg.type != ExpResType.NUMBER) {
ExpError error = new ExpError(source, pos, "Argument must be a number");
return ExpValResult.makeErrorRes(error);
}
if (arg.unitType != DimensionlessUnit.class) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(arg.unitType, DimensionlessUnit.class));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
// Check that a single argument is not an error and is a dimensionless unit or angle unit
private static ExpValResult validateTrigFunction(ParseContext context, ExpValResult arg, String source, int pos) {
if ( arg.state == ExpValResult.State.ERROR ||
arg.state == ExpValResult.State.UNDECIDABLE)
return arg;
if (arg.type != ExpResType.NUMBER) {
ExpError error = new ExpError(source, pos, "Argument must be a number");
return ExpValResult.makeErrorRes(error);
}
if (arg.unitType != DimensionlessUnit.class && arg.unitType != AngleUnit.class) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(arg.unitType, DimensionlessUnit.class));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
////////////////////////////////////////////////////////
// Statically initialize the operators and functions
static {
///////////////////////////////////////////////////
// Unary Operators
addUnaryOp("-", 50, new UnOpFunc() {
@Override
public ExpResult apply(ParseContext context, ExpResult val){
return ExpResult.makeNumResult(-val.value, val.unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult val, String source, int pos) {
if (val.state == ExpValResult.State.VALID && val.type != ExpResType.NUMBER) {
ExpError err = new ExpError(source, pos, "Unary negation only applies to numbers");
return ExpValResult.makeErrorRes(err);
}
return val;
}
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult val, String source, int pos)
throws ExpError {
if (val.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Unary negation only applies to numbers");
}
}
});
addUnaryOp("+", 50, new UnOpFunc() {
@Override
public ExpResult apply(ParseContext context, ExpResult val){
return ExpResult.makeNumResult(val.value, val.unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult val, String source, int pos) {
if (val.state == ExpValResult.State.VALID && val.type != ExpResType.NUMBER) {
ExpError err = new ExpError(source, pos, "Unary positive only applies to numbers");
return ExpValResult.makeErrorRes(err);
}
return val;
}
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult val, String source, int pos)
throws ExpError {
if (val.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Unary positive only applies to numbers");
}
}
});
addUnaryOp("!", 50, new UnOpFunc() {
@Override
public ExpResult apply(ParseContext context, ExpResult val){
return ExpResult.makeNumResult(val.value == 0 ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult val, String source, int pos) {
// If the sub expression result was valid, make it dimensionless, otherwise return the sub expression result
if (val.state == ExpValResult.State.VALID) {
if (val.type == ExpResType.NUMBER)
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
// The expression is valid, but not a number
ExpError error = new ExpError(source, pos, "Argument must be a number");
return ExpValResult.makeErrorRes(error);
} else {
return val;
}
}
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult val, String source, int pos)
throws ExpError {
if (val.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Unary not only applies to numbers");
}
}
});
///////////////////////////////////////////////////
// Binary operators
addBinaryOp("+", 20, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
boolean bothNumbers = (lval.type==ExpResType.NUMBER) && (rval.type==ExpResType.NUMBER);
boolean bothStrings = (lval.type==ExpResType.STRING) && (rval.type==ExpResType.STRING);
if (!bothNumbers && !bothStrings) {
throw new ExpError(source, pos, "Operator '+' requires two numbers or two strings");
}
if (bothNumbers && lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
if (lval.type == ExpResType.STRING && rval.type == ExpResType.STRING) {
return ExpResult.makeStringResult(lval.stringVal.concat(rval.stringVal));
}
return ExpResult.makeNumResult(lval.value + rval.value, lval.unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null)
return mergedErrors;
boolean bothNumbers = (lval.type==ExpResType.NUMBER) && (rval.type==ExpResType.NUMBER);
boolean bothStrings = (lval.type==ExpResType.STRING) && (rval.type==ExpResType.STRING);
if (!bothNumbers && !bothStrings) {
ExpError err = new ExpError(source, pos, "Operator '+' requires two numbers or two strings");
return ExpValResult.makeErrorRes(err);
}
if (bothStrings) {
return ExpValResult.makeValidRes(ExpResType.STRING, DimensionlessUnit.class);
}
// Both numbers
if (lval.unitType != rval.unitType) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, lval.unitType);
}
});
addBinaryOp("-", 20, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source,int pos) throws ExpError {
return ExpResult.makeNumResult(lval.value - rval.value, lval.unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null)
return mergedErrors;
ExpValResult numRes = validateBothNumbers(lval, rval, source, pos);
if (numRes != null) {
return numRes;
}
if (lval.unitType != rval.unitType) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, lval.unitType);
}
});
addBinaryOp("*", 30, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
Class<? extends Unit> newType = context.multUnitTypes(lval.unitType, rval.unitType);
if (newType == null) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
Class<? extends Unit> newType = context.multUnitTypes(lval.unitType, rval.unitType);
return ExpResult.makeNumResult(lval.value * rval.value, newType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null)
return mergedErrors;
ExpValResult numRes = validateBothNumbers(lval, rval, source, pos);
if (numRes != null) {
return numRes;
}
Class<? extends Unit> newType = context.multUnitTypes(lval.unitType, rval.unitType);
if (newType == null) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, newType);
}
});
addBinaryOp("/", 30, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
Class<? extends Unit> newType = context.divUnitTypes(lval.unitType, rval.unitType);
if (newType == null) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
Class<? extends Unit> newType = context.divUnitTypes(lval.unitType, rval.unitType);
return ExpResult.makeNumResult(lval.value / rval.value, newType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null)
return mergedErrors;
ExpValResult numRes = validateBothNumbers(lval, rval, source, pos);
if (numRes != null) {
return numRes;
}
Class<? extends Unit> newType = context.divUnitTypes(lval.unitType, rval.unitType);
if (newType == null) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, newType);
}
});
addBinaryOp("^", 40, true, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != DimensionlessUnit.class ||
rval.unitType != DimensionlessUnit.class) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.pow(lval.value, rval.value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null)
return mergedErrors;
ExpValResult numRes = validateBothNumbers(lval, rval, source, pos);
if (numRes != null) {
return numRes;
}
if ( lval.unitType != DimensionlessUnit.class ||
rval.unitType != DimensionlessUnit.class) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
});
addBinaryOp("%", 30, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(lval.value % rval.value, lval.unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
ExpValResult mergedErrors = mergeBinaryErrors(lval, rval);
if (mergedErrors != null)
return mergedErrors;
ExpValResult numRes = validateBothNumbers(lval, rval, source, pos);
if (numRes != null) {
return numRes;
}
if (lval.unitType != rval.unitType) {
ExpError error = new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, lval.unitType);
}
});
addBinaryOp("==", 10, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkTypedComparison(context, lval, rval, source, pos);
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
boolean equal = evaluteTypedEquality(lval, rval);
return ExpResult.makeNumResult(equal ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateTypedComparison(context, lval, rval, source, pos);
}
});
addBinaryOp("!=", 10, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkTypedComparison(context, lval, rval, source, pos);
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
boolean equal = evaluteTypedEquality(lval, rval);
return ExpResult.makeNumResult(!equal ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateTypedComparison(context, lval, rval, source, pos);
}
});
addBinaryOp("&&", 8, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos){
return ExpResult.makeNumResult((lval.value!=0) && (rval.value!=0) ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateComparison(context, lval, rval, source, pos);
}
});
addBinaryOp("||", 6, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos){
return ExpResult.makeNumResult((lval.value!=0) || (rval.value!=0) ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateComparison(context, lval, rval, source, pos);
}
});
addBinaryOp("<", 12, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(lval.value < rval.value ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateComparison(context, lval, rval, source, pos);
}
});
addBinaryOp("<=", 12, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(lval.value <= rval.value ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateComparison(context, lval, rval, source, pos);
}
});
addBinaryOp(">", 12, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(lval.value > rval.value ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateComparison(context, lval, rval, source, pos);
}
});
addBinaryOp(">=", 12, false, new BinOpFunc() {
@Override
public void checkTypeAndUnits(ParseContext context, ExpResult lval,
ExpResult rval, String source, int pos) throws ExpError {
checkBothNumbers(lval, rval, source, pos);
if (lval.unitType != rval.unitType) {
throw new ExpError(source, pos, getUnitMismatchString(lval.unitType, rval.unitType));
}
}
@Override
public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(lval.value >= rval.value ? 1 : 0, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult lval, ExpValResult rval, String source, int pos) {
return validateComparison(context, lval, rval, source, pos);
}
});
////////////////////////////////////////////////////
// Functions
addFunction("max", 2, -1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
for (int i = 1; i < args.length; ++ i) {
if (args[0].unitType != args[i].unitType)
throw new ExpError(source, pos, getUnitMismatchString(args[0].unitType, args[i].unitType));
}
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
ExpResult res = args[0];
for (int i = 1; i < args.length; ++ i) {
if (args[i].value > res.value)
res = args[i];
}
return res;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSameUnits(context, args, source, pos, args[0].unitType);
}
});
addFunction("min", 2, -1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
for (int i = 1; i < args.length; ++ i) {
if (args[0].unitType != args[i].unitType)
throw new ExpError(source, pos, getUnitMismatchString(args[0].unitType, args[i].unitType));
}
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
ExpResult res = args[0];
for (int i = 1; i < args.length; ++ i) {
if (args[i].value < res.value)
res = args[i];
}
return res;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSameUnits(context, args, source, pos, args[0].unitType);
}
});
addFunction("maxCol", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
if (args[0].type != ExpResType.COLLECTION) {
throw new ExpError(source, pos, "Expected Collection type argument");
}
ExpResult.Collection col = args[0].colVal;
ExpResult.Iterator it = col.getIter();
if (!it.hasNext()) {
throw new ExpError(source, pos, "Can not get max of empty collection");
}
ExpResult ret = col.index(it.nextKey());
Class<? extends Unit> ut = ret.unitType;
if (ret.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take max of non-numeric type in collection");
}
while (it.hasNext()) {
ExpResult comp = col.index(it.nextKey());
if (comp.unitType != ut) {
throw new ExpError(source, pos, "Unmatched Unit types in collection: %s, %s",
ut.getSimpleName(), comp.unitType.getSimpleName());
}
if (comp.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take max of non-numeric type in collection");
}
if (comp.value > ret.value) {
ret = comp;
}
}
return ret;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateCollection(context, args, source, pos);
}
});
addFunction("minCol", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
if (args[0].type != ExpResType.COLLECTION) {
throw new ExpError(source, pos, "Expected Collection type argument");
}
ExpResult.Collection col = args[0].colVal;
ExpResult.Iterator it = col.getIter();
if (!it.hasNext()) {
throw new ExpError(source, pos, "Can not get min of empty collection");
}
ExpResult ret = col.index(it.nextKey());
Class<? extends Unit> ut = ret.unitType;
if (ret.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take min of non-numeric type in collection");
}
while (it.hasNext()) {
ExpResult comp = col.index(it.nextKey());
if (comp.unitType != ut) {
throw new ExpError(source, pos, "Unmatched Unit types in collection: %s, %s",
ut.getSimpleName(), comp.unitType.getSimpleName());
}
if (comp.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take min of non-numeric type in collection");
}
if (comp.value < ret.value) {
ret = comp;
}
}
return ret;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateCollection(context, args, source, pos);
}
});
addFunction("abs", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
// N/A
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) {
return ExpResult.makeNumResult(Math.abs(args[0].value), args[0].unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return args[0];
}
});
addFunction("ceil", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
// N/A
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) {
return ExpResult.makeNumResult(Math.ceil(args[0].value), args[0].unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return args[0];
}
});
addFunction("floor", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
// N/A
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) {
return ExpResult.makeNumResult(Math.floor(args[0].value), args[0].unitType);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return args[0];
}
});
addFunction("signum", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
// N/A
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) {
return ExpResult.makeNumResult(Math.signum(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
if (args[0].state == ExpValResult.State.VALID) {
if (args[0].type == ExpResType.NUMBER) {
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
ExpError err = new ExpError(source, pos, "First parameter must be a number");
return ExpValResult.makeErrorRes(err);
} else {
return args[0];
}
}
});
addFunction("sqrt", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.sqrt(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("cbrt", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.cbrt(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("indexOfMin", 2, -1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
for (int i = 1; i < args.length; ++ i) {
if (args[0].unitType != args[i].unitType)
throw new ExpError(source, pos, getUnitMismatchString(args[0].unitType, args[i].unitType));
}
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
ExpResult res = args[0];
int index = 0;
for (int i = 1; i < args.length; ++ i) {
if (args[i].value < res.value) {
res = args[i];
index = i;
}
}
return ExpResult.makeNumResult(index + 1, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSameUnits(context, args, source, pos, DimensionlessUnit.class);
}
});
addFunction("indexOfMax", 2, -1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
for (int i = 1; i < args.length; ++ i) {
if (args[0].unitType != args[i].unitType)
throw new ExpError(source, pos, getUnitMismatchString(args[0].unitType, args[i].unitType));
}
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
ExpResult res = args[0];
int index = 0;
for (int i = 1; i < args.length; ++ i) {
if (args[i].value > res.value) {
res = args[i];
index = i;
}
}
return ExpResult.makeNumResult(index + 1, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSameUnits(context, args, source, pos, DimensionlessUnit.class);
}
});
addFunction("indexOfMaxCol", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
if (args[0].type != ExpResType.COLLECTION) {
throw new ExpError(source, pos, "Expected Collection type argument");
}
ExpResult.Collection col = args[0].colVal;
ExpResult.Iterator it = col.getIter();
if (!it.hasNext()) {
throw new ExpError(source, pos, "Can not get max of empty collection");
}
ExpResult retKey = it.nextKey();
ExpResult ret = col.index(retKey);
Class<? extends Unit> ut = ret.unitType;
if (ret.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take max of non-numeric type in collection");
}
while (it.hasNext()) {
ExpResult compKey = it.nextKey();
ExpResult comp = col.index(compKey);
if (comp.unitType != ut) {
throw new ExpError(source, pos, "Unmatched Unit types in collection: %s, %s",
ut.getSimpleName(), comp.unitType.getSimpleName());
}
if (comp.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take max of non-numeric type in collection");
}
if (comp.value > ret.value) {
ret = comp;
retKey = compKey;
}
}
return retKey;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateCollection(context, args, source, pos);
}
});
addFunction("indexOfMinCol", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
if (args[0].type != ExpResType.COLLECTION) {
throw new ExpError(source, pos, "Expected Collection type argument");
}
ExpResult.Collection col = args[0].colVal;
ExpResult.Iterator it = col.getIter();
if (!it.hasNext()) {
throw new ExpError(source, pos, "Can not get min of empty collection");
}
ExpResult retKey = it.nextKey();
ExpResult ret = col.index(retKey);
Class<? extends Unit> ut = ret.unitType;
if (ret.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take min of non-numeric type in collection");
}
while (it.hasNext()) {
ExpResult compKey = it.nextKey();
ExpResult comp = col.index(compKey);
if (comp.unitType != ut) {
throw new ExpError(source, pos, "Unmatched Unit types in collection: %s, %s",
ut.getSimpleName(), comp.unitType.getSimpleName());
}
if (comp.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not take min of non-numeric type in collection");
}
if (comp.value < ret.value) {
ret = comp;
retKey = compKey;
}
}
return retKey;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateCollection(context, args, source, pos);
}
});
addFunction("indexOfNearest", 2, 2, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
if (args[0].type != ExpResType.COLLECTION) {
throw new ExpError(source, pos, "Expected Collection type argument as first argument.");
}
if (args[1].type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Expected numerical argument as second argument.");
}
ExpResult.Collection col = args[0].colVal;
ExpResult nearPoint = args[1];
ExpResult.Iterator it = col.getIter();
if (!it.hasNext()) {
throw new ExpError(source, pos, "Can not get nearest value of empty collection.");
}
double nearestDist = Double.MAX_VALUE;
ExpResult retKey = null;
while (it.hasNext()) {
ExpResult compKey = it.nextKey();
ExpResult comp = col.index(compKey);
if (comp.unitType != nearPoint.unitType) {
throw new ExpError(source, pos, "Unmatched Unit types when finding nearest: %s, %s",
nearPoint.unitType.getSimpleName(), comp.unitType.getSimpleName());
}
if (comp.type != ExpResType.NUMBER) {
throw new ExpError(source, pos, "Can not find nearest value of non-numeric type in collection.");
}
double dist = Math.abs(comp.value - nearPoint.value);
if (dist < nearestDist) {
nearestDist = dist;
retKey = compKey;
}
}
return retKey;
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
if (args[1].state == ExpValResult.State.ERROR || args[1].state == ExpValResult.State.UNDECIDABLE) {
return args[1];
}
if (args[1].type != ExpResType.NUMBER) {
return ExpValResult.makeErrorRes(new ExpError(source, pos, "Second argument to 'indexOfNearest' must be a number."));
}
return validateCollection(context, args, source, pos);
}
});
addFunction("size", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
if (args[0].type != ExpResType.COLLECTION) {
throw new ExpError(source, pos, "Expected Collection type argument");
}
ExpResult.Collection col = args[0].colVal;
return ExpResult.makeNumResult(col.getSize(), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateCollection(context, args, source, pos);
}
});
addFunction("choose", 2, -1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
for (int i = 2; i < args.length; ++ i) {
if (args[1].unitType != args[i].unitType)
throw new ExpError(source, pos, getUnitMismatchString(args[1].unitType, args[i].unitType));
}
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
int k = (int) args[0].value;
if (k < 1 || k >= args.length)
throw new ExpError(source, pos,
String.format("Invalid index: %s. Index must be between 1 and %s.", k, args.length-1));
return args[k];
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
ExpValResult mergedErrors = mergeMultipleErrors(args);
if (mergedErrors != null)
return mergedErrors;
if (args[0].type != ExpResType.NUMBER) {
ExpError error = new ExpError(source, pos, "Parameter must be a number");
return ExpValResult.makeErrorRes(error);
}
if (args[0].unitType != DimensionlessUnit.class) {
ExpError error = new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
return ExpValResult.makeErrorRes(error);
}
if (args.length < 2) {
ExpError error = new ExpError(source, pos, "'choose' function must take at least 2 parameters.");
return ExpValResult.makeErrorRes(error);
}
ExpResType valType = args[1].type;
Class<? extends Unit> valUnitType = args[1].unitType;
for (int i = 2; i < args.length; ++ i) {
if (args[i].type != valType) {
ExpError error = new ExpError(source, pos, "All parameter types to 'choose' must be the same type");
return ExpValResult.makeErrorRes(error);
}
if (valType == ExpResType.NUMBER && valUnitType != args[i].unitType) {
ExpError error = new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
return ExpValResult.makeErrorRes(error);
}
}
return ExpValResult.makeValidRes(valType, valUnitType);
}
});
///////////////////////////////////////////////////
// Mathematical Constants
addFunction("E", 0, 0, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
// N/A
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.E, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
});
addFunction("PI", 0, 0, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
// N/A
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.PI, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
});
///////////////////////////////////////////////////
// Trigonometric Functions
addFunction("sin", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class && args[0].unitType != AngleUnit.class)
throw new ExpError(source, pos, getInvalidTrigUnitString(args[0].unitType));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.sin(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateTrigFunction(context, args[0], source, pos);
}
});
addFunction("cos", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class && args[0].unitType != AngleUnit.class)
throw new ExpError(source, pos, getInvalidTrigUnitString(args[0].unitType));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.cos(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateTrigFunction(context, args[0], source, pos);
}
});
addFunction("tan", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class && args[0].unitType != AngleUnit.class)
throw new ExpError(source, pos, getInvalidTrigUnitString(args[0].unitType));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.tan(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateTrigFunction(context, args[0], source, pos);
}
});
///////////////////////////////////////////////////
// Inverse Trigonometric Functions
addFunction("asin", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.asin(args[0].value), AngleUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("acos", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.acos(args[0].value), AngleUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("atan", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.atan(args[0].value), AngleUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("atan2", 2, 2, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
if (args[1].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[1].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.atan2(args[0].value, args[1].value), AngleUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
ExpValResult mergedErrors = mergeMultipleErrors(args);
if (mergedErrors != null)
return mergedErrors;
if (args[0].type != ExpResType.NUMBER || args[1].type != ExpResType.NUMBER ) {
ExpError error = new ExpError(source, pos, "Both parameters must be numbers");
return ExpValResult.makeErrorRes(error);
}
if (args[0].unitType != DimensionlessUnit.class) {
ExpError error = new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
return ExpValResult.makeErrorRes(error);
}
if (args[1].unitType != DimensionlessUnit.class) {
ExpError error = new ExpError(source, pos, getInvalidUnitString(args[1].unitType, DimensionlessUnit.class));
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
});
///////////////////////////////////////////////////
// Exponential Functions
addFunction("exp", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.exp(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("ln", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.log(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("log", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].unitType != DimensionlessUnit.class)
throw new ExpError(source, pos, getInvalidUnitString(args[0].unitType, DimensionlessUnit.class));
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(Math.log10(args[0].value), DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
return validateSingleArgDimensionless(context, args[0], source, pos);
}
});
addFunction("notNull", 1, 1, new CallableFunc() {
@Override
public void checkUnits(ParseContext context, ExpResult[] args,
String source, int pos) throws ExpError {
if (args[0].type != ExpResType.ENTITY) {
throw new ExpError(source, pos, "notNull requires entity as argument");
}
}
@Override
public ExpResult call(ParseContext context, ExpResult[] args, String source, int pos) throws ExpError {
return ExpResult.makeNumResult(args[0].entVal == null ? 0 : 1, DimensionlessUnit.class);
}
@Override
public ExpValResult validate(ParseContext context, ExpValResult[] args, String source, int pos) {
if ( args[0].state == ExpValResult.State.ERROR ||
args[0].state == ExpValResult.State.UNDECIDABLE)
return args[0];
if (args[0].type != ExpResType.ENTITY) {
ExpError error = new ExpError(source, pos, "Argument must be an entity");
return ExpValResult.makeErrorRes(error);
}
return ExpValResult.makeValidRes(ExpResType.NUMBER, DimensionlessUnit.class);
}
});
}
private static String unitToString(Class<? extends Unit> unit) {
ObjectType type = ObjectType.getObjectTypeForClass(unit);
if (type == null)
return "Unknown Unit";
return type.getName();
}
private static String getUnitMismatchString(Class<? extends Unit> u0, Class<? extends Unit> u1) {
String s0 = unitToString(u0);
String s1 = unitToString(u1);
return String.format("Unit mismatch: '%s' and '%s' are not compatible", s0, s1);
}
private static String getInvalidTrigUnitString(Class<? extends Unit> u0) {
String s0 = unitToString(u0);
return String.format("Invalid unit: %s. The input to a trigonometric function must be dimensionless or an angle.", s0);
}
private static String getInvalidUnitString(Class<? extends Unit> u0, Class<? extends Unit> u1) {
String s0 = unitToString(u0);
String s1 = unitToString(u1);
if (u1 == DimensionlessUnit.class)
return String.format("Invalid unit: %s. A dimensionless number is required.", s0);
return String.format("Invalid unit: %s. Units of %s are required.", s0, s1);
}
/**
* A utility class to make dealing with a list of tokens easier
*
*/
private static class TokenList {
private final ArrayList<ExpTokenizer.Token> tokens;
private int pos;
public TokenList(ArrayList<ExpTokenizer.Token> tokens) {
this.tokens = tokens;
this.pos = 0;
}
public void expect(int type, String val, String source) throws ExpError {
if (pos == tokens.size()) {
throw new ExpError(source, source.length(), String.format("Expected \"%s\", past the end of input", val));
}
ExpTokenizer.Token nextTok = tokens.get(pos);
if (nextTok.type != type || !nextTok.value.equals(val)) {
throw new ExpError(source, nextTok.pos, String.format("Expected \"%s\", got \"%s\"", val, nextTok.value));
}
pos++;
}
public ExpTokenizer.Token next() {
if (pos >= tokens.size()) {
return null;
}
return tokens.get(pos++);
}
public ExpTokenizer.Token peek() {
if (pos >= tokens.size()) {
return null;
}
return tokens.get(pos);
}
}
private static class ConstOptimizer implements ExpressionWalker {
@Override
public void visit(ExpNode exp) throws ExpError {
// N/A
}
/**
* Give a node a chance to swap itself out with a different subtree.
*/
@Override
public ExpNode updateRef(ExpNode origNode) throws ExpError {
// Note: Below we are passing 'null' as an EvalContext, this is not typically
// acceptable, but is 'safe enough' when we know the expression is a constant
if (origNode instanceof UnaryOp) {
UnaryOp uo = (UnaryOp)origNode;
if (uo.subExp instanceof Constant) {
// This is an unary operation on a constant, we can replace it with a constant
ExpResult val = uo.evaluate(null);
return new Constant(uo.context, val, origNode.exp, uo.tokenPos);
}
}
if (origNode instanceof BinaryOp) {
BinaryOp bo = (BinaryOp)origNode;
if ((bo.lSubExp instanceof Constant) && (bo.rSubExp instanceof Constant)) {
// both sub expressions are constants, so replace the binop with a constant
ExpResult val = bo.evaluate(null);
return new Constant(bo.context, val, origNode.exp, bo.tokenPos);
}
}
if (origNode instanceof FuncCall) {
FuncCall fc = (FuncCall)origNode;
boolean constArgs = true;
for (int i = 0; i < fc.args.size(); ++i) {
if (!(fc.args.get(i) instanceof Constant)) {
constArgs = false;
}
}
if (constArgs) {
ExpResult val = fc.evaluate(null);
return new Constant(fc.context, val, origNode.exp, fc.tokenPos);
}
}
if (origNode instanceof BuildArray) {
BuildArray ba = (BuildArray)origNode;
boolean constArgs = true;
for (ExpNode val : ba.values) {
if (!(val instanceof Constant))
constArgs = false;
}
if (constArgs) {
ExpResult val = ba.evaluate(null);
return new Constant(ba.context, val, origNode.exp, ba.tokenPos);
}
}
return origNode;
}
}
private static ConstOptimizer CONST_OP = new ConstOptimizer();
private static class RuntimeCheckOptimizer implements ExpressionWalker {
@Override
public void visit(ExpNode exp) throws ExpError {
// N/A
}
@Override
public ExpNode updateRef(ExpNode exp) throws ExpError {
ExpNode noCheckVer = exp.getNoCheckVer();
if (noCheckVer != null)
return noCheckVer;
else
return exp;
}
}
private static RuntimeCheckOptimizer RTC_OP = new RuntimeCheckOptimizer();
private static ExpNode optimizeAndValidateExpression(String input, ExpNode expNode, Expression exp) throws ExpError {
expNode.walk(CONST_OP);
expNode = CONST_OP.updateRef(expNode); // Finally, give the entire expression a chance to optimize itself into a constant
// Run the validation
ExpValResult valRes = expNode.validate();
if (valRes.state == ExpValResult.State.ERROR) {
if (valRes.errors.size() == 0) {
throw new ExpError(input, 0, "An unknown expression error occurred. This is probably a bug. Please inform the developers.");
}
// We received at least one error while validating.
throw valRes.errors.get(0);
}
// Now that validation is complete, we can run the optimizer that removes runtime checks on validated nodes
expNode.walk(RTC_OP);
expNode = RTC_OP.updateRef(expNode); // Give the top level node a chance to optimize
exp.validationResult = valRes;
return expNode;
}
/**
* The main entry point to the expression parsing system, will either return a valid
* expression that can be evaluated, or throw an error.
*/
public static Expression parseExpression(ParseContext context, String input) throws ExpError {
ArrayList<ExpTokenizer.Token> ts;
ts = ExpTokenizer.tokenize(input);
TokenList tokens = new TokenList(ts);
Expression ret = new Expression(input);
ExpNode expNode = parseExp(context, tokens, 0, ret);
// Make sure we've parsed all the tokens
ExpTokenizer.Token peeked = tokens.peek();
if (peeked != null) {
throw new ExpError(input, peeked.pos, "Unexpected additional values");
}
expNode = optimizeAndValidateExpression(input, expNode, ret);
ret.setRootNode(expNode);
return ret;
}
private static ExpNode parseExp(ParseContext context, TokenList tokens, double bindPower, Expression exp) throws ExpError {
ExpNode lhs = parseOpeningExp(context, tokens, bindPower, exp);
// Parse as many indices as are present
while (true) {
ExpTokenizer.Token peeked = tokens.peek();
if (peeked == null || peeked.type != ExpTokenizer.SYM_TYPE) {
break;
}
if (peeked.value.equals(".")) {
tokens.next(); // consume
ExpTokenizer.Token outputName = tokens.next();
if (outputName == null || outputName.type != ExpTokenizer.VAR_TYPE) {
throw new ExpError(exp.source, peeked.pos, "Expected Identifier after '.'");
}
lhs = new ResolveOutput(context, outputName.value, lhs, exp, peeked.pos);
continue;
}
if (peeked.value.equals("(")) {
tokens.next(); // consume
ExpNode indexExp = parseExp(context, tokens, 0, exp);
tokens.expect(ExpTokenizer.SYM_TYPE, ")", exp.source);
lhs = new IndexCollection(context, lhs, indexExp, exp, peeked.pos);
continue;
}
// Not an index or output. Move on
break;
}
// Now peek for a binary op to modify this expression
while (true) {
ExpTokenizer.Token peeked = tokens.peek();
if (peeked == null || peeked.type != ExpTokenizer.SYM_TYPE) {
break;
}
BinaryOpEntry binOp = getBinaryOp(peeked.value);
if (binOp != null && binOp.bindingPower > bindPower) {
// The next token is a binary op and powerful enough to bind us
lhs = handleBinOp(context, tokens, lhs, binOp, exp, peeked.pos);
continue;
}
// Specific check for binding the conditional (?:) operator
if (peeked.value.equals("?") && bindPower == 0) {
lhs = handleConditional(context, tokens, lhs, exp, peeked.pos);
continue;
}
break;
}
// We have bound as many operators as we can, return it
return lhs;
}
private static ExpNode handleBinOp(ParseContext context, TokenList tokens, ExpNode lhs, BinaryOpEntry binOp, Expression exp, int pos) throws ExpError {
tokens.next(); // Consume the operator
// For right associative operators, we weaken the binding power a bit at application time (but not testing time)
double assocMod = binOp.rAssoc ? -0.5 : 0;
ExpNode rhs = parseExp(context, tokens, binOp.bindingPower + assocMod, exp);
//currentPower = oe.bindingPower;
return new BinaryOp(binOp.symbol, context, lhs, rhs, binOp.function, exp, pos);
}
private static ExpNode handleConditional(ParseContext context, TokenList tokens, ExpNode lhs, Expression exp, int pos) throws ExpError {
tokens.next(); // Consume the '?'
ExpNode trueExp = parseExp(context, tokens, 0, exp);
tokens.expect(ExpTokenizer.SYM_TYPE, ":", exp.source);
ExpNode falseExp = parseExp(context, tokens , 0, exp);
return new Conditional(context, lhs, trueExp, falseExp, exp, pos);
}
public static Assignment parseAssignment(ParseContext context, String input) throws ExpError {
ArrayList<ExpTokenizer.Token> ts;
ts = ExpTokenizer.tokenize(input);
TokenList tokens = new TokenList(ts);
Assignment ret = new Assignment(input);
ExpNode lhsNode = parseExp(context, tokens, 0, ret);
tokens.expect(ExpTokenizer.SYM_TYPE, "=", input);
ExpNode rhsNode = parseExp(context, tokens, 0, ret);
// Make sure we've parsed all the tokens
ExpTokenizer.Token peeked = tokens.peek();
if (peeked != null) {
throw new ExpError(input, peeked.pos, "Unexpected additional values");
}
rhsNode = optimizeAndValidateExpression(input, rhsNode, ret);
ret.valueExp = rhsNode;
// Parsing is done, now we need to unwind the lhs expression to get the necessary components
ExpNode indexExp = null;
// Check for an optional index at the end
if (lhsNode instanceof IndexCollection) {
// the lhs ended with an index, split that off
IndexCollection ind = (IndexCollection)lhsNode;
indexExp = ind.index;
lhsNode = ind.collection;
indexExp = optimizeAndValidateExpression(input, indexExp, ret);
}
ret.attribIndex = indexExp;
// Now make sure the last node of the lhs ends with a output resolve
if (!(lhsNode instanceof ResolveOutput)) {
throw new ExpError(input, lhsNode.tokenPos, "Assignment left side must end with an output");
}
ResolveOutput lhsResolve = (ResolveOutput)lhsNode;
ExpNode entNode = lhsResolve.entNode;
entNode = optimizeAndValidateExpression(input, entNode, ret);
ret.entExp = entNode;
if (ret.entExp instanceof Constant) {
ExpResult ent = ret.entExp.evaluate(null);
ret.assigner = context.getConstAssigner(ent, lhsResolve.outputName);
} else {
ret.assigner = context.getAssigner(lhsResolve.outputName);
}
return ret;
}
// The first half of expression parsing, parse a simple expression based on the next token
private static ExpNode parseOpeningExp(ParseContext context, TokenList tokens, double bindPower, Expression exp) throws ExpError{
ExpTokenizer.Token nextTok = tokens.next(); // consume the first token
if (nextTok == null) {
throw new ExpError(exp.source, exp.source.length(), "Unexpected end of string");
}
if (nextTok.type == ExpTokenizer.NUM_TYPE) {
return parseConstant(context, nextTok.value, tokens, exp, nextTok.pos);
}
if (nextTok.type == ExpTokenizer.STRING_TYPE) {
// Return a literal string constant
return new Constant(context, ExpResult.makeStringResult(nextTok.value), exp, nextTok.pos);
}
if (nextTok.type == ExpTokenizer.VAR_TYPE &&
!nextTok.value.equals("this")) {
return parseFuncCall(context, nextTok.value, tokens, exp, nextTok.pos);
}
if (nextTok.type == ExpTokenizer.SQ_TYPE ||
nextTok.value.equals("this")) {
ExpResult namedVal = context.getValFromName(nextTok.value, exp.source, nextTok.pos);
return new Constant(context, namedVal, exp, nextTok.pos);
}
// The next token must be a symbol
if (nextTok.value.equals("{")) {
boolean foundComma = true;
ArrayList<ExpNode> exps = new ArrayList<>();
while(true) {
// Parse an array
ExpTokenizer.Token peeked = tokens.peek();
if (peeked != null && peeked.value.equals("}")) {
tokens.next(); // consume
break;
}
if (!foundComma) {
throw new ExpError(exp.source, peeked.pos, "Expected ',' or '}' in literal array.");
}
foundComma = false;
exps.add(parseExp(context, tokens, 0, exp));
peeked = tokens.peek();
if (peeked != null && peeked.value.equals(",")) {
tokens.next();
foundComma = true;
}
}
return new BuildArray(context, exps, exp, nextTok.pos);
}
// handle parenthesis
if (nextTok.value.equals("(")) {
ExpNode expNode = parseExp(context, tokens, 0, exp);
tokens.expect(ExpTokenizer.SYM_TYPE, ")", exp.source); // Expect the closing paren
return expNode;
}
UnaryOpEntry oe = getUnaryOp(nextTok.value);
if (oe != null) {
ExpNode expNode = parseExp(context, tokens, oe.bindingPower, exp);
return new UnaryOp(oe.symbol, context, expNode, oe.function, exp, nextTok.pos);
}
// We're all out of tricks here, this is an unknown expression
throw new ExpError(exp.source, nextTok.pos, "Can not parse expression");
}
private static ExpNode parseConstant(ParseContext context, String constant, TokenList tokens, Expression exp, int pos) throws ExpError {
double mult = 1;
Class<? extends Unit> ut = DimensionlessUnit.class;
ExpTokenizer.Token peeked = tokens.peek();
if (peeked != null && peeked.type == ExpTokenizer.SQ_TYPE) {
// This constant is followed by a square quoted token, it must be the unit
tokens.next(); // Consume unit token
UnitData unit = context.getUnitByName(peeked.value);
if (unit == null) {
throw new ExpError(exp.source, peeked.pos, "Unknown unit: %s", peeked.value);
}
mult = unit.scaleFactor;
ut = unit.unitType;
}
return new Constant(context, ExpResult.makeNumResult(Double.parseDouble(constant)*mult, ut), exp, pos);
}
private static ExpNode parseFuncCall(ParseContext context, String funcName, TokenList tokens, Expression exp, int pos) throws ExpError {
tokens.expect(ExpTokenizer.SYM_TYPE, "(", exp.source);
ArrayList<ExpNode> arguments = new ArrayList<>();
ExpTokenizer.Token peeked = tokens.peek();
if (peeked == null) {
throw new ExpError(exp.source, exp.source.length(), "Unexpected end of input in argument list");
}
boolean isEmpty = false;
if (peeked.value.equals(")")) {
// Special case with empty argument list
isEmpty = true;
tokens.next(); // Consume closing parens
}
while (!isEmpty) {
ExpNode nextArg = parseExp(context, tokens, 0, exp);
arguments.add(nextArg);
ExpTokenizer.Token nextTok = tokens.next();
if (nextTok == null) {
throw new ExpError(exp.source, exp.source.length(), "Unexpected end of input in argument list.");
}
if (nextTok.value.equals(")")) {
break;
}
if (nextTok.value.equals(",")) {
continue;
}
// Unexpected token
throw new ExpError(exp.source, nextTok.pos, "Unexpected token in arguement list");
}
FunctionEntry fe = getFunctionEntry(funcName);
if (fe == null) {
throw new ExpError(exp.source, pos, "Uknown function: \"%s\"", funcName);
}
if (fe.numMinArgs >= 0 && arguments.size() < fe.numMinArgs){
throw new ExpError(exp.source, pos, "Function \"%s\" expects at least %d arguments. %d provided.",
funcName, fe.numMinArgs, arguments.size());
}
if (fe.numMaxArgs >= 0 && arguments.size() > fe.numMaxArgs){
throw new ExpError(exp.source, pos, "Function \"%s\" expects at most %d arguments. %d provided.",
funcName, fe.numMaxArgs, arguments.size());
}
return new FuncCall(fe.name, context, fe.function, arguments, exp, pos);
}
}
|
JS: Cleanup comments
Signed-off-by: Matt Chudleigh <[email protected]>
|
src/main/java/com/jaamsim/input/ExpParser.java
|
JS: Cleanup comments
|
<ide><path>rc/main/java/com/jaamsim/input/ExpParser.java
<ide> }
<ide>
<ide> public interface EvalContext {
<del> //public ExpResult getVariableValue(String[] names, ExpResult[] indices) throws ExpError;
<del> //public boolean eagerEval();
<del> }
<del>// public interface ValContext {
<del>//
<del>// }
<add> }
<ide>
<ide> private interface ExpressionWalker {
<ide> public void visit(ExpNode exp) throws ExpError;
|
|
Java
|
apache-2.0
|
2bbbc48564b02c33e1e3e1ed361a8c8ded99b738
| 0 |
mtransitapps/commons-android,mtransitapps/commons-android,mtransitapps/commons-android
|
package org.mtransit.android.commons;
import java.util.regex.Pattern;
public final class HtmlUtils implements MTLog.Loggable {
private static final String TAG = HtmlUtils.class.getSimpleName();
@Override
public String getLogTag() {
return TAG;
}
public static final String URL_PARAM_AND = "&";
public static final String URL_PARAM_EQ = "=";
public static final String BR = "<BR/>";
public static final String B1 = "<B>";
public static final String B2 = "</B>";
private static final String BOLD_FORMAT = B1 + "%s" + B2;
public static String applyBold(CharSequence html) {
return String.format(BOLD_FORMAT, html);
}
private static final String FONT_COLOR_1_FORMAT = "<FONT COLOR=\"#%s\">";
private static final String FONT2 = "</FONT>";
private static final String FONT_COLOR_FORMAT = FONT_COLOR_1_FORMAT + "%s" + FONT2;
public static String applyFontColor(CharSequence html, CharSequence color) {
return String.format(FONT_COLOR_FORMAT, color, html);
}
private static final String LINKIFY = "<A HREF=\"%s\">%s</A>";
public static String linkify(CharSequence url) {
return String.format(LINKIFY, url, url);
}
private static final Pattern NEW_LINE_REGEX = Pattern.compile("(\n)");
public static String toHTML(String html) {
return NEW_LINE_REGEX.matcher(html).replaceAll(BR);
}
private static final Pattern REMOVE_BOLD = Pattern.compile(
"(<strong[^>]*>|</strong>|<h[1-6]{1}>|</h[1-6]{1}>|<span[^>]*>|</span>|font\\-weight\\:[\\s]*bold[;]?)", Pattern.CASE_INSENSITIVE);
private static final String REMOVE_BOLD_REPLACEMENT = StringUtils.EMPTY;
public static String removeBold(String html) {
try {
return REMOVE_BOLD.matcher(html).replaceAll(REMOVE_BOLD_REPLACEMENT);
} catch (Exception e) {
MTLog.w(TAG, e, "Error while removing bold!");
return html;
}
}
private static final Pattern LINE_BREAKS = Pattern.compile("(\\n|\\r)", Pattern.CASE_INSENSITIVE);
private static final Pattern FIX_TEXT_VIEW_BR = Pattern.compile("(<ul[^>]*>|</ul>|</li>|</h[1-6]{1}>|<p[^>]*>|</p>|<div[^>]*>|</div>)",
Pattern.CASE_INSENSITIVE);
private static final String FIX_TEXT_VIEW_BR_REPLACEMENT = BR;
private static final Pattern FIX_TEXT_VIEW_BR2 = Pattern.compile("(<li[^>]*>)", Pattern.CASE_INSENSITIVE);
private static final String FIX_TEXT_VIEW_BR_REPLACEMENT2 = "- ";
private static final String BRS_REGEX = "(<br />|<br/>|<br>)";
private static final Pattern FIX_TEXT_VIEW_BR_DUPLICATE = Pattern.compile("((" + BRS_REGEX + "(\\s| )*)+)", Pattern.CASE_INSENSITIVE);
private static final Pattern BR_START_ENDS = Pattern.compile("((^" + BRS_REGEX + ")|(" + BRS_REGEX + "$))", Pattern.CASE_INSENSITIVE);
public static String fixTextViewBR(String html) {
try {
html = LINE_BREAKS.matcher(html).replaceAll(StringUtils.EMPTY);
html = FIX_TEXT_VIEW_BR.matcher(html).replaceAll(FIX_TEXT_VIEW_BR_REPLACEMENT);
html = FIX_TEXT_VIEW_BR2.matcher(html).replaceAll(FIX_TEXT_VIEW_BR_REPLACEMENT2);
html = FIX_TEXT_VIEW_BR_DUPLICATE.matcher(html).replaceAll(FIX_TEXT_VIEW_BR_REPLACEMENT);
html = BR_START_ENDS.matcher(html).replaceAll(StringUtils.EMPTY);
return html;
} catch (Exception e) {
MTLog.w(TAG, e, "Error while fixing TextView BR!");
return html;
}
}
}
|
src/org/mtransit/android/commons/HtmlUtils.java
|
package org.mtransit.android.commons;
import java.util.regex.Pattern;
public final class HtmlUtils implements MTLog.Loggable {
private static final String TAG = HtmlUtils.class.getSimpleName();
@Override
public String getLogTag() {
return TAG;
}
public static final String URL_PARAM_AND = "&";
public static final String URL_PARAM_EQ = "=";
public static final String BR = "<BR/>";
public static final String B1 = "<B>";
public static final String B2 = "</B>";
private static final String BOLD_FORMAT = B1 + "%s" + B2;
public static String applyBold(CharSequence html) {
return String.format(BOLD_FORMAT, html);
}
private static final String FONT_COLOR_1_FORMAT = "<FONT COLOR=\"#%s\">";
private static final String FONT2 = "</FONT>";
private static final String FONT_COLOR_FORMAT = FONT_COLOR_1_FORMAT + "%s" + FONT2;
public static String applyFontColor(CharSequence html, CharSequence color) {
return String.format(FONT_COLOR_FORMAT, color, html);
}
private static final String LINKIFY = "<A HREF=\"%s\">%s</A>";
public static String linkify(CharSequence url) {
return String.format(LINKIFY, url, url);
}
private static final Pattern NEW_LINE_REGEX = Pattern.compile("(\n)");
public static String toHTML(String html) {
return NEW_LINE_REGEX.matcher(html).replaceAll(BR);
}
private static final Pattern REMOVE_BOLD = Pattern.compile(
"(<strong[^>]*>|</strong>|<h[1-6]{1}>|</h[1-6]{1}>|<span[^>]*>|</span>|font\\-weight\\:[\\s]*bold[;]?)", Pattern.CASE_INSENSITIVE);
private static final String REMOVE_BOLD_REPLACEMENT = StringUtils.EMPTY;
public static String removeBold(String html) {
try {
return REMOVE_BOLD.matcher(html).replaceAll(REMOVE_BOLD_REPLACEMENT);
} catch (Exception e) {
MTLog.w(TAG, e, "Error while removing bold!");
return html;
}
}
private static final Pattern FIX_TEXT_VIEW_BR = Pattern.compile("(<ul[^>]*>|</ul>|</li>|</h[1-6]{1}>)", Pattern.CASE_INSENSITIVE);
private static final String FIX_TEXT_VIEW_BR_REPLACEMENT = BR;
private static final Pattern FIX_TEXT_VIEW_BR2 = Pattern.compile("(<li[^>]*>)", Pattern.CASE_INSENSITIVE);
private static final String FIX_TEXT_VIEW_BR_REPLACEMENT2 = "- ";
public static String fixTextViewBR(String html) {
try {
html = FIX_TEXT_VIEW_BR.matcher(html).replaceAll(FIX_TEXT_VIEW_BR_REPLACEMENT);
html = FIX_TEXT_VIEW_BR2.matcher(html).replaceAll(FIX_TEXT_VIEW_BR_REPLACEMENT2);
return html;
} catch (Exception e) {
MTLog.w(TAG, e, "Error while fixing TextView BR!");
return html;
}
}
}
|
Improve HTML text cleaning (remove multiple line breaks) #OCTranspo #RTC
|
src/org/mtransit/android/commons/HtmlUtils.java
|
Improve HTML text cleaning (remove multiple line breaks) #OCTranspo #RTC
|
<ide><path>rc/org/mtransit/android/commons/HtmlUtils.java
<ide> }
<ide> }
<ide>
<del> private static final Pattern FIX_TEXT_VIEW_BR = Pattern.compile("(<ul[^>]*>|</ul>|</li>|</h[1-6]{1}>)", Pattern.CASE_INSENSITIVE);
<add> private static final Pattern LINE_BREAKS = Pattern.compile("(\\n|\\r)", Pattern.CASE_INSENSITIVE);
<add>
<add> private static final Pattern FIX_TEXT_VIEW_BR = Pattern.compile("(<ul[^>]*>|</ul>|</li>|</h[1-6]{1}>|<p[^>]*>|</p>|<div[^>]*>|</div>)",
<add> Pattern.CASE_INSENSITIVE);
<ide>
<ide> private static final String FIX_TEXT_VIEW_BR_REPLACEMENT = BR;
<ide>
<ide> private static final Pattern FIX_TEXT_VIEW_BR2 = Pattern.compile("(<li[^>]*>)", Pattern.CASE_INSENSITIVE);
<ide> private static final String FIX_TEXT_VIEW_BR_REPLACEMENT2 = "- ";
<ide>
<add> private static final String BRS_REGEX = "(<br />|<br/>|<br>)";
<add>
<add> private static final Pattern FIX_TEXT_VIEW_BR_DUPLICATE = Pattern.compile("((" + BRS_REGEX + "(\\s| )*)+)", Pattern.CASE_INSENSITIVE);
<add>
<add> private static final Pattern BR_START_ENDS = Pattern.compile("((^" + BRS_REGEX + ")|(" + BRS_REGEX + "$))", Pattern.CASE_INSENSITIVE);
<add>
<ide> public static String fixTextViewBR(String html) {
<ide> try {
<add> html = LINE_BREAKS.matcher(html).replaceAll(StringUtils.EMPTY);
<ide> html = FIX_TEXT_VIEW_BR.matcher(html).replaceAll(FIX_TEXT_VIEW_BR_REPLACEMENT);
<ide> html = FIX_TEXT_VIEW_BR2.matcher(html).replaceAll(FIX_TEXT_VIEW_BR_REPLACEMENT2);
<add> html = FIX_TEXT_VIEW_BR_DUPLICATE.matcher(html).replaceAll(FIX_TEXT_VIEW_BR_REPLACEMENT);
<add> html = BR_START_ENDS.matcher(html).replaceAll(StringUtils.EMPTY);
<ide> return html;
<ide> } catch (Exception e) {
<ide> MTLog.w(TAG, e, "Error while fixing TextView BR!");
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.