gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/**
* Copyright (c) 2010 Yahoo! Inc. 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. See accompanying LICENSE file.
*/
package org.apache.oozie.command.coord;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import org.apache.hadoop.conf.Configuration;
import org.apache.oozie.CoordinatorJobBean;
import org.apache.oozie.ErrorCode;
import org.apache.oozie.client.Job;
import org.apache.oozie.client.OozieClient;
import org.apache.oozie.command.CommandException;
import org.apache.oozie.executor.jpa.CoordJobGetJPAExecutor;
import org.apache.oozie.executor.jpa.JPAExecutorException;
import org.apache.oozie.service.JPAService;
import org.apache.oozie.service.Services;
import org.apache.oozie.test.XDataTestCase;
import org.apache.oozie.util.XConfiguration;
public class TestCoordSubmitXCommand extends XDataTestCase {
private Services services;
@Override
protected void setUp() throws Exception {
super.setUp();
services = new Services();
services.init();
cleanUpDBTables();
}
@Override
protected void tearDown() throws Exception {
services.destroy();
super.tearDown();
}
/**
* Basic test
*
* @throws Exception
*/
public void testBasicSubmit() throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"NAME\" frequency=\"${coord:days(1)}\" start=\"2009-02-01T01:00Z\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns=\"uri:oozie:coordinator:0.2\"> <controls> <concurrency>2</concurrency> "
+ "<execution>LIFO</execution> </controls> <datasets> "
+ "<dataset name=\"a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "<dataset name=\"local_a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "</datasets> <input-events> "
+ "<data-in name=\"A\" dataset=\"a\"> <instance>${coord:latest(0)}</instance> </data-in> "
+ "</input-events> "
+ "<output-events> <data-out name=\"LOCAL_A\" dataset=\"local_a\"> "
+ "<instance>${coord:current(-1)}</instance> </data-out> </output-events> <action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>${coord:dataIn('A')}</value> </property> "
+ "<property> <name>inputB</name> <value>${coord:dataOut('LOCAL_A')}</value> "
+ "</property></configuration> </workflow> </action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING");
String jobId = sc.call();
assertEquals(jobId.substring(jobId.length() - 2), "-C");
CoordinatorJobBean job = checkCoordJobs(jobId);
if (job != null) {
assertEquals(job.getTimeout(), Services.get().getConf().getInt(
"oozie.service.coord.normal.default.timeout", -2));
}
}
/**
* Basic coordinator submit test with bundleId
*
* @throws Exception
*/
public void testBasicSubmitWithBundleId() throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"NAME\" frequency=\"${coord:days(1)}\" start=\"2009-02-01T01:00Z\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns=\"uri:oozie:coordinator:0.2\"> <controls> <concurrency>2</concurrency> "
+ "<execution>LIFO</execution> </controls> <datasets> "
+ "<dataset name=\"a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "<dataset name=\"local_a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "</datasets> <input-events> "
+ "<data-in name=\"A\" dataset=\"a\"> <instance>${coord:latest(0)}</instance> </data-in> "
+ "</input-events> "
+ "<output-events> <data-out name=\"LOCAL_A\" dataset=\"local_a\"> "
+ "<instance>${coord:current(-1)}</instance> </data-out> </output-events> <action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>${coord:dataIn('A')}</value> </property> "
+ "<property> <name>inputB</name> <value>${coord:dataOut('LOCAL_A')}</value> "
+ "</property></configuration> </workflow> </action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
this.addRecordToBundleActionTable("OOZIE-B", "COORD-NAME", 0, Job.Status.PREP);
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING", "OOZIE-B", "COORD-NAME");
String jobId = sc.call();
assertEquals(jobId.substring(jobId.length() - 2), "-C");
CoordinatorJobBean job = checkCoordJobs(jobId);
if (job != null) {
assertEquals("OOZIE-B", job.getBundleId());
assertEquals("COORD-NAME", job.getAppName());
assertEquals("uri:oozie:coordinator:0.2", job.getAppNamespace());
} else {
fail();
}
}
/**
* Basic coordinator submit test from bundle but with wrong namespace
*
* @throws Exception
*/
public void testBasicSubmitWithWrongNamespace() throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"NAME\" frequency=\"${coord:days(1)}\" start=\"2009-02-01T01:00Z\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns=\"uri:oozie:coordinator:0.1\"> <controls> <concurrency>2</concurrency> "
+ "<execution>LIFO</execution> </controls> <datasets> "
+ "<dataset name=\"a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "<dataset name=\"local_a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "</datasets> <input-events> "
+ "<data-in name=\"A\" dataset=\"a\"> <instance>${coord:latest(0)}</instance> </data-in> "
+ "</input-events> "
+ "<output-events> <data-out name=\"LOCAL_A\" dataset=\"local_a\"> "
+ "<instance>${coord:current(-1)}</instance> </data-out> </output-events> <action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>${coord:dataIn('A')}</value> </property> "
+ "<property> <name>inputB</name> <value>${coord:dataOut('LOCAL_A')}</value> "
+ "</property></configuration> </workflow> </action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
this.addRecordToBundleActionTable("OOZIE-B", "COORD-NAME", 0, Job.Status.PREP);
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING", "OOZIE-B", "COORD-NAME");
try {
sc.call();
fail("Exception expected because namespace is too old when submit coordinator through bundle!");
}
catch (CommandException e) {
// should come here for namespace errors
}
}
/**
* Basic test
*
* @throws Exception
*/
public void testBasicSubmitWithSLA() throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"NAME\" frequency=\"${coord:days(1)}\" start=\"2009-02-01T01:00Z\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='uri:oozie:coordinator:0.2' xmlns:sla='uri:oozie:sla:0.1'> <controls> <timeout>10</timeout> <concurrency>2</concurrency> "
+ "<execution>LIFO</execution> </controls> <datasets> "
+ "<dataset name=\"a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "<dataset name=\"local_a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "</datasets> <input-events> "
+ "<data-in name=\"A\" dataset=\"a\"> <instance>${coord:latest(0)}</instance> </data-in> "
+ "</input-events> "
+ "<output-events> <data-out name=\"LOCAL_A\" dataset=\"local_a\"> "
+ "<instance>${coord:current(-1)}</instance> </data-out> </output-events> <action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>${coord:dataIn('A')}</value> </property> "
+ "<property> <name>inputB</name> <value>${coord:dataOut('LOCAL_A')}</value> "
+ "</property></configuration> </workflow> "
+ " <sla:info>"
+ " <sla:app-name>test-app</sla:app-name>"
+ " <sla:nominal-time>${coord:nominalTime()}</sla:nominal-time>"
+ " <sla:should-start>${5 * MINUTES}</sla:should-start>"
+ " <sla:should-end>${2 * HOURS}</sla:should-end>"
+ " <sla:notification-msg>Notifying User for ${coord:nominalTime()} nominal time </sla:notification-msg>"
+ " <sla:alert-contact>abc@yahoo.com</sla:alert-contact>"
+ " <sla:dev-contact>abc@yahoo.com</sla:dev-contact>"
+ " <sla:qa-contact>abc@yahoo.com</sla:qa-contact>"
+ " <sla:se-contact>abc@yahoo.com</sla:se-contact>"
+ " <sla:alert-frequency>LAST_HOUR</sla:alert-frequency>"
+ " <sla:alert-percentage>10</sla:alert-percentage>" + "</sla:info>" + "</action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING");
String jobId = sc.call();
assertEquals(jobId.substring(jobId.length() - 2), "-C");
checkCoordJobs(jobId);
}
/**
* Use fixed values for frequency
*
* @throws Exception
*/
public void testSubmitFixedValues() throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"NAME\" frequency=\"10\" start=\"2009-02-01T01:00Z\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns=\"uri:oozie:coordinator:0.2\"> <controls> <timeout>10</timeout> <concurrency>2</concurrency> "
+ "<execution>LIFO</execution> </controls> <datasets> "
+ "<dataset name=\"a\" frequency=\"60\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "<dataset name=\"local_a\" frequency=\"120\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "</datasets> <input-events> "
+ "<data-in name=\"A\" dataset=\"a\"> <instance>${coord:latest(0)}</instance> </data-in> "
+ "</input-events> "
+ "<output-events> <data-out name=\"LOCAL_A\" dataset=\"local_a\"> "
+ "<instance>${coord:current(-1)}</instance> </data-out> </output-events> <action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>${coord:dataIn('A')}</value> </property> "
+ "<property> <name>inputB</name> <value>${coord:dataOut('LOCAL_A')}</value> "
+ "</property></configuration> </workflow> </action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING");
String jobId = sc.call();
assertEquals(jobId.substring(jobId.length() - 2), "-C");
checkCoordJobs(jobId);
}
/**
* test schema error. Negative test case.
*
* @throws Exception
*/
public void testSchemaError() throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"NAME\" frequencyERROR=\"10\" start=\"2009-02-01T01:00Z\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns=\"uri:oozie:coordinator:0.2\"> <controls> <timeout>10</timeout> <concurrency>2</concurrency> "
+ "<execution>LIFO</execution> </controls> <datasets> "
+ "<dataset name=\"a\" frequency=\"60\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "<dataset name=\"local_a\" frequency=\"120\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "</datasets> <input-events> "
+ "<data-in name=\"A\" dataset=\"a\"> <instance>${coord:latest(0)}</instance> </data-in> "
+ "</input-events> "
+ "<output-events> <data-out name=\"LOCAL_A\" dataset=\"local_a\"> "
+ "<instance>${coord:current(-1)}</instance> </data-out> </output-events> <action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>${coord:dataIn('A')}</value> </property> "
+ "<property> <name>inputB</name> <value>${coord:dataOut('LOCAL_A')}</value> "
+ "</property></configuration> </workflow> </action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING");
String jobId = null;
try {
sc.call();
fail("Exception expected if schema has errors!");
}
catch (CommandException e) {
// should come here for schema errors
}
}
/**
* Don't include datasets, input-events, or output-events in XML.
*
* @throws Exception
*/
public void testSubmitNoDatasets() throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"NAME\" frequency=\"10\" start=\"2009-02-01T01:00Z\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns=\"uri:oozie:coordinator:0.2\"> "
+ "<controls> <timeout>10</timeout> <concurrency>2</concurrency> "
+ "<execution>LIFO</execution> </controls> "
+ "<action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>blah</value> </property> "
+ "</configuration> </workflow> </action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING");
String jobId = sc.call();
assertEquals(jobId.substring(jobId.length() - 2), "-C");
checkCoordJobs(jobId);
}
/**
* Don't include username. Negative test case.
*
* @throws Exception
*/
public void testSubmitNoUsername() throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"NAME\" frequency=\"10\" start=\"2009-02-01T01:00Z\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns=\"uri:oozie:coordinator:0.2\"> "
+ "<controls> <timeout>10</timeout> <concurrency>2</concurrency> "
+ "<execution>LIFO</execution> </controls> "
+ "<action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>blah</value> </property> "
+ "</configuration> </workflow> </action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
// conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING");
String jobId = null;
try {
sc.call();
fail("Exception expected if user.name is not set!");
}
catch (CommandException e) {
// should come here
}
}
/**
* Don't include controls in XML.
*
* @throws Exception
*/
public void testSubmitNoControls() throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"NAME\" frequency=\"10\" start=\"2009-02-01T01:00Z\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns=\"uri:oozie:coordinator:0.2\"> "
+ "<action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>blah</value> </property> "
+ "</configuration> </workflow> </action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING");
String jobId = sc.call();
assertEquals(jobId.substring(jobId.length() - 2), "-C");
checkCoordJobs(jobId);
}
/**
* Test Done Flag in Schema
*
* @throws Exception
*/
public void testSubmitWithDoneFlag() throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"NAME\" frequency=\"${coord:days(1)}\" start=\"2009-02-01T01:00Z\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns=\"uri:oozie:coordinator:0.2\"> <controls> <timeout>10</timeout> <concurrency>2</concurrency> "
+ "<execution>LIFO</execution> </controls> <datasets> "
+ "<dataset name=\"a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "<dataset name=\"local_a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> "
+ "<done-flag>consume_me</done-flag> </dataset>"
+ "<dataset name=\"local_b\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflowsb/${YEAR}/${DAY}</uri-template> "
+ "<done-flag>${MY_DONE_FLAG}</done-flag> </dataset>"
+ "</datasets> <input-events> "
+ "<data-in name=\"A\" dataset=\"a\"> <instance>${coord:latest(0)}</instance> </data-in> "
+ "<data-in name=\"B\" dataset=\"local_b\"> <instance>${coord:latest(0)}</instance> </data-in> "
+ "</input-events> "
+ "<output-events> <data-out name=\"LOCAL_A\" dataset=\"local_a\"> "
+ "<instance>${coord:current(-1)}</instance> </data-out> </output-events> <action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>${coord:dataIn('A')}</value> </property> "
+ "<property> <name>inputB</name> <value>${coord:dataOut('LOCAL_A')}</value> "
+ "</property></configuration> </workflow> </action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
conf.set("MY_DONE_FLAG", "complete");
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING");
String jobId = sc.call();
assertEquals(jobId.substring(jobId.length() - 2), "-C");
checkCoordJobs(jobId);
}
/**
* Test Done Flag in Schema
*
* @throws Exception
*/
public void testSubmitWithVarAppName() throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"${NAME}\" frequency=\"${coord:days(1)}\" start=\"2009-02-01T01:00Z\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns=\"uri:oozie:coordinator:0.3\"> <controls> <timeout>10</timeout> <concurrency>2</concurrency> "
+ "<execution>LIFO</execution> </controls> <datasets> "
+ "<dataset name=\"a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "<dataset name=\"local_a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> "
+ "<done-flag>consume_me</done-flag> </dataset>"
+ "<dataset name=\"local_b\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflowsb/${YEAR}/${DAY}</uri-template> "
+ "<done-flag>${MY_DONE_FLAG}</done-flag> </dataset>"
+ "</datasets> <input-events> "
+ "<data-in name=\"A\" dataset=\"a\"> <instance>${coord:latest(0)}</instance> </data-in> "
+ "<data-in name=\"B\" dataset=\"local_b\"> <instance>${coord:latest(0)}</instance> </data-in> "
+ "</input-events> "
+ "<output-events> <data-out name=\"LOCAL_A\" dataset=\"local_a\"> "
+ "<instance>${coord:current(-1)}</instance> </data-out> </output-events> <action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>${coord:dataIn('A')}</value> </property> "
+ "<property> <name>inputB</name> <value>${coord:dataOut('LOCAL_A')}</value> "
+ "</property></configuration> </workflow> </action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
conf.set("MY_DONE_FLAG", "complete");
conf.set("NAME", "test_app_name");
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING");
String jobId = sc.call();
assertEquals(jobId.substring(jobId.length() - 2), "-C");
CoordinatorJobBean job = checkCoordJobs(jobId);
if (job != null) {
assertEquals(job.getAppName(), "test_app_name");
}
}
/**
* Don't include controls in XML.
*
* @throws Exception
*/
public void testSubmitReservedVars() throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"NAME\" frequency=\"10\" start=\"2009-02-01T01:00Z\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns=\"uri:oozie:coordinator:0.2\"> "
+ "<action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>blah</value> </property> "
+ "</configuration> </workflow> </action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
conf.set("MINUTES", "1");
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING");
try {
sc.call();
fail("Coord job submission should fail with reserved variable definitions.");
}
catch (CommandException ce) {
}
}
private void _testConfigDefaults(boolean withDefaults) throws Exception {
Configuration conf = new XConfiguration();
String appPath = getTestCaseDir() + File.separator + "coordinator.xml";
String appXml = "<coordinator-app name=\"NAME\" frequency=\"${coord:days(1)}\" start=\"${startTime}\" end=\"2009-02-03T23:59Z\" timezone=\"UTC\" "
+ "xmlns=\"uri:oozie:coordinator:0.2\"> <controls> <concurrency>2</concurrency> "
+ "<execution>LIFO</execution> </controls> <datasets> "
+ "<dataset name=\"a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "<dataset name=\"local_a\" frequency=\"${coord:days(7)}\" initial-instance=\"2009-02-01T01:00Z\" "
+ "timezone=\"UTC\"> <uri-template>file:///tmp/coord/workflows/${YEAR}/${DAY}</uri-template> </dataset> "
+ "</datasets> <input-events> "
+ "<data-in name=\"A\" dataset=\"a\"> <instance>${coord:latest(0)}</instance> </data-in> "
+ "</input-events> "
+ "<output-events> <data-out name=\"LOCAL_A\" dataset=\"local_a\"> "
+ "<instance>${coord:current(-1)}</instance> </data-out> </output-events> <action> <workflow> <app-path>hdfs:///tmp/workflows/</app-path> "
+ "<configuration> <property> <name>inputA</name> <value>${coord:dataIn('A')}</value> </property> "
+ "<property> <name>inputB</name> <value>${coord:dataOut('LOCAL_A')}</value> "
+ "</property></configuration> </workflow> </action> </coordinator-app>";
writeToFile(appXml, appPath);
conf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
conf.set(OozieClient.USER_NAME, getTestUser());
conf.set(OozieClient.GROUP_NAME, "other");
injectKerberosInfo(conf);
CoordSubmitXCommand sc = new CoordSubmitXCommand(conf, "UNIT_TESTING");
if (withDefaults) {
String defaults = "<configuration><property><name>startTime</name>" +
"<value>2009-02-01T01:00Z</value></property></configuration>";
writeToFile(defaults, getTestCaseDir() + File.separator + CoordSubmitCommand.CONFIG_DEFAULT);
String jobId = sc.call();
assertEquals(jobId.substring(jobId.length() - 2), "-C");
}
else {
try {
sc.call();
fail();
}
catch (CommandException ex) {
assertEquals(ErrorCode.E1004, ex.getErrorCode());
}
catch (Exception ex) {
fail();
}
}
}
public void testMissingConfigDefaults() throws Exception {
_testConfigDefaults(false);
}
public void testAvailConfigDefaults() throws Exception {
_testConfigDefaults(true);
}
/**
* Helper methods
*
* @param jobId
*/
private CoordinatorJobBean checkCoordJobs(String jobId) {
try {
JPAService jpaService = Services.get().get(JPAService.class);
CoordinatorJobBean job = jpaService.execute(new CoordJobGetJPAExecutor(jobId));
return job;
}
catch (JPAExecutorException e) {
fail("Job ID " + jobId + " was not stored properly in db");
}
return null;
}
private void writeToFile(String appXml, String appPath) throws IOException {
File wf = new File(appPath);
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter(wf));
out.println(appXml);
}
catch (IOException iex) {
throw iex;
}
finally {
if (out != null) {
out.close();
}
}
}
}
| |
package org.bouncycastle.math;
import java.math.BigInteger;
import java.security.SecureRandom;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.BigIntegers;
/**
* Utility methods for generating primes and testing for primality.
*/
public abstract class Primes
{
private static final BigInteger ONE = BigInteger.valueOf(1);
private static final BigInteger TWO = BigInteger.valueOf(2);
private static final BigInteger THREE = BigInteger.valueOf(3);
/**
* Used to return the output from the
* {@linkplain Primes#enhancedMRProbablePrimeTest(BigInteger, SecureRandom, int) Enhanced
* Miller-Rabin Probabilistic Primality Test}
*/
public static class MROutput
{
private static MROutput probablyPrime()
{
return new MROutput(false, null);
}
private static MROutput provablyCompositeWithFactor(BigInteger factor)
{
return new MROutput(true, factor);
}
private static MROutput provablyCompositeNotPrimePower()
{
return new MROutput(true, null);
}
private boolean provablyComposite;
private BigInteger factor;
private MROutput(boolean provablyComposite, BigInteger factor)
{
this.provablyComposite = provablyComposite;
this.factor = factor;
}
public BigInteger getFactor()
{
return factor;
}
public boolean isProvablyComposite()
{
return provablyComposite;
}
public boolean isNotPrimePower()
{
return provablyComposite && factor == null;
}
}
/**
* Used to return the output from the
* {@linkplain Primes#generateSTRandomPrime(Digest, int, byte[]) Shawe-Taylor Random_Prime
* Routine}
*/
public static class STOutput
{
private BigInteger prime;
private byte[] primeSeed;
private int primeGenCounter;
private STOutput(BigInteger prime, byte[] primeSeed, int primeGenCounter)
{
this.prime = prime;
this.primeSeed = primeSeed;
this.primeGenCounter = primeGenCounter;
}
public BigInteger getPrime()
{
return prime;
}
public byte[] getPrimeSeed()
{
return primeSeed;
}
public int getPrimeGenCounter()
{
return primeGenCounter;
}
}
/**
* FIPS 186-4 C.6 Shawe-Taylor Random_Prime Routine
*
* Construct a provable prime number using a hash function.
*
* @param hash
* the {@link Digest} instance to use (as "Hash()"). Cannot be null.
* @param length
* the length (in bits) of the prime to be generated. Must be at least 2.
* @param inputSeed
* the seed to be used for the generation of the requested prime. Cannot be null or
* empty.
* @return an {@link STOutput} instance containing the requested prime.
*/
public static STOutput generateSTRandomPrime(Digest hash, int length, byte[] inputSeed)
{
if (hash == null)
{
throw new IllegalArgumentException("'hash' cannot be null");
}
if (length < 2)
{
throw new IllegalArgumentException("'length' must be >= 2");
}
if (inputSeed == null || inputSeed.length == 0)
{
throw new IllegalArgumentException("'inputSeed' cannot be null or empty");
}
return implSTRandomPrime(hash, length, Arrays.clone(inputSeed));
}
/**
* FIPS 186-4 C.3.2 Enhanced Miller-Rabin Probabilistic Primality Test
*
* Run several iterations of the Miller-Rabin algorithm with randomly-chosen bases. This is an
* alternative to {@link #isMRProbablePrime(BigInteger, SecureRandom, int)} that provides more
* information about a composite candidate, which may be useful when generating or validating
* RSA moduli.
*
* @param candidate
* the {@link BigInteger} instance to test for primality.
* @param random
* the source of randomness to use to choose bases.
* @param iterations
* the number of randomly-chosen bases to perform the test for.
* @return an {@link MROutput} instance that can be further queried for details.
*/
public static MROutput enhancedMRProbablePrimeTest(BigInteger candidate, SecureRandom random, int iterations)
{
checkCandidate(candidate, "candidate");
if (random == null)
{
throw new IllegalArgumentException("'random' cannot be null");
}
if (iterations < 1)
{
throw new IllegalArgumentException("'iterations' must be > 0");
}
if (candidate.bitLength() == 2)
{
return MROutput.probablyPrime();
}
if (!candidate.testBit(0))
{
return MROutput.provablyCompositeWithFactor(TWO);
}
BigInteger w = candidate;
BigInteger wSubOne = candidate.subtract(ONE);
BigInteger wSubTwo = candidate.subtract(TWO);
int a = wSubOne.getLowestSetBit();
BigInteger m = wSubOne.shiftRight(a);
for (int i = 0; i < iterations; ++i)
{
BigInteger b = BigIntegers.createRandomInRange(TWO, wSubTwo, random);
BigInteger g = b.gcd(w);
if (g.compareTo(ONE) > 0)
{
return MROutput.provablyCompositeWithFactor(g);
}
BigInteger z = b.modPow(m, w);
if (z.equals(ONE) || z.equals(wSubOne))
{
continue;
}
boolean primeToBase = false;
BigInteger x = z;
for (int j = 1; j < a; ++j)
{
z = z.modPow(TWO, w);
if (z.equals(wSubOne))
{
primeToBase = true;
break;
}
if (z.equals(ONE))
{
break;
}
x = z;
}
if (!primeToBase)
{
if (!z.equals(ONE))
{
x = z;
z = z.modPow(TWO, w);
if (!z.equals(ONE))
{
x = z;
}
}
g = x.subtract(ONE).gcd(w);
if (g.compareTo(ONE) > 0)
{
return MROutput.provablyCompositeWithFactor(g);
}
return MROutput.provablyCompositeNotPrimePower();
}
}
return MROutput.probablyPrime();
}
/**
* A fast check for small divisors, up to some implementation-specific limit.
*
* @param candidate
* the {@link BigInteger} instance to test for division by small factors.
*
* @return <code>true</code> if the candidate is found to have any small factors,
* <code>false</code> otherwise.
*/
public static boolean hasAnySmallFactors(BigInteger candidate)
{
checkCandidate(candidate, "candidate");
return implHasAnySmallFactors(candidate);
}
/**
* FIPS 186-4 C.3.1 Miller-Rabin Probabilistic Primality Test
*
* Run several iterations of the Miller-Rabin algorithm with randomly-chosen bases.
*
* @param candidate
* the {@link BigInteger} instance to test for primality.
* @param random
* the source of randomness to use to choose bases.
* @param iterations
* the number of randomly-chosen bases to perform the test for.
* @return <code>false</code> if any witness to compositeness is found amongst the chosen bases
* (so <code>candidate</code> is definitely NOT prime), or else <code>true</code>
* (indicating primality with some probability dependent on the number of iterations
* that were performed).
*/
public static boolean isMRProbablePrime(BigInteger candidate, SecureRandom random, int iterations)
{
checkCandidate(candidate, "candidate");
if (random == null)
{
throw new IllegalArgumentException("'random' cannot be null");
}
if (iterations < 1)
{
throw new IllegalArgumentException("'iterations' must be > 0");
}
if (candidate.bitLength() == 2)
{
return true;
}
if (!candidate.testBit(0))
{
return false;
}
BigInteger w = candidate;
BigInteger wSubOne = candidate.subtract(ONE);
BigInteger wSubTwo = candidate.subtract(TWO);
int a = wSubOne.getLowestSetBit();
BigInteger m = wSubOne.shiftRight(a);
for (int i = 0; i < iterations; ++i)
{
BigInteger b = BigIntegers.createRandomInRange(TWO, wSubTwo, random);
if (!implMRProbablePrimeToBase(w, wSubOne, m, a, b))
{
return false;
}
}
return true;
}
/**
* FIPS 186-4 C.3.1 Miller-Rabin Probabilistic Primality Test (to a fixed base).
*
* Run a single iteration of the Miller-Rabin algorithm against the specified base.
*
* @param candidate
* the {@link BigInteger} instance to test for primality.
* @param base
* the source of randomness to use to choose bases.
* @return <code>false</code> if the specified base is a witness to compositeness (so
* <code>candidate</code> is definitely NOT prime), or else <code>true</code>.
*/
public static boolean isMRProbablePrimeToBase(BigInteger candidate, BigInteger base)
{
checkCandidate(candidate, "candidate");
checkCandidate(base, "base");
if (base.compareTo(candidate.subtract(ONE)) >= 0)
{
throw new IllegalArgumentException("'base' must be < ('candidate' - 1)");
}
if (candidate.bitLength() == 2)
{
return true;
}
BigInteger w = candidate;
BigInteger wSubOne = candidate.subtract(ONE);
int a = wSubOne.getLowestSetBit();
BigInteger m = wSubOne.shiftRight(a);
return implMRProbablePrimeToBase(w, wSubOne, m, a, base);
}
private static void checkCandidate(BigInteger n, String name)
{
if (n == null || n.signum() < 1 || n.bitLength() < 2)
{
throw new IllegalArgumentException("'" + name + "' must be non-null and >= 2");
}
}
private static boolean implHasAnySmallFactors(BigInteger x)
{
/*
* Bundle trial divisors into ~32-bit moduli then use fast tests on the ~32-bit remainders.
*/
int m = 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23;
int r = x.mod(BigInteger.valueOf(m)).intValue();
if ((r & 1) != 0 && (r % 3) != 0 && (r % 5) != 0 && (r % 7) != 0 && (r % 11) != 0
&& (r % 13) != 0 && (r % 17) != 0 && (r % 19) != 0 && (r % 23) != 0)
{
m = 29 * 31 * 37 * 41 * 43;
r = x.mod(BigInteger.valueOf(m)).intValue();
if ((r % 29) != 0 && (r % 31) != 0 && (r % 37) != 0 && (r % 41) != 0 && (r % 43) != 0)
{
m = 47 * 53 * 59 * 61 * 67;
r = x.mod(BigInteger.valueOf(m)).intValue();
if ((r % 47) != 0 && (r % 53) != 0 && (r % 59) != 0 && (r % 61) != 0 && (r % 67) != 0)
{
m = 71 * 73 * 79 * 83;
r = x.mod(BigInteger.valueOf(m)).intValue();
if ((r % 71) != 0 && (r % 73) != 0 && (r % 79) != 0 && (r % 83) != 0)
{
m = 89 * 97 * 101 * 103;
r = x.mod(BigInteger.valueOf(m)).intValue();
if ((r % 89) != 0 && (r % 97) != 0 && (r % 101) != 0 && (r % 103) != 0)
{
m = 107 * 109 * 113 * 127;
r = x.mod(BigInteger.valueOf(m)).intValue();
if ((r % 107) != 0 && (r % 109) != 0 && (r % 113) != 0 && (r % 127) != 0)
{
return false;
}
}
}
}
}
}
return true;
}
private static boolean implMRProbablePrimeToBase(BigInteger w, BigInteger wSubOne, BigInteger m, int a, BigInteger b)
{
BigInteger z = b.modPow(m, w);
if (z.equals(ONE) || z.equals(wSubOne))
{
return true;
}
boolean result = false;
for (int j = 1; j < a; ++j)
{
z = z.modPow(TWO, w);
if (z.equals(wSubOne))
{
result = true;
break;
}
if (z.equals(ONE))
{
return false;
}
}
return result;
}
private static STOutput implSTRandomPrime(Digest d, int length, byte[] primeSeed)
{
int dLen = d.getDigestSize();
if (length < 33)
{
int primeGenCounter = 0;
byte[] c0 = new byte[dLen];
byte[] c1 = new byte[dLen];
for (;;)
{
hash(d, primeSeed, c0, 0);
inc(primeSeed, 1);
hash(d, primeSeed, c1, 0);
inc(primeSeed, 1);
int c = extract32(c0) ^ extract32(c1);
c &= (-1 >>> (32 - length));
c |= (1 << (length - 1)) | 1;
++primeGenCounter;
long c64 = c & 0xFFFFFFFFL;
if (isPrime32(c64))
{
return new STOutput(BigInteger.valueOf(c64), primeSeed, primeGenCounter);
}
if (primeGenCounter > (4 * length))
{
throw new IllegalStateException("Too many iterations in Shawe-Taylor Random_Prime Routine");
}
}
}
STOutput rec = implSTRandomPrime(d, (length + 3)/2, primeSeed);
BigInteger c0 = rec.getPrime();
primeSeed = rec.getPrimeSeed();
int primeGenCounter = rec.getPrimeGenCounter();
int outlen = 8 * dLen;
int iterations = (length - 1)/outlen;
int oldCounter = primeGenCounter;
BigInteger x = hashGen(d, primeSeed, iterations + 1);
x = x.mod(ONE.shiftLeft(length - 1)).setBit(length - 1);
BigInteger c0x2 = c0.shiftLeft(1);
BigInteger tx2 = x.subtract(ONE).divide(c0x2).add(ONE).shiftLeft(1);
int dt = 0;
BigInteger c = tx2.multiply(c0).add(ONE);
/*
* TODO Since the candidate primes are generated by constant steps ('c0x2'),
* sieving could be used here in place of the 'hasAnySmallFactors' approach.
*/
for (;;)
{
if (c.bitLength() > length)
{
tx2 = ONE.shiftLeft(length - 1).subtract(ONE).divide(c0x2).add(ONE).shiftLeft(1);
c = tx2.multiply(c0).add(ONE);
}
++primeGenCounter;
/*
* This is an optimization of the original algorithm, using trial division to screen out
* many non-primes quickly.
*
* NOTE: 'primeSeed' is still incremented as if we performed the full check!
*/
if (!implHasAnySmallFactors(c))
{
BigInteger a = hashGen(d, primeSeed, iterations + 1);
a = a.mod(c.subtract(THREE)).add(TWO);
tx2 = tx2.add(BigInteger.valueOf(dt));
dt = 0;
BigInteger z = a.modPow(tx2, c);
if (c.gcd(z.subtract(ONE)).equals(ONE) && z.modPow(c0, c).equals(ONE))
{
return new STOutput(c, primeSeed, primeGenCounter);
}
}
else
{
inc(primeSeed, iterations + 1);
}
if (primeGenCounter >= ((4 * length) + oldCounter))
{
throw new IllegalStateException("Too many iterations in Shawe-Taylor Random_Prime Routine");
}
dt += 2;
c = c.add(c0x2);
}
}
private static int extract32(byte[] bs)
{
int result = 0;
int count = Math.min(4, bs.length);
for (int i = 0; i < count; ++i)
{
int b = bs[bs.length - (i + 1)] & 0xFF;
result |= (b << (8 * i));
}
return result;
}
private static void hash(Digest d, byte[] input, byte[] output, int outPos)
{
d.update(input, 0, input.length);
d.doFinal(output, outPos);
}
private static BigInteger hashGen(Digest d, byte[] seed, int count)
{
int dLen = d.getDigestSize();
int pos = count * dLen;
byte[] buf = new byte[pos];
for (int i = 0; i < count; ++i)
{
pos -= dLen;
hash(d, seed, buf, pos);
inc(seed, 1);
}
return new BigInteger(1, buf);
}
private static void inc(byte[] seed, int c)
{
int pos = seed.length;
while (c > 0 && --pos >= 0)
{
c += (seed[pos] & 0xFF);
seed[pos] = (byte)c;
c >>>= 8;
}
}
private static boolean isPrime32(long x)
{
if (x >>> 32 != 0L)
{
throw new IllegalArgumentException("Size limit exceeded");
}
/*
* Use wheel factorization with 2, 3, 5 to select trial divisors.
*/
if (x <= 5L)
{
return x == 2L || x == 3L || x == 5L;
}
if ((x & 1L) == 0L || (x % 3L) == 0L || (x % 5L) == 0L)
{
return false;
}
long[] ds = new long[]{ 1L, 7L, 11L, 13L, 17L, 19L, 23L, 29L };
long base = 0L;
for (int pos = 1; ; pos = 0)
{
/*
* Trial division by wheel-selected divisors
*/
while (pos < ds.length)
{
long d = base + ds[pos];
if (x % d == 0L)
{
return x < 30L;
}
++pos;
}
base += 30L;
if (base * base >= x)
{
return true;
}
}
}
}
| |
/*
* Copyright (c) 2010-2013 Evolveum
*
* 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.evolveum.midpoint.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
/**
*
* @author lazyman
*
*/
public final class JAXBUtil {
private static final Trace LOGGER = TraceManager.getTrace(JAXBUtil.class);
private static final Map<Package, String> packageNamespaces = new HashMap<>();
private static final Map<QName, Class> classQNames = new HashMap<>();
private static final Set<String> scannedPackages = new HashSet<>();
public static String getSchemaNamespace(Package pkg) {
XmlSchema xmlSchemaAnn = pkg.getAnnotation(XmlSchema.class);
if (xmlSchemaAnn == null) {
return null;
}
return xmlSchemaAnn.namespace();
}
public static <T> String getTypeLocalName(Class<T> type) {
XmlType xmlTypeAnn = type.getAnnotation(XmlType.class);
if (xmlTypeAnn == null) {
return null;
}
return xmlTypeAnn.name();
}
public static <T> QName getTypeQName(Class<T> type) {
String namespace = getSchemaNamespace(type.getPackage());
String localPart = getTypeLocalName(type);
if (localPart == null) {
return null;
}
return new QName(namespace, localPart);
}
public static boolean isElement(Object element) {
if (element == null) {
return false;
}
if (element instanceof Element) {
return true;
} else if (element instanceof JAXBElement) {
return true;
} else {
return false;
}
}
public static QName getElementQName(Object element) {
if (element == null) {
return null;
}
if (element instanceof Element) {
return DOMUtil.getQName((Element) element);
} else if (element instanceof JAXBElement) {
return ((JAXBElement<?>) element).getName();
} else {
throw new IllegalArgumentException("Not an element: " + element);
}
}
public static String getElementLocalName(Object element) {
if (element == null) {
return null;
}
if (element instanceof Element) {
return ((Element) element).getLocalName();
} else if (element instanceof JAXBElement) {
return ((JAXBElement<?>) element).getName().getLocalPart();
} else {
throw new IllegalArgumentException("Not an element: " + element);
}
}
/**
* Returns short description of element content for diagnostics use (logs,
* dumps).
*
* Works with DOM and JAXB elements.
*
* @param element
* DOM or JAXB element
* @return short description of element content
*/
public static String getTextContentDump(Object element) {
if (element == null) {
return null;
}
if (element instanceof Element) {
return ((Element) element).getTextContent();
} else {
return element.toString();
}
}
/**
* @param element
* @return
*/
public static Document getDocument(Object element) {
if (element instanceof Element) {
return ((Element) element).getOwnerDocument();
} else {
return DOMUtil.getDocument();
}
}
/**
* Looks for an element with specified name. Considers both DOM and JAXB
* elements. Assumes single element instance in the list.
*
* @param elements
* @param elementName
*/
public static Object findElement(List<Object> elements, QName elementName) {
if (elements == null) {
return null;
}
for (Object element : elements) {
if (elementName.equals(getElementQName(element))) {
return element;
}
}
return null;
}
/**
* @param parentElement
* @return
*/
@SuppressWarnings("unchecked")
public static List<Object> listChildElements(Object parentElement) {
if (parentElement == null) {
return null;
}
List<Object> childElements = new ArrayList<Object>();
if (parentElement instanceof Element) {
Element parentEl = (Element) parentElement;
NodeList childNodes = parentEl.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
if (item.getNodeType() == Node.ELEMENT_NODE) {
childElements.add(item);
}
}
} else if (parentElement instanceof JAXBElement) {
JAXBElement<?> jaxbElement = (JAXBElement<?>)parentElement;
Object jaxbObject = jaxbElement.getValue();
Method xsdAnyMethod = lookForXsdAnyElementMethod(jaxbObject);
if (xsdAnyMethod == null) {
throw new IllegalArgumentException("No xsd any method in "+jaxbObject);
}
Object result = null;
try {
result = xsdAnyMethod.invoke(jaxbObject);
} catch (IllegalArgumentException e) {
throw new IllegalStateException("Unable to invoke xsd any method "+xsdAnyMethod.getName()+" on "+jaxbObject+": "+e.getMessage(),e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unable to invoke xsd any method "+xsdAnyMethod.getName()+" on "+jaxbObject+": "+e.getMessage(),e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Unable to invoke xsd any method "+xsdAnyMethod.getName()+" on "+jaxbObject+": "+e.getMessage(),e);
}
try {
childElements = (List<Object>)result;
} catch (ClassCastException e) {
throw new IllegalStateException("Xsd any method "+xsdAnyMethod.getName()+" on "+jaxbObject+" returned unexpected type "+result.getClass(),e);
}
} else {
throw new IllegalArgumentException("Not an element: " + parentElement + " ("
+ parentElement.getClass().getName() + ")");
}
return childElements;
}
private static Method lookForXsdAnyElementMethod(Object jaxbObject) {
Class<? extends Object> jaxbClass = jaxbObject.getClass();
for (Method method: jaxbClass.getMethods()) {
for (Annotation annotation: method.getAnnotations()) {
if (annotation.annotationType().isAssignableFrom(XmlAnyElement.class)) {
return method;
}
}
}
return null;
}
public static <T> Class<T> findClassForType(QName typeName, Package pkg) {
String namespace = packageNamespaces.get(pkg);
if (namespace == null) {
XmlSchema xmlSchemaAnnotation = pkg.getAnnotation(XmlSchema.class);
namespace = xmlSchemaAnnotation.namespace();
packageNamespaces.put(pkg, namespace);
}
if (namespace == null) {
throw new IllegalArgumentException("No namespace annotation in "+pkg);
}
if (!namespace.equals(typeName.getNamespaceURI())) {
throw new IllegalArgumentException("Looking for type in namespace " + typeName.getNamespaceURI() +
", but the package annotation indicates namespace " + namespace);
}
Class clazz = classQNames.get(typeName);
if (clazz != null && pkg.equals(clazz.getPackage())) {
return clazz;
}
if (!scannedPackages.contains(pkg)) {
scannedPackages.add(pkg.getName());
for (Class c : ClassPathUtil.listClasses(pkg)) {
QName foundTypeQName = getTypeQName(c);
if (foundTypeQName != null) {
classQNames.put(foundTypeQName, c);
}
if (typeName.equals(foundTypeQName)) {
return c;
}
}
}
return null;
}
public static boolean compareElementList(List<Object> aList, List<Object> bList, boolean considerNamespacePrefixes) {
if (aList.size() != bList.size()) {
return false;
}
Iterator<Object> bIterator = bList.iterator();
for (Object a: aList) {
Object b = bIterator.next();
if (a instanceof Element) {
if (!(b instanceof Element)) {
return false;
}
if (!DOMUtil.compareElement((Element)a, (Element)b, considerNamespacePrefixes)) {
return false;
}
} else {
if (!a.equals(b)) {
return false;
}
}
}
return true;
}
}
| |
/*
* 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.pig.backend.hadoop.executionengine.fetch;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pig.PigConfiguration;
import org.apache.pig.backend.datastorage.DataStorageException;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PhyPlanSetter;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.PhysicalOperator;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhyPlanVisitor;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhysicalPlan;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POCollectedGroup;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POCounter;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POCross;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.PODemux;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.PODistinct;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POFRJoin;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POGlobalRearrange;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POLoad;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POLocalRearrange;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POMergeCogroup;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POMergeJoin;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.PONative;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POOptimizedForEach;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POPackage;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POPartialAgg;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POPartitionRearrange;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POPreCombinerLocalRearrange;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.PORank;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POSkewedJoin;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POSort;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POSplit;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POStore;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POStream;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.util.PlanHelper;
import org.apache.pig.impl.PigContext;
import org.apache.pig.impl.PigImplConstants;
import org.apache.pig.impl.builtin.SampleLoader;
import org.apache.pig.impl.plan.DepthFirstWalker;
import org.apache.pig.impl.plan.VisitorException;
import org.apache.pig.impl.util.Utils;
/**
* FetchOptimizer determines whether the entire physical plan is fetchable, meaning
* that the task's result can be directly read (fetched) from the underlying storage
* rather than creating MR jobs. During the check {@link FetchablePlanVisitor} is used
* to walk through the plan.
*
*/
public class FetchOptimizer {
private static final Log LOG = LogFactory.getLog(FetchOptimizer.class);
/**
* Checks whether the fetch is enabled
*
* @param pc
* @return true if fetching is enabled
*/
public static boolean isFetchEnabled(PigContext pc) {
return "true".equalsIgnoreCase(
pc.getProperties().getProperty(PigConfiguration.PIG_OPT_FETCH, "true"));
}
/**
* Visits the plan with {@link FetchablePlanVisitor} and checks whether the
* plan is fetchable.
*
* @param pc PigContext
* @param pp the physical plan to be examined
* @return true if the plan is fetchable
* @throws VisitorException
*/
public static boolean isPlanFetchable(PigContext pc, PhysicalPlan pp) throws VisitorException {
if (isEligible(pc, pp)) {
FetchablePlanVisitor fpv = new FetchablePlanVisitor(pc, pp);
fpv.visit();
// Plan is fetchable only if FetchablePlanVisitor returns true AND
// limit is present in the plan, i.e: limit is pushed up to the loader.
// Limit is a safeguard. If the input is large, and there is no limit,
// fetch optimizer will fetch the entire input to the client. That can be dangerous.
if (!fpv.isPlanFetchable()) {
return false;
}
for (POLoad load : PlanHelper.getPhysicalOperators(pp, POLoad.class)) {
if (load.getLimit() == -1) {
return false;
}
}
pc.getProperties().setProperty(PigImplConstants.CONVERTED_TO_FETCH, "true");
init(pp);
return true;
}
return false;
}
private static void init(PhysicalPlan pp) throws VisitorException {
//mark POStream ops 'fetchable'
LinkedList<POStream> posList = PlanHelper.getPhysicalOperators(pp, POStream.class);
for (POStream pos : posList) {
pos.setFetchable(true);
}
}
/**
* Checks whether the plan fulfills the prerequisites needed for fetching.
*
* @param pc PigContext
* @param pp the physical plan to be examined
* @return
*/
private static boolean isEligible(PigContext pc, PhysicalPlan pp) {
if (!isFetchEnabled(pc)) {
return false;
}
List<PhysicalOperator> roots = pp.getRoots();
for (PhysicalOperator po : roots) {
if (!(po instanceof POLoad)) {
String msg = "Expected physical operator at root is POLoad. Found : "
+ po.getClass().getCanonicalName() + ". Fetch optimizer will be disabled.";
LOG.debug(msg);
return false;
}
}
//consider single leaf jobs only
int leafSize = pp.getLeaves().size();
if (pp.getLeaves().size() != 1) {
LOG.debug("Expected physical plan should have one leaf. Found " + leafSize);
return false;
}
return true;
}
/**
* A plan is considered 'fetchable' if:
* <pre>
* - it contains only: LIMIT, FILTER, FOREACH, STREAM, UNION(no implicit SPLIT is allowed)
* - no STORE
* - no scalar aliases ({@link org.apache.pig.impl.builtin.ReadScalars ReadScalars})
* - {@link org.apache.pig.LoadFunc LoadFunc} is not a {@link org.apache.pig.impl.builtin.SampleLoader SampleLoader}
* </pre>
*/
private static class FetchablePlanVisitor extends PhyPlanVisitor {
private boolean planFetchable = true;
private PigContext pc;
public FetchablePlanVisitor(PigContext pc, PhysicalPlan plan) {
super(plan, new DepthFirstWalker<PhysicalOperator, PhysicalPlan>(plan));
this.pc = pc;
}
@Override
public void visit() throws VisitorException {
super.visit();
}
@Override
public void visitLoad(POLoad ld) throws VisitorException{
if (ld.getLoadFunc() instanceof SampleLoader) {
planFetchable = false;
}
}
@Override
public void visitStore(POStore st) throws VisitorException{
String basePathName = st.getSFile().getFileName();
//plan is fetchable if POStore belongs to EXPLAIN
if ("fakefile".equals(basePathName)) {
return;
}
//Otherwise check if target storage format equals to the intermediate storage format
//and its path points to a temporary storage path
boolean hasTmpStorageClass = st.getStoreFunc().getClass()
.equals(Utils.getTmpFileStorageClass(pc.getProperties()));
try {
boolean hasTmpTargetPath = isTempPath(basePathName);
if (!(hasTmpStorageClass && hasTmpTargetPath)) {
planFetchable = false;
}
}
catch (IOException e) {
String msg = "Internal error. Could not retrieve temporary store location.";
throw new VisitorException(msg, e);
}
}
@Override
public void visitNative(PONative nat) throws VisitorException {
planFetchable = false;
}
@Override
public void visitCollectedGroup(POCollectedGroup mg) throws VisitorException {
planFetchable = false;
}
@Override
public void visitLocalRearrange(POLocalRearrange lr) throws VisitorException {
planFetchable = false;
}
@Override
public void visitGlobalRearrange(POGlobalRearrange gr) throws VisitorException {
planFetchable = false;
}
@Override
public void visitPackage(POPackage pkg) throws VisitorException {
planFetchable = false;
}
@Override
public void visitSplit(POSplit spl) throws VisitorException {
planFetchable = false;
}
@Override
public void visitDemux(PODemux demux) throws VisitorException {
planFetchable = false;
}
@Override
public void visitCounter(POCounter poCounter) throws VisitorException {
planFetchable = false;
}
@Override
public void visitRank(PORank rank) throws VisitorException {
planFetchable = false;
}
@Override
public void visitDistinct(PODistinct distinct) throws VisitorException {
planFetchable = false;
}
@Override
public void visitSort(POSort sort) throws VisitorException {
planFetchable = false;
}
@Override
public void visitCross(POCross cross) throws VisitorException {
planFetchable = false;
}
@Override
public void visitFRJoin(POFRJoin join) throws VisitorException {
planFetchable = false;
}
@Override
public void visitMergeJoin(POMergeJoin join) throws VisitorException {
planFetchable = false;
}
@Override
public void visitMergeCoGroup(POMergeCogroup mergeCoGrp) throws VisitorException {
planFetchable = false;
}
@Override
public void visitSkewedJoin(POSkewedJoin sk) throws VisitorException {
planFetchable = false;
}
@Override
public void visitPartitionRearrange(POPartitionRearrange pr) throws VisitorException {
planFetchable = false;
}
@Override
public void visitPOOptimizedForEach(POOptimizedForEach optimizedForEach)
throws VisitorException {
planFetchable = false;
}
@Override
public void visitPreCombinerLocalRearrange(
POPreCombinerLocalRearrange preCombinerLocalRearrange) {
planFetchable = false;
}
@Override
public void visitPartialAgg(POPartialAgg poPartialAgg) {
planFetchable = false;
}
private boolean isPlanFetchable() {
return planFetchable;
}
private boolean isTempPath(String basePathName) throws DataStorageException {
String tdir = pc.getProperties().getProperty("pig.temp.dir", "/tmp");
String tempStore = pc.getDfs().asContainer(tdir + "/temp").toString();
Matcher matcher = Pattern.compile(tempStore + "-?[0-9]+").matcher(basePathName);
return matcher.lookingAt();
}
}
}
| |
package org.basex.query.util.regex;
import java.util.*;
/**
* Escape sequence.
*
* @author BaseX Team 2005-22, BSD License
* @author Leo Woerteler
*/
public final class Escape extends RegExp {
/** Comparator for int ranges. */
private static final Comparator<int[]> CMP = Comparator.comparingInt(o -> o[0]);
/** Character classes. */
private static final Map<String, CharRange[]> MAP = new HashMap<>();
/** Initial name characters. */
private static final String INITIAL;
/** Everything except initial name characters. */
private static final String NOT_INITIAL;
/** Name characters. */
private static final String CHAR;
/** Everything except name characters. */
private static final String NOT_CHAR;
/** Word characters. */
private static final String WORD;
/** Everything except word characters. */
private static final String NOT_WORD;
/** Digits. */
private static final String DIGIT = "\\p{Nd}";
/** Everything except digits. */
private static final String NOT_DIGIT = "\\P{Nd}";
/** Image. */
private final String img;
/**
* Constructor.
* @param img image string
*/
private Escape(final String img) {
this.img = img;
}
/**
* Creates a regular expression from the given escape sequence.
* @param esc escape sequence
* @return regular expression
*/
public static RegExp get(final String esc) {
if(esc.startsWith("\\p{Is") || esc.startsWith("\\P{Is")) {
final CharRange[] rng = MAP.get(esc);
return rng != null ? new CharClass(new CharGroup(rng), null) : null;
}
final String e;
switch(esc.charAt(1)) {
case 'i': e = '[' + INITIAL + ']'; break;
case 'I': e = '[' + NOT_INITIAL + ']'; break;
case 'c': e = '[' + CHAR + ']'; break;
case 'C': e = '[' + NOT_CHAR + ']'; break;
case 'd': e = DIGIT; break;
case 'D': e = NOT_DIGIT; break;
case 'w': e = '[' + WORD + ']'; break;
case 'W': e = '[' + NOT_WORD + ']'; break;
default: e = esc;
}
return new Escape(e);
}
/**
* Gets the character escaped by the given single escape.
* @param single single-char escape sequence
* @return the escaped char
*/
public static char getCp(final String single) {
switch(single.charAt(1)) {
case 'n': return '\n';
case 'r': return '\r';
case 't': return '\t';
default: return single.charAt(1);
}
}
/**
* Translates the given escape into character ranges if possible.
* @param esc escape sequence
* @return array of regular expressions suitable for char groups
*/
public static RegExp[] inGroup(final String esc) {
if(esc.startsWith("\\p{Is") || esc.startsWith("\\P{Is")) {
final CharRange[] rng = MAP.get(esc);
if(rng != null) return rng;
}
if(esc.length() > 2) return new RegExp[] { new Escape(esc) };
final String e;
switch(esc.charAt(1)) {
case 'i': e = INITIAL; break;
case 'I': e = NOT_INITIAL; break;
case 'c': e = CHAR; break;
case 'C': e = NOT_CHAR; break;
case 'd': e = DIGIT; break;
case 'D': e = NOT_DIGIT; break;
case 'w': e = WORD; break;
case 'W': e = NOT_WORD; break;
default: e = esc;
}
return new RegExp[] { new Escape(e) };
}
@Override
void toRegEx(final StringBuilder sb) {
sb.append(img);
}
/**
* Reads ranges from a string.
* @param string input string
* @return ranges
*/
private static int[][] read(final String string) {
final ArrayList<int[]> ranges = new ArrayList<>();
final int sl = string.length();
for(int s = 0; s < sl;) {
final int[] rng = new int[2];
s += Character.charCount(rng[0] = string.codePointAt(s));
s += Character.charCount(rng[1] = string.codePointAt(s));
ranges.add(rng);
}
return ranges.toArray(new int[0][]);
}
/**
* Merges codepoint ranges.
* @param rss ranges
* @return merged ranges
*/
private static int[][] merge(final int[][]... rss) {
final ArrayList<int[]> ranges = new ArrayList<>();
for(final int[][] rs : rss) Collections.addAll(ranges, rs);
ranges.sort(CMP);
for(int i = 0; i < ranges.size(); i++) {
final int[] rng = ranges.get(i);
while(i + 1 < ranges.size()) {
final int[] rng2 = ranges.get(i + 1);
if(rng2[0] - rng[1] > 1) break;
rng[1] = rng2[1];
ranges.remove(i + 1);
}
}
return ranges.toArray(new int[0][]);
}
/**
* Inverts code point ranges.
* @param rng ranges
* @return inverted ranges
*/
private static int[][] invert(final int[][] rng) {
int start = Character.MIN_CODE_POINT;
final ArrayList<int[]> ranges = new ArrayList<>();
for(final int[] in : rng) {
if(in[0] - 1 >= start) ranges.add(new int[] { start, in[0] - 1 });
start = in[1] + 1;
}
if(start <= Character.MAX_CODE_POINT)
ranges.add(new int[] { start, Character.MAX_CODE_POINT });
return ranges.toArray(new int[0][]);
}
/**
* Serializes the given ranges to a string.
* @param ranges ranges to serialize
* @return resulting string
*/
private static String serialize(final int[][] ranges) {
final StringBuilder sb = new StringBuilder();
for(final int[] rng : ranges) {
sb.append(escape(rng[0]));
if(rng[1] != rng[0]) sb.append('-').append(escape(rng[1]));
}
return sb.toString();
}
/**
* Escapes code points for use in character ranges.
* @param cp code point
* @return char representation
*/
static char[] escape(final int cp) {
switch(cp) {
case '[':
case ']':
case '-':
case '\\':
case '^':
return new char[] { '\\', (char) cp };
case '\n':
return new char[] { '\\', 'n' };
case '\r':
return new char[] { '\\', 'r' };
case '\t':
return new char[] { '\\', 't' };
default:
return Character.toChars(cp);
}
}
/**
* Adds a new named character range to the map.
* @param m map
* @param n name
* @param r range
*/
private static void add(final Map<String, int[][]> m, final String n, final int[] r) {
final int[][] old = m.get(n), nw = { r };
m.put(n, old == null ? nw : merge(old, nw));
}
static {
// taken from http://www.w3.org/TR/2000/WD-xml-2e-20000814#NT-Letter
final int[][] baseChar = read("\u0041\u005A\u0061\u007A\u00C0\u00D6\u00D8\u00F6" +
"\u00F8\u00FF\u0100\u0131\u0134\u013E\u0141\u0148\u014A\u017E\u0180\u01C3\u01CD" +
"\u01F0\u01F4\u01F5\u01FA\u0217\u0250\u02A8\u02BB\u02C1\u0386\u0386\u0388\u038A" +
"\u038C\u038C\u038E\u03A1\u03A3\u03CE\u03D0\u03D6\u03DA\u03DA\u03DC\u03DC\u03DE" +
"\u03DE\u03E0\u03E0\u03E2\u03F3\u0401\u040C\u040E\u044F\u0451\u045C\u045E\u0481" +
"\u0490\u04C4\u04C7\u04C8\u04CB\u04CC\u04D0\u04EB\u04EE\u04F5\u04F8\u04F9\u0531" +
"\u0556\u0559\u0559\u0561\u0586\u05D0\u05EA\u05F0\u05F2\u0621\u063A\u0641\u064A" +
"\u0671\u06B7\u06BA\u06BE\u06C0\u06CE\u06D0\u06D3\u06D5\u06D5\u06E5\u06E6\u0905" +
"\u0939\u093D\u093D\u0958\u0961\u0985\u098C\u098F\u0990\u0993\u09A8\u09AA\u09B0" +
"\u09B2\u09B2\u09B6\u09B9\u09DC\u09DD\u09DF\u09E1\u09F0\u09F1\u0A05\u0A0A\u0A0F" +
"\u0A10\u0A13\u0A28\u0A2A\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59\u0A5C" +
"\u0A5E\u0A5E\u0A72\u0A74\u0A85\u0A8B\u0A8D\u0A8D\u0A8F\u0A91\u0A93\u0AA8\u0AAA" +
"\u0AB0\u0AB2\u0AB3\u0AB5\u0AB9\u0ABD\u0ABD\u0AE0\u0AE0\u0B05\u0B0C\u0B0F\u0B10" +
"\u0B13\u0B28\u0B2A\u0B30\u0B32\u0B33\u0B36\u0B39\u0B3D\u0B3D\u0B5C\u0B5D\u0B5F" +
"\u0B61\u0B85\u0B8A\u0B8E\u0B90\u0B92\u0B95\u0B99\u0B9A\u0B9C\u0B9C\u0B9E\u0B9F" +
"\u0BA3\u0BA4\u0BA8\u0BAA\u0BAE\u0BB5\u0BB7\u0BB9\u0C05\u0C0C\u0C0E\u0C10\u0C12" +
"\u0C28\u0C2A\u0C33\u0C35\u0C39\u0C60\u0C61\u0C85\u0C8C\u0C8E\u0C90\u0C92\u0CA8" +
"\u0CAA\u0CB3\u0CB5\u0CB9\u0CDE\u0CDE\u0CE0\u0CE1\u0D05\u0D0C\u0D0E\u0D10\u0D12" +
"\u0D28\u0D2A\u0D39\u0D60\u0D61\u0E01\u0E2E\u0E30\u0E30\u0E32\u0E33\u0E40\u0E45" +
"\u0E81\u0E82\u0E84\u0E84\u0E87\u0E88\u0E8A\u0E8A\u0E8D\u0E8D\u0E94\u0E97\u0E99" +
"\u0E9F\u0EA1\u0EA3\u0EA5\u0EA5\u0EA7\u0EA7\u0EAA\u0EAB\u0EAD\u0EAE\u0EB0\u0EB0" +
"\u0EB2\u0EB3\u0EBD\u0EBD\u0EC0\u0EC4\u0F40\u0F47\u0F49\u0F69\u10A0\u10C5\u10D0" +
"\u10F6\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109\u110B\u110C\u110E\u1112" +
"\u113C\u113C\u113E\u113E\u1140\u1140\u114C\u114C\u114E\u114E\u1150\u1150\u1154" +
"\u1155\u1159\u1159\u115F\u1161\u1163\u1163\u1165\u1165\u1167\u1167\u1169\u1169" +
"\u116D\u116E\u1172\u1173\u1175\u1175\u119E\u119E\u11A8\u11A8\u11AB\u11AB\u11AE" +
"\u11AF\u11B7\u11B8\u11BA\u11BA\u11BC\u11C2\u11EB\u11EB\u11F0\u11F0\u11F9\u11F9" +
"\u1E00\u1E9B\u1EA0\u1EF9\u1F00\u1F15\u1F18\u1F1D\u1F20\u1F45\u1F48\u1F4D\u1F50" +
"\u1F57\u1F59\u1F59\u1F5B\u1F5B\u1F5D\u1F5D\u1F5F\u1F7D\u1F80\u1FB4\u1FB6\u1FBC" +
"\u1FBE\u1FBE\u1FC2\u1FC4\u1FC6\u1FCC\u1FD0\u1FD3\u1FD6\u1FDB\u1FE0\u1FEC\u1FF2" +
"\u1FF4\u1FF6\u1FFC\u2126\u2126\u212A\u212B\u212E\u212E\u2180\u2182\u3041\u3094" +
"\u30A1\u30FA\u3105\u312C\uAC00\uD7A3");
final int[][] ideographic = read("\u4E00\u9FA5\u3007\u3007\u3021\u3029");
final int[][] combiningChar = read("\u0300\u0345\u0360\u0361\u0483\u0486\u0591" +
"\u05A1\u05A3\u05B9\u05BB\u05BD\u05BF\u05BF\u05C1\u05C2\u05C4\u05C4\u064B\u0652" +
"\u0670\u0670\u06D6\u06DC\u06DD\u06DF\u06E0\u06E4\u06E7\u06E8\u06EA\u06ED\u0901" +
"\u0903\u093C\u093C\u093E\u094C\u094D\u094D\u0951\u0954\u0962\u0963\u0981\u0983" +
"\u09BC\u09BC\u09BE\u09BE\u09BF\u09BF\u09C0\u09C4\u09C7\u09C8\u09CB\u09CD\u09D7" +
"\u09D7\u09E2\u09E3\u0A02\u0A02\u0A3C\u0A3C\u0A3E\u0A3E\u0A3F\u0A3F\u0A40\u0A42" +
"\u0A47\u0A48\u0A4B\u0A4D\u0A70\u0A71\u0A81\u0A83\u0ABC\u0ABC\u0ABE\u0AC5\u0AC7" +
"\u0AC9\u0ACB\u0ACD\u0B01\u0B03\u0B3C\u0B3C\u0B3E\u0B43\u0B47\u0B48\u0B4B\u0B4D" +
"\u0B56\u0B57\u0B82\u0B83\u0BBE\u0BC2\u0BC6\u0BC8\u0BCA\u0BCD\u0BD7\u0BD7\u0C01" +
"\u0C03\u0C3E\u0C44\u0C46\u0C48\u0C4A\u0C4D\u0C55\u0C56\u0C82\u0C83\u0CBE\u0CC4" +
"\u0CC6\u0CC8\u0CCA\u0CCD\u0CD5\u0CD6\u0D02\u0D03\u0D3E\u0D43\u0D46\u0D48\u0D4A" +
"\u0D4D\u0D57\u0D57\u0E31\u0E31\u0E34\u0E3A\u0E47\u0E4E\u0EB1\u0EB1\u0EB4\u0EB9" +
"\u0EBB\u0EBC\u0EC8\u0ECD\u0F18\u0F19\u0F35\u0F35\u0F37\u0F37\u0F39\u0F39\u0F3E" +
"\u0F3E\u0F3F\u0F3F\u0F71\u0F84\u0F86\u0F8B\u0F90\u0F95\u0F97\u0F97\u0F99\u0FAD" +
"\u0FB1\u0FB7\u0FB9\u0FB9\u20D0\u20DC\u20E1\u20E1\u302A\u302F\u3099\u3099\u309A" +
'\u309A');
final int[][] digit = read("\u0030\u0039\u0660\u0669\u06F0\u06F9\u0966\u096F\u09E6" +
"\u09EF\u0A66\u0A6F\u0AE6\u0AEF\u0B66\u0B6F\u0BE7\u0BEF\u0C66\u0C6F\u0CE6\u0CEF" +
"\u0D66\u0D6F\u0E50\u0E59\u0ED0\u0ED9\u0F20\u0F29");
final int[][] extender = read("\u00B7\u00B7\u02D0\u02D0\u02D1\u02D1\u0387\u0387" +
"\u0640\u0640\u0E46\u0E46\u0EC6\u0EC6\u3005\u3005\u3031\u3035\u309D\u309E\u30FC" +
'\u30FE');
final int[][] word = read("\u0024\u0024\u002b\u002b\u0030\u0039\u003c\u003e\u0041" +
"\u005a\u005e\u005e\u0060\u007a\u007c\u007c\u007e\u007e\u00a2\u00aa\u00ac\u00ac" +
"\u00ae\u00b6\u00b8\u00ba\u00bc\u00be\u00c0\u0377\u037a\u037d\u0384\u0386\u0388" +
"\u038a\u038c\u038c\u038e\u03a1\u03a3\u0527\u0531\u0556\u0559\u0559\u0561\u0587" +
"\u0591\u05bd\u05bf\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05c7\u05d0\u05ea\u05f0" +
"\u05f2\u0606\u0608\u060b\u060b\u060e\u061a\u0620\u0669\u066e\u06d3\u06d5\u06dc" +
"\u06de\u06ff\u0710\u074a\u074d\u07b1\u07c0\u07f6\u07fa\u07fa\u0800\u082d\u0840" +
"\u085b\u0900\u0963\u0966\u096f\u0971\u0977\u0979\u097f\u0981\u0983\u0985\u098c" +
"\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9\u09bc\u09c4\u09c7" +
"\u09c8\u09cb\u09ce\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09fb\u0a01\u0a03" +
"\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38" +
"\u0a39\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d\u0a51\u0a51\u0a59\u0a5c" +
"\u0a5e\u0a5e\u0a66\u0a75\u0a81\u0a83\u0a85\u0a8d\u0a8f\u0a91\u0a93\u0aa8\u0aaa" +
"\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5\u0ac7\u0ac9\u0acb\u0acd\u0ad0\u0ad0" +
"\u0ae0\u0ae3\u0ae6\u0aef\u0af1\u0af1\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13" +
"\u0b28\u0b2a\u0b30\u0b32\u0b33\u0b35\u0b39\u0b3c\u0b44\u0b47\u0b48\u0b4b\u0b4d" +
"\u0b56\u0b57\u0b5c\u0b5d\u0b5f\u0b63\u0b66\u0b77\u0b82\u0b83\u0b85\u0b8a\u0b8e" +
"\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa" +
"\u0bae\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd\u0bd0\u0bd0\u0bd7\u0bd7\u0be6" +
"\u0bfa\u0c01\u0c03\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39" +
"\u0c3d\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60\u0c63\u0c66" +
"\u0c6f\u0c78\u0c7f\u0c82\u0c83\u0c85\u0c8c\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3" +
"\u0cb5\u0cb9\u0cbc\u0cc4\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6\u0cde\u0cde\u0ce0" +
"\u0ce3\u0ce6\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d3a" +
"\u0d3d\u0d44\u0d46\u0d48\u0d4a\u0d4e\u0d57\u0d57\u0d60\u0d63\u0d66\u0d75\u0d79" +
"\u0d7f\u0d82\u0d83\u0d85\u0d96\u0d9a\u0db1\u0db3\u0dbb\u0dbd\u0dbd\u0dc0\u0dc6" +
"\u0dca\u0dca\u0dcf\u0dd4\u0dd6\u0dd6\u0dd8\u0ddf\u0df2\u0df3\u0e01\u0e3a\u0e3f" +
"\u0e4e\u0e50\u0e59\u0e81\u0e82\u0e84\u0e84\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d" +
"\u0e94\u0e97\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7\u0eaa\u0eab\u0ead" +
"\u0eb9\u0ebb\u0ebd\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9\u0edc\u0edd" +
"\u0f00\u0f03\u0f13\u0f39\u0f3e\u0f47\u0f49\u0f6c\u0f71\u0f84\u0f86\u0f97\u0f99" +
"\u0fbc\u0fbe\u0fcc\u0fce\u0fcf\u0fd5\u0fd8\u1000\u1049\u1050\u10c5\u10d0\u10fa" +
"\u10fc\u10fc\u1100\u1248\u124a\u124d\u1250\u1256\u1258\u1258\u125a\u125d\u1260" +
"\u1288\u128a\u128d\u1290\u12b0\u12b2\u12b5\u12b8\u12be\u12c0\u12c0\u12c2\u12c5" +
"\u12c8\u12d6\u12d8\u1310\u1312\u1315\u1318\u135a\u135d\u1360\u1369\u137c\u1380" +
"\u1399\u13a0\u13f4\u1401\u166c\u166f\u167f\u1681\u169a\u16a0\u16ea\u16ee\u16f0" +
"\u1700\u170c\u170e\u1714\u1720\u1734\u1740\u1753\u1760\u176c\u176e\u1770\u1772" +
"\u1773\u1780\u17b3\u17b6\u17d3\u17d7\u17d7\u17db\u17dd\u17e0\u17e9\u17f0\u17f9" +
"\u180b\u180d\u1810\u1819\u1820\u1877\u1880\u18aa\u18b0\u18f5\u1900\u191c\u1920" +
"\u192b\u1930\u193b\u1940\u1940\u1946\u196d\u1970\u1974\u1980\u19ab\u19b0\u19c9" +
"\u19d0\u19da\u19de\u1a1b\u1a20\u1a5e\u1a60\u1a7c\u1a7f\u1a89\u1a90\u1a99\u1aa7" +
"\u1aa7\u1b00\u1b4b\u1b50\u1b59\u1b61\u1b7c\u1b80\u1baa\u1bae\u1bb9\u1bc0\u1bf3" +
"\u1c00\u1c37\u1c40\u1c49\u1c4d\u1c7d\u1cd0\u1cd2\u1cd4\u1cf2\u1d00\u1de6\u1dfc" +
"\u1f15\u1f18\u1f1d\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b" +
"\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4\u1fb6\u1fc4\u1fc6\u1fd3\u1fd6\u1fdb\u1fdd" +
"\u1fef\u1ff2\u1ff4\u1ff6\u1ffe\u2044\u2044\u2052\u2052\u2070\u2071\u2074\u207c" +
"\u207f\u208c\u2090\u209c\u20a0\u20b9\u20d0\u20f0\u2100\u2189\u2190\u2328\u232b" +
"\u23f3\u2400\u2426\u2440\u244a\u2460\u26ff\u2701\u2767\u2776\u27c4\u27c7\u27ca" +
"\u27cc\u27cc\u27ce\u27e5\u27f0\u2982\u2999\u29d7\u29dc\u29fb\u29fe\u2b4c\u2b50" +
"\u2b59\u2c00\u2c2e\u2c30\u2c5e\u2c60\u2cf1\u2cfd\u2cfd\u2d00\u2d25\u2d30\u2d65" +
"\u2d6f\u2d6f\u2d7f\u2d96\u2da0\u2da6\u2da8\u2dae\u2db0\u2db6\u2db8\u2dbe\u2dc0" +
"\u2dc6\u2dc8\u2dce\u2dd0\u2dd6\u2dd8\u2dde\u2de0\u2dff\u2e2f\u2e2f\u2e80\u2e99" +
"\u2e9b\u2ef3\u2f00\u2fd5\u2ff0\u2ffb\u3004\u3007\u3012\u3013\u3020\u302f\u3031" +
"\u303c\u303e\u303f\u3041\u3096\u3099\u309f\u30a1\u30fa\u30fc\u30ff\u3105\u312d" +
"\u3131\u318e\u3190\u31ba\u31c0\u31e3\u31f0\u321e\u3220\u32fe\u3300\u4db5\u4dc0" +
"\u9fcb\ua000\ua48c\ua490\ua4c6\ua4d0\ua4fd\ua500\ua60c\ua610\ua62b\ua640\ua672" +
"\ua67c\ua67d\ua67f\ua697\ua6a0\ua6f1\ua700\ua78e\ua790\ua791\ua7a0\ua7a9\ua7fa" +
"\ua82b\ua830\ua839\ua840\ua873\ua880\ua8c4\ua8d0\ua8d9\ua8e0\ua8f7\ua8fb\ua8fb" +
"\ua900\ua92d\ua930\ua953\ua960\ua97c\ua980\ua9c0\ua9cf\ua9d9\uaa00\uaa36\uaa40" +
"\uaa4d\uaa50\uaa59\uaa60\uaa7b\uaa80\uaac2\uaadb\uaadd\uab01\uab06\uab09\uab0e" +
"\uab11\uab16\uab20\uab26\uab28\uab2e\uabc0\uabea\uabec\uabed\uabf0\uabf9\uac00" +
"\ud7a3\ud7b0\ud7c6\ud7cb\ud7fb\uf900\ufa2d\ufa30\ufa6d\ufa70\ufad9\ufb00\ufb06" +
"\ufb13\ufb17\ufb1d\ufb36\ufb38\ufb3c\ufb3e\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46" +
"\ufbc1\ufbd3\ufd3d\ufd50\ufd8f\ufd92\ufdc7\ufdd0\ufdfd\ufe00\ufe0f\ufe20\ufe26" +
"\ufe62\ufe62\ufe64\ufe66\ufe69\ufe69\ufe70\ufe74\ufe76\ufefc\uff04\uff04\uff0b" +
"\uff0b\uff10\uff19\uff1c\uff1e\uff21\uff3a\uff3e\uff3e\uff40\uff5a\uff5c\uff5c" +
"\uff5e\uff5e\uff66\uffbe\uffc2\uffc7\uffca\uffcf\uffd2\uffd7\uffda\uffdc\uffe0" +
"\uffe6\uffe8\uffee\ufffc\ufffd\ud800\udc00\ud800\udc0b\ud800\udc0d\ud800\udc26" +
"\ud800\udc28\ud800\udc3a\ud800\udc3c\ud800\udc3d\ud800\udc3f\ud800\udc4d\ud800" +
"\udc50\ud800\udc5d\ud800\udc80\ud800\udcfa\ud800\udd02\ud800\udd02\ud800\udd07" +
"\ud800\udd33\ud800\udd37\ud800\udd8a\ud800\udd90\ud800\udd9b\ud800\uddd0\ud800" +
"\uddfd\ud800\ude80\ud800\ude9c\ud800\udea0\ud800\uded0\ud800\udf00\ud800\udf1e" +
"\ud800\udf20\ud800\udf23\ud800\udf30\ud800\udf4a\ud800\udf80\ud800\udf9d\ud800" +
"\udfa0\ud800\udfc3\ud800\udfc8\ud800\udfcf\ud800\udfd1\ud800\udfd5\ud801\udc00" +
"\ud801\udc9d\ud801\udca0\ud801\udca9\ud802\udc00\ud802\udc05\ud802\udc08\ud802" +
"\udc08\ud802\udc0a\ud802\udc35\ud802\udc37\ud802\udc38\ud802\udc3c\ud802\udc3c" +
"\ud802\udc3f\ud802\udc55\ud802\udc58\ud802\udc5f\ud802\udd00\ud802\udd1b\ud802" +
"\udd20\ud802\udd39\ud802\ude00\ud802\ude03\ud802\ude05\ud802\ude06\ud802\ude0c" +
"\ud802\ude13\ud802\ude15\ud802\ude17\ud802\ude19\ud802\ude33\ud802\ude38\ud802" +
"\ude3a\ud802\ude3f\ud802\ude47\ud802\ude60\ud802\ude7e\ud802\udf00\ud802\udf35" +
"\ud802\udf40\ud802\udf55\ud802\udf58\ud802\udf72\ud802\udf78\ud802\udf7f\ud803" +
"\udc00\ud803\udc48\ud803\ude60\ud803\ude7e\ud804\udc00\ud804\udc46\ud804\udc52" +
"\ud804\udc6f\ud804\udc80\ud804\udcba\ud808\udc00\ud808\udf6e\ud809\udc00\ud809" +
"\udc62\ud80c\udc00\ud80d\udc2e\ud81a\udc00\ud81a\ude38\ud82c\udc00\ud82c\udc01" +
"\ud834\udc00\ud834\udcf5\ud834\udd00\ud834\udd26\ud834\udd29\ud834\udd72\ud834" +
"\udd7b\ud834\udddd\ud834\ude00\ud834\ude45\ud834\udf00\ud834\udf56\ud834\udf60" +
"\ud834\udf71\ud835\udc00\ud835\udc54\ud835\udc56\ud835\udc9c\ud835\udc9e\ud835" +
"\udc9f\ud835\udca2\ud835\udca2\ud835\udca5\ud835\udca6\ud835\udca9\ud835\udcac" +
"\ud835\udcae\ud835\udcb9\ud835\udcbb\ud835\udcbb\ud835\udcbd\ud835\udcc3\ud835" +
"\udcc5\ud835\udd05\ud835\udd07\ud835\udd0a\ud835\udd0d\ud835\udd14\ud835\udd16" +
"\ud835\udd1c\ud835\udd1e\ud835\udd39\ud835\udd3b\ud835\udd3e\ud835\udd40\ud835" +
"\udd44\ud835\udd46\ud835\udd46\ud835\udd4a\ud835\udd50\ud835\udd52\ud835\udea5" +
"\ud835\udea8\ud835\udfcb\ud835\udfce\ud835\udfff\ud83c\udc00\ud83c\udc2b\ud83c" +
"\udc30\ud83c\udc93\ud83c\udca0\ud83c\udcae\ud83c\udcb1\ud83c\udcbe\ud83c\udcc1" +
"\ud83c\udccf\ud83c\udcd1\ud83c\udcdf\ud83c\udd00\ud83c\udd0a\ud83c\udd10\ud83c" +
"\udd2e\ud83c\udd30\ud83c\udd69\ud83c\udd70\ud83c\udd9a\ud83c\udde6\ud83c\ude02" +
"\ud83c\ude10\ud83c\ude3a\ud83c\ude40\ud83c\ude48\ud83c\ude50\ud83c\ude51\ud83c" +
"\udf00\ud83c\udf20\ud83c\udf30\ud83c\udf35\ud83c\udf37\ud83c\udf7c\ud83c\udf80" +
"\ud83c\udf93\ud83c\udfa0\ud83c\udfc4\ud83c\udfc6\ud83c\udfca\ud83c\udfe0\ud83c" +
"\udff0\ud83d\udc00\ud83d\udc3e\ud83d\udc40\ud83d\udc40\ud83d\udc42\ud83d\udcf7" +
"\ud83d\udcf9\ud83d\udcfc\ud83d\udd00\ud83d\udd3d\ud83d\udd50\ud83d\udd67\ud83d" +
"\uddfb\ud83d\uddff\ud83d\ude01\ud83d\ude10\ud83d\ude12\ud83d\ude14\ud83d\ude16" +
"\ud83d\ude16\ud83d\ude18\ud83d\ude18\ud83d\ude1a\ud83d\ude1a\ud83d\ude1c\ud83d" +
"\ude1e\ud83d\ude20\ud83d\ude25\ud83d\ude28\ud83d\ude2b\ud83d\ude2d\ud83d\ude2d" +
"\ud83d\ude30\ud83d\ude33\ud83d\ude35\ud83d\ude40\ud83d\ude45\ud83d\ude4f\ud83d" +
"\ude80\ud83d\udec5\ud83d\udf00\ud83d\udf73\ud83f\udffe\ud869\uded6\ud869\udf00" +
"\ud86d\udf34\ud86d\udf40\ud86e\udc1d\ud87e\udc00\ud87e\ude1d\ud87f\udffe\ud87f" +
"\udfff\ud8bf\udffe\ud8bf\udfff\ud8ff\udffe\ud8ff\udfff\ud93f\udffe\ud93f\udfff" +
"\ud97f\udffe\ud97f\udfff\ud9bf\udffe\ud9bf\udfff\ud9ff\udffe\ud9ff\udfff\uda3f" +
"\udffe\uda3f\udfff\uda7f\udffe\uda7f\udfff\udabf\udffe\udabf\udfff\udaff\udffe" +
"\udaff\udfff\udb3f\udffe\udb3f\udfff\udb40\udd00\udb40\uddef\udb7f\udffe\udb7f" +
"\udfff\udbbf\udffe\udbbf\udfff\udbff\udffe\udbff\udfff");
final int[][] letter = merge(baseChar, ideographic),
initialNameChar = merge(letter, read("__::")),
nameChar = merge(initialNameChar, digit, read("-."), combiningChar, extender);
INITIAL = serialize(initialNameChar);
NOT_INITIAL = serialize(invert(initialNameChar));
CHAR = serialize(nameChar);
NOT_CHAR = serialize(invert(nameChar));
WORD = serialize(word);
NOT_WORD = serialize(invert(word));
// easy to reproduce from http://www.w3.org/TR/xsd-unicode-blocknames/#blocks
final HashMap<String, int[][]> m = new HashMap<>();
add(m, "BasicLatin", new int[] { 0x0000, 0x007F });
add(m, "Latin-1Supplement", new int[] { 0x0080, 0x00FF });
add(m, "LatinExtended-A", new int[] { 0x0100, 0x017F });
add(m, "LatinExtended-B", new int[] { 0x0180, 0x024F });
add(m, "IPAExtensions", new int[] { 0x0250, 0x02AF });
add(m, "SpacingModifierLetters", new int[] { 0x02B0, 0x02FF });
add(m, "CombiningDiacriticalMarks", new int[] { 0x0300, 0x036F });
add(m, "Greek", new int[] { 0x0370, 0x03FF });
add(m, "GreekandCoptic", new int[] { 0x0370, 0x03FF });
add(m, "Cyrillic", new int[] { 0x0400, 0x04FF });
add(m, "CyrillicSupplementary", new int[] { 0x0500, 0x052F });
add(m, "CyrillicSupplement", new int[] { 0x0500, 0x052F });
add(m, "Armenian", new int[] { 0x0530, 0x058F });
add(m, "Hebrew", new int[] { 0x0590, 0x05FF });
add(m, "Arabic", new int[] { 0x0600, 0x06FF });
add(m, "Syriac", new int[] { 0x0700, 0x074F });
add(m, "ArabicSupplement", new int[] { 0x0750, 0x077F });
add(m, "Thaana", new int[] { 0x0780, 0x07BF });
add(m, "NKo", new int[] { 0x07C0, 0x07FF });
add(m, "Samaritan", new int[] { 0x0800, 0x083F });
add(m, "Mandaic", new int[] { 0x0840, 0x085F });
add(m, "Devanagari", new int[] { 0x0900, 0x097F });
add(m, "Bengali", new int[] { 0x0980, 0x09FF });
add(m, "Gurmukhi", new int[] { 0x0A00, 0x0A7F });
add(m, "Gujarati", new int[] { 0x0A80, 0x0AFF });
add(m, "Oriya", new int[] { 0x0B00, 0x0B7F });
add(m, "Tamil", new int[] { 0x0B80, 0x0BFF });
add(m, "Telugu", new int[] { 0x0C00, 0x0C7F });
add(m, "Kannada", new int[] { 0x0C80, 0x0CFF });
add(m, "Malayalam", new int[] { 0x0D00, 0x0D7F });
add(m, "Sinhala", new int[] { 0x0D80, 0x0DFF });
add(m, "Thai", new int[] { 0x0E00, 0x0E7F });
add(m, "Lao", new int[] { 0x0E80, 0x0EFF });
add(m, "Tibetan", new int[] { 0x0F00, 0x0FBF });
add(m, "Tibetan", new int[] { 0x0F00, 0x0FFF });
add(m, "Myanmar", new int[] { 0x1000, 0x109F });
add(m, "Georgian", new int[] { 0x10A0, 0x10FF });
add(m, "HangulJamo", new int[] { 0x1100, 0x11FF });
add(m, "Ethiopic", new int[] { 0x1200, 0x137F });
add(m, "EthiopicSupplement", new int[] { 0x1380, 0x139F });
add(m, "Cherokee", new int[] { 0x13A0, 0x13FF });
add(m, "UnifiedCanadianAboriginalSyllabics", new int[] { 0x1400, 0x167F });
add(m, "Ogham", new int[] { 0x1680, 0x169F });
add(m, "Runic", new int[] { 0x16A0, 0x16FF });
add(m, "Tagalog", new int[] { 0x1700, 0x171F });
add(m, "Hanunoo", new int[] { 0x1720, 0x173F });
add(m, "Buhid", new int[] { 0x1740, 0x175F });
add(m, "Tagbanwa", new int[] { 0x1760, 0x177F });
add(m, "Khmer", new int[] { 0x1780, 0x17FF });
add(m, "Mongolian", new int[] { 0x1800, 0x18AF });
add(m, "UnifiedCanadianAboriginalSyllabicsExtended", new int[] { 0x18B0, 0x18FF });
add(m, "Limbu", new int[] { 0x1900, 0x194F });
add(m, "TaiLe", new int[] { 0x1950, 0x197F });
add(m, "NewTaiLue", new int[] { 0x1980, 0x19DF });
add(m, "KhmerSymbols", new int[] { 0x19E0, 0x19FF });
add(m, "Buginese", new int[] { 0x1A00, 0x1A1F });
add(m, "TaiTham", new int[] { 0x1A20, 0x1AAF });
add(m, "Balinese", new int[] { 0x1B00, 0x1B7F });
add(m, "Sundanese", new int[] { 0x1B80, 0x1BBF });
add(m, "Batak", new int[] { 0x1BC0, 0x1BFF });
add(m, "Lepcha", new int[] { 0x1C00, 0x1C4F });
add(m, "OlChiki", new int[] { 0x1C50, 0x1C7F });
add(m, "VedicExtensions", new int[] { 0x1CD0, 0x1CFF });
add(m, "PhoneticExtensions", new int[] { 0x1D00, 0x1D7F });
add(m, "PhoneticExtensionsSupplement", new int[] { 0x1D80, 0x1DBF });
add(m, "CombiningDiacriticalMarksSupplement", new int[] { 0x1DC0, 0x1DFF });
add(m, "LatinExtendedAdditional", new int[] { 0x1E00, 0x1EFF });
add(m, "GreekExtended", new int[] { 0x1F00, 0x1FFF });
add(m, "GeneralPunctuation", new int[] { 0x2000, 0x206F });
add(m, "SuperscriptsandSubscripts", new int[] { 0x2070, 0x209F });
add(m, "CurrencySymbols", new int[] { 0x20A0, 0x20CF });
add(m, "CombiningMarksforSymbols", new int[] { 0x20D0, 0x20FF });
add(m, "CombiningDiacriticalMarksforSymbols", new int[] { 0x20D0, 0x20FF });
add(m, "LetterlikeSymbols", new int[] { 0x2100, 0x214F });
add(m, "NumberForms", new int[] { 0x2150, 0x218F });
add(m, "Arrows", new int[] { 0x2190, 0x21FF });
add(m, "MathematicalOperators", new int[] { 0x2200, 0x22FF });
add(m, "MiscellaneousTechnical", new int[] { 0x2300, 0x23FF });
add(m, "ControlPictures", new int[] { 0x2400, 0x243F });
add(m, "OpticalCharacterRecognition", new int[] { 0x2440, 0x245F });
add(m, "EnclosedAlphanumerics", new int[] { 0x2460, 0x24FF });
add(m, "BoxDrawing", new int[] { 0x2500, 0x257F });
add(m, "BlockElements", new int[] { 0x2580, 0x259F });
add(m, "GeometricShapes", new int[] { 0x25A0, 0x25FF });
add(m, "MiscellaneousSymbols", new int[] { 0x2600, 0x26FF });
add(m, "Dingbats", new int[] { 0x2700, 0x27BF });
add(m, "MiscellaneousMathematicalSymbols-A", new int[] { 0x27C0, 0x27EF });
add(m, "SupplementalArrows-A", new int[] { 0x27F0, 0x27FF });
add(m, "BraillePatterns", new int[] { 0x2800, 0x28FF });
add(m, "SupplementalArrows-B", new int[] { 0x2900, 0x297F });
add(m, "MiscellaneousMathematicalSymbols-B", new int[] { 0x2980, 0x29FF });
add(m, "SupplementalMathematicalOperators", new int[] { 0x2A00, 0x2AFF });
add(m, "MiscellaneousSymbolsandArrows", new int[] { 0x2B00, 0x2BFF });
add(m, "Glagolitic", new int[] { 0x2C00, 0x2C5F });
add(m, "LatinExtended-C", new int[] { 0x2C60, 0x2C7F });
add(m, "Coptic", new int[] { 0x2C80, 0x2CFF });
add(m, "GeorgianSupplement", new int[] { 0x2D00, 0x2D2F });
add(m, "Tifinagh", new int[] { 0x2D30, 0x2D7F });
add(m, "EthiopicExtended", new int[] { 0x2D80, 0x2DDF });
add(m, "CyrillicExtended-A", new int[] { 0x2DE0, 0x2DFF });
add(m, "SupplementalPunctuation", new int[] { 0x2E00, 0x2E7F });
add(m, "CJKRadicalsSupplement", new int[] { 0x2E80, 0x2EFF });
add(m, "KangxiRadicals", new int[] { 0x2F00, 0x2FDF });
add(m, "IdeographicDescriptionCharacters", new int[] { 0x2FF0, 0x2FFF });
add(m, "CJKSymbolsandPunctuation", new int[] { 0x3000, 0x303F });
add(m, "Hiragana", new int[] { 0x3040, 0x309F });
add(m, "Katakana", new int[] { 0x30A0, 0x30FF });
add(m, "Bopomofo", new int[] { 0x3100, 0x312F });
add(m, "HangulCompatibilityJamo", new int[] { 0x3130, 0x318F });
add(m, "Kanbun", new int[] { 0x3190, 0x319F });
add(m, "BopomofoExtended", new int[] { 0x31A0, 0x31BF });
add(m, "CJKStrokes", new int[] { 0x31C0, 0x31EF });
add(m, "KatakanaPhoneticExtensions", new int[] { 0x31F0, 0x31FF });
add(m, "EnclosedCJKLettersandMonths", new int[] { 0x3200, 0x32FF });
add(m, "CJKCompatibility", new int[] { 0x3300, 0x33FF });
add(m, "CJKUnifiedIdeographsExtensionA", new int[] { 0x3400, 0x4DB5 });
add(m, "CJKUnifiedIdeographsExtensionA", new int[] { 0x3400, 0x4DBF });
add(m, "YijingHexagramSymbols", new int[] { 0x4DC0, 0x4DFF });
add(m, "CJKUnifiedIdeographs", new int[] { 0x4E00, 0x9FFF });
add(m, "YiSyllables", new int[] { 0xA000, 0xA48F });
add(m, "YiRadicals", new int[] { 0xA490, 0xA4CF });
add(m, "Lisu", new int[] { 0xA4D0, 0xA4FF });
add(m, "Vai", new int[] { 0xA500, 0xA63F });
add(m, "CyrillicExtended-B", new int[] { 0xA640, 0xA69F });
add(m, "Bamum", new int[] { 0xA6A0, 0xA6FF });
add(m, "ModifierToneLetters", new int[] { 0xA700, 0xA71F });
add(m, "LatinExtended-D", new int[] { 0xA720, 0xA7FF });
add(m, "SylotiNagri", new int[] { 0xA800, 0xA82F });
add(m, "CommonIndicNumberForms", new int[] { 0xA830, 0xA83F });
add(m, "Phags-pa", new int[] { 0xA840, 0xA87F });
add(m, "Saurashtra", new int[] { 0xA880, 0xA8DF });
add(m, "DevanagariExtended", new int[] { 0xA8E0, 0xA8FF });
add(m, "KayahLi", new int[] { 0xA900, 0xA92F });
add(m, "Rejang", new int[] { 0xA930, 0xA95F });
add(m, "HangulJamoExtended-A", new int[] { 0xA960, 0xA97F });
add(m, "Javanese", new int[] { 0xA980, 0xA9DF });
add(m, "Cham", new int[] { 0xAA00, 0xAA5F });
add(m, "MyanmarExtended-A", new int[] { 0xAA60, 0xAA7F });
add(m, "TaiViet", new int[] { 0xAA80, 0xAADF });
add(m, "EthiopicExtended-A", new int[] { 0xAB00, 0xAB2F });
add(m, "MeeteiMayek", new int[] { 0xABC0, 0xABFF });
add(m, "HangulSyllables", new int[] { 0xAC00, 0xD7A3 });
add(m, "HangulSyllables", new int[] { 0xAC00, 0xD7AF });
add(m, "HangulJamoExtended-B", new int[] { 0xD7B0, 0xD7FF });
add(m, "HighSurrogates", new int[] { 0xD800, 0xDB7F });
add(m, "HighPrivateUseSurrogates", new int[] { 0xDB80, 0xDBFF });
add(m, "LowSurrogates", new int[] { 0xDC00, 0xDFFF });
add(m, "PrivateUse", new int[] { 0xE000, 0xF8FF });
add(m, "PrivateUseArea", new int[] { 0xE000, 0xF8FF });
add(m, "CJKCompatibilityIdeographs", new int[] { 0xF900, 0xFAFF });
add(m, "AlphabeticPresentationForms", new int[] { 0xFB00, 0xFB4F });
add(m, "ArabicPresentationForms-A", new int[] { 0xFB50, 0xFDFF });
add(m, "VariationSelectors", new int[] { 0xFE00, 0xFE0F });
add(m, "VerticalForms", new int[] { 0xFE10, 0xFE1F });
add(m, "CombiningHalfMarks", new int[] { 0xFE20, 0xFE2F });
add(m, "CJKCompatibilityForms", new int[] { 0xFE30, 0xFE4F });
add(m, "SmallFormVariants", new int[] { 0xFE50, 0xFE6F });
add(m, "ArabicPresentationForms-B", new int[] { 0xFE70, 0xFEFE });
add(m, "ArabicPresentationForms-B", new int[] { 0xFE70, 0xFEFF });
add(m, "Specials", new int[] { 0xFEFF, 0xFEFF });
add(m, "HalfwidthandFullwidthForms", new int[] { 0xFF00, 0xFFEF });
add(m, "Specials", new int[] { 0xFFF0, 0xFFFD });
add(m, "Specials", new int[] { 0xFFF0, 0xFFFF });
add(m, "LinearBSyllabary", new int[] { 0x10000, 0x1007F });
add(m, "LinearBIdeograms", new int[] { 0x10080, 0x100FF });
add(m, "AegeanNumbers", new int[] { 0x10100, 0x1013F });
add(m, "AncientGreekNumbers", new int[] { 0x10140, 0x1018F });
add(m, "AncientSymbols", new int[] { 0x10190, 0x101CF });
add(m, "PhaistosDisc", new int[] { 0x101D0, 0x101FF });
add(m, "Lycian", new int[] { 0x10280, 0x1029F });
add(m, "Carian", new int[] { 0x102A0, 0x102DF });
add(m, "OldItalic", new int[] { 0x10300, 0x1032F });
add(m, "Gothic", new int[] { 0x10330, 0x1034F });
add(m, "Ugaritic", new int[] { 0x10380, 0x1039F });
add(m, "OldPersian", new int[] { 0x103A0, 0x103DF });
add(m, "Deseret", new int[] { 0x10400, 0x1044F });
add(m, "Shavian", new int[] { 0x10450, 0x1047F });
add(m, "Osmanya", new int[] { 0x10480, 0x104AF });
add(m, "CypriotSyllabary", new int[] { 0x10800, 0x1083F });
add(m, "ImperialAramaic", new int[] { 0x10840, 0x1085F });
add(m, "Phoenician", new int[] { 0x10900, 0x1091F });
add(m, "Lydian", new int[] { 0x10920, 0x1093F });
add(m, "Kharoshthi", new int[] { 0x10A00, 0x10A5F });
add(m, "OldSouthArabian", new int[] { 0x10A60, 0x10A7F });
add(m, "Avestan", new int[] { 0x10B00, 0x10B3F });
add(m, "InscriptionalParthian", new int[] { 0x10B40, 0x10B5F });
add(m, "InscriptionalPahlavi", new int[] { 0x10B60, 0x10B7F });
add(m, "OldTurkic", new int[] { 0x10C00, 0x10C4F });
add(m, "RumiNumeralSymbols", new int[] { 0x10E60, 0x10E7F });
add(m, "Brahmi", new int[] { 0x11000, 0x1107F });
add(m, "Kaithi", new int[] { 0x11080, 0x110CF });
add(m, "Cuneiform", new int[] { 0x12000, 0x123FF });
add(m, "CuneiformNumbersandPunctuation", new int[] { 0x12400, 0x1247F });
add(m, "EgyptianHieroglyphs", new int[] { 0x13000, 0x1342F });
add(m, "BamumSupplement", new int[] { 0x16800, 0x16A3F });
add(m, "KanaSupplement", new int[] { 0x1B000, 0x1B0FF });
add(m, "ByzantineMusicalSymbols", new int[] { 0x1D000, 0x1D0FF });
add(m, "MusicalSymbols", new int[] { 0x1D100, 0x1D1FF });
add(m, "AncientGreekMusicalNotation", new int[] { 0x1D200, 0x1D24F });
add(m, "TaiXuanJingSymbols", new int[] { 0x1D300, 0x1D35F });
add(m, "CountingRodNumerals", new int[] { 0x1D360, 0x1D37F });
add(m, "MathematicalAlphanumericSymbols", new int[] { 0x1D400, 0x1D7FF });
add(m, "MahjongTiles", new int[] { 0x1F000, 0x1F02F });
add(m, "DominoTiles", new int[] { 0x1F030, 0x1F09F });
add(m, "PlayingCards", new int[] { 0x1F0A0, 0x1F0FF });
add(m, "EnclosedAlphanumericSupplement", new int[] { 0x1F100, 0x1F1FF });
add(m, "EnclosedIdeographicSupplement", new int[] { 0x1F200, 0x1F2FF });
add(m, "MiscellaneousSymbolsAndPictographs", new int[] { 0x1F300, 0x1F5FF });
add(m, "Emoticons", new int[] { 0x1F600, 0x1F64F });
add(m, "TransportAndMapSymbols", new int[] { 0x1F680, 0x1F6FF });
add(m, "AlchemicalSymbols", new int[] { 0x1F700, 0x1F77F });
add(m, "CJKUnifiedIdeographsExtensionB", new int[] { 0x20000, 0x2A6D6 });
add(m, "CJKUnifiedIdeographsExtensionB", new int[] { 0x20000, 0x2A6DF });
add(m, "CJKUnifiedIdeographsExtensionC", new int[] { 0x2A700, 0x2B73F });
add(m, "CJKUnifiedIdeographsExtensionD", new int[] { 0x2B740, 0x2B81F });
add(m, "CJKCompatibilityIdeographsSupplement", new int[] { 0x2F800, 0x2FA1F });
add(m, "Tags", new int[] { 0xE0000, 0xE007F });
add(m, "VariationSelectorsSupplement", new int[] { 0xE0100, 0xE01EF });
add(m, "PrivateUse", new int[] { 0xF0000, 0xFFFFD });
add(m, "SupplementaryPrivateUseArea-A", new int[] { 0xF0000, 0xFFFFF });
add(m, "PrivateUse", new int[] { 0x100000, 0x10FFFD });
add(m, "SupplementaryPrivateUseArea-B", new int[] { 0x100000, 0x10FFFF });
// add entries for all known character classes
m.forEach((key, vals) -> {
final int vl = vals.length;
final CharRange[] rs = new CharRange[vl];
for(int v = 0; v < vl; v++) rs[v] = new CharRange(vals[v][0], vals[v][1]);
MAP.put("\\p{Is" + key + '}', rs);
final int[][] not = invert(vals);
final int nl = not.length;
final CharRange[] nrs = new CharRange[nl];
for(int n = 0; n < nl; n++) nrs[n] = new CharRange(not[n][0], not[n][1]);
MAP.put("\\P{Is" + key + '}', nrs);
});
}
}
| |
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. 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 com.hazelcast.internal.serialization.impl.portable;
import com.hazelcast.nio.serialization.ClassDefinition;
import com.hazelcast.nio.serialization.FieldDefinition;
import com.hazelcast.nio.serialization.FieldType;
import com.hazelcast.nio.serialization.GenericRecord;
import com.hazelcast.nio.serialization.GenericRecordBuilder;
import com.hazelcast.nio.serialization.HazelcastSerializationException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
public class PortableGenericRecordBuilder implements GenericRecordBuilder {
private final ClassDefinition classDefinition;
private final Object[] objects;
private final boolean[] isSet;
private final boolean isClone;
public PortableGenericRecordBuilder(ClassDefinition classDefinition) {
this.classDefinition = classDefinition;
this.objects = new Object[classDefinition.getFieldCount()];
this.isClone = false;
this.isSet = new boolean[objects.length];
}
PortableGenericRecordBuilder(ClassDefinition classDefinition, Object[] objects) {
this.classDefinition = classDefinition;
this.objects = objects;
this.isClone = true;
this.isSet = new boolean[objects.length];
}
/**
* @return newly created GenericRecord
* @throws HazelcastSerializationException if a field is not written when building with builder from
* {@link GenericRecordBuilder#portable(ClassDefinition)} and
* {@link GenericRecord#newBuilder()}
*/
@Nonnull
@Override
public GenericRecord build() {
if (!isClone) {
for (int i = 0; i < isSet.length; i++) {
if (!isSet[i]) {
throw new HazelcastSerializationException("All fields must be written when building"
+ " a GenericRecord for portable, unwritten field :" + classDefinition.getField(i));
}
}
}
return new DeserializedPortableGenericRecord(classDefinition, objects);
}
@Nonnull
@Override
public GenericRecordBuilder setInt(@Nonnull String fieldName, int value) {
return set(fieldName, value, FieldType.INT);
}
@Nonnull
@Override
public GenericRecordBuilder setLong(@Nonnull String fieldName, long value) {
return set(fieldName, value, FieldType.LONG);
}
@Nonnull
@Override
public GenericRecordBuilder setString(@Nonnull String fieldName, String value) {
return set(fieldName, value, FieldType.UTF);
}
@Nonnull
@Override
public GenericRecordBuilder setBoolean(@Nonnull String fieldName, boolean value) {
return set(fieldName, value, FieldType.BOOLEAN);
}
@Nonnull
@Override
public GenericRecordBuilder setByte(@Nonnull String fieldName, byte value) {
return set(fieldName, value, FieldType.BYTE);
}
@Nonnull
@Override
public GenericRecordBuilder setChar(@Nonnull String fieldName, char value) {
return set(fieldName, value, FieldType.CHAR);
}
@Nonnull
@Override
public GenericRecordBuilder setDouble(@Nonnull String fieldName, double value) {
return set(fieldName, value, FieldType.DOUBLE);
}
@Nonnull
@Override
public GenericRecordBuilder setFloat(@Nonnull String fieldName, float value) {
return set(fieldName, value, FieldType.FLOAT);
}
@Nonnull
@Override
public GenericRecordBuilder setShort(@Nonnull String fieldName, short value) {
return set(fieldName, value, FieldType.SHORT);
}
@Nonnull
@Override
public GenericRecordBuilder setGenericRecord(@Nonnull String fieldName, @Nullable GenericRecord value) {
return set(fieldName, value, FieldType.PORTABLE);
}
@Nonnull
@Override
public GenericRecordBuilder setDecimal(@Nonnull String fieldName, @Nullable BigDecimal value) {
return set(fieldName, value, FieldType.DECIMAL);
}
@Nonnull
@Override
public GenericRecordBuilder setTime(@Nonnull String fieldName, @Nullable LocalTime value) {
return set(fieldName, value, FieldType.TIME);
}
@Nonnull
@Override
public GenericRecordBuilder setDate(@Nonnull String fieldName, @Nullable LocalDate value) {
return set(fieldName, value, FieldType.DATE);
}
@Nonnull
@Override
public GenericRecordBuilder setTimestamp(@Nonnull String fieldName, @Nullable LocalDateTime value) {
return set(fieldName, value, FieldType.TIMESTAMP);
}
@Nonnull
@Override
public GenericRecordBuilder setTimestampWithTimezone(@Nonnull String fieldName, @Nullable OffsetDateTime value) {
return set(fieldName, value, FieldType.TIMESTAMP_WITH_TIMEZONE);
}
@Nonnull
@Override
public GenericRecordBuilder setGenericRecordArray(@Nonnull String fieldName, @Nullable GenericRecord[] value) {
return set(fieldName, value, FieldType.PORTABLE_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setByteArray(@Nonnull String fieldName, byte[] value) {
return set(fieldName, value, FieldType.BYTE_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setBooleanArray(@Nonnull String fieldName, boolean[] value) {
return set(fieldName, value, FieldType.BOOLEAN_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setCharArray(@Nonnull String fieldName, char[] value) {
return set(fieldName, value, FieldType.CHAR_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setIntArray(@Nonnull String fieldName, int[] value) {
return set(fieldName, value, FieldType.INT_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setLongArray(@Nonnull String fieldName, long[] value) {
return set(fieldName, value, FieldType.LONG_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setDoubleArray(@Nonnull String fieldName, double[] value) {
return set(fieldName, value, FieldType.DOUBLE_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setFloatArray(@Nonnull String fieldName, float[] value) {
return set(fieldName, value, FieldType.FLOAT_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setShortArray(@Nonnull String fieldName, short[] value) {
return set(fieldName, value, FieldType.SHORT_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setStringArray(@Nonnull String fieldName, String[] value) {
return set(fieldName, value, FieldType.UTF_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setDecimalArray(@Nonnull String fieldName, BigDecimal[] value) {
return set(fieldName, value, FieldType.DECIMAL_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setTimeArray(@Nonnull String fieldName, LocalTime[] value) {
return set(fieldName, value, FieldType.TIME_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setDateArray(@Nonnull String fieldName, LocalDate[] value) {
return set(fieldName, value, FieldType.DATE_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setTimestampArray(@Nonnull String fieldName, LocalDateTime[] value) {
return set(fieldName, value, FieldType.TIMESTAMP_ARRAY);
}
@Nonnull
@Override
public GenericRecordBuilder setTimestampWithTimezoneArray(@Nonnull String fieldName, OffsetDateTime[] value) {
return set(fieldName, value, FieldType.TIMESTAMP_WITH_TIMEZONE_ARRAY);
}
private GenericRecordBuilder set(@Nonnull String fieldName, Object value, FieldType fieldType) {
FieldDefinition fd = check(fieldName, fieldType);
int index = fd.getIndex();
if (isSet[index]) {
if (!isClone) {
throw new HazelcastSerializationException("It is illegal to the overwrite the field");
} else {
throw new HazelcastSerializationException("Field can only overwritten once with `cloneWithBuilder`");
}
}
objects[index] = value;
isSet[index] = true;
return this;
}
@Nonnull
private FieldDefinition check(@Nonnull String fieldName, FieldType fieldType) {
FieldDefinition fd = classDefinition.getField(fieldName);
if (fd == null) {
throw new HazelcastSerializationException("Invalid field name: '" + fieldName
+ "' for ClassDefinition {id: " + classDefinition.getClassId()
+ ", version: " + classDefinition.getVersion() + "}");
}
if (!fd.getType().equals(fieldType)) {
throw new HazelcastSerializationException("Invalid field type: '" + fieldName
+ "' for ClassDefinition {id: " + classDefinition.getClassId() + ", version: "
+ classDefinition.getVersion() + "}" + ", expected : " + fd.getType() + ", given : " + fieldType);
}
return fd;
}
}
| |
/*
* Copyright 2010-2013 Ning, Inc.
* Copyright 2014-2018 Groupon, Inc
* Copyright 2014-2018 The Billing Project, LLC
*
* The Billing 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 org.killbill.billing.jaxrs;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.nio.charset.Charset;
import java.util.EventListener;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.sql.DataSource;
import org.apache.shiro.web.servlet.ShiroFilter;
import org.eclipse.jetty.servlet.FilterHolder;
import org.joda.time.LocalDate;
import org.killbill.billing.GuicyKillbillTestWithEmbeddedDBModule;
import org.killbill.billing.api.TestApiListener;
import org.killbill.billing.beatrix.integration.db.TestDBRouterAPI;
import org.killbill.billing.client.KillBillClientException;
import org.killbill.billing.client.KillBillHttpClient;
import org.killbill.billing.client.api.gen.AccountApi;
import org.killbill.billing.client.api.gen.AdminApi;
import org.killbill.billing.client.api.gen.BundleApi;
import org.killbill.billing.client.api.gen.CatalogApi;
import org.killbill.billing.client.api.gen.CreditApi;
import org.killbill.billing.client.api.gen.CustomFieldApi;
import org.killbill.billing.client.api.gen.ExportApi;
import org.killbill.billing.client.api.gen.InvoiceApi;
import org.killbill.billing.client.api.gen.InvoiceItemApi;
import org.killbill.billing.client.api.gen.InvoicePaymentApi;
import org.killbill.billing.client.api.gen.NodesInfoApi;
import org.killbill.billing.client.api.gen.OverdueApi;
import org.killbill.billing.client.api.gen.PaymentApi;
import org.killbill.billing.client.api.gen.PaymentGatewayApi;
import org.killbill.billing.client.api.gen.PaymentMethodApi;
import org.killbill.billing.client.api.gen.PaymentTransactionApi;
import org.killbill.billing.client.api.gen.PluginInfoApi;
import org.killbill.billing.client.api.gen.SecurityApi;
import org.killbill.billing.client.api.gen.SubscriptionApi;
import org.killbill.billing.client.api.gen.TagApi;
import org.killbill.billing.client.api.gen.TagDefinitionApi;
import org.killbill.billing.client.api.gen.TenantApi;
import org.killbill.billing.client.api.gen.UsageApi;
import org.killbill.billing.client.model.gen.InvoicePayment;
import org.killbill.billing.client.model.gen.Payment;
import org.killbill.billing.client.model.gen.PaymentTransaction;
import org.killbill.billing.client.model.gen.Tenant;
import org.killbill.billing.invoice.glue.DefaultInvoiceModule;
import org.killbill.billing.jaxrs.resources.TestDBRouterResource;
import org.killbill.billing.jetty.HttpServer;
import org.killbill.billing.jetty.HttpServerConfig;
import org.killbill.billing.lifecycle.glue.BusModule;
import org.killbill.billing.notification.plugin.api.ExtBusEventType;
import org.killbill.billing.osgi.api.OSGIServiceRegistration;
import org.killbill.billing.payment.api.TransactionType;
import org.killbill.billing.payment.glue.PaymentModule;
import org.killbill.billing.payment.provider.MockPaymentProviderPluginModule;
import org.killbill.billing.platform.api.KillbillConfigSource;
import org.killbill.billing.server.config.KillbillServerConfig;
import org.killbill.billing.server.listeners.KillbillGuiceListener;
import org.killbill.billing.server.modules.KillbillServerModule;
import org.killbill.billing.tenant.api.TenantCacheInvalidation;
import org.killbill.billing.util.cache.CacheControllerDispatcher;
import org.killbill.billing.util.config.definition.PaymentConfig;
import org.killbill.billing.util.config.definition.SecurityConfig;
import org.killbill.bus.api.PersistentBus;
import org.killbill.notificationq.api.NotificationQueueService;
import org.skife.config.ConfigSource;
import org.skife.config.ConfigurationObjectFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.util.Modules;
public class TestJaxrsBase extends KillbillClient {
private static final Logger log = LoggerFactory.getLogger(TestJaxrsBase.class);
protected final int DEFAULT_CONNECT_TIMEOUT_SEC = 10;
protected final int DEFAULT_READ_TIMEOUT_SEC = 60;
protected final int DEFAULT_REQUEST_TIMEOUT_SEC = DEFAULT_READ_TIMEOUT_SEC;
protected static final String PLUGIN_NAME = "noop";
@Inject
protected OSGIServiceRegistration<Servlet> servletRouter;
@Inject
protected CacheControllerDispatcher cacheControllerDispatcher;
@Inject
protected
@javax.inject.Named(BusModule.EXTERNAL_BUS_NAMED)
PersistentBus externalBus;
@Inject
protected PersistentBus internalBus;
@Inject
protected TestApiListener busHandler;
@Inject
protected NotificationQueueService notificationQueueService;
@Inject
@Named(KillbillServerModule.SHIRO_DATA_SOURCE_ID)
protected DataSource shiroDataSource;
@Inject
protected SecurityConfig securityConfig;
@Inject
protected TenantCacheInvalidation tenantCacheInvalidation;
private static TestKillbillGuiceListener listener;
// static because needed in @BeforeSuite and in each instance class
private static HttpServerConfig config;
private HttpServer server;
private CallbackServer callbackServer;
@Override
protected KillbillConfigSource getConfigSource(final Map<String, String> extraProperties) {
return getConfigSource("/org/killbill/billing/server/killbill.properties", extraProperties);
}
public class TestKillbillGuiceListener extends KillbillGuiceListener {
private final KillbillServerConfig serverConfig;
private final KillbillConfigSource configSource;
public TestKillbillGuiceListener(final KillbillServerConfig serverConfig, final KillbillConfigSource configSource) {
super();
this.serverConfig = serverConfig;
this.configSource = configSource;
}
@Override
protected Module getModule(final ServletContext servletContext) {
return Modules.override(new KillbillServerModule(servletContext, serverConfig, configSource)).with(new GuicyKillbillTestWithEmbeddedDBModule(configSource, clock),
new InvoiceModuleWithMockSender(configSource),
new PaymentMockModule(configSource),
new Module() {
@Override
public void configure(final Binder binder) {
binder.bind(TestDBRouterAPI.class).asEagerSingleton();
binder.bind(TestDBRouterResource.class).asEagerSingleton();
}
});
}
}
public static class InvoiceModuleWithMockSender extends DefaultInvoiceModule {
public InvoiceModuleWithMockSender(final KillbillConfigSource configSource) {
super(configSource);
}
}
private final class PaymentMockModule extends PaymentModule {
public PaymentMockModule(final KillbillConfigSource configSource) {
super(configSource);
}
@Override
protected void installPaymentProviderPlugins(final PaymentConfig config) {
install(new MockPaymentProviderPluginModule(PLUGIN_NAME, clock, configSource));
}
}
protected void setupClient(final String username, final String password, final String apiKey, final String apiSecret) {
requestOptions = requestOptions.extend()
.withTenantApiKey(apiKey)
.withTenantApiSecret(apiSecret)
.build();
killBillHttpClient = new KillBillHttpClient(String.format("http://%s:%d", config.getServerHost(), config.getServerPort()),
username,
password,
apiKey,
apiSecret,
null,
null,
DEFAULT_CONNECT_TIMEOUT_SEC * 1000,
DEFAULT_READ_TIMEOUT_SEC * 1000,
DEFAULT_REQUEST_TIMEOUT_SEC * 1000);
accountApi = new AccountApi(killBillHttpClient);
adminApi = new AdminApi(killBillHttpClient);
bundleApi = new BundleApi(killBillHttpClient);
catalogApi = new CatalogApi(killBillHttpClient);
creditApi = new CreditApi(killBillHttpClient);
customFieldApi = new CustomFieldApi(killBillHttpClient);
exportApi = new ExportApi(killBillHttpClient);
invoiceApi = new InvoiceApi(killBillHttpClient);
invoiceItemApi = new InvoiceItemApi(killBillHttpClient);
invoicePaymentApi = new InvoicePaymentApi(killBillHttpClient);
nodesInfoApi = new NodesInfoApi(killBillHttpClient);
overdueApi = new OverdueApi(killBillHttpClient);
paymentApi = new PaymentApi(killBillHttpClient);
paymentGatewayApi = new PaymentGatewayApi(killBillHttpClient);
paymentMethodApi = new PaymentMethodApi(killBillHttpClient);
paymentTransactionApi = new PaymentTransactionApi(killBillHttpClient);
pluginInfoApi = new PluginInfoApi(killBillHttpClient);
securityApi = new SecurityApi(killBillHttpClient);
subscriptionApi = new SubscriptionApi(killBillHttpClient);
tagApi = new TagApi(killBillHttpClient);
tagDefinitionApi = new TagDefinitionApi(killBillHttpClient);
tenantApi = new TenantApi(killBillHttpClient);
usageApi = new UsageApi(killBillHttpClient);
}
protected void loginTenant(final String apiKey, final String apiSecret) {
setupClient(USERNAME, PASSWORD, apiKey, apiSecret);
}
protected void logoutTenant() {
setupClient(USERNAME, PASSWORD, null, null);
}
protected void login(final String username, final String password) {
setupClient(username, password, DEFAULT_API_KEY, DEFAULT_API_SECRET);
}
protected void logout() {
setupClient(null, null, null, null);
}
@BeforeMethod(groups = "slow")
public void beforeMethod() throws Exception {
if (hasFailed()) {
return;
}
super.beforeMethod();
// Because we truncate the tables, the database record_id auto_increment will be reset
tenantCacheInvalidation.setLatestRecordIdProcessed(0L);
externalBus.startQueue();
internalBus.startQueue();
cacheControllerDispatcher.clearAll();
busHandler.reset();
callbackServlet.reset();
clock.resetDeltaFromReality();
clock.setDay(new LocalDate(2012, 8, 25));
// Make sure to re-generate the api key and secret (could be cached by Shiro)
DEFAULT_API_KEY = UUID.randomUUID().toString();
DEFAULT_API_SECRET = UUID.randomUUID().toString();
// Recreate the tenant (tables have been cleaned-up)
createTenant(DEFAULT_API_KEY, DEFAULT_API_SECRET, true);
}
protected Tenant createTenant(final String apiKey, final String apiSecret, final boolean useGlobalDefault) throws KillBillClientException {
callbackServlet.assertListenerStatus();
callbackServlet.reset();
loginTenant(apiKey, apiSecret);
final Tenant tenant = new Tenant();
tenant.setApiKey(apiKey);
tenant.setApiSecret(apiSecret);
requestOptions = requestOptions.extend()
.withTenantApiKey(apiKey)
.withTenantApiSecret(apiSecret)
.build();
callbackServlet.pushExpectedEvent(ExtBusEventType.TENANT_CONFIG_CHANGE);
if (!useGlobalDefault) {
// Catalog
callbackServlet.pushExpectedEvent(ExtBusEventType.TENANT_CONFIG_CHANGE);
}
final Tenant createdTenant = tenantApi.createTenant(tenant, useGlobalDefault, requestOptions);
// Register tenant for callback
final String callback = callbackServer.getServletEndpoint();
tenantApi.registerPushNotificationCallback(callback, requestOptions);
// Use the flaky version... In the non-happy path, the catalog event sent during tenant creation is received
// before we had the chance to register our servlet. In this case, instead of 2 events, we will only see one
// and the flakyAssertListenerStatus will timeout but not fail the test
callbackServlet.flakyAssertListenerStatus();
createdTenant.setApiSecret(apiSecret);
return createdTenant;
}
@AfterMethod(groups = "slow")
public void afterMethod() throws Exception {
if (hasFailed()) {
return;
}
killBillHttpClient.close();
externalBus.stopQueue();
internalBus.stopQueue();
}
@BeforeClass(groups = "slow")
public void beforeClass() throws Exception {
if (hasFailed()) {
return;
}
listener.getInstantiatedInjector().injectMembers(this);
}
@BeforeSuite(groups = "slow")
public void beforeSuite() throws Exception {
if (hasFailed()) {
return;
}
super.beforeSuite();
// We need to setup these earlier than other tests because the server is started once in @BeforeSuite
final KillbillConfigSource configSource = getConfigSource(extraPropertiesForTestSuite);
final ConfigSource skifeConfigSource = new ConfigSource() {
@Override
public String getString(final String propertyName) {
return configSource.getString(propertyName);
}
};
final KillbillServerConfig serverConfig = new ConfigurationObjectFactory(skifeConfigSource).build(KillbillServerConfig.class);
listener = new TestKillbillGuiceListener(serverConfig, configSource);
config = new ConfigurationObjectFactory(System.getProperties()).build(HttpServerConfig.class);
server = new HttpServer();
server.configure(config, getListeners(), getFilters());
server.start();
callbackServlet = new CallbackServlet();
callbackServer = new CallbackServer(callbackServlet);
callbackServer.startServer();
}
protected Iterable<EventListener> getListeners() {
return new Iterable<EventListener>() {
@Override
public Iterator<EventListener> iterator() {
// Note! This needs to be in sync with web.xml
return ImmutableList.<EventListener>of(listener).iterator();
}
};
}
protected Map<FilterHolder, String> getFilters() {
// Note! This needs to be in sync with web.xml
return ImmutableMap.<FilterHolder, String>of(new FilterHolder(new ShiroFilter()), "/*");
}
@AfterSuite(groups = "slow")
public void afterSuite() {
try {
server.stop();
callbackServer.stopServer();
} catch (final Exception ignored) {
}
}
protected static List<PaymentTransaction> getInvoicePaymentTransactions(final List<InvoicePayment> payments, final TransactionType transactionType) {
final Iterable<PaymentTransaction> transform = Iterables.concat(Iterables.transform(payments, new Function<InvoicePayment, Iterable<PaymentTransaction>>() {
@Override
public Iterable<PaymentTransaction> apply(final InvoicePayment input) {
return input.getTransactions();
}
}));
return filterTransactions(transform, transactionType);
}
protected static List<PaymentTransaction> getPaymentTransactions(final List<Payment> payments, final TransactionType transactionType) {
final Iterable<PaymentTransaction> transform = Iterables.concat(Iterables.transform(payments, new Function<Payment, Iterable<PaymentTransaction>>() {
@Override
public Iterable<PaymentTransaction> apply(final Payment input) {
return input.getTransactions();
}
}));
return filterTransactions(transform, transactionType);
}
protected static List<PaymentTransaction> filterTransactions(final Iterable<PaymentTransaction> paymentTransaction, final TransactionType transactionType) {
return ImmutableList.copyOf(Iterables.filter(paymentTransaction, new Predicate<PaymentTransaction>() {
@Override
public boolean apply(final PaymentTransaction input) {
return input.getTransactionType().equals(transactionType);
}
}));
}
protected String uploadTenantCatalog(final String catalog, final boolean fetch) throws IOException, KillBillClientException {
final String body = getResourceBodyString(catalog);
catalogApi.uploadCatalogXml(body, requestOptions);
return fetch ? catalogApi.getCatalogXml(null, null, requestOptions) : null;
}
protected void uploadTenantOverdueConfig(final String overdue) throws IOException, KillBillClientException {
final String body = getResourceBodyString(overdue);
callbackServlet.pushExpectedEvent(ExtBusEventType.TENANT_CONFIG_CHANGE);
overdueApi.uploadOverdueConfigXml(body, requestOptions);
callbackServlet.assertListenerStatus();
}
protected String getResourceBodyString(final String resource) throws IOException {
final String resourcePath = Resources.getResource(resource).getPath();
final File catalogFile = new File(resourcePath);
return Files.toString(catalogFile, Charset.forName("UTF-8"));
}
protected void printThreadDump() {
final StringBuilder dump = new StringBuilder("Thread dump:\n");
final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
final ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100);
for (final ThreadInfo threadInfo : threadInfos) {
dump.append('"');
dump.append(threadInfo.getThreadName());
dump.append("\" ");
final Thread.State state = threadInfo.getThreadState();
dump.append("\n java.lang.Thread.State: ");
dump.append(state);
final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
for (final StackTraceElement stackTraceElement : stackTraceElements) {
dump.append("\n at ");
dump.append(stackTraceElement);
}
dump.append("\n\n");
}
log.warn(dump.toString());
}
}
| |
package thahn.java.agui.widget;
import thahn.java.agui.app.controller.Handler;
import thahn.java.agui.app.controller.HandlerThread;
import thahn.java.agui.app.controller.Looper;
import thahn.java.agui.app.controller.Message;
import thahn.java.agui.utils.Log;
/**
* <p>A filter constrains data with a filtering pattern.</p>
*
* <p>Filters are usually created by {@link android.widget.Filterable}
* classes.</p>
*
* <p>Filtering operations performed by calling {@link #filter(CharSequence)} or
* {@link #filter(CharSequence, android.widget.Filter.FilterListener)} are
* performed asynchronously. When these methods are called, a filtering request
* is posted in a request queue and processed later. Any call to one of these
* methods will cancel any previous non-executed filtering request.</p>
*
* @see android.widget.Filterable
*/
public abstract class Filter {
private static final String LOG_TAG = "Filter";
private static final String THREAD_NAME = "Filter";
private static final int FILTER_TOKEN = 0xD0D0F00D;
private static final int FINISH_TOKEN = 0xDEADBEEF;
private Handler mThreadHandler;
private Handler mResultHandler;
private Delayer mDelayer;
private final Object mLock = new Object();
/**
* <p>Creates a new asynchronous filter.</p>
*/
public Filter() {
mResultHandler = new ResultsHandler();
}
/**
* Provide an interface that decides how long to delay the message for a given query. Useful
* for heuristics such as posting a delay for the delete key to avoid doing any work while the
* user holds down the delete key.
*
* @param delayer The delayer.
* @hide
*/
public void setDelayer(Delayer delayer) {
synchronized (mLock) {
mDelayer = delayer;
}
}
/**
* <p>Starts an asynchronous filtering operation. Calling this method
* cancels all previous non-executed filtering requests and posts a new
* filtering request that will be executed later.</p>
*
* @param constraint the constraint used to filter the data
*
* @see #filter(CharSequence, android.widget.Filter.FilterListener)
*/
public final void filter(CharSequence constraint) {
filter(constraint, null);
}
/**
* <p>Starts an asynchronous filtering operation. Calling this method
* cancels all previous non-executed filtering requests and posts a new
* filtering request that will be executed later.</p>
*
* <p>Upon completion, the listener is notified.</p>
*
* @param constraint the constraint used to filter the data
* @param listener a listener notified upon completion of the operation
*
* @see #filter(CharSequence)
* @see #performFiltering(CharSequence)
* @see #publishResults(CharSequence, android.widget.Filter.FilterResults)
*/
public final void filter(CharSequence constraint, FilterListener listener) {
synchronized (mLock) {
if (mThreadHandler == null) {
HandlerThread thread = new HandlerThread(
THREAD_NAME, 0);//android.os.Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mThreadHandler = new RequestHandler(thread.getLooper());
}
final long delay = (mDelayer == null) ? 0 : mDelayer.getPostingDelay(constraint);
Message message = mThreadHandler.obtainMessage(FILTER_TOKEN);
RequestArguments args = new RequestArguments();
// make sure we use an immutable copy of the constraint, so that
// it doesn't change while the filter operation is in progress
args.constraint = constraint != null ? constraint.toString() : null;
args.listener = listener;
message.obj = args;
mThreadHandler.removeMessages(FILTER_TOKEN);
mThreadHandler.removeMessages(FINISH_TOKEN);
mThreadHandler.sendMessageDelayed(message, delay);
}
}
/**
* <p>Invoked in a worker thread to filter the data according to the
* constraint. Subclasses must implement this method to perform the
* filtering operation. Results computed by the filtering operation
* must be returned as a {@link android.widget.Filter.FilterResults} that
* will then be published in the UI thread through
* {@link #publishResults(CharSequence,
* android.widget.Filter.FilterResults)}.</p>
*
* <p><strong>Contract:</strong> When the constraint is null, the original
* data must be restored.</p>
*
* @param constraint the constraint used to filter the data
* @return the results of the filtering operation
*
* @see #filter(CharSequence, android.widget.Filter.FilterListener)
* @see #publishResults(CharSequence, android.widget.Filter.FilterResults)
* @see android.widget.Filter.FilterResults
*/
protected abstract FilterResults performFiltering(CharSequence constraint);
/**
* <p>Invoked in the UI thread to publish the filtering results in the
* user interface. Subclasses must implement this method to display the
* results computed in {@link #performFiltering}.</p>
*
* @param constraint the constraint used to filter the data
* @param results the results of the filtering operation
*
* @see #filter(CharSequence, android.widget.Filter.FilterListener)
* @see #performFiltering(CharSequence)
* @see android.widget.Filter.FilterResults
*/
protected abstract void publishResults(CharSequence constraint,
FilterResults results);
/**
* <p>Converts a value from the filtered set into a CharSequence. Subclasses
* should override this method to convert their results. The default
* implementation returns an empty String for null values or the default
* String representation of the value.</p>
*
* @param resultValue the value to convert to a CharSequence
* @return a CharSequence representing the value
*/
public CharSequence convertResultToString(Object resultValue) {
return resultValue == null ? "" : resultValue.toString();
}
/**
* <p>Holds the results of a filtering operation. The results are the values
* computed by the filtering operation and the number of these values.</p>
*/
protected static class FilterResults {
public FilterResults() {
// nothing to see here
}
/**
* <p>Contains all the values computed by the filtering operation.</p>
*/
public Object values;
/**
* <p>Contains the number of values computed by the filtering
* operation.</p>
*/
public int count;
}
/**
* <p>Listener used to receive a notification upon completion of a filtering
* operation.</p>
*/
public static interface FilterListener {
/**
* <p>Notifies the end of a filtering operation.</p>
*
* @param count the number of values computed by the filter
*/
public void onFilterComplete(int count);
}
/**
* <p>Worker thread handler. When a new filtering request is posted from
* {@link android.widget.Filter#filter(CharSequence, android.widget.Filter.FilterListener)},
* it is sent to this handler.</p>
*/
private class RequestHandler extends Handler {
public RequestHandler(Looper looper) {
super(looper);
}
/**
* <p>Handles filtering requests by calling
* {@link Filter#performFiltering} and then sending a message
* with the results to the results handler.</p>
*
* @param msg the filtering request
*/
public void handleMessage(Message msg) {
int what = msg.what;
Message message;
switch (what) {
case FILTER_TOKEN:
RequestArguments args = (RequestArguments) msg.obj;
try {
args.results = performFiltering(args.constraint);
} catch (Exception e) {
args.results = new FilterResults();
Log.w(LOG_TAG, "An exception occured during performFiltering()!", e);
} finally {
message = mResultHandler.obtainMessage(what);
message.obj = args;
message.sendToTarget();
}
synchronized (mLock) {
if (mThreadHandler != null) {
Message finishMessage = mThreadHandler.obtainMessage(FINISH_TOKEN);
mThreadHandler.sendMessageDelayed(finishMessage, 3000);
}
}
break;
case FINISH_TOKEN:
synchronized (mLock) {
if (mThreadHandler != null) {
mThreadHandler.getLooper().quit();
mThreadHandler = null;
}
}
break;
}
}
}
/**
* <p>Handles the results of a filtering operation. The results are
* handled in the UI thread.</p>
*/
private class ResultsHandler extends Handler {
/**
* <p>Messages received from the request handler are processed in the
* UI thread. The processing involves calling
* {@link Filter#publishResults(CharSequence,
* android.widget.Filter.FilterResults)}
* to post the results back in the UI and then notifying the listener,
* if any.</p>
*
* @param msg the filtering results
*/
@Override
public void handleMessage(Message msg) {
RequestArguments args = (RequestArguments) msg.obj;
publishResults(args.constraint, args.results);
if (args.listener != null) {
int count = args.results != null ? args.results.count : -1;
args.listener.onFilterComplete(count);
}
}
}
/**
* <p>Holds the arguments of a filtering request as well as the results
* of the request.</p>
*/
private static class RequestArguments {
/**
* <p>The constraint used to filter the data.</p>
*/
CharSequence constraint;
/**
* <p>The listener to notify upon completion. Can be null.</p>
*/
FilterListener listener;
/**
* <p>The results of the filtering operation.</p>
*/
FilterResults results;
}
/**
* @hide
*/
public interface Delayer {
/**
* @param constraint The constraint passed to {@link Filter#filter(CharSequence)}
* @return The delay that should be used for
* {@link Handler#sendMessageDelayed(android.os.Message, long)}
*/
long getPostingDelay(CharSequence constraint);
}
}
| |
/*
* Druid - a distributed column store.
* Copyright 2012 - 2015 Metamarkets Group 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.druid.client;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.MapMaker;
import com.metamx.common.StringUtils;
import com.metamx.common.lifecycle.LifecycleStart;
import com.metamx.common.lifecycle.LifecycleStop;
import com.metamx.emitter.EmittingLogger;
import io.druid.concurrent.Execs;
import io.druid.curator.inventory.CuratorInventoryManager;
import io.druid.curator.inventory.CuratorInventoryManagerStrategy;
import io.druid.curator.inventory.InventoryManagerConfig;
import io.druid.timeline.DataSegment;
import org.apache.curator.framework.CuratorFramework;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
/**
*/
public abstract class ServerInventoryView<InventoryType> implements ServerView, InventoryView
{
private final EmittingLogger log;
private final CuratorInventoryManager<DruidServer, InventoryType> inventoryManager;
private final AtomicBoolean started = new AtomicBoolean(false);
private final ConcurrentMap<ServerCallback, Executor> serverCallbacks = new MapMaker().makeMap();
private final ConcurrentMap<SegmentCallback, Executor> segmentCallbacks = new MapMaker().makeMap();
public ServerInventoryView(
final EmittingLogger log,
final String announcementsPath,
final String inventoryPath,
final CuratorFramework curator,
final ObjectMapper jsonMapper,
final TypeReference<InventoryType> typeReference
)
{
this.log = log;
this.inventoryManager = new CuratorInventoryManager<>(
curator,
new InventoryManagerConfig()
{
@Override
public String getContainerPath()
{
return announcementsPath;
}
@Override
public String getInventoryPath()
{
return inventoryPath;
}
},
Execs.singleThreaded("ServerInventoryView-%s"),
new CuratorInventoryManagerStrategy<DruidServer, InventoryType>()
{
@Override
public DruidServer deserializeContainer(byte[] bytes)
{
try {
return jsonMapper.readValue(bytes, DruidServer.class);
}
catch (IOException e) {
throw Throwables.propagate(e);
}
}
@Override
public byte[] serializeContainer(DruidServer container)
{
try {
return jsonMapper.writeValueAsBytes(container);
}
catch (JsonProcessingException e) {
throw Throwables.propagate(e);
}
}
@Override
public InventoryType deserializeInventory(byte[] bytes)
{
try {
return jsonMapper.readValue(bytes, typeReference);
}
catch (IOException e) {
CharBuffer.wrap(StringUtils.fromUtf8(bytes).toCharArray());
CharBuffer charBuffer = Charsets.UTF_8.decode(ByteBuffer.wrap(bytes));
log.error(e, "Could not parse json: %s", charBuffer.toString());
throw Throwables.propagate(e);
}
}
@Override
public byte[] serializeInventory(InventoryType inventory)
{
try {
return jsonMapper.writeValueAsBytes(inventory);
}
catch (JsonProcessingException e) {
throw Throwables.propagate(e);
}
}
@Override
public void newContainer(DruidServer container)
{
log.info("New Server[%s]", container);
}
@Override
public void deadContainer(DruidServer deadContainer)
{
log.info("Server Disappeared[%s]", deadContainer);
runServerCallbacks(deadContainer);
}
@Override
public DruidServer updateContainer(DruidServer oldContainer, DruidServer newContainer)
{
return newContainer.addDataSegments(oldContainer);
}
@Override
public DruidServer addInventory(
final DruidServer container,
String inventoryKey,
final InventoryType inventory
)
{
return addInnerInventory(container, inventoryKey, inventory);
}
@Override
public DruidServer updateInventory(
DruidServer container, String inventoryKey, InventoryType inventory
)
{
return updateInnerInventory(container, inventoryKey, inventory);
}
@Override
public DruidServer removeInventory(final DruidServer container, String inventoryKey)
{
return removeInnerInventory(container, inventoryKey);
}
@Override
public void inventoryInitialized()
{
log.info("Inventory Initialized");
runSegmentCallbacks(
new Function<SegmentCallback, CallbackAction>()
{
@Override
public CallbackAction apply(SegmentCallback input)
{
return input.segmentViewInitialized();
}
}
);
}
}
);
}
@LifecycleStart
public void start() throws Exception
{
synchronized (started) {
if (!started.get()) {
inventoryManager.start();
started.set(true);
}
}
}
@LifecycleStop
public void stop() throws IOException
{
synchronized (started) {
if (started.getAndSet(false)) {
inventoryManager.stop();
}
}
}
public boolean isStarted()
{
return started.get();
}
@Override
public DruidServer getInventoryValue(String containerKey)
{
return inventoryManager.getInventoryValue(containerKey);
}
@Override
public Iterable<DruidServer> getInventory()
{
return inventoryManager.getInventory();
}
@Override
public void registerServerCallback(Executor exec, ServerCallback callback)
{
serverCallbacks.put(callback, exec);
}
@Override
public void registerSegmentCallback(Executor exec, SegmentCallback callback)
{
segmentCallbacks.put(callback, exec);
}
public InventoryManagerConfig getInventoryManagerConfig()
{
return inventoryManager.getConfig();
}
protected void runSegmentCallbacks(
final Function<SegmentCallback, CallbackAction> fn
)
{
for (final Map.Entry<SegmentCallback, Executor> entry : segmentCallbacks.entrySet()) {
entry.getValue().execute(
new Runnable()
{
@Override
public void run()
{
if (CallbackAction.UNREGISTER == fn.apply(entry.getKey())) {
segmentCallbacks.remove(entry.getKey());
}
}
}
);
}
}
protected void runServerCallbacks(final DruidServer server)
{
for (final Map.Entry<ServerCallback, Executor> entry : serverCallbacks.entrySet()) {
entry.getValue().execute(
new Runnable()
{
@Override
public void run()
{
if (CallbackAction.UNREGISTER == entry.getKey().serverRemoved(server)) {
serverCallbacks.remove(entry.getKey());
}
}
}
);
}
}
protected void addSingleInventory(
final DruidServer container,
final DataSegment inventory
)
{
log.debug("Server[%s] added segment[%s]", container.getName(), inventory.getIdentifier());
if (container.getSegment(inventory.getIdentifier()) != null) {
log.warn(
"Not adding or running callbacks for existing segment[%s] on server[%s]",
inventory.getIdentifier(),
container.getName()
);
return;
}
container.addDataSegment(inventory.getIdentifier(), inventory);
runSegmentCallbacks(
new Function<SegmentCallback, CallbackAction>()
{
@Override
public CallbackAction apply(SegmentCallback input)
{
return input.segmentAdded(container.getMetadata(), inventory);
}
}
);
}
protected void removeSingleInventory(final DruidServer container, String inventoryKey)
{
log.debug("Server[%s] removed segment[%s]", container.getName(), inventoryKey);
final DataSegment segment = container.getSegment(inventoryKey);
if (segment == null) {
log.warn(
"Not running cleanup or callbacks for non-existing segment[%s] on server[%s]",
inventoryKey,
container.getName()
);
return;
}
container.removeDataSegment(inventoryKey);
runSegmentCallbacks(
new Function<SegmentCallback, CallbackAction>()
{
@Override
public CallbackAction apply(SegmentCallback input)
{
return input.segmentRemoved(container.getMetadata(), segment);
}
}
);
}
protected abstract DruidServer addInnerInventory(
final DruidServer container,
String inventoryKey,
final InventoryType inventory
);
protected abstract DruidServer updateInnerInventory(
final DruidServer container,
String inventoryKey,
final InventoryType inventory
);
protected abstract DruidServer removeInnerInventory(
final DruidServer container,
String inventoryKey
);
}
| |
/*
* Copyright 2000-2015 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.maddyhome.idea.copyright.ui;
import com.intellij.ide.DataManager;
import com.intellij.ide.util.scopeChooser.PackageSetChooserCombo;
import com.intellij.ide.util.scopeChooser.ScopeChooserConfigurable;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.options.ex.Settings;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.LabeledComponent;
import com.intellij.openapi.util.Comparing;
import com.intellij.packageDependencies.DefaultScopesProvider;
import com.intellij.packageDependencies.DependencyValidationManager;
import com.intellij.psi.search.scope.packageSet.CustomScopesProviderEx;
import com.intellij.psi.search.scope.packageSet.NamedScope;
import com.intellij.psi.search.scope.packageSet.NamedScopesHolder;
import com.intellij.ui.HyperlinkLabel;
import com.intellij.ui.JBColor;
import com.intellij.ui.ListCellRendererWrapper;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.components.editors.JBComboBoxTableCellEditorComponent;
import com.intellij.ui.table.TableView;
import com.intellij.util.Function;
import com.intellij.util.ui.*;
import com.maddyhome.idea.copyright.CopyrightManager;
import com.maddyhome.idea.copyright.CopyrightProfile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.util.*;
import java.util.List;
public class ProjectSettingsPanel {
private final Project myProject;
private final CopyrightProfilesPanel myProfilesModel;
private final CopyrightManager myManager;
private final TableView<ScopeSetting> myScopeMappingTable;
private final ListTableModel<ScopeSetting> myScopeMappingModel;
private final JComboBox myProfilesComboBox = new JComboBox();
private final HyperlinkLabel myScopesLink = new HyperlinkLabel();
public ProjectSettingsPanel(Project project, CopyrightProfilesPanel profilesModel) {
myProject = project;
myProfilesModel = profilesModel;
myProfilesModel.addItemsChangeListener(new Runnable() {
public void run() {
final Object selectedItem = myProfilesComboBox.getSelectedItem();
reloadCopyrightProfiles();
myProfilesComboBox.setSelectedItem(selectedItem);
final ArrayList<ScopeSetting> toRemove = new ArrayList<>();
for (ScopeSetting setting : myScopeMappingModel.getItems()) {
if (setting.getProfile() == null) {
toRemove.add(setting);
}
}
for (ScopeSetting setting : toRemove) {
myScopeMappingModel.removeRow(myScopeMappingModel.indexOf(setting));
}
}
});
myManager = CopyrightManager.getInstance(project);
ColumnInfo[] columns = {new ScopeColumn(), new SettingColumn()};
myScopeMappingModel = new ListTableModel<>(columns, new ArrayList<>(), 0);
myScopeMappingTable = new TableView<>(myScopeMappingModel);
reloadCopyrightProfiles();
myProfilesComboBox.setRenderer(new ListCellRendererWrapper<CopyrightProfile>() {
@Override
public void customize(JList list, CopyrightProfile value, int index, boolean selected, boolean hasFocus) {
if (value == null) {
setText("No copyright");
}
else {
setText(value.getName());
}
}
});
myScopesLink.setVisible(!myProject.isDefault());
myScopesLink.setHyperlinkText("Select Scopes to add new scopes or modify existing ones");
myScopesLink.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(final HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
DataContext context = DataManager.getInstance().getDataContextFromFocus().getResult();
if (context != null) {
Settings settings = Settings.KEY.getData(context);
if (settings != null) {
settings.select(settings.find(ScopeChooserConfigurable.PROJECT_SCOPES));
}
}
}
}
});
}
public void reloadCopyrightProfiles() {
final DefaultComboBoxModel boxModel = (DefaultComboBoxModel)myProfilesComboBox.getModel();
boxModel.removeAllElements();
boxModel.addElement(null);
for (CopyrightProfile profile : myProfilesModel.getAllProfiles().values()) {
boxModel.addElement(profile);
}
}
public JComponent getMainComponent() {
final LabeledComponent<JComboBox> component = new LabeledComponent<>();
component.setText("Default &project copyright:");
component.setLabelLocation(BorderLayout.WEST);
component.setComponent(myProfilesComboBox);
ElementProducer<ScopeSetting> producer = new ElementProducer<ScopeSetting>() {
@Override
public ScopeSetting createElement() {
return new ScopeSetting(DefaultScopesProvider.getAllScope(), myProfilesModel.getAllProfiles().values().iterator().next());
}
@Override
public boolean canCreateElement() {
return !myProfilesModel.getAllProfiles().isEmpty();
}
};
ToolbarDecorator decorator = ToolbarDecorator.createDecorator(myScopeMappingTable, producer);
return JBUI.Panels.simplePanel(0, 10)
.addToTop(component)
.addToCenter(decorator.createPanel())
.addToBottom(myScopesLink);
}
public boolean isModified() {
final CopyrightProfile defaultCopyright = myManager.getDefaultCopyright();
final Object selected = myProfilesComboBox.getSelectedItem();
if (defaultCopyright != selected) {
if (selected == null) return true;
if (defaultCopyright == null) return true;
if (!defaultCopyright.equals(selected)) return true;
}
final Map<String, String> map = myManager.getCopyrightsMapping();
if (map.size() != myScopeMappingModel.getItems().size()) return true;
final Iterator<String> iterator = map.keySet().iterator();
for (ScopeSetting setting : myScopeMappingModel.getItems()) {
final NamedScope scope = setting.getScope();
if (!iterator.hasNext()) return true;
final String scopeName = iterator.next();
if (scope == null || !Comparing.strEqual(scopeName, scope.getName())) return true;
final String profileName = map.get(scope.getName());
if (profileName == null) return true;
if (!profileName.equals(setting.getProfileName())) return true;
}
return false;
}
public void apply() {
Collection<CopyrightProfile> profiles = new ArrayList<>(myManager.getCopyrights());
myManager.clearCopyrights();
for (CopyrightProfile profile : profiles) {
myManager.addCopyright(profile);
}
final List<ScopeSetting> settingList = myScopeMappingModel.getItems();
for (ScopeSetting scopeSetting : settingList) {
myManager.mapCopyright(scopeSetting.getScope().getName(), scopeSetting.getProfileName());
}
myManager.setDefaultCopyright((CopyrightProfile)myProfilesComboBox.getSelectedItem());
}
public void reset() {
myProfilesComboBox.setSelectedItem(myManager.getDefaultCopyright());
final List<ScopeSetting> mappings = new ArrayList<>();
final Map<String, String> copyrights = myManager.getCopyrightsMapping();
final DependencyValidationManager manager = DependencyValidationManager.getInstance(myProject);
final Set<String> scopes2Unmap = new HashSet<>();
for (final String scopeName : copyrights.keySet()) {
final NamedScope scope = manager.getScope(scopeName);
if (scope != null) {
mappings.add(new ScopeSetting(scope, copyrights.get(scopeName)));
}
else {
scopes2Unmap.add(scopeName);
}
}
for (String scopeName : scopes2Unmap) {
myManager.unmapCopyright(scopeName);
}
myScopeMappingModel.setItems(mappings);
}
private class ScopeSetting {
private NamedScope myScope;
private CopyrightProfile myProfile;
private String myProfileName;
private ScopeSetting(NamedScope scope, CopyrightProfile profile) {
myScope = scope;
myProfile = profile;
if (myProfile != null) {
myProfileName = myProfile.getName();
}
}
public ScopeSetting(NamedScope scope, String profile) {
myScope = scope;
myProfileName = profile;
}
public CopyrightProfile getProfile() {
if (myProfileName != null) {
myProfile = myProfilesModel.getAllProfiles().get(getProfileName());
}
return myProfile;
}
public void setProfile(@NotNull CopyrightProfile profile) {
myProfile = profile;
myProfileName = profile.getName();
}
public NamedScope getScope() {
return myScope;
}
public void setScope(NamedScope scope) {
myScope = scope;
}
public String getProfileName() {
return myProfile != null ? myProfile.getName() : myProfileName;
}
}
private class SettingColumn extends MyColumnInfo<CopyrightProfile> {
private SettingColumn() {
super("Copyright");
}
public TableCellRenderer getRenderer(final ScopeSetting scopeSetting) {
return new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
final Component rendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (!isSelected) {
final CopyrightProfile profile = myProfilesModel.getAllProfiles().get(scopeSetting.getProfileName());
setForeground(profile == null ? JBColor.RED : UIUtil.getTableForeground());
}
setText(scopeSetting.getProfileName());
return rendererComponent;
}
};
}
public TableCellEditor getEditor(final ScopeSetting scopeSetting) {
return new AbstractTableCellEditor() {
private final JBComboBoxTableCellEditorComponent myProfilesChooser = new JBComboBoxTableCellEditorComponent();
public Object getCellEditorValue() {
return myProfilesChooser.getEditorValue();
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
final List<CopyrightProfile> copyrights = new ArrayList<>(myProfilesModel.getAllProfiles().values());
Collections.sort(copyrights, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()));
myProfilesChooser.setCell(table, row, column);
myProfilesChooser.setOptions(copyrights.toArray());
myProfilesChooser.setDefaultValue(scopeSetting.getProfile());
myProfilesChooser.setToString(o -> ((CopyrightProfile)o).getName());
return myProfilesChooser;
}
};
}
public CopyrightProfile valueOf(final ScopeSetting object) {
return object.getProfile();
}
public void setValue(final ScopeSetting scopeSetting, final CopyrightProfile copyrightProfile) {
if (copyrightProfile != null) {
scopeSetting.setProfile(copyrightProfile);
}
}
}
private class ScopeColumn extends MyColumnInfo<NamedScope> {
private ScopeColumn() {
super("Scope");
}
public TableCellRenderer getRenderer(final ScopeSetting mapping) {
return new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (value == null) {
setText("");
}
else {
final String scopeName = ((NamedScope)value).getName();
if (!isSelected) {
final NamedScope scope = NamedScopesHolder.getScope(myProject, scopeName);
if (scope == null) setForeground(JBColor.RED);
}
setText(scopeName);
}
return this;
}
};
}
public TableCellEditor getEditor(final ScopeSetting mapping) {
return new AbstractTableCellEditor() {
private PackageSetChooserCombo myScopeChooser;
@Nullable
public Object getCellEditorValue() {
return myScopeChooser.getSelectedScope();
}
public Component getTableCellEditorComponent(final JTable table, Object value, boolean isSelected, int row, int column) {
myScopeChooser = new PackageSetChooserCombo(myProject, value == null ? null : ((NamedScope)value).getName(), false, false){
@Override
protected NamedScope[] createModel() {
final NamedScope[] model = super.createModel();
final ArrayList<NamedScope> filteredScopes = new ArrayList<>(Arrays.asList(model));
CustomScopesProviderEx.filterNoSettingsScopes(myProject, filteredScopes);
return filteredScopes.toArray(new NamedScope[filteredScopes.size()]);
}
};
((JBComboBoxTableCellEditorComponent)myScopeChooser.getChildComponent()).setCell(table, row, column);
return myScopeChooser;
}
};
}
public NamedScope valueOf(final ScopeSetting mapping) {
return mapping.getScope();
}
public void setValue(final ScopeSetting mapping, final NamedScope set) {
mapping.setScope(set);
}
}
private static abstract class MyColumnInfo<T> extends ColumnInfo<ScopeSetting, T> {
protected MyColumnInfo(final String name) {
super(name);
}
@Override
public boolean isCellEditable(final ScopeSetting item) {
return true;
}
}
}
| |
/*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.stetho.inspector.elements.android;
import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import com.facebook.stetho.common.Accumulator;
import com.facebook.stetho.common.Predicate;
import com.facebook.stetho.common.ThreadBound;
import com.facebook.stetho.common.Util;
import com.facebook.stetho.common.android.ViewUtil;
import com.facebook.stetho.inspector.elements.DocumentProvider;
import com.facebook.stetho.inspector.elements.Descriptor;
import com.facebook.stetho.inspector.elements.DescriptorMap;
import com.facebook.stetho.inspector.elements.DocumentProviderListener;
import com.facebook.stetho.inspector.elements.NodeDescriptor;
import com.facebook.stetho.inspector.elements.ObjectDescriptor;
import com.facebook.stetho.inspector.helper.ThreadBoundProxy;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
final class AndroidDocumentProvider extends ThreadBoundProxy
implements DocumentProvider, AndroidDescriptorHost {
private static final int INSPECT_OVERLAY_COLOR = 0x40FFFFFF;
private static final int INSPECT_HOVER_COLOR = 0x404040ff;
private final Application mApplication;
private final DescriptorMap mDescriptorMap;
private final AndroidDocumentRoot mDocumentRoot;
private final ViewHighlighter mHighlighter;
private final InspectModeHandler mInspectModeHandler;
private @Nullable DocumentProviderListener mListener;
// We don't yet have an an implementation for reliably detecting fine-grained changes in the
// View tree. So, for now at least, we have a timer that runs every so often and just reports
// that we changed. Our listener will then read the entire Document from us and transmit the
// changes to Chrome. Detecting, reporting, and traversing fine-grained changes is a future work
// item (see Issue #210).
private static final long REPORT_CHANGED_INTERVAL_MS = 1000;
private boolean mIsReportChangesTimerPosted = false;
private final Runnable mReportChangesTimer = new Runnable() {
@Override
public void run() {
mIsReportChangesTimerPosted = false;
if (mListener != null) {
mListener.onPossiblyChanged();
mIsReportChangesTimerPosted = true;
postDelayed(this, REPORT_CHANGED_INTERVAL_MS);
}
}
};
public AndroidDocumentProvider(Application application, ThreadBound enforcer) {
super(enforcer);
mApplication = Util.throwIfNull(application);
mDocumentRoot = new AndroidDocumentRoot(application);
mDescriptorMap = new DescriptorMap()
.beginInit()
.register(Activity.class, new ActivityDescriptor())
.register(AndroidDocumentRoot.class, mDocumentRoot)
.register(Application.class, new ApplicationDescriptor())
.register(Dialog.class, new DialogDescriptor());
DialogFragmentDescriptor.register(mDescriptorMap);
FragmentDescriptor.register(mDescriptorMap)
.register(Object.class, new ObjectDescriptor())
.register(TextView.class, new TextViewDescriptor())
.register(View.class, new ViewDescriptor())
.register(ViewGroup.class, new ViewGroupDescriptor())
.register(Window.class, new WindowDescriptor())
.setHost(this)
.endInit();
mHighlighter = ViewHighlighter.newInstance();
mInspectModeHandler = new InspectModeHandler();
}
@Override
public void dispose() {
verifyThreadAccess();
mHighlighter.clearHighlight();
mInspectModeHandler.disable();
removeCallbacks(mReportChangesTimer);
mIsReportChangesTimerPosted = false;
mListener = null;
}
@Override
public void setListener(DocumentProviderListener listener) {
verifyThreadAccess();
mListener = listener;
if (mListener == null && mIsReportChangesTimerPosted) {
mIsReportChangesTimerPosted = false;
removeCallbacks(mReportChangesTimer);
} else if (mListener != null && !mIsReportChangesTimerPosted) {
mIsReportChangesTimerPosted = true;
postDelayed(mReportChangesTimer, REPORT_CHANGED_INTERVAL_MS);
}
}
@Override
public Object getRootElement() {
verifyThreadAccess();
return mDocumentRoot;
}
@Override
public NodeDescriptor getNodeDescriptor(Object element) {
verifyThreadAccess();
return getDescriptor(element);
}
@Override
public void highlightElement(Object element, int color) {
verifyThreadAccess();
View highlightingView = getHighlightingView(element);
if (highlightingView == null) {
mHighlighter.clearHighlight();
} else {
mHighlighter.setHighlightedView(highlightingView, color);
}
}
@Override
public void hideHighlight() {
verifyThreadAccess();
mHighlighter.clearHighlight();
}
@Override
public void setInspectModeEnabled(boolean enabled) {
verifyThreadAccess();
if (enabled) {
mInspectModeHandler.enable();
} else {
mInspectModeHandler.disable();
}
}
@Override
public void setAttributesAsText(Object element, String text) {
verifyThreadAccess();
Descriptor descriptor = mDescriptorMap.get(element.getClass());
if (descriptor != null) {
descriptor.setAttributesAsText(element, text);
}
}
// Descriptor.Host implementation
@Override
public Descriptor getDescriptor(Object element) {
return (element == null) ? null : mDescriptorMap.get(element.getClass());
}
@Override
public void onAttributeModified(Object element, String name, String value) {
if (mListener != null) {
mListener.onAttributeModified(element, name, value);
}
}
@Override
public void onAttributeRemoved(Object element, String name) {
if (mListener != null) {
mListener.onAttributeRemoved(element, name);
}
}
// AndroidDescriptorHost implementation
@Override
public View getHighlightingView(Object element) {
if (element == null) {
return null;
}
View highlightingView = null;
Class<?> theClass = element.getClass();
Descriptor lastDescriptor = null;
while (highlightingView == null && theClass != null) {
Descriptor descriptor = mDescriptorMap.get(theClass);
if (descriptor == null) {
return null;
}
if (descriptor != lastDescriptor && descriptor instanceof HighlightableDescriptor) {
highlightingView = ((HighlightableDescriptor) descriptor).getViewForHighlighting(element);
}
lastDescriptor = descriptor;
theClass = theClass.getSuperclass();
}
return highlightingView;
}
private void getWindows(final Accumulator<Window> accumulator) {
Descriptor appDescriptor = getDescriptor(mApplication);
if (appDescriptor != null) {
Accumulator<Object> elementAccumulator = new Accumulator<Object>() {
@Override
public void store(Object element) {
if (element instanceof Window) {
// Store the Window and do not recurse into its children.
accumulator.store((Window) element);
} else {
// Recursively scan this element's children in search of more Windows.
Descriptor elementDescriptor = getDescriptor(element);
if (elementDescriptor != null) {
elementDescriptor.getChildren(element, this);
}
}
}
};
appDescriptor.getChildren(mApplication, elementAccumulator);
}
}
private final class InspectModeHandler {
private final Predicate<View> mViewSelector = new Predicate<View>() {
@Override
public boolean apply(View view) {
return !(view instanceof DocumentHiddenView);
}
};
private List<View> mOverlays;
public void enable() {
verifyThreadAccess();
if (mOverlays != null) {
disable();
}
mOverlays = new ArrayList<>();
getWindows(new Accumulator<Window>() {
@Override
public void store(Window object) {
if (object.peekDecorView() instanceof ViewGroup) {
final ViewGroup decorView = (ViewGroup) object.peekDecorView();
OverlayView overlayView = new OverlayView(mApplication);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
decorView.addView(overlayView, layoutParams);
decorView.bringChildToFront(overlayView);
mOverlays.add(overlayView);
}
}
});
}
public void disable() {
verifyThreadAccess();
if (mOverlays == null) {
return;
}
for (int i = 0; i < mOverlays.size(); ++i) {
final View overlayView = mOverlays.get(i);
ViewGroup decorViewGroup = (ViewGroup)overlayView.getParent();
decorViewGroup.removeView(overlayView);
}
mOverlays = null;
}
private final class OverlayView extends DocumentHiddenView {
public OverlayView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(INSPECT_OVERLAY_COLOR);
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (getParent() instanceof View) {
final View parent = (View)getParent();
View view = ViewUtil.hitTest(parent, event.getX(), event.getY(), mViewSelector);
if (event.getAction() != MotionEvent.ACTION_CANCEL) {
if (view != null) {
mHighlighter.setHighlightedView(view, INSPECT_HOVER_COLOR);
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mListener != null) {
mListener.onInspectRequested(view);
}
}
}
}
}
return true;
}
}
}
}
| |
/*
* 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.devtools.j2objc.javac;
import com.google.devtools.j2objc.ast.Javadoc;
import com.google.devtools.j2objc.ast.SimpleName;
import com.google.devtools.j2objc.ast.SourcePosition;
import com.google.devtools.j2objc.ast.TagElement;
import com.google.devtools.j2objc.ast.TagElement.TagKind;
import com.google.devtools.j2objc.ast.TextElement;
import com.google.devtools.j2objc.ast.TreeNode;
import com.google.devtools.j2objc.util.ErrorUtil;
import com.sun.source.doctree.AuthorTree;
import com.sun.source.doctree.CommentTree;
import com.sun.source.doctree.DeprecatedTree;
import com.sun.source.doctree.DocCommentTree;
import com.sun.source.doctree.DocTree;
import com.sun.source.doctree.EndElementTree;
import com.sun.source.doctree.EntityTree;
import com.sun.source.doctree.ErroneousTree;
import com.sun.source.doctree.IdentifierTree;
import com.sun.source.doctree.LinkTree;
import com.sun.source.doctree.LiteralTree;
import com.sun.source.doctree.ParamTree;
import com.sun.source.doctree.ReferenceTree;
import com.sun.source.doctree.ReturnTree;
import com.sun.source.doctree.SeeTree;
import com.sun.source.doctree.SinceTree;
import com.sun.source.doctree.StartElementTree;
import com.sun.source.doctree.TextTree;
import com.sun.source.doctree.ThrowsTree;
import com.sun.source.doctree.VersionTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.DocSourcePositions;
import com.sun.source.util.DocTreeScanner;
import com.sun.source.util.DocTrees;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.tree.DCTree;
import java.util.Collections;
import java.util.List;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.VariableElement;
/**
* Converts a javac javadoc comment into a Javadoc AST node.
*/
class JavadocConverter extends DocTreeScanner<Void, TagElement> {
private final Element element;
private final DocCommentTree docComment;
private final DocSourcePositions docSourcePositions;
private final String source;
private final CompilationUnitTree unit;
private final boolean reportWarnings;
private JavadocConverter(Element element, DocCommentTree docComment, String source,
DocTrees docTrees, CompilationUnitTree unit, boolean reportWarnings) {
this.element = element;
this.docComment = docComment;
this.source = source;
this.docSourcePositions = docTrees.getSourcePositions();
this.unit = unit;
this.reportWarnings = reportWarnings;
}
/** Returns an AST node for the javadoc comment of a specified class, method, or field element. */
static Javadoc convertJavadoc(
TreePath path, String source, JavacEnvironment env, boolean reportWarnings) {
DocTrees docTrees = DocTrees.instance(env.task());
DocCommentTree docComment = docTrees.getDocCommentTree(path);
if (docComment == null) {
return null; // Declaration does not have a javadoc comment.
}
JavadocConverter converter =
new JavadocConverter(
env.treeUtilities().getElement(path),
docComment,
source,
docTrees,
path.getCompilationUnit(),
reportWarnings);
Javadoc result = new Javadoc();
// First tag is the description.
TagElement newTag = new TagElement().setTagKind(TagElement.TagKind.DESCRIPTION);
converter.scan(docComment.getFirstSentence(), newTag);
converter.scan(docComment.getBody(), newTag);
if (!newTag.getFragments().isEmpty()) {
List<TreeNode> fragments = newTag.getFragments();
int start = fragments.get(0).getStartPosition();
TreeNode lastFragment = fragments.get(fragments.size() - 1);
int end = start + lastFragment.getLength();
converter.setPos(newTag, start, end);
result.addTag(newTag);
}
for (DocTree tag : docComment.getBlockTags()) {
if (tag.getKind() != DocTree.Kind.ERRONEOUS) {
newTag = new TagElement();
converter.scan(tag, newTag);
result.addTag(newTag);
}
}
return result;
}
@Override
public Void visitAuthor(AuthorTree node, TagElement tag) {
setTagValues(tag, TagElement.TagKind.AUTHOR, node, node.getName());
return null;
}
@Override
public Void visitComment(CommentTree node, TagElement tag) {
tag.addFragment(setPos(node, new TextElement().setText(node.getBody())));
return null;
}
@Override
public Void visitDeprecated(DeprecatedTree node, TagElement tag) {
setTagValues(tag, TagElement.TagKind.DEPRECATED, node, node.getBody());
return null;
}
@Override
public Void visitEndElement(EndElementTree node, TagElement tag) {
String text = String.format("</%s>", node.getName().toString());
int pos = pos(node);
tag.addFragment(setPos(new TextElement().setText(text), pos, pos + text.length()));
return null;
}
@Override
public Void visitEntity(EntityTree node, TagElement tag) {
String text = String.format("&%s;", node.getName().toString());
tag.addFragment(setPos(node, new TextElement().setText(text)));
return null;
}
@Override
public Void visitErroneous(ErroneousTree node, TagElement tag) {
if (reportWarnings) {
// Update node's position to be relative to the whole source file, instead of just
// the doc-comment's start. That way, the diagnostic printer will fetch the correct
// text for the line the error is on.
((DCTree.DCErroneous) node).pos =
((DCTree) node).pos((DCTree.DCDocComment) docComment).getStartPosition();
ErrorUtil.warning(node.getDiagnostic().toString());
} else {
// Include erroneous text in doc-comment as is.
TreeNode newNode = setPos(node, new TextElement().setText(node.getBody()));
tag.addFragment(newNode);
}
return null;
}
@Override
public Void visitIdentifier(IdentifierTree node, TagElement tag) {
tag.addFragment(setPos(node, new TextElement().setText(node.getName().toString())));
return null;
}
@Override
public Void visitLink(LinkTree node, TagElement tag) {
TagElement newTag = new TagElement().setTagKind(TagKind.parse("@" + node.getTagName()));
setPos(node, newTag);
if (node.getLabel().isEmpty()) {
scan(node.getReference(), newTag);
} else {
scan(node.getLabel(), newTag);
}
tag.addFragment(newTag);
return null;
}
@Override
public Void visitLiteral(LiteralTree node, TagElement tag) {
TagElement newTag = new TagElement();
TagKind tagKind = node.getKind() == DocTree.Kind.CODE ? TagKind.CODE : TagKind.LITERAL;
setTagValues(newTag, tagKind, node, node.getBody());
tag.addFragment(newTag);
return null;
}
@Override
public Void visitParam(ParamTree node, TagElement tag) {
IdentifierTree identifier = node.getName();
if (identifier == null || node.isTypeParameter()) {
return null;
}
List<? extends VariableElement> params = element instanceof ExecutableElement
? ((ExecutableElement) element).getParameters() : Collections.emptyList();
tag.setTagKind(TagElement.TagKind.PARAM);
String name = identifier.toString();
VariableElement param = null;
for (VariableElement p : params) {
if (name.equals(p.getSimpleName().toString())) {
param = p;
break;
}
}
// param will be null if the @param tag refers to a nonexistent parameter.
TreeNode nameNode = param != null ? new SimpleName(param) : new SimpleName(name);
setPos(identifier, nameNode);
tag.addFragment(nameNode);
scan(node.getDescription(), tag);
int lastEnd = nameNode.getStartPosition();
for (TreeNode fragment : tag.getFragments()) {
// Fix up positions to match JDT's.
// TODO(tball): remove and fix JavadocGenerator after javac switch.
if (fragment.getKind() == TreeNode.Kind.TEXT_ELEMENT) {
TextElement text = (TextElement) fragment;
text.setText(" " + text.getText());
text.setSourceRange(text.getStartPosition(), text.getLength() + 1);
}
int thisEnd = lastEnd + fragment.getLength();
setPos(fragment, lastEnd, thisEnd);
lastEnd = thisEnd;
}
setPos(tag, pos(node), endPos(node));
tag.setLineNumber(nameNode.getLineNumber());
return null;
}
@Override
public Void visitReference(ReferenceTree node, TagElement tag) {
TreeNode newNode = new TextElement().setText(node.getSignature());
tag.addFragment(setPos(node, newNode));
return null;
}
@Override
public Void visitReturn(ReturnTree node, TagElement tag) {
tag.setTagKind(TagElement.TagKind.RETURN);
setPos(node, tag);
scan(node.getDescription(), tag);
return null;
}
@Override
public Void visitSee(SeeTree node, TagElement tag) {
tag.setTagKind(TagElement.TagKind.SEE);
setPos(node, tag);
scan(node.getReference(), tag);
return null;
}
@Override
public Void visitSince(SinceTree node, TagElement tag) {
setTagValues(tag, TagElement.TagKind.SINCE, node, node.getBody());
return null;
}
@Override
public Void visitStartElement(StartElementTree node, TagElement tag) {
StringBuilder sb = new StringBuilder("<");
sb.append(node.getName());
for (DocTree attr : node.getAttributes()) {
sb.append(' ');
sb.append(attr);
}
sb.append('>');
tag.addFragment(setPos(node, new TextElement().setText(sb.toString())));
return null;
}
@Override
public Void visitText(TextTree node, TagElement tag) {
String[] lines = node.getBody().split("\n");
int linePos = pos(node);
for (String line : lines) {
if (line.length() > 0) {
linePos = source.indexOf(line, linePos);
int endPos = linePos + line.length();
TreeNode newNode = setPos(new TextElement().setText(line), linePos, endPos);
tag.addFragment(newNode);
}
}
return null;
}
@Override
public Void visitThrows(ThrowsTree node, TagElement tag) {
setTagValues(tag, TagElement.TagKind.THROWS, node, node.getExceptionName());
scan(node.getDescription(), tag);
return null;
}
@Override
public Void visitVersion(VersionTree node, TagElement tag) {
setTagValues(tag, TagElement.TagKind.VERSION, node, node.getBody());
return null;
}
/**
* Updates a tag element with values from the javadoc node.
*/
private TagElement setTagValues(TagElement tag, TagKind tagKind, DocTree javadocNode,
DocTree body) {
tag.setTagKind(tagKind);
setPos(javadocNode, tag);
scan(body, tag);
return tag;
}
private TagElement setTagValues(TagElement tag, TagKind tagKind, DocTree javadocNode,
List<? extends DocTree> body) {
tag.setTagKind(tagKind);
setPos(javadocNode, tag);
scan(body, tag);
return tag;
}
/**
* Set a TreeNode's position using the original DocTree.
*/
private TreeNode setPos(DocTree node, TreeNode newNode) {
int pos = pos(node);
return newNode.setPosition(new SourcePosition(pos, length(node), lineNumber(pos)));
}
/**
* Set a TreeNode's position using begin and end source offsets. Its line number
* is unchanged.
*/
private TreeNode setPos(TreeNode newNode, int pos, int endPos) {
return newNode.setPosition(new SourcePosition(pos, endPos - pos, lineNumber(pos)));
}
private int pos(DocTree node) {
return (int) docSourcePositions.getStartPosition(unit, docComment, node);
}
private int endPos(DocTree node) {
return (int) docSourcePositions.getEndPosition(unit, docComment, node);
}
private int lineNumber(int pos) {
return (int) unit.getLineMap().getLineNumber(pos);
}
private int length(DocTree node) {
return endPos(node) - pos(node);
}
}
| |
/*
* Copyright (C) 2016 Square, 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 okhttp3.internal.platform;
import android.os.Build;
import android.util.Log;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.util.List;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.Protocol;
import okhttp3.internal.Util;
import okhttp3.internal.tls.BasicTrustRootIndex;
import okhttp3.internal.tls.CertificateChainCleaner;
import okhttp3.internal.tls.TrustRootIndex;
import static okhttp3.internal.Util.assertionError;
/** Android 2.3 or better. */
class AndroidPlatform extends Platform {
private static final int MAX_LOG_LENGTH = 4000;
private final Class<?> sslParametersClass;
private final OptionalMethod<Socket> setUseSessionTickets;
private final OptionalMethod<Socket> setHostname;
// Non-null on Android 5.0+.
private final OptionalMethod<Socket> getAlpnSelectedProtocol;
private final OptionalMethod<Socket> setAlpnProtocols;
private final CloseGuard closeGuard = CloseGuard.get();
AndroidPlatform(Class<?> sslParametersClass, OptionalMethod<Socket> setUseSessionTickets,
OptionalMethod<Socket> setHostname, OptionalMethod<Socket> getAlpnSelectedProtocol,
OptionalMethod<Socket> setAlpnProtocols) {
this.sslParametersClass = sslParametersClass;
this.setUseSessionTickets = setUseSessionTickets;
this.setHostname = setHostname;
this.getAlpnSelectedProtocol = getAlpnSelectedProtocol;
this.setAlpnProtocols = setAlpnProtocols;
}
@Override public void connectSocket(Socket socket, InetSocketAddress address,
int connectTimeout) throws IOException {
try {
socket.connect(address, connectTimeout);
} catch (AssertionError e) {
if (Util.isAndroidGetsocknameError(e)) throw new IOException(e);
throw e;
} catch (SecurityException e) {
// Before android 4.3, socket.connect could throw a SecurityException
// if opening a socket resulted in an EACCES error.
IOException ioException = new IOException("Exception in connect");
ioException.initCause(e);
throw ioException;
} catch (ClassCastException e) {
// On android 8.0, socket.connect throws a ClassCastException due to a bug
// see https://issuetracker.google.com/issues/63649622
if (Build.VERSION.SDK_INT == 26) {
IOException ioException = new IOException("Exception in connect");
ioException.initCause(e);
throw ioException;
} else {
throw e;
}
}
}
@Override protected X509TrustManager trustManager(SSLSocketFactory sslSocketFactory) {
Object context = readFieldOrNull(sslSocketFactory, sslParametersClass, "sslParameters");
if (context == null) {
// If that didn't work, try the Google Play Services SSL provider before giving up. This
// must be loaded by the SSLSocketFactory's class loader.
try {
Class<?> gmsSslParametersClass = Class.forName(
"com.google.android.gms.org.conscrypt.SSLParametersImpl", false,
sslSocketFactory.getClass().getClassLoader());
context = readFieldOrNull(sslSocketFactory, gmsSslParametersClass, "sslParameters");
} catch (ClassNotFoundException e) {
return super.trustManager(sslSocketFactory);
}
}
X509TrustManager x509TrustManager = readFieldOrNull(
context, X509TrustManager.class, "x509TrustManager");
if (x509TrustManager != null) return x509TrustManager;
return readFieldOrNull(context, X509TrustManager.class, "trustManager");
}
@Override public void configureTlsExtensions(
SSLSocket sslSocket, String hostname, List<Protocol> protocols) {
// Enable SNI and session tickets.
if (hostname != null) {
setUseSessionTickets.invokeOptionalWithoutCheckedException(sslSocket, true);
setHostname.invokeOptionalWithoutCheckedException(sslSocket, hostname);
}
// Enable ALPN.
if (setAlpnProtocols != null && setAlpnProtocols.isSupported(sslSocket)) {
Object[] parameters = {concatLengthPrefixed(protocols)};
setAlpnProtocols.invokeWithoutCheckedException(sslSocket, parameters);
}
}
@Override public String getSelectedProtocol(SSLSocket socket) {
if (getAlpnSelectedProtocol == null) return null;
if (!getAlpnSelectedProtocol.isSupported(socket)) return null;
byte[] alpnResult = (byte[]) getAlpnSelectedProtocol.invokeWithoutCheckedException(socket);
return alpnResult != null ? new String(alpnResult, Util.UTF_8) : null;
}
@Override public void log(int level, String message, Throwable t) {
int logLevel = level == WARN ? Log.WARN : Log.DEBUG;
if (t != null) message = message + '\n' + Log.getStackTraceString(t);
// Split by line, then ensure each line can fit into Log's maximum length.
for (int i = 0, length = message.length(); i < length; i++) {
int newline = message.indexOf('\n', i);
newline = newline != -1 ? newline : length;
do {
int end = Math.min(newline, i + MAX_LOG_LENGTH);
Log.println(logLevel, "OkHttp", message.substring(i, end));
i = end;
} while (i < newline);
}
}
@Override public Object getStackTraceForCloseable(String closer) {
return closeGuard.createAndOpen(closer);
}
@Override public void logCloseableLeak(String message, Object stackTrace) {
boolean reported = closeGuard.warnIfOpen(stackTrace);
if (!reported) {
// Unable to report via CloseGuard. As a last-ditch effort, send it to the logger.
log(WARN, message, null);
}
}
@Override public boolean isCleartextTrafficPermitted(String hostname) {
try {
Class<?> networkPolicyClass = Class.forName("android.security.NetworkSecurityPolicy");
Method getInstanceMethod = networkPolicyClass.getMethod("getInstance");
Object networkSecurityPolicy = getInstanceMethod.invoke(null);
return api24IsCleartextTrafficPermitted(hostname, networkPolicyClass, networkSecurityPolicy);
} catch (ClassNotFoundException | NoSuchMethodException e) {
return super.isCleartextTrafficPermitted(hostname);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw assertionError("unable to determine cleartext support", e);
}
}
private boolean api24IsCleartextTrafficPermitted(String hostname, Class<?> networkPolicyClass,
Object networkSecurityPolicy) throws InvocationTargetException, IllegalAccessException {
try {
Method isCleartextTrafficPermittedMethod = networkPolicyClass
.getMethod("isCleartextTrafficPermitted", String.class);
return (boolean) isCleartextTrafficPermittedMethod.invoke(networkSecurityPolicy, hostname);
} catch (NoSuchMethodException e) {
return api23IsCleartextTrafficPermitted(hostname, networkPolicyClass, networkSecurityPolicy);
}
}
private boolean api23IsCleartextTrafficPermitted(String hostname, Class<?> networkPolicyClass,
Object networkSecurityPolicy) throws InvocationTargetException, IllegalAccessException {
try {
Method isCleartextTrafficPermittedMethod = networkPolicyClass
.getMethod("isCleartextTrafficPermitted");
return (boolean) isCleartextTrafficPermittedMethod.invoke(networkSecurityPolicy);
} catch (NoSuchMethodException e) {
return super.isCleartextTrafficPermitted(hostname);
}
}
/**
* Checks to see if Google Play Services Dynamic Security Provider is present which provides ALPN
* support. If it isn't checks to see if device is Android 5.0+ since 4.x device have broken
* ALPN support.
*/
private static boolean supportsAlpn() {
if (Security.getProvider("GMSCore_OpenSSL") != null) {
return true;
} else {
try {
Class.forName("android.net.Network"); // Arbitrary class added in Android 5.0.
return true;
} catch (ClassNotFoundException ignored) { }
}
return false;
}
public CertificateChainCleaner buildCertificateChainCleaner(X509TrustManager trustManager) {
try {
Class<?> extensionsClass = Class.forName("android.net.http.X509TrustManagerExtensions");
Constructor<?> constructor = extensionsClass.getConstructor(X509TrustManager.class);
Object extensions = constructor.newInstance(trustManager);
Method checkServerTrusted = extensionsClass.getMethod(
"checkServerTrusted", X509Certificate[].class, String.class, String.class);
return new AndroidCertificateChainCleaner(extensions, checkServerTrusted);
} catch (Exception e) {
return super.buildCertificateChainCleaner(trustManager);
}
}
public static Platform buildIfSupported() {
// Attempt to find Android 2.3+ APIs.
try {
Class<?> sslParametersClass;
try {
sslParametersClass = Class.forName("com.android.org.conscrypt.SSLParametersImpl");
} catch (ClassNotFoundException e) {
// Older platform before being unbundled.
sslParametersClass = Class.forName(
"org.apache.harmony.xnet.provider.jsse.SSLParametersImpl");
}
OptionalMethod<Socket> setUseSessionTickets = new OptionalMethod<>(
null, "setUseSessionTickets", boolean.class);
OptionalMethod<Socket> setHostname = new OptionalMethod<>(
null, "setHostname", String.class);
OptionalMethod<Socket> getAlpnSelectedProtocol = null;
OptionalMethod<Socket> setAlpnProtocols = null;
if (supportsAlpn()) {
getAlpnSelectedProtocol
= new OptionalMethod<>(byte[].class, "getAlpnSelectedProtocol");
setAlpnProtocols
= new OptionalMethod<>(null, "setAlpnProtocols", byte[].class);
}
return new AndroidPlatform(sslParametersClass, setUseSessionTickets, setHostname,
getAlpnSelectedProtocol, setAlpnProtocols);
} catch (ClassNotFoundException ignored) {
// This isn't an Android runtime.
}
return null;
}
@Override
public TrustRootIndex buildTrustRootIndex(X509TrustManager trustManager) {
try {
// From org.conscrypt.TrustManagerImpl, we want the method with this signature:
// private TrustAnchor findTrustAnchorByIssuerAndSignature(X509Certificate lastCert);
Method method = trustManager.getClass().getDeclaredMethod(
"findTrustAnchorByIssuerAndSignature", X509Certificate.class);
method.setAccessible(true);
return new AndroidTrustRootIndex(trustManager, method);
} catch (NoSuchMethodException e) {
return super.buildTrustRootIndex(trustManager);
}
}
/**
* X509TrustManagerExtensions was added to Android in API 17 (Android 4.2, released in late 2012).
* This is the best way to get a clean chain on Android because it uses the same code as the TLS
* handshake.
*/
static final class AndroidCertificateChainCleaner extends CertificateChainCleaner {
private final Object x509TrustManagerExtensions;
private final Method checkServerTrusted;
AndroidCertificateChainCleaner(Object x509TrustManagerExtensions, Method checkServerTrusted) {
this.x509TrustManagerExtensions = x509TrustManagerExtensions;
this.checkServerTrusted = checkServerTrusted;
}
@SuppressWarnings({"unchecked", "SuspiciousToArrayCall"}) // Reflection on List<Certificate>.
@Override public List<Certificate> clean(List<Certificate> chain, String hostname)
throws SSLPeerUnverifiedException {
try {
X509Certificate[] certificates = chain.toArray(new X509Certificate[chain.size()]);
return (List<Certificate>) checkServerTrusted.invoke(
x509TrustManagerExtensions, certificates, "RSA", hostname);
} catch (InvocationTargetException e) {
SSLPeerUnverifiedException exception = new SSLPeerUnverifiedException(e.getMessage());
exception.initCause(e);
throw exception;
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
}
@Override public boolean equals(Object other) {
return other instanceof AndroidCertificateChainCleaner; // All instances are equivalent.
}
@Override public int hashCode() {
return 0;
}
}
/**
* Provides access to the internal dalvik.system.CloseGuard class. Android uses this in
* combination with android.os.StrictMode to report on leaked java.io.Closeable's. Available since
* Android API 11.
*/
static final class CloseGuard {
private final Method getMethod;
private final Method openMethod;
private final Method warnIfOpenMethod;
CloseGuard(Method getMethod, Method openMethod, Method warnIfOpenMethod) {
this.getMethod = getMethod;
this.openMethod = openMethod;
this.warnIfOpenMethod = warnIfOpenMethod;
}
Object createAndOpen(String closer) {
if (getMethod != null) {
try {
Object closeGuardInstance = getMethod.invoke(null);
openMethod.invoke(closeGuardInstance, closer);
return closeGuardInstance;
} catch (Exception ignored) {
}
}
return null;
}
boolean warnIfOpen(Object closeGuardInstance) {
boolean reported = false;
if (closeGuardInstance != null) {
try {
warnIfOpenMethod.invoke(closeGuardInstance);
reported = true;
} catch (Exception ignored) {
}
}
return reported;
}
static CloseGuard get() {
Method getMethod;
Method openMethod;
Method warnIfOpenMethod;
try {
Class<?> closeGuardClass = Class.forName("dalvik.system.CloseGuard");
getMethod = closeGuardClass.getMethod("get");
openMethod = closeGuardClass.getMethod("open", String.class);
warnIfOpenMethod = closeGuardClass.getMethod("warnIfOpen");
} catch (Exception ignored) {
getMethod = null;
openMethod = null;
warnIfOpenMethod = null;
}
return new CloseGuard(getMethod, openMethod, warnIfOpenMethod);
}
}
/**
* An index of trusted root certificates that exploits knowledge of Android implementation
* details. This class is potentially much faster to initialize than {@link BasicTrustRootIndex}
* because it doesn't need to load and index trusted CA certificates.
*
* <p>This class uses APIs added to Android in API 14 (Android 4.0, released October 2011). This
* class shouldn't be used in Android API 17 or better because those releases are better served by
* {@link AndroidPlatform.AndroidCertificateChainCleaner}.
*/
static final class AndroidTrustRootIndex implements TrustRootIndex {
private final X509TrustManager trustManager;
private final Method findByIssuerAndSignatureMethod;
AndroidTrustRootIndex(X509TrustManager trustManager, Method findByIssuerAndSignatureMethod) {
this.findByIssuerAndSignatureMethod = findByIssuerAndSignatureMethod;
this.trustManager = trustManager;
}
@Override public X509Certificate findByIssuerAndSignature(X509Certificate cert) {
try {
TrustAnchor trustAnchor = (TrustAnchor) findByIssuerAndSignatureMethod.invoke(
trustManager, cert);
return trustAnchor != null
? trustAnchor.getTrustedCert()
: null;
} catch (IllegalAccessException e) {
throw assertionError("unable to get issues and signature", e);
} catch (InvocationTargetException e) {
return null;
}
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof AndroidTrustRootIndex)) {
return false;
}
AndroidTrustRootIndex that = (AndroidTrustRootIndex) obj;
return trustManager.equals(that.trustManager)
&& findByIssuerAndSignatureMethod.equals(that.findByIssuerAndSignatureMethod);
}
@Override
public int hashCode() {
return trustManager.hashCode() + 31 * findByIssuerAndSignatureMethod.hashCode();
}
}
}
| |
/*
* 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 com.intellij.codeInsight.daemon.impl.analysis;
import com.intellij.codeInsight.AnnotationTargetUtil;
import com.intellij.codeInsight.daemon.JavaErrorMessages;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixAction;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.QuickFixFactory;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.patterns.ElementPattern;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.source.PsiClassReferenceType;
import com.intellij.psi.impl.source.PsiImmediateClassType;
import com.intellij.psi.util.ClassUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.HashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.intellij.patterns.PsiJavaPatterns.psiElement;
/**
* @author ven
*/
public class AnnotationsHighlightUtil {
private static final Logger LOG = Logger.getInstance("com.intellij.codeInsight.daemon.impl.analysis.AnnotationsHighlightUtil");
@Nullable
static HighlightInfo checkNameValuePair(PsiNameValuePair pair) {
PsiReference ref = pair.getReference();
if (ref == null) return null;
PsiMethod method = (PsiMethod)ref.resolve();
if (method == null) {
if (pair.getName() != null) {
final String description = JavaErrorMessages.message("annotation.unknown.method", ref.getCanonicalText());
PsiElement element = ref.getElement();
final HighlightInfo highlightInfo =
HighlightInfo.newHighlightInfo(HighlightInfoType.WRONG_REF).range(element).descriptionAndTooltip(description).create();
QuickFixAction.registerQuickFixAction(highlightInfo, QuickFixFactory.getInstance().createCreateAnnotationMethodFromUsageFix(pair));
return highlightInfo;
}
else {
String description = JavaErrorMessages.message("annotation.missing.method", ref.getCanonicalText());
PsiElement element = ref.getElement();
final HighlightInfo highlightInfo =
HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element).descriptionAndTooltip(description).create();
for (IntentionAction action : QuickFixFactory.getInstance().createAddAnnotationAttributeNameFixes(pair)) {
QuickFixAction.registerQuickFixAction(highlightInfo, action);
}
return highlightInfo;
}
}
else {
PsiType returnType = method.getReturnType();
assert returnType != null : method;
PsiAnnotationMemberValue value = pair.getValue();
HighlightInfo info = checkMemberValueType(value, returnType);
if (info != null) return info;
return checkDuplicateAttribute(pair);
}
}
@Nullable
private static HighlightInfo checkDuplicateAttribute(PsiNameValuePair pair) {
PsiAnnotationParameterList annotation = (PsiAnnotationParameterList)pair.getParent();
PsiNameValuePair[] attributes = annotation.getAttributes();
for (PsiNameValuePair attribute : attributes) {
if (attribute == pair) break;
String name = pair.getName();
if (Comparing.equal(attribute.getName(), name)) {
String description = JavaErrorMessages.message("annotation.duplicate.attribute",
name == null ? PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME : name);
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(pair).descriptionAndTooltip(description).create();
}
}
return null;
}
private static String formatReference(PsiJavaCodeReferenceElement ref) {
return ref.getCanonicalText();
}
@Nullable
static HighlightInfo checkMemberValueType(@Nullable PsiAnnotationMemberValue value, PsiType expectedType) {
if (value == null) return null;
if (expectedType instanceof PsiClassType && expectedType.equalsToText(CommonClassNames.JAVA_LANG_CLASS)) {
if (!(value instanceof PsiClassObjectAccessExpression)) {
String description = JavaErrorMessages.message("annotation.non.class.literal.attribute.value");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(value).descriptionAndTooltip(description).create();
}
}
if (value instanceof PsiAnnotation) {
PsiJavaCodeReferenceElement nameRef = ((PsiAnnotation)value).getNameReferenceElement();
if (nameRef == null) return null;
if (expectedType instanceof PsiClassType) {
PsiClass aClass = ((PsiClassType)expectedType).resolve();
if (aClass != null && nameRef.isReferenceTo(aClass)) return null;
}
if (expectedType instanceof PsiArrayType) {
PsiType componentType = ((PsiArrayType)expectedType).getComponentType();
if (componentType instanceof PsiClassType) {
PsiClass aClass = ((PsiClassType)componentType).resolve();
if (aClass != null && nameRef.isReferenceTo(aClass)) return null;
}
}
String description = JavaErrorMessages.message("incompatible.types", JavaHighlightUtil.formatType(expectedType), formatReference(nameRef) );
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(value).descriptionAndTooltip(description).create();
}
if (value instanceof PsiArrayInitializerMemberValue) {
if (expectedType instanceof PsiArrayType) return null;
String description = JavaErrorMessages.message("annotation.illegal.array.initializer", JavaHighlightUtil.formatType(expectedType));
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(value).descriptionAndTooltip(description).create();
}
if (value instanceof PsiExpression) {
PsiExpression expr = (PsiExpression)value;
PsiType type = expr.getType();
final PsiClass psiClass = PsiUtil.resolveClassInType(type);
if (psiClass != null && psiClass.isEnum() && !(expr instanceof PsiReferenceExpression && ((PsiReferenceExpression)expr).resolve() instanceof PsiEnumConstant)) {
String description = JavaErrorMessages.message("annotation.non.enum.constant.attribute.value");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(value).descriptionAndTooltip(description).create();
}
if (type != null && TypeConversionUtil.areTypesAssignmentCompatible(expectedType, expr) ||
expectedType instanceof PsiArrayType &&
TypeConversionUtil.areTypesAssignmentCompatible(((PsiArrayType)expectedType).getComponentType(), expr)) {
return null;
}
String description = JavaErrorMessages.message("incompatible.types", JavaHighlightUtil.formatType(expectedType), JavaHighlightUtil.formatType(type));
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(value).descriptionAndTooltip(description).create();
QuickFixAction.registerQuickFixAction(info, QuickFixFactory.getInstance().createSurroundWithQuotesAnnotationParameterValueFix(value, expectedType));
return info;
}
LOG.error("Unknown annotation member value: " + value);
return null;
}
static HighlightInfo checkDuplicateAnnotations(@NotNull PsiAnnotation annotationToCheck, @NotNull LanguageLevel languageLevel) {
PsiAnnotationOwner owner = annotationToCheck.getOwner();
if (owner == null) return null;
PsiJavaCodeReferenceElement element = annotationToCheck.getNameReferenceElement();
if (element == null) return null;
PsiElement resolved = element.resolve();
if (!(resolved instanceof PsiClass)) return null;
PsiClass annotationType = (PsiClass)resolved;
PsiClass contained = contained(annotationType);
String containedElementFQN = contained == null ? null : contained.getQualifiedName();
if (containedElementFQN != null) {
String containerName = annotationType.getQualifiedName();
if (isAnnotationRepeatedTwice(owner, containedElementFQN)) {
String description = JavaErrorMessages.message("annotation.container.wrong.place", containerName);
return annotationError(annotationToCheck, description);
}
}
else if (isAnnotationRepeatedTwice(owner, annotationType.getQualifiedName())) {
if (!languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) {
String description = JavaErrorMessages.message("annotation.duplicate.annotation");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element).descriptionAndTooltip(description).create();
}
PsiAnnotation metaAnno = PsiImplUtil.findAnnotation(annotationType.getModifierList(), CommonClassNames.JAVA_LANG_ANNOTATION_REPEATABLE);
if (metaAnno == null) {
String explanation = JavaErrorMessages.message("annotation.non.repeatable", annotationType.getQualifiedName());
String description = JavaErrorMessages.message("annotation.duplicate.explained", explanation);
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element).descriptionAndTooltip(description).create();
}
String explanation = doCheckRepeatableAnnotation(metaAnno);
if (explanation != null) {
String description = JavaErrorMessages.message("annotation.duplicate.explained", explanation);
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element).descriptionAndTooltip(description).create();
}
PsiClass container = getRepeatableContainer(metaAnno);
if (container != null) {
PsiAnnotation.TargetType[] targets = AnnotationTargetUtil.getTargetsForLocation(owner);
PsiAnnotation.TargetType applicable = AnnotationTargetUtil.findAnnotationTarget(container, targets);
if (applicable == null) {
String target = JavaErrorMessages.message("annotation.target." + targets[0]);
String message = JavaErrorMessages.message("annotation.container.not.applicable", container.getName(), target);
return annotationError(annotationToCheck, message);
}
}
}
return null;
}
// returns contained element
private static PsiClass contained(PsiClass annotationType) {
if (!annotationType.isAnnotationType()) return null;
PsiMethod[] values = annotationType.findMethodsByName("value", false);
if (values.length != 1) return null;
PsiMethod value = values[0];
PsiType returnType = value.getReturnType();
if (!(returnType instanceof PsiArrayType)) return null;
PsiType type = ((PsiArrayType)returnType).getComponentType();
if (!(type instanceof PsiClassType)) return null;
PsiClass contained = ((PsiClassType)type).resolve();
if (contained == null || !contained.isAnnotationType()) return null;
if (PsiImplUtil.findAnnotation(contained.getModifierList(), CommonClassNames.JAVA_LANG_ANNOTATION_REPEATABLE) == null) return null;
return contained;
}
private static boolean isAnnotationRepeatedTwice(@NotNull PsiAnnotationOwner owner, @Nullable String qualifiedName) {
int count = 0;
for (PsiAnnotation annotation : owner.getAnnotations()) {
PsiJavaCodeReferenceElement nameRef = annotation.getNameReferenceElement();
if (nameRef == null) continue;
PsiElement resolved = nameRef.resolve();
if (!(resolved instanceof PsiClass) || !Comparing.equal(qualifiedName, ((PsiClass)resolved).getQualifiedName())) continue;
if (++count == 2) return true;
}
return false;
}
@Nullable
static HighlightInfo checkMissingAttributes(PsiAnnotation annotation) {
PsiJavaCodeReferenceElement nameRef = annotation.getNameReferenceElement();
if (nameRef == null) return null;
PsiClass aClass = (PsiClass)nameRef.resolve();
if (aClass != null && aClass.isAnnotationType()) {
Set<String> names = new HashSet<>();
PsiNameValuePair[] attributes = annotation.getParameterList().getAttributes();
for (PsiNameValuePair attribute : attributes) {
final String name = attribute.getName();
if (name != null) {
names.add(name);
}
else {
names.add(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME);
}
}
PsiMethod[] annotationMethods = aClass.getMethods();
List<String> missed = new ArrayList<>();
for (PsiMethod method : annotationMethods) {
if (PsiUtil.isAnnotationMethod(method)) {
PsiAnnotationMethod annotationMethod = (PsiAnnotationMethod)method;
if (annotationMethod.getDefaultValue() == null) {
if (!names.contains(annotationMethod.getName())) {
missed.add(annotationMethod.getName());
}
}
}
}
if (!missed.isEmpty()) {
StringBuffer buff = new StringBuffer("'" + missed.get(0) + "'");
for (int i = 1; i < missed.size(); i++) {
buff.append(", ");
buff.append("'").append(missed.get(i)).append("'");
}
String description = JavaErrorMessages.message("annotation.missing.attribute", buff);
HighlightInfo info =
HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(nameRef).descriptionAndTooltip(description).create();
IntentionAction fix = QuickFixFactory.getInstance().createAddMissingRequiredAnnotationParametersFix(
annotation, annotationMethods, missed);
QuickFixAction.registerQuickFixAction(info, fix);
return info;
}
}
return null;
}
@Nullable
static HighlightInfo checkConstantExpression(PsiExpression expression) {
final PsiElement parent = expression.getParent();
if (PsiUtil.isAnnotationMethod(parent) || parent instanceof PsiNameValuePair || parent instanceof PsiArrayInitializerMemberValue) {
if (!PsiUtil.isConstantExpression(expression)) {
String description = JavaErrorMessages.message("annotation.non.constant.attribute.value");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(description).create();
}
}
return null;
}
@Nullable
static HighlightInfo checkValidAnnotationType(PsiType type, final PsiTypeElement typeElement) {
if (type != null && type.accept(AnnotationReturnTypeVisitor.INSTANCE).booleanValue()) {
return null;
}
String description = JavaErrorMessages.message("annotation.invalid.annotation.member.type", type != null ? type.getPresentableText() : null);
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(typeElement).descriptionAndTooltip(description).create();
}
private static final ElementPattern<PsiElement> ANY_ANNOTATION_ALLOWED = psiElement().andOr(
psiElement().withParent(PsiNameValuePair.class),
psiElement().withParents(PsiArrayInitializerMemberValue.class, PsiNameValuePair.class),
psiElement().withParents(PsiArrayInitializerMemberValue.class, PsiAnnotationMethod.class),
psiElement().withParent(PsiAnnotationMethod.class).afterLeaf(PsiKeyword.DEFAULT)
);
@Nullable
public static HighlightInfo checkApplicability(@NotNull PsiAnnotation annotation, @NotNull LanguageLevel level, @NotNull PsiFile file) {
if (ANY_ANNOTATION_ALLOWED.accepts(annotation)) {
return null;
}
PsiJavaCodeReferenceElement nameRef = annotation.getNameReferenceElement();
if (nameRef == null) return null;
PsiAnnotationOwner owner = annotation.getOwner();
PsiAnnotation.TargetType[] targets = AnnotationTargetUtil.getTargetsForLocation(owner);
if (owner == null || targets.length == 0) {
String message = JavaErrorMessages.message("annotation.not.allowed.here");
return annotationError(annotation, message);
}
if (!(owner instanceof PsiModifierList)) {
HighlightInfo info = HighlightUtil.checkFeature(annotation, HighlightUtil.Feature.TYPE_ANNOTATIONS, level, file);
if (info != null) return info;
}
PsiAnnotation.TargetType applicable = AnnotationTargetUtil.findAnnotationTarget(annotation, targets);
if (applicable == PsiAnnotation.TargetType.UNKNOWN) return null;
if (applicable == null) {
String target = JavaErrorMessages.message("annotation.target." + targets[0]);
String message = JavaErrorMessages.message("annotation.not.applicable", nameRef.getText(), target);
return annotationError(annotation, message);
}
if (applicable == PsiAnnotation.TargetType.TYPE_USE) {
if (owner instanceof PsiClassReferenceType) {
PsiJavaCodeReferenceElement ref = ((PsiClassReferenceType)owner).getReference();
HighlightInfo info = checkReferenceTarget(annotation, ref);
if (info != null) return info;
}
else if (owner instanceof PsiModifierList || owner instanceof PsiTypeElement) {
PsiElement nextElement = owner instanceof PsiTypeElement
? (PsiTypeElement)owner
: PsiTreeUtil.skipSiblingsForward((PsiModifierList)owner, PsiComment.class, PsiWhiteSpace.class, PsiTypeParameterList.class);
if (nextElement instanceof PsiTypeElement) {
PsiTypeElement typeElement = (PsiTypeElement)nextElement;
PsiType type = typeElement.getType();
if (PsiType.VOID.equals(type)) {
String message = JavaErrorMessages.message("annotation.not.allowed.void");
return annotationError(annotation, message);
}
if (!(type instanceof PsiPrimitiveType)) {
PsiJavaCodeReferenceElement ref = getOutermostReferenceElement(typeElement.getInnermostComponentReferenceElement());
HighlightInfo info = checkReferenceTarget(annotation, ref);
if (info != null) return info;
}
PsiElement context = PsiTreeUtil.skipParentsOfType(typeElement, PsiTypeElement.class);
if (context instanceof PsiClassObjectAccessExpression) {
String message = JavaErrorMessages.message("annotation.not.allowed.class");
return annotationError(annotation, message);
}
}
}
}
return null;
}
private static HighlightInfo annotationError(PsiAnnotation annotation, String message) {
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(annotation).descriptionAndTooltip(message).create();
QuickFixAction.registerQuickFixAction(info, new DeleteAnnotationAction(annotation));
return info;
}
@Nullable
private static HighlightInfo checkReferenceTarget(PsiAnnotation annotation, @Nullable PsiJavaCodeReferenceElement ref) {
if (ref == null) return null;
PsiElement refTarget = ref.resolve();
if (refTarget == null) return null;
String message = null;
if (!(refTarget instanceof PsiClass)) {
message = JavaErrorMessages.message("annotation.not.allowed.ref");
}
else {
PsiElement parent = ref.getParent();
if (parent instanceof PsiJavaCodeReferenceElement) {
PsiElement qualified = ((PsiJavaCodeReferenceElement)parent).resolve();
if (qualified instanceof PsiMember && ((PsiMember)qualified).hasModifierProperty(PsiModifier.STATIC)) {
message = JavaErrorMessages.message("annotation.not.allowed.static");
}
}
}
return message != null ? annotationError(annotation, message) : null;
}
@Nullable
private static PsiJavaCodeReferenceElement getOutermostReferenceElement(@Nullable PsiJavaCodeReferenceElement ref) {
if (ref == null) return null;
PsiElement qualifier;
while ((qualifier = ref.getQualifier()) instanceof PsiJavaCodeReferenceElement) {
ref = (PsiJavaCodeReferenceElement)qualifier;
}
return ref;
}
@Nullable
static HighlightInfo checkAnnotationType(PsiAnnotation annotation) {
PsiJavaCodeReferenceElement nameReferenceElement = annotation.getNameReferenceElement();
if (nameReferenceElement != null) {
PsiElement resolved = nameReferenceElement.resolve();
if (!(resolved instanceof PsiClass) || !((PsiClass)resolved).isAnnotationType()) {
String description = JavaErrorMessages.message("annotation.annotation.type.expected");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(nameReferenceElement).descriptionAndTooltip(description).create();
}
}
return null;
}
@Nullable
static HighlightInfo checkCyclicMemberType(PsiTypeElement typeElement, PsiClass aClass) {
LOG.assertTrue(aClass.isAnnotationType());
PsiType type = typeElement.getType();
final Set<PsiClass> checked = new HashSet<>();
if (cyclicDependencies(aClass, type, checked, aClass.getManager())) {
String description = JavaErrorMessages.message("annotation.cyclic.element.type");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(typeElement).descriptionAndTooltip(description).create();
}
return null;
}
private static boolean cyclicDependencies(PsiClass aClass, PsiType type, @NotNull Set<PsiClass> checked,@NotNull PsiManager manager) {
final PsiClass resolvedClass = PsiUtil.resolveClassInType(type);
if (resolvedClass != null && resolvedClass.isAnnotationType()) {
if (aClass == resolvedClass) {
return true;
}
if (!checked.add(resolvedClass) || !manager.isInProject(resolvedClass)) return false;
final PsiMethod[] methods = resolvedClass.getMethods();
for (PsiMethod method : methods) {
if (cyclicDependencies(aClass, method.getReturnType(), checked,manager)) return true;
}
}
return false;
}
static HighlightInfo checkClashesWithSuperMethods(@NotNull PsiAnnotationMethod psiMethod) {
final PsiIdentifier nameIdentifier = psiMethod.getNameIdentifier();
if (nameIdentifier != null) {
final PsiMethod[] methods = psiMethod.findDeepestSuperMethods();
for (PsiMethod method : methods) {
final PsiClass containingClass = method.getContainingClass();
if (containingClass != null) {
final String qualifiedName = containingClass.getQualifiedName();
if (CommonClassNames.JAVA_LANG_OBJECT.equals(qualifiedName) || CommonClassNames.JAVA_LANG_ANNOTATION_ANNOTATION.equals(qualifiedName)) {
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(nameIdentifier).descriptionAndTooltip(
"@interface member clashes with '" + JavaHighlightUtil.formatMethod(method) + "' in " + HighlightUtil.formatClass(containingClass)).create();
}
}
}
}
return null;
}
@Nullable
static HighlightInfo checkAnnotationDeclaration(final PsiElement parent, final PsiReferenceList list) {
if (PsiUtil.isAnnotationMethod(parent)) {
PsiAnnotationMethod method = (PsiAnnotationMethod)parent;
if (list == method.getThrowsList()) {
String description = JavaErrorMessages.message("annotation.members.may.not.have.throws.list");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(list).descriptionAndTooltip(description).create();
}
}
else if (parent instanceof PsiClass && ((PsiClass)parent).isAnnotationType()) {
if (PsiKeyword.EXTENDS.equals(list.getFirstChild().getText())) {
String description = JavaErrorMessages.message("annotation.may.not.have.extends.list");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(list).descriptionAndTooltip(description).create();
}
}
return null;
}
@Nullable
static HighlightInfo checkPackageAnnotationContainingFile(PsiPackageStatement statement, PsiFile file) {
PsiModifierList annotationList = statement.getAnnotationList();
if (annotationList != null && !PsiPackage.PACKAGE_INFO_FILE.equals(file.getName())) {
String message = JavaErrorMessages.message("invalid.package.annotation.containing.file");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(annotationList.getTextRange()).descriptionAndTooltip(message).create();
}
return null;
}
@Nullable
static HighlightInfo checkTargetAnnotationDuplicates(PsiAnnotation annotation) {
PsiJavaCodeReferenceElement nameRef = annotation.getNameReferenceElement();
if (nameRef == null) return null;
PsiElement resolved = nameRef.resolve();
if (!(resolved instanceof PsiClass) || !CommonClassNames.JAVA_LANG_ANNOTATION_TARGET.equals(((PsiClass)resolved).getQualifiedName())) {
return null;
}
PsiNameValuePair[] attributes = annotation.getParameterList().getAttributes();
if (attributes.length < 1) return null;
PsiAnnotationMemberValue value = attributes[0].getValue();
if (!(value instanceof PsiArrayInitializerMemberValue)) return null;
PsiAnnotationMemberValue[] arrayInitializers = ((PsiArrayInitializerMemberValue) value).getInitializers();
Set<PsiElement> targets = new HashSet<>();
for (PsiAnnotationMemberValue initializer : arrayInitializers) {
if (initializer instanceof PsiReferenceExpression) {
PsiElement target = ((PsiReferenceExpression) initializer).resolve();
if (target != null) {
if (targets.contains(target)) {
String description = JavaErrorMessages.message("repeated.annotation.target");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(initializer).descriptionAndTooltip(description).create();
}
targets.add(target);
}
}
}
return null;
}
@Nullable
static HighlightInfo checkFunctionalInterface(@NotNull PsiAnnotation annotation, @NotNull LanguageLevel languageLevel) {
if (languageLevel.isAtLeast(LanguageLevel.JDK_1_8) && Comparing.strEqual(annotation.getQualifiedName(), CommonClassNames.JAVA_LANG_FUNCTIONAL_INTERFACE)) {
final PsiAnnotationOwner owner = annotation.getOwner();
if (owner instanceof PsiModifierList) {
final PsiElement parent = ((PsiModifierList)owner).getParent();
if (parent instanceof PsiClass) {
final String errorMessage = LambdaHighlightingUtil.checkInterfaceFunctional((PsiClass)parent, ((PsiClass)parent).getName() + " is not a functional interface");
if (errorMessage != null) {
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(annotation).descriptionAndTooltip(errorMessage).create();
}
}
}
}
return null;
}
@Nullable
static HighlightInfo checkRepeatableAnnotation(PsiAnnotation annotation) {
String qualifiedName = annotation.getQualifiedName();
if (!CommonClassNames.JAVA_LANG_ANNOTATION_REPEATABLE.equals(qualifiedName)) return null;
String description = doCheckRepeatableAnnotation(annotation);
if (description != null) {
PsiAnnotationMemberValue containerRef = PsiImplUtil.findAttributeValue(annotation, null);
if (containerRef != null) {
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(containerRef).descriptionAndTooltip(description).create();
}
}
return null;
}
@Nullable
private static String doCheckRepeatableAnnotation(@NotNull PsiAnnotation annotation) {
PsiAnnotationOwner owner = annotation.getOwner();
if (!(owner instanceof PsiModifierList)) return null;
PsiElement target = ((PsiModifierList)owner).getParent();
if (!(target instanceof PsiClass) || !((PsiClass)target).isAnnotationType()) return null;
PsiClass container = getRepeatableContainer(annotation);
if (container == null) return null;
PsiMethod[] methods = container.findMethodsByName("value", false);
if (methods.length == 0) {
return JavaErrorMessages.message("annotation.container.no.value", container.getQualifiedName());
}
if (methods.length == 1) {
PsiType expected = new PsiImmediateClassType((PsiClass)target, PsiSubstitutor.EMPTY).createArrayType();
if (!expected.equals(methods[0].getReturnType())) {
return JavaErrorMessages.message("annotation.container.bad.type", container.getQualifiedName(), JavaHighlightUtil.formatType(expected));
}
}
RetentionPolicy targetPolicy = getRetentionPolicy((PsiClass)target);
if (targetPolicy != null) {
RetentionPolicy containerPolicy = getRetentionPolicy(container);
if (containerPolicy != null && targetPolicy.compareTo(containerPolicy) > 0) {
return JavaErrorMessages.message("annotation.container.low.retention", container.getQualifiedName(), containerPolicy);
}
}
Set<PsiAnnotation.TargetType> repeatableTargets = AnnotationTargetUtil.getAnnotationTargets((PsiClass)target);
if (repeatableTargets != null) {
Set<PsiAnnotation.TargetType> containerTargets = AnnotationTargetUtil.getAnnotationTargets(container);
if (containerTargets != null && !repeatableTargets.containsAll(containerTargets)) {
return JavaErrorMessages.message("annotation.container.wide.target", container.getQualifiedName());
}
}
return null;
}
@Nullable
private static PsiClass getRepeatableContainer(@NotNull PsiAnnotation annotation) {
PsiAnnotationMemberValue containerRef = PsiImplUtil.findAttributeValue(annotation, null);
if (!(containerRef instanceof PsiClassObjectAccessExpression)) return null;
PsiType containerType = ((PsiClassObjectAccessExpression)containerRef).getOperand().getType();
if (!(containerType instanceof PsiClassType)) return null;
PsiClass container = ((PsiClassType)containerType).resolve();
if (container == null || !container.isAnnotationType()) return null;
return container;
}
@Nullable
static HighlightInfo checkReceiverPlacement(PsiReceiverParameter parameter) {
PsiElement owner = parameter.getParent().getParent();
if (owner == null) return null;
if (!(owner instanceof PsiMethod)) {
String text = JavaErrorMessages.message("receiver.wrong.context");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(parameter.getIdentifier()).descriptionAndTooltip(text).create();
}
PsiMethod method = (PsiMethod)owner;
if (isStatic(method) || method.isConstructor() && isStatic(method.getContainingClass())) {
String text = JavaErrorMessages.message("receiver.static.context");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(parameter.getIdentifier()).descriptionAndTooltip(text).create();
}
PsiElement leftNeighbour = PsiTreeUtil.skipWhitespacesBackward(parameter);
if (leftNeighbour != null && !PsiUtil.isJavaToken(leftNeighbour, JavaTokenType.LPARENTH)) {
String text = JavaErrorMessages.message("receiver.wrong.position");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(parameter.getIdentifier()).descriptionAndTooltip(text).create();
}
return null;
}
@Nullable
static HighlightInfo checkReceiverType(PsiReceiverParameter parameter) {
PsiElement owner = parameter.getParent().getParent();
if (!(owner instanceof PsiMethod)) return null;
PsiMethod method = (PsiMethod)owner;
PsiClass enclosingClass = method.getContainingClass();
if (method.isConstructor() && enclosingClass != null) {
enclosingClass = enclosingClass.getContainingClass();
}
if (enclosingClass != null) {
PsiClassType type = PsiElementFactory.SERVICE.getInstance(parameter.getProject()).createType(enclosingClass, PsiSubstitutor.EMPTY);
if (!type.equals(parameter.getType())) {
PsiElement range = ObjectUtils.notNull(parameter.getTypeElement(), parameter);
String text = JavaErrorMessages.message("receiver.type.mismatch");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(range).descriptionAndTooltip(text).create();
}
PsiThisExpression identifier = parameter.getIdentifier();
if (!enclosingClass.equals(PsiUtil.resolveClassInType(identifier.getType()))) {
String text = JavaErrorMessages.message("receiver.name.mismatch");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(identifier).descriptionAndTooltip(text).create();
}
}
return null;
}
private static boolean isStatic(PsiModifierListOwner owner) {
if (owner == null) return false;
if (owner instanceof PsiClass && ClassUtil.isTopLevelClass((PsiClass)owner)) return true;
PsiModifierList modifierList = owner.getModifierList();
return modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC);
}
@Nullable
public static RetentionPolicy getRetentionPolicy(@NotNull PsiClass annotation) {
PsiModifierList modifierList = annotation.getModifierList();
if (modifierList != null) {
PsiAnnotation retentionAnno = modifierList.findAnnotation(CommonClassNames.JAVA_LANG_ANNOTATION_RETENTION);
if (retentionAnno == null) return RetentionPolicy.CLASS;
PsiAnnotationMemberValue policyRef = PsiImplUtil.findAttributeValue(retentionAnno, null);
if (policyRef instanceof PsiReference) {
PsiElement field = ((PsiReference)policyRef).resolve();
if (field instanceof PsiEnumConstant) {
String name = ((PsiEnumConstant)field).getName();
try {
//noinspection ConstantConditions
return Enum.valueOf(RetentionPolicy.class, name);
}
catch (Exception e) {
LOG.warn("Unknown policy: " + name);
}
}
}
}
return null;
}
public static class AnnotationReturnTypeVisitor extends PsiTypeVisitor<Boolean> {
public static final AnnotationReturnTypeVisitor INSTANCE = new AnnotationReturnTypeVisitor();
@Override
public Boolean visitType(PsiType type) {
return Boolean.FALSE;
}
@Override
public Boolean visitPrimitiveType(PsiPrimitiveType primitiveType) {
return PsiType.VOID.equals(primitiveType) || PsiType.NULL.equals(primitiveType) ? Boolean.FALSE : Boolean.TRUE;
}
@Override
public Boolean visitArrayType(PsiArrayType arrayType) {
if (arrayType.getArrayDimensions() != 1) return Boolean.FALSE;
PsiType componentType = arrayType.getComponentType();
return componentType.accept(this);
}
@Override
public Boolean visitClassType(PsiClassType classType) {
if (classType.getParameters().length > 0) {
PsiClassType rawType = classType.rawType();
return rawType.equalsToText(CommonClassNames.JAVA_LANG_CLASS);
}
PsiClass aClass = classType.resolve();
if (aClass != null && (aClass.isAnnotationType() || aClass.isEnum())) {
return Boolean.TRUE;
}
return classType.equalsToText(CommonClassNames.JAVA_LANG_CLASS) || classType.equalsToText(CommonClassNames.JAVA_LANG_STRING);
}
}
private static class DeleteAnnotationAction implements IntentionAction {
private final PsiAnnotation myAnnotation;
private DeleteAnnotationAction(PsiAnnotation annotation) {
myAnnotation = annotation;
}
@NotNull
@Override
public String getText() {
return "Remove";
}
@NotNull
@Override
public String getFamilyName() {
return getText();
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return true;
}
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
myAnnotation.delete();
}
@Override
public boolean startInWriteAction() {
return true;
}
}
}
| |
/**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.core.commons.controllers.filechooser;
import java.util.ArrayList;
import java.util.List;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.util.vfs.MergeSource;
import org.olat.core.util.vfs.NamedContainerImpl;
import org.olat.core.util.vfs.NamedLeaf;
import org.olat.core.util.vfs.VFSContainer;
import org.olat.core.util.vfs.VFSItem;
import org.olat.core.util.vfs.filters.VFSContainerFilter;
import org.olat.core.util.vfs.filters.VFSItemFilter;
/**
* <h3>Description:</h3>
* UI Factory to handle the file chooser package
* <p>
* Initial Date: 13.06.2008 <br>
*
* @author Florian Gnaegi, frentix GmbH, http://www.frentix.com
*/
public class FileChooserUIFactory {
private static final VFSItemFilter containerFilter = new VFSContainerFilter();
/**
* Factory method to create a file chooser workflow controller that allows the
* usage of a custom vfs item filter. The tree will display a title
* and a description above the tree.
*
* @param ureq
* @param wControl
* @param rootContainer The root container that should be selected from
* @param customItemFilter The custom filter to be used or NULL to not use any
* filter at all
* @param onlyLeafsSelectable true: container elements can't be selected;
* false: all items can be selected
*/
public static FileChooserController createFileChooserController(UserRequest ureq, WindowControl wControl, VFSContainer rootContainer, VFSItemFilter customItemFilter, boolean onlyLeafsSelectable) {
return new FileChooserController(ureq, wControl, rootContainer, customItemFilter, onlyLeafsSelectable, true);
}
/**
* Factory method to create a file chooser workflow controller that allows the
* usage of a custom vfs item filter. The tree will not have a title,
* just the tree
*
* @param ureq
* @param wControl
* @param rootContainer The root container that should be selected from
* @param customItemFilter The custom filter to be used or NULL to not use any
* filter at all
* @param onlyLeafsSelectable true: container elements can't be selected;
* false: all items can be selected
*/
public static FileChooserController createFileChooserControllerWithoutTitle(UserRequest ureq, WindowControl wControl, VFSContainer rootContainer, VFSItemFilter customItemFilter, boolean onlyLeafsSelectable) {
return new FileChooserController(ureq, wControl, rootContainer, customItemFilter, onlyLeafsSelectable, false);
}
/**
* Factory method to create a file chooser workflow controller allows
* filtering of files by setting a boolean. The tree will display a title
* and a description above the tree.
*
* @param ureq
* @param wControl
* @param rootContainer
* The root container that should be selected from
* @param showLeafs
* true: show directories and files; false: show only directories
* @param onlyLeafsSelectable
* true: container elements can't be selected; false: all items
* can be selected
*/
public static FileChooserController createFileChooserController(UserRequest ureq, WindowControl wControl, VFSContainer rootContainer, boolean showLeafs, boolean onlyLeafsSelectable) {
return new FileChooserController(ureq, wControl, rootContainer, (showLeafs ? null : containerFilter), onlyLeafsSelectable, true);
}
/**
* Factory method to create a file chooser workflow controller allows
* filtering of files by setting a boolean. The tree will not have a title,
* just the tree
*
* @param ureq
* @param wControl
* @param rootContainer
* The root container that should be selected from
* @param showLeafs
* true: show directories and files; false: show only directories
* @param onlyLeafsSelectable
* true: container elements can't be selected; false: all items
* can be selected
*/
public static FileChooserController createFileChooserControllerWithoutTitle(UserRequest ureq, WindowControl wControl, VFSContainer rootContainer, boolean showLeafs, boolean onlyLeafsSelectable) {
return new FileChooserController(ureq, wControl, rootContainer, (showLeafs ? null : containerFilter), onlyLeafsSelectable, false);
}
/**
* Get the vfs item that was selected by the user
*
* @param event
* The file choosen event
*
* @return
*/
public static VFSItem getSelectedItem(FileChoosenEvent event) {
return event.getSelectedItem();
}
/**
* Get the path as string of the selected item relative to the root
* container and the relative base path
*
* @param event The file choosen event
* @param rootContainer
* The root container for which the relative path should be
* calculated
* @param relativeBasePath
* when NULL, the path will be calculated relative to the
* rootContainer; when NULL, the relativeBasePath must
* represent a relative path within the root container that
* serves as the base. In this case, the calculated relative item
* path will start from this relativeBasePath
* @return
*/
public static String getSelectedRelativeItemPath(FileChoosenEvent event, VFSContainer rootContainer, String relativeBasePath) {
// 1) Create path absolute to the root container
VFSItem selectedItem = event.getSelectedItem();
if (selectedItem == null) return null;
String absPath = "";
VFSItem tmpItem = selectedItem;
// Check for merged containers to fix problems with named containers, see OLAT-3848
List<NamedContainerImpl> namedRootChilds = new ArrayList<NamedContainerImpl>();
for (VFSItem rootItem : rootContainer.getItems()) {
if (rootItem instanceof NamedContainerImpl) {
namedRootChilds.add((NamedContainerImpl) rootItem);
}
}
// Check if root container is the same as the item and vice versa. It is
// necessary to perform the check on both containers to catch all potential
// cases with MergedSource and NamedContainer where the check in one
// direction is not necessarily the same as the opposite check
while ( tmpItem != null && !rootContainer.isSame(tmpItem) && !tmpItem.isSame(rootContainer)) {
String itemFileName = tmpItem.getName();
//fxdiff FXOLAT-125: virtual file system for CP
if(tmpItem instanceof NamedLeaf) {
itemFileName = ((NamedLeaf)tmpItem).getDelegate().getName();
}
// Special case: check if this is a named container, see OLAT-3848
for (NamedContainerImpl namedRootChild : namedRootChilds) {
if (namedRootChild.isSame(tmpItem)) {
itemFileName = namedRootChild.getName();
}
}
absPath = "/" + itemFileName + absPath;
tmpItem = tmpItem.getParentContainer();
if (tmpItem != null) {
// test if this this is a merge source child container, see OLAT-5726
VFSContainer grandParent = tmpItem.getParentContainer();
if (grandParent instanceof MergeSource) {
MergeSource mergeGrandParent = (MergeSource) grandParent;
if (mergeGrandParent.isContainersChild((VFSContainer) tmpItem)) {
// skip this parent container and use the merge grand-parent
// instead, otherwhise path contains the container twice
tmpItem = mergeGrandParent;
}
}
}
}
if (relativeBasePath == null) {
return absPath;
}
// 2) Compute rel path to base dir of the current file
// selpath = /a/irwas/subsub/nochsub/note.html 5
// filenam = /a/irwas/index.html 3
// --> subsub/nochsub/note.gif
// or /a/irwas/bla/index.html
// to /a/other/b/gugus.gif
// --> ../../ other/b/gugus.gif
// or /a/other/b/main.html
// to /a/irwas/bla/goto.html
// --> ../../ other/b/gugus.gif
String base = relativeBasePath; // assume "/" is here
if (!(base.indexOf("/") == 0)) {
base = "/" + base;
}
String[] baseA = base.split("/");
String[] targetA = absPath.split("/");
int sp = 1;
for (; sp < Math.min(baseA.length, targetA.length); sp++) {
if (!baseA[sp].equals(targetA[sp])) {
break;
}
}
// special case: self-reference
if (absPath.equals(base)) {
sp = 1;
}
StringBuilder buffer = new StringBuilder();
for (int i = sp; i < baseA.length - 1; i++) {
buffer.append("../");
}
for (int i = sp; i < targetA.length; i++) {
buffer.append(targetA[i] + "/");
}
buffer.deleteCharAt(buffer.length() - 1);
String path = buffer.toString();
String trimmed = path; // selectedPath.substring(1);
return trimmed;
}
}
| |
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.dmn.core;
import java.util.HashMap;
import java.util.Map;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.kie.dmn.api.core.DMNContext;
import org.kie.dmn.api.core.DMNModel;
import org.kie.dmn.api.core.DMNResult;
import org.kie.dmn.api.core.DMNRuntime;
import org.kie.dmn.api.core.FEELPropertyAccessible;
import org.kie.dmn.core.compiler.RuntimeTypeCheckOption;
import org.kie.dmn.core.impl.DMNContextFPAImpl;
import org.kie.dmn.core.internal.utils.DMNRuntimeBuilder;
import org.kie.dmn.core.internal.utils.DMNRuntimeBuilder.DMNRuntimeBuilderConfigured;
import org.kie.dmn.core.util.DMNRuntimeUtil;
import org.kie.dmn.typesafe.DMNAllTypesIndex;
import org.kie.dmn.typesafe.DMNTypeSafePackageName;
import org.kie.dmn.typesafe.DMNTypeSafeTypeGenerator;
import org.kie.memorycompiler.KieMemoryCompiler;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.kie.dmn.core.BaseVariantTest.VariantTestConf.BUILDER_DEFAULT_NOCL_TYPECHECK;
import static org.kie.dmn.core.BaseVariantTest.VariantTestConf.BUILDER_DEFAULT_NOCL_TYPECHECK_TYPESAFE;
import static org.kie.dmn.core.BaseVariantTest.VariantTestConf.BUILDER_STRICT;
import static org.kie.dmn.core.BaseVariantTest.VariantTestConf.KIE_API_TYPECHECK;
import static org.kie.dmn.core.BaseVariantTest.VariantTestConf.KIE_API_TYPECHECK_TYPESAFE;
@RunWith(Parameterized.class)
public abstract class BaseVariantTest {
private DMNTypeSafePackageName.Factory factory;
public enum VariantTestConf implements VariantTest {
KIE_API_TYPECHECK {
@Override
public DMNRuntime createRuntime(String string, Class<?> class1) {
return DMNRuntimeUtil.createRuntime(string, class1);
}
@Override
public DMNRuntime createRuntimeWithAdditionalResources(String string, Class<?> class1, String... string2) {
return DMNRuntimeUtil.createRuntimeWithAdditionalResources(string, class1, string2);
}
@Override
public boolean isTypeSafe() {
return false;
}
},
BUILDER_STRICT {
private DMNRuntimeBuilderConfigured builder() {
return DMNRuntimeBuilder.usingStrict();
}
@Override
public DMNRuntime createRuntime(String string, Class<?> class1) {
return builder().fromClasspathResource(string, class1).getOrElseThrow(RuntimeException::new);
}
@Override
public DMNRuntime createRuntimeWithAdditionalResources(String string, Class<?> class1, String... string2) {
return builder().fromClasspathResources(string, class1, string2).getOrElseThrow(RuntimeException::new);
}
@Override
public boolean isTypeSafe() {
return false;
}
},
BUILDER_DEFAULT_NOCL_TYPECHECK {
private DMNRuntimeBuilderConfigured builder() {
return DMNRuntimeBuilder.fromDefaults().setRootClassLoader(null).setOption(new RuntimeTypeCheckOption(true)).buildConfiguration();
}
@Override
public DMNRuntime createRuntime(String string, Class<?> class1) {
return builder().fromClasspathResource(string, class1).getOrElseThrow(RuntimeException::new);
}
@Override
public DMNRuntime createRuntimeWithAdditionalResources(String string, Class<?> class1, String... string2) {
return builder().fromClasspathResources(string, class1, string2).getOrElseThrow(RuntimeException::new);
}
@Override
public boolean isTypeSafe() {
return false;
}
},
KIE_API_TYPECHECK_TYPESAFE {
@Override
public DMNRuntime createRuntime(String string, Class<?> class1) {
return DMNRuntimeUtil.createRuntime(string, class1);
}
@Override
public DMNRuntime createRuntimeWithAdditionalResources(String string, Class<?> class1, String... string2) {
return DMNRuntimeUtil.createRuntimeWithAdditionalResources(string, class1, string2);
}
@Override
public boolean isTypeSafe() {
return true;
}
},
BUILDER_DEFAULT_NOCL_TYPECHECK_TYPESAFE {
private DMNRuntimeBuilderConfigured builder() {
return DMNRuntimeBuilder.fromDefaults().setRootClassLoader(null).setOption(new RuntimeTypeCheckOption(true)).buildConfiguration();
}
@Override
public DMNRuntime createRuntime(String string, Class<?> class1) {
return builder().fromClasspathResource(string, class1).getOrElseThrow(RuntimeException::new);
}
@Override
public DMNRuntime createRuntimeWithAdditionalResources(String string, Class<?> class1, String... string2) {
return builder().fromClasspathResources(string, class1, string2).getOrElseThrow(RuntimeException::new);
}
@Override
public boolean isTypeSafe() {
return true;
}
}
}
@Parameterized.Parameters(name = "{0}")
public static Object[] params() {
return new Object[]{KIE_API_TYPECHECK, BUILDER_STRICT, BUILDER_DEFAULT_NOCL_TYPECHECK, BUILDER_DEFAULT_NOCL_TYPECHECK_TYPESAFE, KIE_API_TYPECHECK_TYPESAFE};
}
private final VariantTestConf testConfig;
public BaseVariantTest(final VariantTestConf testConfig) {
this.testConfig = testConfig;
}
public DMNRuntime createRuntime(final Class testClass) {
DMNRuntime runtime = DMNRuntimeUtil.createRuntime(testClass);
if (testConfig.isTypeSafe()) {
createTypeSafeInput(runtime);
}
return runtime;
}
public DMNRuntime createRuntime(String string, Class<?> class1) {
DMNRuntime runtime = testConfig.createRuntime(string, class1);
if (testConfig.isTypeSafe()) {
createTypeSafeInput(runtime);
}
return runtime;
}
public DMNRuntime createRuntimeWithAdditionalResources(String string, Class<?> class1, String... string2) {
DMNRuntime runtimeWithAdditionalResources = testConfig.createRuntimeWithAdditionalResources(string, class1, string2);
if (testConfig.isTypeSafe()) {
createTypeSafeInput(runtimeWithAdditionalResources);
}
return runtimeWithAdditionalResources;
}
protected Map<String, Class<?>> allCompiledClasses;
protected String testName = "";
private void createTypeSafeInput(DMNRuntime runtime) {
String prefix = String.format("%s%s", testName, testConfig.name());
factory = new DMNTypeSafePackageName.ModelFactory(prefix);
DMNAllTypesIndex index = new DMNAllTypesIndex(factory, runtime.getModels().toArray(new DMNModel[]{}));
Map<String, String> allSources = new HashMap<>();
for (DMNModel m : runtime.getModels()) {
Map<String, String> allTypesSourceCode = new DMNTypeSafeTypeGenerator(m, index, factory)
.processTypes()
.generateSourceCodeOfAllTypes();
allSources.putAll(allTypesSourceCode);
}
if(!allSources.isEmpty()) {
allCompiledClasses = KieMemoryCompiler.compile(allSources, this.getClass().getClassLoader());
}
}
protected DMNResult evaluateModel(DMNRuntime runtime, DMNModel dmnModel, DMNContext context) {
if (testConfig.isTypeSafe()) {
return evaluateTypeSafe(runtime, dmnModel, context);
} else {
return runtime.evaluateAll(dmnModel, context);
}
}
private DMNResult evaluateTypeSafe(DMNRuntime runtime, DMNModel dmnModel, DMNContext context) {
Map<String, Object> inputMap = context.getAll();
FEELPropertyAccessible inputSet;
try {
inputSet = createInstanceFromCompiledClasses(allCompiledClasses, factory.create(dmnModel), "InputSet");
inputSet.fromMap(inputMap);
return runtime.evaluateAll(dmnModel, new DMNContextFPAImpl(inputSet));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected FEELPropertyAccessible createInstanceFromCompiledClasses(Map<String, Class<?>> compile, DMNTypeSafePackageName packageName, String className) throws Exception {
Class<?> inputSetClass = compile.get(packageName.appendPackage(className));
assertThat(inputSetClass, notNullValue());
Object inputSetInstance = inputSetClass.getDeclaredConstructor().newInstance();
return (FEELPropertyAccessible) inputSetInstance;
}
}
interface VariantTest {
DMNRuntime createRuntime(String string, Class<?> class1);
DMNRuntime createRuntimeWithAdditionalResources(String string, Class<?> class1, String... string2);
boolean isTypeSafe();
}
| |
/**
* Copyright 2014 Netflix, 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 rx.internal.operators;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import rx.Observable.OnSubscribe;
import rx.Observable.Operator;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.observables.GroupedObservable;
import rx.observers.SerializedObserver;
import rx.subscriptions.Subscriptions;
public final class OperatorPivot<K1, K2, T> implements Operator<GroupedObservable<K2, GroupedObservable<K1, T>>, GroupedObservable<K1, GroupedObservable<K2, T>>> {
@Override
public Subscriber<? super GroupedObservable<K1, GroupedObservable<K2, T>>> call(final Subscriber<? super GroupedObservable<K2, GroupedObservable<K1, T>>> child) {
final AtomicReference<State> state = new AtomicReference<State>(State.create());
final PivotSubscriber<K1, K2, T> pivotSubscriber = new PivotSubscriber<K1, K2, T>(child, state);
child.add(Subscriptions.create(new Action0() {
@Override
public void call() {
State current;
State newState = null;
do {
current = state.get();
newState = current.unsubscribe();
} while (!state.compareAndSet(current, newState));
// If all outer/inner groups are completed/unsubscribed then we can shut it all down
if (newState.shouldComplete()) {
pivotSubscriber.groups.completeAll(newState);
}
// otherwise it is just marked as unsubscribed and groups being completed/unsubscribed will allow it to cleanup
}
}));
return pivotSubscriber;
}
private static final class PivotSubscriber<K1, K2, T> extends Subscriber<GroupedObservable<K1, GroupedObservable<K2, T>>> {
private final Subscriber<? super GroupedObservable<K2, GroupedObservable<K1, T>>> child;
private final AtomicReference<State> state;
private final GroupState<K1, K2, T> groups;
private PivotSubscriber(Subscriber<? super GroupedObservable<K2, GroupedObservable<K1, T>>> child, AtomicReference<State> state) {
this.child = child;
this.state = state;
this.groups = new GroupState<K1, K2, T>(this, child);
}
@Override
public void onCompleted() {
State current;
State newState = null;
do {
current = state.get();
newState = current.complete();
} while (!state.compareAndSet(current, newState));
// special case for empty (no groups emitted) or all groups already done
if (newState.shouldComplete()) {
groups.completeAll(newState);
}
}
@Override
public void onError(Throwable e) {
// we immediately tear everything down if we receive an error
child.onError(e);
}
@Override
public void onNext(final GroupedObservable<K1, GroupedObservable<K2, T>> k1Group) {
groups.startK1Group(state, k1Group.getKey());
k1Group.unsafeSubscribe(new Subscriber<GroupedObservable<K2, T>>(this) {
@Override
public void onCompleted() {
groups.completeK1Group(state, k1Group.getKey());
}
@Override
public void onError(Throwable e) {
child.onError(e);
}
@Override
public void onNext(final GroupedObservable<K2, T> k2Group) {
/*
* In this scope once pivoted, k2 == outer and k2.k1 == inner
*/
final Inner<K1, K2, T> inner = groups.getOrCreateFor(state, child, k1Group.getKey(), k2Group.getKey());
if (inner == null) {
// we have been unsubscribed
return;
}
k2Group.unsafeSubscribe(new Subscriber<T>(this) {
@Override
public void onCompleted() {
/*
* we don't actually propagate onCompleted to the 'inner.subscriber' here
* since multiple upstream groups will be sent to a single downstream
* and a single upstream group completing does not indicate total completion
*/
}
@Override
public void onError(Throwable e) {
inner.subscriber.onError(e);
}
@Override
public void onNext(T t) {
inner.subscriber.onNext(t);
}
});
}
});
}
}
private static final class GroupState<K1, K2, T> {
private final ConcurrentHashMap<KeyPair<K1, K2>, Inner<K1, K2, T>> innerSubjects = new ConcurrentHashMap<KeyPair<K1, K2>, Inner<K1, K2, T>>();
private final ConcurrentHashMap<K2, Outer<K1, K2, T>> outerSubjects = new ConcurrentHashMap<K2, Outer<K1, K2, T>>();
private final Subscription parentSubscription;
private final Subscriber<? super GroupedObservable<K2, GroupedObservable<K1, T>>> child;
/** Indicates a terminal state. */
volatile int completed;
/** Field updater for completed. */
@SuppressWarnings("rawtypes")
static final AtomicIntegerFieldUpdater<GroupState> COMPLETED_UPDATER = AtomicIntegerFieldUpdater.newUpdater(GroupState.class, "completed");
public GroupState(Subscription parentSubscription, Subscriber<? super GroupedObservable<K2, GroupedObservable<K1, T>>> child) {
this.parentSubscription = parentSubscription;
this.child = child;
}
public void startK1Group(AtomicReference<State> state, K1 key) {
State current;
State newState;
do {
current = state.get();
newState = current.addK1(key);
} while (!state.compareAndSet(current, newState));
}
public void completeK1Group(AtomicReference<State> state, K1 key) {
State current;
State newState = null;
do {
current = state.get();
newState = current.removeK1(key);
} while (!state.compareAndSet(current, newState));
if (newState.shouldComplete()) {
completeAll(newState);
}
}
public void startK1K2Group(AtomicReference<State> state, KeyPair<K1, K2> keyPair) {
State current;
State newState;
do {
current = state.get();
newState = current.addK1k2(keyPair);
} while (!state.compareAndSet(current, newState));
}
public void completeK1K2Group(AtomicReference<State> state, KeyPair<K1, K2> keyPair) {
State current;
State newState = null;
do {
current = state.get();
newState = current.removeK1k2(keyPair);
} while (!state.compareAndSet(current, newState));
if (newState.shouldComplete()) {
completeAll(newState);
}
}
public void completeAll(State state) {
if (COMPLETED_UPDATER.compareAndSet(this, 0, 1)) {
/*
* after we are completely done emitting we can now shut down the groups
*/
for (Entry<K2, Outer<K1, K2, T>> outer : outerSubjects.entrySet()) {
outer.getValue().subscriber.onCompleted();
}
for (Entry<KeyPair<K1, K2>, Inner<K1, K2, T>> inner : innerSubjects.entrySet()) {
inner.getValue().subscriber.onCompleted();
}
// unsubscribe eagerly
if (state.unsubscribed) {
parentSubscription.unsubscribe(); // unsubscribe from parent
}
child.onCompleted();
}
}
private Inner<K1, K2, T> getOrCreateFor(final AtomicReference<State> state, final Subscriber<? super GroupedObservable<K2, GroupedObservable<K1, T>>> child, K1 key1, K2 key2) {
Outer<K1, K2, T> outer = getOrCreateOuter(state, child, key2);
if (outer == null) {
// we have been unsubscribed
return null;
}
Inner<K1, K2, T> orCreateInnerSubject = getOrCreateInnerSubject(state, outer, key1, key2);
return orCreateInnerSubject;
}
private Inner<K1, K2, T> getOrCreateInnerSubject(final AtomicReference<State> state, final Outer<K1, K2, T> outer, final K1 key1, final K2 key2) {
KeyPair<K1, K2> keyPair = new KeyPair<K1, K2>(key1, key2);
Inner<K1, K2, T> innerSubject = innerSubjects.get(keyPair);
if (innerSubject != null) {
return innerSubject;
} else {
Inner<K1, K2, T> newInner = Inner.create(this, state, outer, keyPair);
Inner<K1, K2, T> existing = innerSubjects.putIfAbsent(keyPair, newInner);
if (existing != null) {
// we lost the race to create so return the one that did
return existing;
} else {
startK1K2Group(state, keyPair);
outer.subscriber.onNext(newInner.group);
return newInner;
}
}
}
private Outer<K1, K2, T> getOrCreateOuter(final AtomicReference<State> state, final Subscriber<? super GroupedObservable<K2, GroupedObservable<K1, T>>> child, final K2 key2) {
Outer<K1, K2, T> outerSubject = outerSubjects.get(key2);
if (outerSubject != null) {
return outerSubject;
} else {
// this group doesn't exist
if (child.isUnsubscribed()) {
// we have been unsubscribed on the outer so won't send any more groups
return null;
}
Outer<K1, K2, T> newOuter = Outer.<K1, K2, T> create(key2);
Outer<K1, K2, T> existing = outerSubjects.putIfAbsent(key2, newOuter);
if (existing != null) {
// we lost the race to create so return the one that did
return existing;
} else {
child.onNext(newOuter.group);
return newOuter;
}
}
}
}
private static final class Inner<K1, K2, T> {
private final Observer<T> subscriber;
private final GroupedObservable<K1, T> group;
private Inner(BufferUntilSubscriber<T> subscriber, GroupedObservable<K1, T> group) {
// since multiple threads are being pivoted we need to make sure this is serialized
this.subscriber = new SerializedObserver<T>(subscriber);
this.group = group;
}
public static <K1, K2, T> Inner<K1, K2, T> create(final GroupState<K1, K2, T> groupState, final AtomicReference<State> state, final Outer<K1, K2, T> outer, final KeyPair<K1, K2> keyPair) {
final BufferUntilSubscriber<T> subject = BufferUntilSubscriber.create();
GroupedObservable<K1, T> group = new GroupedObservable<K1, T>(keyPair.k1, new OnSubscribe<T>() {
@Override
public void call(final Subscriber<? super T> o) {
o.add(Subscriptions.create(new Action0() {
@Override
public void call() {
groupState.completeK1K2Group(state, keyPair);
}
}));
subject.unsafeSubscribe(new Subscriber<T>(o) {
@Override
public void onCompleted() {
groupState.completeK1K2Group(state, keyPair);
o.onCompleted();
}
@Override
public void onError(Throwable e) {
o.onError(e);
}
@Override
public void onNext(T t) {
if (!isUnsubscribed()) {
o.onNext(t);
}
}
});
}
});
return new Inner<K1, K2, T>(subject, group);
}
}
private static final class Outer<K1, K2, T> {
private final Observer<GroupedObservable<K1, T>> subscriber;
private final GroupedObservable<K2, GroupedObservable<K1, T>> group;
private Outer(BufferUntilSubscriber<GroupedObservable<K1, T>> subscriber, GroupedObservable<K2, GroupedObservable<K1, T>> group) {
// since multiple threads are being pivoted we need to make sure this is serialized
this.subscriber = new SerializedObserver<GroupedObservable<K1, T>>(subscriber);
this.group = group;
}
public static <K1, K2, T> Outer<K1, K2, T> create(final K2 key2) {
final BufferUntilSubscriber<GroupedObservable<K1, T>> subject = BufferUntilSubscriber.create();
GroupedObservable<K2, GroupedObservable<K1, T>> group = new GroupedObservable<K2, GroupedObservable<K1, T>>(key2, new OnSubscribe<GroupedObservable<K1, T>>() {
@Override
public void call(final Subscriber<? super GroupedObservable<K1, T>> o) {
subject.unsafeSubscribe(new Subscriber<GroupedObservable<K1, T>>(o) {
@Override
public void onCompleted() {
o.onCompleted();
}
@Override
public void onError(Throwable e) {
o.onError(e);
}
@Override
public void onNext(GroupedObservable<K1, T> t) {
if (!isUnsubscribed()) {
o.onNext(t);
}
}
});
}
});
return new Outer<K1, K2, T>(subject, group);
}
}
private static final class State {
private final boolean unsubscribed;
private final boolean completed;
private final Set<Object> k1Keys;
private final Set<KeyPair<?, ?>> k1k2Keys;
private State(boolean completed, boolean unsubscribed, Set<Object> k1Keys, Set<KeyPair<?, ?>> k1k2Keys) {
this.completed = completed;
this.unsubscribed = unsubscribed;
this.k1Keys = k1Keys;
this.k1k2Keys = k1k2Keys;
}
public static State create() {
return new State(false, false, Collections.emptySet(), Collections.<KeyPair<?, ?>> emptySet());
}
public State addK1(Object key) {
Set<Object> newKeys = new HashSet<Object>(k1Keys);
newKeys.add(key);
return new State(completed, unsubscribed, newKeys, k1k2Keys);
}
public State removeK1(Object key) {
Set<Object> newKeys = new HashSet<Object>(k1Keys);
newKeys.remove(key);
return new State(completed, unsubscribed, newKeys, k1k2Keys);
}
public State addK1k2(KeyPair<?, ?> key) {
Set<KeyPair<?, ?>> newKeys = new HashSet<KeyPair<?, ?>>(k1k2Keys);
newKeys.add(key);
return new State(completed, unsubscribed, k1Keys, newKeys);
}
public State removeK1k2(KeyPair<?, ?> key) {
Set<KeyPair<?, ?>> newKeys = new HashSet<KeyPair<?, ?>>(k1k2Keys);
newKeys.remove(key);
return new State(completed, unsubscribed, k1Keys, newKeys);
}
public State complete() {
return new State(true, unsubscribed, k1Keys, k1k2Keys);
}
public State unsubscribe() {
return new State(completed, true, k1Keys, k1k2Keys);
}
public boolean shouldComplete() {
if (k1Keys.isEmpty() && completed) {
return true;
} else if (unsubscribed) {
// if unsubscribed and all groups are completed/unsubscribed we can complete
return k1k2Keys.isEmpty();
} else {
return false;
}
}
@Override
public String toString() {
return "State => k1: " + k1Keys.size() + " k1k2: " + k1k2Keys.size() + " completed: " + completed + " unsubscribed: " + unsubscribed;
}
}
private static final class KeyPair<K1, K2> {
private final K1 k1;
private final K2 k2;
KeyPair(K1 k1, K2 k2) {
this.k1 = k1;
this.k2 = k2;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((k1 == null) ? 0 : k1.hashCode());
result = prime * result + ((k2 == null) ? 0 : k2.hashCode());
return result;
}
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
KeyPair other = (KeyPair) obj;
if (k1 == null) {
if (other.k1 != null)
return false;
} else if (!k1.equals(other.k1))
return false;
if (k2 == null) {
if (other.k2 != null)
return false;
} else if (!k2.equals(other.k2))
return false;
return true;
}
@Override
public String toString() {
return k2 + "." + k1;
}
}
}
| |
// Copyright 2021 Google 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.
/**
* PlacementServiceSoapBindingStub.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202102;
public class PlacementServiceSoapBindingStub extends org.apache.axis.client.Stub implements com.google.api.ads.admanager.axis.v202102.PlacementServiceInterface {
private java.util.Vector cachedSerClasses = new java.util.Vector();
private java.util.Vector cachedSerQNames = new java.util.Vector();
private java.util.Vector cachedSerFactories = new java.util.Vector();
private java.util.Vector cachedDeserFactories = new java.util.Vector();
static org.apache.axis.description.OperationDesc [] _operations;
static {
_operations = new org.apache.axis.description.OperationDesc[4];
_initOperationDesc1();
}
private static void _initOperationDesc1(){
org.apache.axis.description.OperationDesc oper;
org.apache.axis.description.ParameterDesc param;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("createPlacements");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "placements"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "Placement"), com.google.api.ads.admanager.axis.v202102.Placement[].class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "Placement"));
oper.setReturnClass(com.google.api.ads.admanager.axis.v202102.Placement[].class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApiExceptionFault"),
"com.google.api.ads.admanager.axis.v202102.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApiException"),
true
));
_operations[0] = oper;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("getPlacementsByStatement");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "filterStatement"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "Statement"), com.google.api.ads.admanager.axis.v202102.Statement.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "PlacementPage"));
oper.setReturnClass(com.google.api.ads.admanager.axis.v202102.PlacementPage.class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApiExceptionFault"),
"com.google.api.ads.admanager.axis.v202102.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApiException"),
true
));
_operations[1] = oper;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("performPlacementAction");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "placementAction"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "PlacementAction"), com.google.api.ads.admanager.axis.v202102.PlacementAction.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "filterStatement"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "Statement"), com.google.api.ads.admanager.axis.v202102.Statement.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "UpdateResult"));
oper.setReturnClass(com.google.api.ads.admanager.axis.v202102.UpdateResult.class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApiExceptionFault"),
"com.google.api.ads.admanager.axis.v202102.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApiException"),
true
));
_operations[2] = oper;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("updatePlacements");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "placements"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "Placement"), com.google.api.ads.admanager.axis.v202102.Placement[].class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "Placement"));
oper.setReturnClass(com.google.api.ads.admanager.axis.v202102.Placement[].class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApiExceptionFault"),
"com.google.api.ads.admanager.axis.v202102.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApiException"),
true
));
_operations[3] = oper;
}
public PlacementServiceSoapBindingStub() throws org.apache.axis.AxisFault {
this(null);
}
public PlacementServiceSoapBindingStub(java.net.URL endpointURL, javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
this(service);
super.cachedEndpoint = endpointURL;
}
public PlacementServiceSoapBindingStub(javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
if (service == null) {
super.service = new org.apache.axis.client.Service();
} else {
super.service = service;
}
((org.apache.axis.client.Service)super.service).setTypeMappingVersion("1.2");
java.lang.Class cls;
javax.xml.namespace.QName qName;
javax.xml.namespace.QName qName2;
java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class;
java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class;
java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class;
java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class;
java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class;
java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class;
java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class;
java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class;
java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class;
java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class;
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ActivatePlacements");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.ActivatePlacements.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApiError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.ApiError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApiException");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.ApiException.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApiVersionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.ApiVersionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApiVersionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.ApiVersionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ApplicationException");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.ApplicationException.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ArchivePlacements");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.ArchivePlacements.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "AuthenticationError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.AuthenticationError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "AuthenticationError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.AuthenticationErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "BooleanValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.BooleanValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "CollectionSizeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.CollectionSizeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "CollectionSizeError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.CollectionSizeErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "CommonError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.CommonError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "CommonError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.CommonErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "Date");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.Date.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "DateTime");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.DateTime.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "DateTimeValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.DateTimeValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "DateValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.DateValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "DeactivatePlacements");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.DeactivatePlacements.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "EntityChildrenLimitReachedError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.EntityChildrenLimitReachedError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "EntityChildrenLimitReachedError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.EntityChildrenLimitReachedErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "EntityLimitReachedError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.EntityLimitReachedError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "EntityLimitReachedError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.EntityLimitReachedErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "FeatureError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.FeatureError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "FeatureError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.FeatureErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "FieldPathElement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.FieldPathElement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "InternalApiError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.InternalApiError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "InternalApiError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.InternalApiErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "InventoryStatus");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.InventoryStatus.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "NotNullError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.NotNullError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "NotNullError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.NotNullErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "NullError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.NullError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "NullError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.NullErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "NumberValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.NumberValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ObjectValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.ObjectValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ParseError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.ParseError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ParseError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.ParseErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "PermissionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.PermissionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "PermissionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.PermissionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "Placement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.Placement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "PlacementAction");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.PlacementAction.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "PlacementError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.PlacementError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "PlacementError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.PlacementErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "PlacementPage");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.PlacementPage.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "PublisherQueryLanguageContextError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.PublisherQueryLanguageContextError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "PublisherQueryLanguageContextError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.PublisherQueryLanguageContextErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "PublisherQueryLanguageSyntaxError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.PublisherQueryLanguageSyntaxError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "PublisherQueryLanguageSyntaxError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.PublisherQueryLanguageSyntaxErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "QuotaError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.QuotaError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "QuotaError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.QuotaErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "RangeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.RangeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "RangeError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.RangeErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "RegExError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.RegExError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "RegExError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.RegExErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "RequiredCollectionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.RequiredCollectionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "RequiredCollectionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.RequiredCollectionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "RequiredError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.RequiredError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "RequiredError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.RequiredErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ServerError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.ServerError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "ServerError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.ServerErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "SetValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.SetValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "SiteTargetingInfo");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.SiteTargetingInfo.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "SoapRequestHeader");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.SoapRequestHeader.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "SoapResponseHeader");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.SoapResponseHeader.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "Statement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.Statement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "StatementError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.StatementError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "StatementError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.StatementErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "String_ValueMapEntry");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.String_ValueMapEntry.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "StringFormatError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.StringFormatError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "StringFormatError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.StringFormatErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "StringLengthError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.StringLengthError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "StringLengthError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.StringLengthErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "TextValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.TextValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "TypeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.TypeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "UniqueError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.UniqueError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "UpdateResult");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.UpdateResult.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "Value");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202102.Value.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
}
protected org.apache.axis.client.Call createCall() throws java.rmi.RemoteException {
try {
org.apache.axis.client.Call _call = super._createCall();
if (super.maintainSessionSet) {
_call.setMaintainSession(super.maintainSession);
}
if (super.cachedUsername != null) {
_call.setUsername(super.cachedUsername);
}
if (super.cachedPassword != null) {
_call.setPassword(super.cachedPassword);
}
if (super.cachedEndpoint != null) {
_call.setTargetEndpointAddress(super.cachedEndpoint);
}
if (super.cachedTimeout != null) {
_call.setTimeout(super.cachedTimeout);
}
if (super.cachedPortName != null) {
_call.setPortName(super.cachedPortName);
}
java.util.Enumeration keys = super.cachedProperties.keys();
while (keys.hasMoreElements()) {
java.lang.String key = (java.lang.String) keys.nextElement();
_call.setProperty(key, super.cachedProperties.get(key));
}
// All the type mapping information is registered
// when the first call is made.
// The type mapping information is actually registered in
// the TypeMappingRegistry of the service, which
// is the reason why registration is only needed for the first call.
synchronized (this) {
if (firstCall()) {
// must set encoding style before registering serializers
_call.setEncodingStyle(null);
for (int i = 0; i < cachedSerFactories.size(); ++i) {
java.lang.Class cls = (java.lang.Class) cachedSerClasses.get(i);
javax.xml.namespace.QName qName =
(javax.xml.namespace.QName) cachedSerQNames.get(i);
java.lang.Object x = cachedSerFactories.get(i);
if (x instanceof Class) {
java.lang.Class sf = (java.lang.Class)
cachedSerFactories.get(i);
java.lang.Class df = (java.lang.Class)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
else if (x instanceof javax.xml.rpc.encoding.SerializerFactory) {
org.apache.axis.encoding.SerializerFactory sf = (org.apache.axis.encoding.SerializerFactory)
cachedSerFactories.get(i);
org.apache.axis.encoding.DeserializerFactory df = (org.apache.axis.encoding.DeserializerFactory)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
}
}
}
return _call;
}
catch (java.lang.Throwable _t) {
throw new org.apache.axis.AxisFault("Failure trying to get the Call object", _t);
}
}
public com.google.api.ads.admanager.axis.v202102.Placement[] createPlacements(com.google.api.ads.admanager.axis.v202102.Placement[] placements) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202102.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[0]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "createPlacements"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {placements});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.admanager.axis.v202102.Placement[]) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.admanager.axis.v202102.Placement[]) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.admanager.axis.v202102.Placement[].class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.admanager.axis.v202102.ApiException) {
throw (com.google.api.ads.admanager.axis.v202102.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
public com.google.api.ads.admanager.axis.v202102.PlacementPage getPlacementsByStatement(com.google.api.ads.admanager.axis.v202102.Statement filterStatement) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202102.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[1]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "getPlacementsByStatement"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {filterStatement});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.admanager.axis.v202102.PlacementPage) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.admanager.axis.v202102.PlacementPage) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.admanager.axis.v202102.PlacementPage.class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.admanager.axis.v202102.ApiException) {
throw (com.google.api.ads.admanager.axis.v202102.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
public com.google.api.ads.admanager.axis.v202102.UpdateResult performPlacementAction(com.google.api.ads.admanager.axis.v202102.PlacementAction placementAction, com.google.api.ads.admanager.axis.v202102.Statement filterStatement) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202102.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[2]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "performPlacementAction"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {placementAction, filterStatement});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.admanager.axis.v202102.UpdateResult) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.admanager.axis.v202102.UpdateResult) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.admanager.axis.v202102.UpdateResult.class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.admanager.axis.v202102.ApiException) {
throw (com.google.api.ads.admanager.axis.v202102.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
public com.google.api.ads.admanager.axis.v202102.Placement[] updatePlacements(com.google.api.ads.admanager.axis.v202102.Placement[] placements) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202102.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[3]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "updatePlacements"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {placements});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.admanager.axis.v202102.Placement[]) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.admanager.axis.v202102.Placement[]) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.admanager.axis.v202102.Placement[].class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.admanager.axis.v202102.ApiException) {
throw (com.google.api.ads.admanager.axis.v202102.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
}
| |
/**
* Copyright 2004-2020 the original author or 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.ibatis.common.beans;
import com.ibatis.common.resources.Resources;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* A Probe implementation for working with DOM objects.
*/
public class DomProbe extends BaseProbe {
@Override
public String[] getReadablePropertyNames(Object object) {
List props = new ArrayList();
Element e = resolveElement(object);
NodeList nodes = e.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
props.add(nodes.item(i).getNodeName());
}
return (String[]) props.toArray(new String[props.size()]);
}
@Override
public String[] getWriteablePropertyNames(Object object) {
List props = new ArrayList();
Element e = resolveElement(object);
NodeList nodes = e.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
props.add(nodes.item(i).getNodeName());
}
return (String[]) props.toArray(new String[props.size()]);
}
public Class getPropertyTypeForSetter(Object object, String name) {
Element e = findNestedNodeByName(resolveElement(object), name, false);
// todo alias types, don't use exceptions like this
try {
return Resources.classForName(e.getAttribute("type"));
} catch (ClassNotFoundException e1) {
return Object.class;
}
}
public Class getPropertyTypeForGetter(Object object, String name) {
Element e = findNestedNodeByName(resolveElement(object), name, false);
// todo alias types, don't use exceptions like this
try {
return Resources.classForName(e.getAttribute("type"));
} catch (ClassNotFoundException e1) {
return Object.class;
}
}
public boolean hasWritableProperty(Object object, String propertyName) {
return findNestedNodeByName(resolveElement(object), propertyName, false) != null;
}
public boolean hasReadableProperty(Object object, String propertyName) {
return findNestedNodeByName(resolveElement(object), propertyName, false) != null;
}
public Object getObject(Object object, String name) {
Object value = null;
Element element = findNestedNodeByName(resolveElement(object), name, false);
if (element != null) {
value = getElementValue(element);
}
return value;
}
public void setObject(Object object, String name, Object value) {
Element element = findNestedNodeByName(resolveElement(object), name, true);
if (element != null) {
setElementValue(element, value);
}
}
@Override
protected void setProperty(Object object, String property, Object value) {
Element element = findNodeByName(resolveElement(object), property, 0, true);
if (element != null) {
setElementValue(element, value);
}
}
@Override
protected Object getProperty(Object object, String property) {
Object value = null;
Element element = findNodeByName(resolveElement(object), property, 0, false);
if (element != null) {
value = getElementValue(element);
}
return value;
}
/**
* Resolve element.
*
* @param object
* the object
* @return the element
*/
private Element resolveElement(Object object) {
Element element = null;
if (object instanceof Document) {
element = (Element) ((Document) object).getLastChild();
} else if (object instanceof Element) {
element = (Element) object;
} else {
throw new ProbeException("An unknown object type was passed to DomProbe. Must be a Document.");
}
return element;
}
/**
* Sets the element value.
*
* @param element
* the element
* @param value
* the value
*/
private void setElementValue(Element element, Object value) {
CharacterData data = null;
Element prop = element;
if (value instanceof Collection) {
Iterator items = ((Collection) value).iterator();
while (items.hasNext()) {
Document valdoc = (Document) items.next();
NodeList list = valdoc.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node newNode = element.getOwnerDocument().importNode(list.item(i), true);
element.appendChild(newNode);
}
}
} else if (value instanceof Document) {
Document valdoc = (Document) value;
Node lastChild = valdoc.getLastChild();
NodeList list = lastChild.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node newNode = element.getOwnerDocument().importNode(list.item(i), true);
element.appendChild(newNode);
}
} else if (value instanceof Element) {
Node newNode = element.getOwnerDocument().importNode((Element) value, true);
element.appendChild(newNode);
} else {
// Find text child element
NodeList texts = prop.getChildNodes();
if (texts.getLength() == 1) {
Node child = texts.item(0);
if (child instanceof CharacterData) {
// Use existing text.
data = (CharacterData) child;
} else {
// Remove non-text, add text.
prop.removeChild(child);
Text text = prop.getOwnerDocument().createTextNode(String.valueOf(value));
prop.appendChild(text);
data = text;
}
} else if (texts.getLength() > 1) {
// Remove all, add text.
for (int i = texts.getLength() - 1; i >= 0; i--) {
prop.removeChild(texts.item(i));
}
Text text = prop.getOwnerDocument().createTextNode(String.valueOf(value));
prop.appendChild(text);
data = text;
} else {
// Add text.
Text text = prop.getOwnerDocument().createTextNode(String.valueOf(value));
prop.appendChild(text);
data = text;
}
data.setData(String.valueOf(value));
}
// Set type attribute
// prop.setAttribute("type", value == null ? "null" : value.getClass().getName());
}
/**
* Gets the element value.
*
* @param element
* the element
* @return the element value
*/
private Object getElementValue(Element element) {
StringBuilder value = null;
Element prop = element;
if (prop != null) {
// Find text child elements
NodeList texts = prop.getChildNodes();
if (texts.getLength() > 0) {
value = new StringBuilder();
for (int i = 0; i < texts.getLength(); i++) {
Node text = texts.item(i);
if (text instanceof CharacterData) {
value.append(((CharacterData) text).getData());
}
}
}
}
// convert to proper type
// value = convert(value.toString());
if (value == null) {
return null;
} else {
return value.toString();
}
}
/**
* Find nested node by name.
*
* @param element
* the element
* @param name
* the name
* @param create
* the create
* @return the element
*/
private Element findNestedNodeByName(Element element, String name, boolean create) {
Element child = element;
StringTokenizer parser = new StringTokenizer(name, ".", false);
while (parser.hasMoreTokens()) {
String childName = parser.nextToken();
if (childName.indexOf('[') > -1) {
String propName = childName.substring(0, childName.indexOf('['));
int i = Integer.parseInt(childName.substring(childName.indexOf('[') + 1, childName.indexOf(']')));
child = findNodeByName(child, propName, i, create);
} else {
child = findNodeByName(child, childName, 0, create);
}
if (child == null) {
break;
}
}
return child;
}
/**
* Find node by name.
*
* @param element
* the element
* @param name
* the name
* @param index
* the index
* @param create
* the create
* @return the element
*/
private Element findNodeByName(Element element, String name, int index, boolean create) {
Element prop = null;
// Find named property element
NodeList propNodes = element.getElementsByTagName(name);
if (propNodes.getLength() > index) {
prop = (Element) propNodes.item(index);
} else {
if (create) {
for (int i = 0; i < index + 1; i++) {
prop = element.getOwnerDocument().createElement(name);
element.appendChild(prop);
}
}
}
return prop;
}
/**
* Converts a DOM node to a complete xml string.
*
* @param node
* - the node to process
* @param indent
* - how to indent the children of the node
* @return The node as a String
*/
public static String nodeToString(Node node, String indent) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
switch (node.getNodeType()) {
case Node.DOCUMENT_NODE:
printWriter.println("<xml version=\"1.0\">\n");
// recurse on each child
NodeList nodes = node.getChildNodes();
if (nodes != null) {
for (int i = 0; i < nodes.getLength(); i++) {
printWriter.print(nodeToString(nodes.item(i), ""));
}
}
break;
case Node.ELEMENT_NODE:
String name = node.getNodeName();
printWriter.print(indent + "<" + name);
NamedNodeMap attributes = node.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node current = attributes.item(i);
printWriter.print(" " + current.getNodeName() + "=\"" + current.getNodeValue() + "\"");
}
printWriter.print(">");
// recurse on each child
NodeList children = node.getChildNodes();
if (children != null) {
for (int i = 0; i < children.getLength(); i++) {
printWriter.print(nodeToString(children.item(i), indent + indent));
}
}
printWriter.print("</" + name + ">");
break;
case Node.TEXT_NODE:
printWriter.print(node.getNodeValue());
break;
}
printWriter.flush();
String result = stringWriter.getBuffer().toString();
printWriter.close();
return result;
}
}
| |
package upacifico.ec.academic.web.managedBean;
import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataIntegrityViolationException;
import upacifico.ec.academic.entity.CesAuthorization;
import upacifico.ec.academic.entity.GeneralCompetence;
import upacifico.ec.academic.entity.PostgraduateProgram;
import upacifico.ec.academic.entity.PostgraduateProgramType;
import upacifico.ec.academic.facade.AcademicFacade;
import upacifico.ec.core.entity.Faculty;
import upacifico.ec.core.facade.CoreFacade;
import upacifico.ec.core.web.util.WebViewUtil;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
/**
* Pacific University http://upacifico.edu.ec
*
* @author Msc. Ing. Eduardo Alfonso Sanchez eddie.alfonso@gmail.com
* Date & Time: 7/2/2017 12:55
*/
@ManagedBean
@ViewScoped
public class PostgraduateProgramManaged implements Serializable {
private final static Logger LOGGER = Logger.getLogger(PostgraduateProgramManaged.class.getName());
@ManagedProperty("#{academicFacadeImpl}")
private AcademicFacade mainFacade;
@ManagedProperty("#{coreFacadeImpl}")
private CoreFacade coreFacade;
private PostgraduateProgram entity;
private List<PostgraduateProgram> entityList;
private List<Faculty> facultyList;
private List<PostgraduateProgramType> postgraduateProgramTypeList;
/**
* For load all the general competence available
*/
private List<GeneralCompetence> generalCompetenceList;
/**
* for select by user to add the competence of the program
*/
private List<GeneralCompetence> generalCompetenceSelectedList;
/**
* for select the general competence that the user want to delete of program
*/
private List<GeneralCompetence> generalCompetenceUnSelectList;
private long idEntityToUpdate;
@PostConstruct
public void init() {
LOGGER.debug("Init PostgraduateProgram");
/**
** Put here some code that is common to load in the insert, list and update
**
**/
}
/**
* For insert to database
*/
public void insertAction() {
LOGGER.debug("insert data");
try {
this.mainFacade.insertPostgraduateProgram(this.entity);
WebViewUtil.addMessageInsertSuccessful(false);
this.loadForInsert();
} catch (ConstraintViolationException e) {
WebViewUtil.addMessageInsertError("duplicateData", false);
LOGGER.debug("Error Captured: " + e.getMessage() + "Type: " + e.getClass());
} catch (Throwable e) {
WebViewUtil.addMessageInsertError(e, false);
LOGGER.debug("Error Captured: " + e.getMessage() + "Type: " + e.getClass());
}
}
/**
* For load from database
*/
public void listAction() {
LOGGER.debug("list data");
try {
this.entityList = this.mainFacade.getAllPostgraduateProgram();
} catch (Throwable e) {
WebViewUtil.addMessageListError(e, false);
LOGGER.debug("Error Captured: " + e.getMessage() + "Type: " + e.getClass());
}
}
/**
* For updating to database
*/
public String updateAction() {
LOGGER.debug("update data");
try {
this.mainFacade.updatePostgraduateProgram(this.entity);
WebViewUtil.addMessageUpdateSuccessful(true);
} catch (DataIntegrityViolationException e) {
WebViewUtil.addMessageUpdateError("duplicateData", false);
LOGGER.debug("Error Captured: " + e.getMessage() + "Type: " + e.getClass());
return "";
} catch (Throwable e) {
WebViewUtil.addMessageUpdateError(e, false);
LOGGER.debug("Error Captured: " + e.getMessage() + "Type: " + e.getClass());
return "";
}
return "/view/academic/listPostgraduateProgram?faces-redirect=true";
}
/**
* Load the necessary data for insert
*
* @return
*/
public String loadForInsert() {
LOGGER.debug("load for data for insert");
this.entity = new PostgraduateProgram();
this.entity.setFaculty(new Faculty());
this.entity.setPostgraduateProgramType(new PostgraduateProgramType());
try {
this.facultyList = this.coreFacade.getAllFaculty();
this.postgraduateProgramTypeList = this.mainFacade.getAllPostgraduateProgramType();
this.generalCompetenceList = this.mainFacade.getAllGeneralCompetence();
return "";
} catch (Throwable e) {
WebViewUtil.addMessageGenericError(e, true);
LOGGER.debug("Error Captured: " + e.getMessage());
}
return "/view/index?faces-redirect=true";
}
/**
* Load entity for update
*
* @return
*/
public String loadForUpdate() {
LOGGER.debug("load for data for update");
if (this.idEntityToUpdate != 0) {
try {
this.entity = this.mainFacade.getWithGeneralCompetencesPostgraduateProgram(idEntityToUpdate);
this.facultyList = this.coreFacade.getAllFaculty();
this.postgraduateProgramTypeList = this.mainFacade.getAllPostgraduateProgramType();
this.generalCompetenceList = this.mainFacade.getAllGeneralCompetence();
//For select i only show the competence thay not exist in the program
this.generalCompetenceList.removeAll(this.entity.getGeneralCompetenceSet());
return "";
} catch (Throwable e) {
WebViewUtil.addMessageListError(e, true);
LOGGER.debug("Error Captured: " + e.getMessage() + "Trazas: " + Arrays.toString(e.getStackTrace()));
}
} else {
WebViewUtil.addMessageListError("entityNoFound", true);
}
return "/view/index?faces-redirect=true";
}
/**
* Delete the entity
*
* @param id
*/
public void deleteAction(long id) {
try {
this.mainFacade.deletePostgraduateProgram(id);
WebViewUtil.addMessageGenericSuccessful(false);
} catch (Throwable e) {
WebViewUtil.addMessageGenericError(e, false);
LOGGER.debug("Error Captured: " + e.getMessage() + "Type: " + e.getClass());
}
}
/**
* Add general competence to program
*/
public void addGeneralCompetenceToProgram() {
LOGGER.debug("Competencias seleccionadas para adicionar: " + this.generalCompetenceSelectedList.size());
this.generalCompetenceList.removeAll(this.generalCompetenceSelectedList);
this.entity.getGeneralCompetenceSet().addAll(this.generalCompetenceSelectedList);
}
/**
* Remove general competence from program
*/
public void removeGeneralCompetenceFromProgram() {
LOGGER.debug("Competencias seleccionadas para eliminar: " + this.generalCompetenceUnSelectList.size());
this.entity.getGeneralCompetenceSet().removeAll(this.generalCompetenceUnSelectList);
this.generalCompetenceList.addAll(this.generalCompetenceUnSelectList);
}
public AcademicFacade getMainFacade() {
return mainFacade;
}
public void setMainFacade(AcademicFacade mainFacade) {
this.mainFacade = mainFacade;
}
public PostgraduateProgram getEntity() {
return entity;
}
public void setEntity(PostgraduateProgram entity) {
this.entity = entity;
}
public List<PostgraduateProgram> getEntityList() {
return entityList;
}
public void setEntityList(List<PostgraduateProgram> entityList) {
this.entityList = entityList;
}
public long getIdEntityToUpdate() {
return idEntityToUpdate;
}
public void setIdEntityToUpdate(long idEntityToUpdate) {
this.idEntityToUpdate = idEntityToUpdate;
}
public List<Faculty> getFacultyList() {
return facultyList;
}
public void setFacultyList(List<Faculty> facultyList) {
this.facultyList = facultyList;
}
public CoreFacade getCoreFacade() {
return coreFacade;
}
public void setCoreFacade(CoreFacade coreFacade) {
this.coreFacade = coreFacade;
}
public List<PostgraduateProgramType> getPostgraduateProgramTypeList() {
return postgraduateProgramTypeList;
}
public void setPostgraduateProgramTypeList(List<PostgraduateProgramType> postgraduateProgramTypeList) {
this.postgraduateProgramTypeList = postgraduateProgramTypeList;
}
public List<GeneralCompetence> getGeneralCompetenceList() {
return generalCompetenceList;
}
public void setGeneralCompetenceList(List<GeneralCompetence> generalCompetenceList) {
this.generalCompetenceList = generalCompetenceList;
}
public List<GeneralCompetence> getGeneralCompetenceSelectedList() {
return generalCompetenceSelectedList;
}
public void setGeneralCompetenceSelectedList(List<GeneralCompetence> generalCompetenceSelectedList) {
this.generalCompetenceSelectedList = generalCompetenceSelectedList;
}
public List<GeneralCompetence> getGeneralCompetenceUnSelectList() {
return generalCompetenceUnSelectList;
}
public void setGeneralCompetenceUnSelectList(List<GeneralCompetence> generalCompetenceUnSelectList) {
this.generalCompetenceUnSelectList = generalCompetenceUnSelectList;
}
}
| |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.java;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.completion.CompletionMemory;
import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil;
import com.intellij.codeInsight.documentation.DocumentationManagerProtocol;
import com.intellij.codeInsight.documentation.PlatformDocumentationUtil;
import com.intellij.codeInsight.documentation.QuickDocUtil;
import com.intellij.codeInsight.editorActions.CodeDocumentationUtil;
import com.intellij.codeInsight.javadoc.JavaDocExternalFilter;
import com.intellij.codeInsight.javadoc.JavaDocInfoGenerator;
import com.intellij.codeInsight.javadoc.JavaDocInfoGeneratorFactory;
import com.intellij.codeInsight.javadoc.JavaDocUtil;
import com.intellij.ide.util.PackageUtil;
import com.intellij.lang.CodeDocumentationAwareCommenter;
import com.intellij.lang.LangBundle;
import com.intellij.lang.LanguageCommenters;
import com.intellij.lang.documentation.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.JavaSdkVersionUtil;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileSystem;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.beanProperties.BeanPropertyElement;
import com.intellij.psi.impl.source.javadoc.PsiDocParamRef;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiFormatUtilBase;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.SmartList;
import com.intellij.util.Url;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.HttpRequests;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.builtInWebServer.BuiltInWebBrowserUrlProviderKt;
import java.util.*;
import static com.intellij.util.ObjectUtils.notNull;
/**
* @author Maxim.Mossienko
*/
public class JavaDocumentationProvider implements CodeDocumentationProvider, ExternalDocumentationProvider {
private static final Logger LOG = Logger.getInstance(JavaDocumentationProvider.class);
private static final String LINE_SEPARATOR = "\n";
private static final String PARAM_TAG = "@param";
private static final String RETURN_TAG = "@return";
private static final String THROWS_TAG = "@throws";
public static final String HTML_EXTENSION = ".html";
public static final String PACKAGE_SUMMARY_FILE = "package-summary.html";
@Override
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) {
return QuickDocUtil.inferLinkFromFullDocumentation(this, element, originalElement,
getQuickNavigationInfoInner(element, originalElement));
}
@Nullable
private static String getQuickNavigationInfoInner(PsiElement element, PsiElement originalElement) {
if (element instanceof PsiClass) {
return generateClassInfo((PsiClass)element);
}
else if (element instanceof PsiMethod) {
return generateMethodInfo((PsiMethod)element, calcSubstitutor(originalElement));
}
else if (element instanceof PsiField) {
return generateFieldInfo((PsiField)element, calcSubstitutor(originalElement));
}
else if (element instanceof PsiVariable) {
return generateVariableInfo((PsiVariable)element);
}
else if (element instanceof PsiPackage) {
return generatePackageInfo((PsiPackage)element);
}
else if (element instanceof BeanPropertyElement) {
return generateMethodInfo(((BeanPropertyElement)element).getMethod(), PsiSubstitutor.EMPTY);
}
else if (element instanceof PsiJavaModule) {
return generateModuleInfo((PsiJavaModule)element);
}
return null;
}
private static PsiSubstitutor calcSubstitutor(PsiElement originalElement) {
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
if (originalElement instanceof PsiReferenceExpression) {
LOG.assertTrue(originalElement.isValid());
substitutor = ((PsiReferenceExpression)originalElement).advancedResolve(true).getSubstitutor();
}
return substitutor;
}
@Override
public List<String> getUrlFor(final PsiElement element, final PsiElement originalElement) {
return getExternalJavaDocUrl(element);
}
private static void newLine(StringBuilder buffer) {
// Don't know why space has to be added after newline for good text alignment...
buffer.append("\n ");
}
private static void generateInitializer(StringBuilder buffer, PsiVariable variable) {
PsiExpression initializer = variable.getInitializer();
if (initializer != null) {
JavaDocInfoGenerator.appendExpressionValue(buffer, initializer);
PsiExpression constantInitializer = JavaDocInfoGenerator.calcInitializerExpression(variable);
if (constantInitializer != null) {
buffer.append(DocumentationMarkup.GRAYED_START);
JavaDocInfoGenerator.appendExpressionValue(buffer, constantInitializer);
buffer.append(DocumentationMarkup.GRAYED_END);
}
}
}
private static void generateModifiers(StringBuilder buffer, PsiModifierListOwner element) {
String modifiers = PsiFormatUtil.formatModifiers(element, PsiFormatUtilBase.JAVADOC_MODIFIERS_ONLY);
if (modifiers.length() > 0) {
buffer.append(modifiers);
buffer.append(" ");
}
}
private static String generatePackageInfo(PsiPackage aPackage) {
return aPackage.getQualifiedName();
}
private static void generateOrderEntryAndPackageInfo(StringBuilder buffer, @NotNull PsiElement element) {
PsiFile file = element.getContainingFile();
if (file != null) {
generateOrderEntryInfo(buffer, file.getVirtualFile(), element.getProject());
}
if (file instanceof PsiJavaFile) {
String packageName = ((PsiJavaFile)file).getPackageName();
if (packageName.length() > 0) {
buffer.append(packageName);
newLine(buffer);
}
}
}
private static void generateOrderEntryInfo(StringBuilder buffer, VirtualFile file, Project project) {
if (file != null) {
ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex();
if (index.isInLibrary(file)) {
index.getOrderEntriesForFile(file).stream()
.filter(LibraryOrSdkOrderEntry.class::isInstance).findFirst()
.ifPresent(entry -> buffer.append('[').append(StringUtil.escapeXmlEntities(entry.getPresentableName())).append("] "));
}
else {
Module module = index.getModuleForFile(file);
if (module != null) {
buffer.append('[').append(module.getName()).append("] ");
}
}
}
}
public static String generateClassInfo(PsiClass aClass) {
StringBuilder buffer = new StringBuilder();
if (aClass instanceof PsiAnonymousClass) return LangBundle.message("java.terms.anonymous.class");
generateOrderEntryAndPackageInfo(buffer, aClass);
generateModifiers(buffer, aClass);
final String classString = aClass.isAnnotationType() ? "java.terms.annotation.interface"
: aClass.isInterface()
? "java.terms.interface"
: aClass instanceof PsiTypeParameter
? "java.terms.type.parameter"
: aClass.isEnum() ? "java.terms.enum" : "java.terms.class";
buffer.append(LangBundle.message(classString)).append(" ");
buffer.append(JavaDocUtil.getShortestClassName(aClass, aClass));
generateTypeParameters(aClass, buffer);
if (!aClass.isEnum() && !aClass.isAnnotationType()) {
PsiReferenceList extendsList = aClass.getExtendsList();
writeExtends(aClass, buffer, extendsList == null ? PsiClassType.EMPTY_ARRAY : extendsList.getReferencedTypes());
}
writeImplements(aClass, buffer, aClass.getImplementsListTypes());
return buffer.toString();
}
public static void writeImplements(PsiClass aClass, StringBuilder buffer, PsiClassType[] refs) {
if (refs.length > 0) {
newLine(buffer);
buffer.append("implements ");
writeTypeRefs(aClass, buffer, refs);
}
}
public static void writeExtends(PsiClass aClass, StringBuilder buffer, PsiClassType[] refs) {
if (refs.length > 0 || !aClass.isInterface() && !CommonClassNames.JAVA_LANG_OBJECT.equals(aClass.getQualifiedName())) {
buffer.append(" extends ");
if (refs.length == 0) {
buffer.append("Object");
}
else {
writeTypeRefs(aClass, buffer, refs);
}
}
}
private static void writeTypeRefs(PsiClass aClass, StringBuilder buffer, PsiClassType[] refs) {
for (int i = 0; i < refs.length; i++) {
JavaDocInfoGenerator.generateType(buffer, refs[i], aClass, false, true);
if (i < refs.length - 1) {
buffer.append(", ");
}
}
}
public static void generateTypeParameters(PsiTypeParameterListOwner typeParameterOwner, StringBuilder buffer) {
if (typeParameterOwner.hasTypeParameters()) {
PsiTypeParameter[] params = typeParameterOwner.getTypeParameters();
buffer.append("<");
for (int i = 0; i < params.length; i++) {
PsiTypeParameter p = params[i];
buffer.append(p.getName());
PsiClassType[] refs = p.getExtendsList().getReferencedTypes();
if (refs.length > 0) {
buffer.append(" extends ");
for (int j = 0; j < refs.length; j++) {
JavaDocInfoGenerator.generateType(buffer, refs[j], typeParameterOwner, false, true);
if (j < refs.length - 1) {
buffer.append(" & ");
}
}
}
if (i < params.length - 1) {
buffer.append(", ");
}
}
buffer.append(">");
}
}
@SuppressWarnings({"HardCodedStringLiteral"})
public static String generateMethodInfo(PsiMethod method, PsiSubstitutor substitutor) {
StringBuilder buffer = new StringBuilder();
PsiClass parentClass = method.getContainingClass();
if (parentClass != null && !(parentClass instanceof PsiAnonymousClass)) {
if (method.isConstructor()) {
generateOrderEntryAndPackageInfo(buffer, parentClass);
}
buffer.append(JavaDocUtil.getShortestClassName(parentClass, method));
newLine(buffer);
}
generateModifiers(buffer, method);
generateTypeParameters(method, buffer);
if (method.getReturnType() != null) {
JavaDocInfoGenerator.generateType(buffer, substitutor.substitute(method.getReturnType()), method, false, true);
buffer.append(" ");
}
buffer.append(method.getName());
buffer.append("(");
PsiParameter[] params = method.getParameterList().getParameters();
for (int i = 0; i < params.length; i++) {
PsiParameter param = params[i];
JavaDocInfoGenerator.generateType(buffer, substitutor.substitute(param.getType()), method, false, true);
buffer.append(" ");
buffer.append(param.getName());
if (i < params.length - 1) {
buffer.append(", ");
}
}
buffer.append(")");
PsiClassType[] refs = method.getThrowsList().getReferencedTypes();
if (refs.length > 0) {
newLine(buffer);
buffer.append(" throws ");
for (int i = 0; i < refs.length; i++) {
PsiClass throwsClass = refs[i].resolve();
if (throwsClass != null) {
buffer.append(JavaDocUtil.getShortestClassName(throwsClass, method));
}
else {
buffer.append(refs[i].getPresentableText());
}
if (i < refs.length - 1) {
buffer.append(", ");
}
}
}
return buffer.toString();
}
private static String generateFieldInfo(PsiField field, PsiSubstitutor substitutor) {
StringBuilder buffer = new StringBuilder();
PsiClass parentClass = field.getContainingClass();
if (parentClass != null && !(parentClass instanceof PsiAnonymousClass)) {
buffer.append(JavaDocUtil.getShortestClassName(parentClass, field));
newLine(buffer);
}
generateModifiers(buffer, field);
JavaDocInfoGenerator.generateType(buffer, substitutor.substitute(field.getType()), field, false, true);
buffer.append(" ");
buffer.append(field.getName());
generateInitializer(buffer, field);
JavaDocInfoGenerator.enumConstantOrdinal(buffer, field, parentClass, "\n");
return buffer.toString();
}
private static String generateVariableInfo(PsiVariable variable) {
StringBuilder buffer = new StringBuilder();
generateModifiers(buffer, variable);
JavaDocInfoGenerator.generateType(buffer, variable.getType(), variable, false, true);
buffer.append(" ");
buffer.append(variable.getName());
generateInitializer(buffer, variable);
return buffer.toString();
}
private static String generateModuleInfo(PsiJavaModule module) {
StringBuilder sb = new StringBuilder();
VirtualFile file = PsiImplUtil.getModuleVirtualFile(module);
generateOrderEntryInfo(sb, file, module.getProject());
sb.append(LangBundle.message("java.terms.module")).append(' ').append(module.getName());
return sb.toString();
}
@Override
public PsiComment findExistingDocComment(final PsiComment comment) {
if (comment instanceof PsiDocComment) {
final PsiJavaDocumentedElement owner = ((PsiDocComment)comment).getOwner();
if (owner != null) {
return owner.getDocComment();
}
}
return null;
}
@Nullable
@Override
public Pair<PsiElement, PsiComment> parseContext(@NotNull PsiElement startPoint) {
PsiElement current = startPoint;
while (current != null) {
if (current instanceof PsiJavaDocumentedElement && !(current instanceof PsiTypeParameter) && !(current instanceof PsiAnonymousClass)) {
PsiDocComment comment = ((PsiJavaDocumentedElement)current).getDocComment();
return Pair.create(current instanceof PsiField ? ((PsiField)current).getModifierList() : current, comment);
}
else if (PackageUtil.isPackageInfoFile(current)) {
return Pair.create(current, getPackageInfoComment(current));
}
current = current.getParent();
}
return null;
}
@Override
public String generateDocumentationContentStub(PsiComment _comment) {
final PsiJavaDocumentedElement commentOwner = ((PsiDocComment)_comment).getOwner();
final StringBuilder builder = new StringBuilder();
final CodeDocumentationAwareCommenter commenter =
(CodeDocumentationAwareCommenter)LanguageCommenters.INSTANCE.forLanguage(_comment.getLanguage());
if (commentOwner instanceof PsiMethod) {
PsiMethod psiMethod = (PsiMethod)commentOwner;
generateParametersTakingDocFromSuperMethods(builder, commenter, psiMethod);
final PsiTypeParameterList typeParameterList = psiMethod.getTypeParameterList();
if (typeParameterList != null) {
createTypeParamsListComment(builder, commenter, typeParameterList);
}
if (psiMethod.getReturnType() != null && !PsiType.VOID.equals(psiMethod.getReturnType())) {
builder.append(CodeDocumentationUtil.createDocCommentLine(RETURN_TAG, _comment.getContainingFile(), commenter));
builder.append(LINE_SEPARATOR);
}
final PsiJavaCodeReferenceElement[] references = psiMethod.getThrowsList().getReferenceElements();
for (PsiJavaCodeReferenceElement reference : references) {
builder.append(CodeDocumentationUtil.createDocCommentLine(THROWS_TAG, _comment.getContainingFile(), commenter));
builder.append(reference.getText());
builder.append(LINE_SEPARATOR);
}
}
else if (commentOwner instanceof PsiClass) {
final PsiTypeParameterList typeParameterList = ((PsiClass)commentOwner).getTypeParameterList();
if (typeParameterList != null) {
createTypeParamsListComment(builder, commenter, typeParameterList);
}
}
return builder.length() > 0 ? builder.toString() : null;
}
public static void generateParametersTakingDocFromSuperMethods(StringBuilder builder,
CodeDocumentationAwareCommenter commenter,
PsiMethod psiMethod) {
final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
final Map<String, String> param2Description = new HashMap<>();
final PsiMethod[] superMethods = psiMethod.findSuperMethods();
for (PsiMethod superMethod : superMethods) {
final PsiDocComment comment = superMethod.getDocComment();
if (comment != null) {
final PsiDocTag[] params = comment.findTagsByName("param");
for (PsiDocTag param : params) {
final PsiElement[] dataElements = param.getDataElements();
String paramName = null;
for (PsiElement dataElement : dataElements) {
if (dataElement instanceof PsiDocParamRef) {
//noinspection ConstantConditions
paramName = dataElement.getReference().getCanonicalText();
break;
}
}
if (paramName != null) {
param2Description.put(paramName, param.getText());
}
}
}
}
for (PsiParameter parameter : parameters) {
String description = param2Description.get(parameter.getName());
if (description != null) {
builder.append(CodeDocumentationUtil.createDocCommentLine("", psiMethod.getContainingFile(), commenter));
if (description.indexOf('\n') > -1) description = description.substring(0, description.lastIndexOf('\n'));
builder.append(description);
}
else {
builder.append(CodeDocumentationUtil.createDocCommentLine(PARAM_TAG, psiMethod.getContainingFile(), commenter));
builder.append(parameter.getName());
}
builder.append(LINE_SEPARATOR);
}
}
public static void createTypeParamsListComment(final StringBuilder buffer,
final CodeDocumentationAwareCommenter commenter,
final PsiTypeParameterList typeParameterList) {
final PsiTypeParameter[] typeParameters = typeParameterList.getTypeParameters();
for (PsiTypeParameter typeParameter : typeParameters) {
buffer.append(CodeDocumentationUtil.createDocCommentLine(PARAM_TAG, typeParameterList.getContainingFile(), commenter));
buffer.append("<").append(typeParameter.getName()).append(">");
buffer.append(LINE_SEPARATOR);
}
}
@Override
public String generateDoc(PsiElement element, PsiElement originalElement) {
// for new Class(<caret>) or methodCall(<caret>) proceed from method call or new expression
// same for new Cl<caret>ass() or method<caret>Call()
if (element instanceof PsiExpressionList ||
element instanceof PsiReferenceExpression && element.getParent() instanceof PsiMethodCallExpression) {
element = element.getParent();
originalElement = null;
}
if (element instanceof PsiCallExpression && CodeInsightSettings.getInstance().SHOW_PARAMETER_NAME_HINTS_ON_COMPLETION) {
PsiMethod method = CompletionMemory.getChosenMethod((PsiCallExpression)element);
if (method != null) element = method;
}
if (element instanceof PsiMethodCallExpression) {
return getMethodCandidateInfo((PsiMethodCallExpression)element);
}
// Try hard for documentation of incomplete new Class instantiation
PsiElement elt = element;
if (originalElement != null && !(originalElement instanceof PsiPackage || originalElement instanceof PsiFileSystemItem)) {
elt = PsiTreeUtil.prevLeaf(originalElement);
}
if (elt instanceof PsiErrorElement) {
elt = elt.getPrevSibling();
}
else if (elt != null && !(elt instanceof PsiNewExpression)) {
elt = elt.getParent();
}
if (elt instanceof PsiNewExpression) {
PsiClass targetClass = null;
if (element instanceof PsiJavaCodeReferenceElement) { // new Class<caret>
PsiElement resolve = ((PsiJavaCodeReferenceElement)element).resolve();
if (resolve instanceof PsiClass) targetClass = (PsiClass)resolve;
} else if (element instanceof PsiClass) { //Class in completion
targetClass = (PsiClass)element;
} else if (element instanceof PsiNewExpression) { // new Class(<caret>)
PsiJavaCodeReferenceElement reference = ((PsiNewExpression)element).getClassReference();
if (reference != null) {
PsiElement resolve = reference.resolve();
if (resolve instanceof PsiClass) targetClass = (PsiClass)resolve;
}
}
if (targetClass != null) {
PsiMethod[] constructors = targetClass.getConstructors();
if (constructors.length > 0) {
if (constructors.length == 1) return generateDoc(constructors[0], originalElement);
final StringBuilder sb = new StringBuilder();
for(PsiMethod constructor:constructors) {
final String str = PsiFormatUtil.formatMethod(constructor, PsiSubstitutor.EMPTY,
PsiFormatUtilBase.SHOW_NAME |
PsiFormatUtilBase.SHOW_TYPE |
PsiFormatUtilBase.SHOW_PARAMETERS,
PsiFormatUtilBase.SHOW_TYPE | PsiFormatUtilBase.SHOW_NAME);
createElementLink(sb, constructor, StringUtil.escapeXmlEntities(str));
}
return CodeInsightBundle.message("javadoc.constructor.candidates", targetClass.getName(), sb);
}
}
}
//external documentation finder
return generateExternalJavadoc(element);
}
@Nullable
public static String generateExternalJavadoc(@NotNull final PsiElement element) {
List<String> docURLs = getExternalJavaDocUrl(element);
return generateExternalJavadoc(element, docURLs);
}
@Nullable
public static String generateExternalJavadoc(@NotNull final PsiElement element, @Nullable List<String> docURLs) {
final JavaDocInfoGenerator javaDocInfoGenerator = JavaDocInfoGeneratorFactory.create(element.getProject(), element);
return generateExternalJavadoc(javaDocInfoGenerator, docURLs);
}
@Nullable
public static String generateExternalJavadoc(@NotNull final PsiElement element, @NotNull JavaDocInfoGenerator generator) {
final List<String> docURLs = getExternalJavaDocUrl(element);
return generateExternalJavadoc(generator, docURLs);
}
@Nullable
private static String generateExternalJavadoc(@NotNull JavaDocInfoGenerator generator, @Nullable List<String> docURLs) {
return JavaDocExternalFilter.filterInternalDocInfo(generator.generateDocInfo(docURLs));
}
private String getMethodCandidateInfo(PsiMethodCallExpression expr) {
final PsiResolveHelper rh = JavaPsiFacade.getInstance(expr.getProject()).getResolveHelper();
final CandidateInfo[] candidates = rh.getReferencedMethodCandidates(expr, true);
final String text = expr.getText();
if (candidates.length > 0) {
if (candidates.length == 1) {
PsiElement element = candidates[0].getElement();
if (element instanceof PsiMethod) return generateDoc(element, null);
}
final StringBuilder sb = new StringBuilder();
for (final CandidateInfo candidate : candidates) {
final PsiElement element = candidate.getElement();
if (!(element instanceof PsiMethod)) {
continue;
}
final String str = PsiFormatUtil.formatMethod((PsiMethod)element, candidate.getSubstitutor(),
PsiFormatUtilBase.SHOW_NAME |
PsiFormatUtilBase.SHOW_TYPE |
PsiFormatUtilBase.SHOW_PARAMETERS,
PsiFormatUtilBase.SHOW_TYPE);
createElementLink(sb, element, StringUtil.escapeXmlEntities(str));
}
return CodeInsightBundle.message("javadoc.candidates", text, sb);
}
return CodeInsightBundle.message("javadoc.candidates.not.found", text);
}
private static void createElementLink(StringBuilder sb, PsiElement element, String str) {
sb.append(" <a href=\"" + DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL);
sb.append(JavaDocUtil.getReferenceText(element.getProject(), element));
sb.append("\">");
sb.append(str);
sb.append("</a>");
sb.append("<br>");
}
@Nullable
public static List<String> getExternalJavaDocUrl(final PsiElement element) {
List<String> urls = null;
if (element instanceof PsiClass) {
urls = findUrlForClass((PsiClass)element);
}
else if (element instanceof PsiField) {
PsiField field = (PsiField)element;
PsiClass aClass = field.getContainingClass();
if (aClass != null) {
urls = findUrlForClass(aClass);
if (urls != null) {
for (int i = 0; i < urls.size(); i++) {
urls.set(i, urls.get(i) + "#" + field.getName());
}
}
}
}
else if (element instanceof PsiMethod) {
PsiMethod method = (PsiMethod)element;
PsiClass aClass = method.getContainingClass();
if (aClass != null) {
List<String> classUrls = findUrlForClass(aClass);
if (classUrls != null) {
urls = new SmartList<>();
final Set<String> signatures = getHtmlMethodSignatures(method, PsiUtil.getLanguageLevel(method));
for (String signature : signatures) {
for (String classUrl : classUrls) {
urls.add(classUrl + "#" + signature);
}
}
}
}
}
else if (element instanceof PsiPackage) {
urls = findUrlForPackage((PsiPackage)element);
}
else if (element instanceof PsiDirectory) {
PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(((PsiDirectory)element));
if (aPackage != null) {
urls = findUrlForPackage(aPackage);
}
}
if (urls == null || urls.isEmpty()) {
return null;
}
else {
for (int i = 0; i < urls.size(); i++) {
urls.set(i, FileUtil.toSystemIndependentName(urls.get(i)));
}
return urls;
}
}
public static Set<String> getHtmlMethodSignatures(@NotNull PsiMethod method, @Nullable LanguageLevel preferredFormat) {
final Set<String> signatures = new LinkedHashSet<>();
if (preferredFormat != null) signatures.add(formatMethodSignature(method, preferredFormat));
signatures.add(formatMethodSignature(method, LanguageLevel.JDK_10));
signatures.add(formatMethodSignature(method, LanguageLevel.JDK_1_8));
signatures.add(formatMethodSignature(method, LanguageLevel.JDK_1_5));
return signatures;
}
private static String formatMethodSignature(@NotNull PsiMethod method, @NotNull LanguageLevel languageLevel) {
boolean replaceConstructorWithInit = languageLevel.isAtLeast(LanguageLevel.JDK_10) && method.isConstructor();
int options = (replaceConstructorWithInit ? 0 : PsiFormatUtilBase.SHOW_NAME) | PsiFormatUtilBase.SHOW_PARAMETERS;
int parameterOptions = PsiFormatUtilBase.SHOW_TYPE | PsiFormatUtilBase.SHOW_FQ_CLASS_NAMES | PsiFormatUtilBase.SHOW_RAW_NON_TOP_TYPE;
String signature = PsiFormatUtil.formatMethod(method, PsiSubstitutor.EMPTY, options, parameterOptions, 999);
if (replaceConstructorWithInit) {
signature = "<init>" + signature;
}
if (languageLevel.isAtLeast(LanguageLevel.JDK_10)) {
signature = signature.replace(" ", "");
}
else if (languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) {
signature = signature.replaceAll("\\(|\\)|, ", "-").replaceAll("\\[]", ":A");
}
return signature;
}
@Nullable
public static PsiDocComment getPackageInfoComment(@NotNull PsiElement packageInfoFile) {
return PsiTreeUtil.getChildOfType(packageInfoFile, PsiDocComment.class);
}
@Nullable
public static List<String> findUrlForClass(@NotNull PsiClass aClass) {
String qName = aClass.getQualifiedName();
if (qName != null) {
PsiFile file = aClass.getContainingFile();
if (file instanceof PsiJavaFile) {
VirtualFile virtualFile = file.getOriginalFile().getVirtualFile();
if (virtualFile != null) {
String pkgName = ((PsiJavaFile)file).getPackageName();
String relPath = (pkgName.isEmpty() ? qName : pkgName.replace('.', '/') + '/' + qName.substring(pkgName.length() + 1)) + HTML_EXTENSION;
return findUrlForVirtualFile(file.getProject(), virtualFile, relPath);
}
}
}
return null;
}
@Nullable
public static List<String> findUrlForPackage(@NotNull PsiPackage aPackage) {
String qName = aPackage.getQualifiedName().replace('.', '/') + '/' + PACKAGE_SUMMARY_FILE;
for (PsiDirectory directory : aPackage.getDirectories()) {
List<String> url = findUrlForVirtualFile(aPackage.getProject(), directory.getVirtualFile(), qName);
if (url != null) {
return url;
}
}
return null;
}
@Nullable
private static List<String> findUrlForVirtualFile(Project project, VirtualFile virtualFile, String relPath) {
ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
Module module = fileIndex.getModuleForFile(virtualFile);
if (module == null) {
VirtualFileSystem fs = virtualFile.getFileSystem();
if (fs instanceof JarFileSystem) {
VirtualFile jar = ((JarFileSystem)fs).getLocalByEntry(virtualFile);
if (jar != null) {
module = fileIndex.getModuleForFile(jar);
}
}
}
if (module != null) {
String[] extPaths = JavaModuleExternalPaths.getInstance(module).getJavadocUrls();
List<String> httpRoots = PlatformDocumentationUtil.getHttpRoots(extPaths, relPath);
// if found nothing and the file is from library classes, fall back to order entries
if (httpRoots != null || !fileIndex.isInLibraryClasses(virtualFile)) {
return httpRoots;
}
}
PsiJavaModule javaModule = JavaModuleGraphUtil.findDescriptorByFile(virtualFile, project);
String altRelPath = javaModule != null ? javaModule.getName() + '/' + relPath : null;
for (OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(virtualFile)) {
boolean altUrl = orderEntry instanceof JdkOrderEntry && JavaSdkVersionUtil.isAtLeast(((JdkOrderEntry)orderEntry).getJdk(), JavaSdkVersion.JDK_11);
for (VirtualFile root : orderEntry.getFiles(JavadocOrderRootType.getInstance())) {
if (root.getFileSystem() == JarFileSystem.getInstance()) {
VirtualFile file = root.findFileByRelativePath(relPath);
if (file == null && altRelPath != null) file = root.findFileByRelativePath(altRelPath);
if (file != null) {
List<Url> urls = BuiltInWebBrowserUrlProviderKt.getBuiltInServerUrls(file, project, null);
if (!urls.isEmpty()) {
return ContainerUtil.map(urls, Url::toExternalForm);
}
}
}
}
String[] webUrls = JavadocOrderRootType.getUrls(orderEntry);
if (webUrls.length > 0) {
List<String> httpRoots = new ArrayList<>();
if (altUrl && altRelPath != null) {
httpRoots.addAll(notNull(PlatformDocumentationUtil.getHttpRoots(webUrls, altRelPath), Collections.emptyList()));
}
httpRoots.addAll(notNull(PlatformDocumentationUtil.getHttpRoots(webUrls, relPath), Collections.emptyList()));
if (!httpRoots.isEmpty()) {
return httpRoots;
}
}
}
return null;
}
@Override
public PsiElement getDocumentationElementForLink(final PsiManager psiManager, final String link, final PsiElement context) {
return JavaDocUtil.findReferenceTarget(psiManager, link, context);
}
@Override
public String fetchExternalDocumentation(Project project, PsiElement element, List<String> docUrls) {
return fetchExternalJavadoc(element, project, docUrls);
}
@Override
public boolean hasDocumentationFor(PsiElement element, PsiElement originalElement) {
return CompositeDocumentationProvider.hasUrlsFor(this, element, originalElement);
}
@Override
public boolean canPromptToConfigureDocumentation(PsiElement element) {
return false;
}
@Override
public void promptToConfigureDocumentation(PsiElement element) { }
@Nullable
@Override
public PsiElement getCustomDocumentationElement(@NotNull Editor editor, @NotNull PsiFile file, @Nullable PsiElement contextElement,
int targetOffset) {
PsiDocComment docComment = PsiTreeUtil.getParentOfType(contextElement, PsiDocComment.class, false);
if (docComment != null && JavaDocUtil.isInsidePackageInfo(docComment)) {
PsiDirectory directory = file.getContainingDirectory();
if (directory != null) {
return JavaDirectoryService.getInstance().getPackage(directory);
}
}
return null;
}
public static String fetchExternalJavadoc(PsiElement element, Project project, List<String> docURLs) {
return fetchExternalJavadoc(element, docURLs, new JavaDocExternalFilter(project));
}
public static String fetchExternalJavadoc(PsiElement element, List<String> docURLs, @NotNull JavaDocExternalFilter docFilter) {
if (docURLs != null) {
for (String docURL : docURLs) {
try {
String externalDoc = docFilter.getExternalDocInfoForElement(docURL, element);
if (!StringUtil.isEmpty(externalDoc)) {
return externalDoc;
}
}
catch (ProcessCanceledException ignored) {
break;
}
catch (IndexNotReadyException e) {
throw e;
}
catch (HttpRequests.HttpStatusException e) {
LOG.info(e.getUrl() + ": " + e.getStatusCode());
}
catch (Exception e) {
LOG.info(e);
}
}
}
return null;
}
}
| |
/*
* Copyright 2016 Tom Gibara
*
* 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.tomgibara.storage;
import static com.tomgibara.storage.Stores.immutableException;
import java.util.Arrays;
import com.tomgibara.bits.BitStore;
import com.tomgibara.bits.BitWriter;
import com.tomgibara.bits.Bits;
import com.tomgibara.storage.StoreAccessors.StoreInts;
abstract class SmallValueStore extends AbstractStore<Integer> implements StoreInts {
// statics - ternary packing
private static final byte[] TERNARY_PACK = new byte[1024];
private static final int[] TERNARY_UNPACK = new int[243];
private static byte tPack(int value) {
int sum = 0;
for (int i = 0; i < 5; i++) {
sum = 3 * sum + (value & 3);
value >>= 2;
}
return (byte) sum;
}
private static int tUnpack(byte value) {
int v = value & 0xff;
int bits = 0;
for (int i = 0; i < 5; i++) {
bits = (bits << 2) | (v % 3);
v /= 3;
}
return bits;
}
static {
for (int i = 0; i < 243; i++) {
byte p = (byte) i;
int u = tUnpack(p);
TERNARY_PACK[u] = p;
TERNARY_UNPACK[i] = u;
}
}
// statics - quinary packing
private static final int[] QUINARY_PACK = new int[512];
private static final int[] QUINARY_UNPACK = new int[125];
private static byte qPack(int value) {
int sum = 0;
for (int i = 0; i < 3; i++) {
sum = 5 * sum + (value & 7);
value >>= 3;
}
return (byte) sum;
}
private static int qUnpack(int v) {
int bits = 0;
for (int i = 0; i < 3; i++) {
bits = (bits << 3) | (v % 5);
v /= 5;
}
return bits;
}
static {
for (int i = 0; i < 125; i++) {
int u = qUnpack(i);
QUINARY_PACK[u] = i;
QUINARY_UNPACK[i] = u;
}
}
// statics
static Storage<Integer> newStorage(int range, StoreType<Integer> type) {
if (type.nullGettable) {
return SmallValueStore.newNullStorage(range);
}
if (type.nullSettable) {
int nv = type.nullValue;
if (nv < 0) throw new IllegalArgumentException("negative nullValue");
if (nv >= range) throw new IllegalArgumentException("nullValue meets or exceeds range");
}
return SmallValueStore.newNonNullStorage(range, type);
}
// type must not be null gettable
static SmallValueStorage newNonNullStorage(int range, StoreType<Integer> type) {
int nullValue = type.nullSettable ? type.nullValue : -1;
switch (range) {
case 1: return new SmallValueStorage(type, (size, value) -> new UnaryStore(checkedSize(size), nullValue, value));
case 2: return new SmallValueStorage(type, (size, value) -> new BinaryStore(checkedSize(size), nullValue, value));
case 3: return new SmallValueStorage(type, (size, value) -> new TernaryStore(checkedSize(size), nullValue, value));
case 5: return new SmallValueStorage(type, (size, value) -> new QuinaryStore(checkedSize(size), nullValue, value));
default: return new SmallValueStorage(type, (size, value) -> new ArbitraryStore(checkedSize(size), nullValue, range, value));
}
}
static NullSmallStorage newNullStorage(int range) {
switch (range) {
case 1: return (size, value) -> new ZeroOrNullStore(checkedSize(size), value);
case 2: return (size, value) -> new NullableStore(new TernaryStore(checkedSize(size), 0, value));
case 4: return (size, value) -> new NullableStore(new QuinaryStore(checkedSize(size), 0, value));
default: return (size, value) -> new NullableStore(new ArbitraryStore(checkedSize(size), 0, range + 1, value));
}
}
private static int checkedSize(int size) {
if (size < 0) throw new IllegalArgumentException("negative size");
return size;
}
// fields
final int size;
// -1 indicates not settable
final int nullValue;
// constructors
SmallValueStore(int size, int nullValue) {
this.size = size;
this.nullValue = nullValue;
}
// methods
@Override
public StoreType<Integer> type() {
return nullValue < 0 ? StoreType.INT.settingNullDisallowed() : StoreType.INT.settingNullToValue(nullValue);
}
@Override
public int size() {
return size;
}
@Override
public boolean isNull(int index) {
if (index < 0 || index >= size) throw new IllegalArgumentException("invalid index");
return false;
}
@Override
public BitStore population() {
return Bits.oneBits(size);
}
@Override
public abstract SmallValueStore mutableCopy();
@Override
public abstract SmallValueStore immutableCopy();
@Override
public abstract SmallValueStore immutableView();
@Override
public abstract SmallValueStore resizedCopy(int newSize);
@Override
public void transpose(int i, int j) {
checkIndex(i);
checkIndex(j);
if (i == j) return;
setImpl(j, setImpl(i, getImpl(j)));
}
@Override
boolean fastFill(int from, int to, Integer value) {
if (from == 0 && to == size) {
fillImpl(value);
} else {
fillImpl(from, to, value);
}
return true;
}
// store ints methods
@Override
public boolean isInt(int index) {
return true;
}
@Override
public int getInt(int index) {
checkIndex(index);
return getImpl(index);
}
@Override
public void setInt(int index, int value) {
checkIndex(index);
checkImpl(value);
if (!isMutable()) throw new IllegalStateException("immutable");
setImpl(index, value);
}
// for extension
abstract int range();
// note: caller responsible for checking value is valid
abstract int setImpl(int index, int value);
// note: caller responsible for checking value is valid
abstract int getImpl(int index);
// note: caller responsible for checking value is valid
abstract void fillImpl(int value);
// note: caller responsible for checking value is valid
abstract void fillImpl(int from, int to, int value);
abstract void checkImpl(int value);
// helper methods
void checkIndex(int index) {
if (index < 0) throw new IllegalArgumentException("negative index");
if (index >= size) throw new IllegalArgumentException("index too large");
}
void checkNewSize(int newSize) {
if (newSize < 0) throw new IllegalArgumentException("negative newSize");
if (nullValue < 0 && newSize > size) throw new IllegalArgumentException("cannot create copy with greater size, no null value");
}
void initCheck(Integer initialValue) {
if (initialValue == null && nullValue < 0 && size > 0) throw new IllegalArgumentException("cannot create sized store, no null value");
}
// assumes initCheck has already been performed
void initFill(Integer initialValue) {
int i = initialValue == null ? nullValue : initialValue.intValue();
if (i > 0) fillImpl(i);
}
int settableValue(Object value) {
if (value == null) return nullValue;
return value instanceof Integer ? (Integer) value : -1;
}
// inner classes
static final class SmallValueStorage implements Storage<Integer> {
interface Factory { SmallValueStore newStore(int size, Integer value); }
private final StoreType<Integer> type;
private final Factory newStore;
SmallValueStorage(StoreType<Integer> type, Factory newStore) {
this.type = type;
this.newStore = newStore;
}
@Override
public StoreType<Integer> type() { return type; }
@Override
//TODO optimize other storage methods?
public SmallValueStore newStore(int size, Integer value) {
return newStore.newStore(size, value);
}
}
private final static class UnaryStore extends SmallValueStore {
private final boolean mutable;
UnaryStore(int size, int nullValue, Integer initialValue) {
super(size, nullValue);
initCheck(initialValue);
mutable = true;
initFill(initialValue);
}
UnaryStore(int size, int nullValue, boolean mutable) {
super(size, nullValue);
this.mutable = mutable;
}
@Override
public Integer get(int index) {
checkIndex(index);
return 0;
}
@Override
public Integer set(int index, Integer value) {
checkIndex(index);
checkValue(value);
checkMutable();
return 0;
}
@Override
public boolean isSettable(Object value) {
return settableValue(value) == 0;
}
@Override
public BitStore population() {
return Bits.oneBits(size);
}
@Override
public void fill(Integer value) {
checkValue(value);
checkMutable();
fillImpl(value);
}
@Override
public boolean isMutable() { return mutable; }
@Override
public UnaryStore mutableCopy() { return new UnaryStore(size, nullValue, true); }
@Override
public UnaryStore immutableCopy() { return new UnaryStore(size, nullValue, false); }
@Override
public UnaryStore immutableView() { return new UnaryStore(size, nullValue, false); }
@Override
public UnaryStore resizedCopy(int newSize) {
checkNewSize(newSize);
return new UnaryStore(newSize, nullValue, true);
}
@Override
public <W extends Integer> void setStore(int position, Store<W> store) {
int from = 0;
int to = checkSetStore(position, store);
if (store instanceof RangeStore<?>) {
RangeStore<W> range = (RangeStore<W>) store;
store = range.store;
from = range.from;
to = range.to;
}
if (store instanceof UnaryStore) {
/* no op */
} else {
setStoreImpl(position, store, from, to);
}
}
@Override
public void transpose(int i, int j) {
checkIndex(i);
checkIndex(j);
checkMutable();
}
private void checkValue(Integer value) {
if (value == null) {
if (nullValue < 0) StoreType.failNull();
} else {
checkImpl(value);
}
}
private void checkMutable() {
if (!mutable) throw immutableException();
}
@Override
int range() { return 1; }
@Override
int getImpl(int index) { return 0; }
@Override
int setImpl(int index, int value) { return 0; }
@Override
void fillImpl(int value) { }
@Override
void fillImpl(int from, int to, int value) { }
@Override
void checkImpl(int value) {
if (value != 0) throw new IllegalArgumentException("non-zero value");
}
}
private final static class BinaryStore extends SmallValueStore {
private final BitStore bits;
BinaryStore(int size, int nullValue, Integer initialValue) {
super(size, nullValue);
initCheck(initialValue);
bits = Bits.store(size);
initFill(initialValue);
}
BinaryStore(BitStore bits, int nullValue) {
super(bits.size(), nullValue);
this.bits = bits;
}
@Override
public Integer get(int index) {
checkIndex(index);
return valueOf( bits.getBit(index) );
}
@Override
public Integer set(int index, Integer value) {
checkIndex(index);
boolean v = checkedValue(value);
return valueOf( bits.getThenSetBit(index, v) );
}
@Override
public boolean isSettable(Object value) {
int i = settableValue(value);
return i == 0 || i == 1;
}
@Override
public void fill(Integer value) {
bits.setAll(checkedValue(value));
}
@Override
public boolean isMutable() { return bits.isMutable(); }
@Override
public BinaryStore mutableCopy() { return new BinaryStore(bits.mutableCopy(), nullValue); }
@Override
public BinaryStore immutableCopy() { return new BinaryStore(bits.immutableCopy(), nullValue); }
@Override
public BinaryStore immutableView() { return new BinaryStore(bits.immutable(), nullValue); }
@Override
public BinaryStore resizedCopy(int newSize) {
checkNewSize(newSize);
BitStore newBits = Bits.resizedCopyOf(bits, newSize, false);
if (newSize > size && nullValue == 1) newBits.range(size, newSize).fill();
return new BinaryStore(newBits, nullValue);
}
@Override
public <W extends Integer> void setStore(int position, Store<W> store) {
int from = 0;
int to = checkSetStore(position, store);
if (store instanceof RangeStore<?>) {
RangeStore<W> range = (RangeStore<W>) store;
store = range.store;
from = range.from;
to = range.to;
}
if (store instanceof BinaryStore) {
bits.setStore(position, ((BinaryStore) store).bits.range(from, to));
} else {
setStoreImpl(position, store, from, to);
}
}
@Override
public void transpose(int i, int j) {
bits.permute().transpose(i, j);
}
@Override
int range() { return 2; }
@Override
int getImpl(int index) {
return valueOf( bits.getBit(index) );
}
@Override
int setImpl(int index, int value) {
return valueOf( bits.getThenSetBit(index, value != 0) );
}
@Override
void fillImpl(int value) {
bits.setAll(value != 0);
}
@Override
void fillImpl(int from, int to, int value) {
bits.range(from, to).setAll(value != 0);
}
@Override
void checkImpl(int value) {
if (value != 0 && value != 1) throw new IllegalArgumentException("value not 0 or 1");
}
private boolean checkedValue(Integer value) {
if (value == null) {
if (nullValue < 0) StoreType.failNull();
return nullValue > 0;
}
switch (value) {
case 0 : return false;
case 1 : return true;
default: throw new IllegalArgumentException("value not 0 or 1");
}
}
private int valueOf(boolean v) {
return v ? 1 : 0;
}
}
private final static class TernaryStore extends SmallValueStore {
private final byte[] data;
private final boolean mutable;
TernaryStore(int size, int nullValue, Integer initialValue) {
super(size, nullValue);
initCheck(initialValue);
int length = (size + 4) / 5;
data = new byte[length];
mutable = true;
initFill(initialValue);
}
TernaryStore(int size, int nullValue, byte[] data, boolean mutable) {
super(size, nullValue);
this.data = data;
this.mutable = mutable;
}
@Override
public Integer get(int index) {
checkIndex(index);
return getImpl(index);
}
@Override
public Integer set(int index, Integer value) {
checkIndex(index);
return setImpl(index, checkedValue(value));
}
@Override
public boolean isSettable(Object value) {
int i = settableValue(value);
return i >= 0 && i < 3;
}
@Override
public void fill(Integer value) {
fillImpl(checkedValue(value));
}
@Override
public boolean isMutable() {
return mutable;
}
@Override
public TernaryStore mutableCopy() {
return new TernaryStore(size, nullValue, data.clone(), true);
}
@Override
public TernaryStore immutableCopy() {
return new TernaryStore(size, nullValue, data.clone(), false);
}
@Override
public TernaryStore immutableView() {
return new TernaryStore(size, nullValue, data, false);
}
@Override
public TernaryStore resizedCopy(int newSize) {
checkNewSize(newSize);
int newLength = (newSize + 4) / 5;
byte[] newData = Arrays.copyOfRange(data, 0, newLength);
TernaryStore store = new TernaryStore(newSize, nullValue, newData, true);
if (newSize > size) {
int limit = Math.min(size / 5 * 5 + 5, newSize);
for (int i = size; i < limit; i++) store.setImpl(i, nullValue);
if (newLength > data.length) {
Arrays.fill(newData, data.length, newLength, fiveCopies(nullValue));
}
}
return store;
}
@Override
int range() { return 3; }
@Override
int getImpl(int index) {
int i = index / 5;
int j = index % 5;
byte p = data[i];
int u = tUnpack(p);
int d = (4-j) << 1;
return (u >> d) & 3;
}
@Override
int setImpl(int index, int value) {
int i = index / 5;
int j = index % 5;
byte p = data[i];
int u = tUnpack(p);
int d = (4-j) << 1;
int v = (u >> d) & 3;
u &= ~(3 << d);
u |= value << d;
data[i] = tPack(u);
return v;
}
@Override
void fillImpl(int value) {
Arrays.fill(data, fiveCopies(value));
}
@Override
void fillImpl(int from, int to, int value) {
for (int i = from; i < to; i++) {
setImpl(i, value);
}
}
@Override
void checkImpl(int value) {
if (value < 0) throw new IllegalArgumentException("negative value");
if (value >= 3) throw new IllegalArgumentException("value too large");
}
private int checkedValue(Integer value) {
if (value == null) {
if (nullValue < 0) StoreType.failNull();
return nullValue;
}
checkImpl(value);
return value;
}
private byte fiveCopies(int value) {
int u = 0;
for (int i = 0; i < 5; i++) {
u <<= 2;
u |= value;
}
return tPack(u);
}
}
private final static class QuinaryStore extends SmallValueStore {
private final BitStore bits;
QuinaryStore(int size, int nullValue, Integer initialValue) {
super(size, nullValue);
initCheck(initialValue);
bits = Bits.store((size + 2) / 3 * 7);
initFill(initialValue);
}
QuinaryStore(int size, int nullValue, BitStore bits) {
super(size, nullValue);
this.bits = bits;
}
@Override
public Integer get(int index) {
checkIndex(index);
return getImpl(index);
}
@Override
public Integer set(int index, Integer value) {
checkIndex(index);
return setImpl(index, checkedValue(value));
}
@Override
public boolean isSettable(Object value) {
int i = settableValue(value);
return i >= 0 && i < 5;
}
@Override
public void fill(Integer value) {
fillImpl(checkedValue(value));
}
@Override
public boolean isMutable() {
return bits.isMutable();
}
@Override
public QuinaryStore mutableCopy() {
return new QuinaryStore(size, nullValue, bits.mutableCopy());
}
@Override
public QuinaryStore immutableCopy() {
return new QuinaryStore(size, nullValue, bits.immutableCopy());
}
@Override
public QuinaryStore immutableView() {
return new QuinaryStore(size, nullValue, bits.immutable());
}
@Override
public QuinaryStore resizedCopy(int newSize) {
checkNewSize(newSize);
BitStore newBits = Bits.resizedCopyOf(bits, newSize * 7, false);
QuinaryStore store = new QuinaryStore(newSize, nullValue, newBits);
if (size < newSize) {
int limit = Math.min(size / 3 * 3 + 3, newSize);
for (int i = size; i < limit; i++) {
store.setImpl(i, nullValue);
}
int nbs = newBits.size();
int obs = bits.size();
if (nbs > obs) {
int p = fiveCopies(nullValue);
BitWriter w = newBits.openWriter(obs, nbs);
for (int i = (nbs - obs) / 7; i > 0; i--) w.write(p, 7);
w.flush();
}
}
return store;
}
@Override
int range() { return 5; }
@Override
int getImpl(int index) {
int i = index / 3;
int j = index % 3;
int p = getBits(i);
int u = qUnpack(p);
int d = (2-j) * 3;
return (u >> d) & 7;
}
@Override
int setImpl(int index, int value) {
int i = index / 3;
int j = index % 3;
int p = getBits(i);
int u = qUnpack(p);
int d = (2-j) * 3;
int v = (u >> d) & 7;
u &= ~(7 << d);
u |= value << d;
setBits(i, qPack(u));
return v;
}
@Override
void fillImpl(int value) {
if (value == 0) {
bits.clear();
} else {
int p = fiveCopies(value);
BitWriter w = bits.openWriter();
int limit = bits.size() / 7;
for (int i = 0; i < limit; i++) {
w.write(p, 7);
}
w.flush();
}
}
@Override
void fillImpl(int from, int to, int value) {
for (int i = from; i < to; i++) {
setImpl(i, value);
}
}
@Override
void checkImpl(int value) {
if (value < 0) throw new IllegalArgumentException("negative value");
if (value >= 5) throw new IllegalArgumentException("value too large");
}
private int checkedValue(Integer value) {
if (value == null) {
if (nullValue < 0) StoreType.failNull();
return nullValue;
}
checkImpl(value);
return value;
}
private int getBits(int index) {
return (int) bits.getBits(index * 7, 7);
}
private void setBits(int index, int value) {
bits.setBits(index * 7, value, 7);
}
private int fiveCopies(int value) {
int u = 0;
for (int i = 0; i < 3; i++) {
u <<= 3;
u |= value;
}
return qPack(u);
}
}
private final static class ArbitraryStore extends SmallValueStore /* implements StoreInts */ {
private final int range;
private final int count;
private final BitStore bits;
ArbitraryStore(int size, int nullValue, int range, Integer initialValue) {
super(size, nullValue);
initCheck(initialValue);
this.range = range;
count = 32 - Integer.numberOfLeadingZeros(range - 1);
bits = Bits.store(size * count);
initFill(initialValue);
}
ArbitraryStore(ArbitraryStore that, BitStore bits) {
super(bits.size() / that.count, that.nullValue);
this.range = that.range;
this.count = that.count;
this.bits = bits;
}
@Override
public Integer get(int index) {
checkIndex(index);
return getImpl(index);
}
@Override
public Integer set(int index, Integer value) {
checkIndex(index);
return setImpl(index, checkedValue(value));
}
@Override
public boolean isSettable(Object value) {
int i = settableValue(value);
return i >= 0 && i < range;
}
@Override
public void fill(Integer value) {
fillImpl(checkedValue(value));
}
@Override
public boolean isMutable() { return bits.isMutable(); }
@Override
public ArbitraryStore mutableCopy() { return new ArbitraryStore(this, bits.mutableCopy()); }
@Override
public ArbitraryStore immutableCopy() { return new ArbitraryStore(this, bits.immutableCopy()); }
@Override
public ArbitraryStore immutableView() { return new ArbitraryStore(this, bits.immutable()); }
@Override
public ArbitraryStore resizedCopy(int newSize) {
checkNewSize(newSize);
BitStore newBits = Bits.resizedCopyOf(bits, newSize * count, false);
ArbitraryStore store = new ArbitraryStore(this, newBits);
if (size < newSize) {
BitWriter w = newBits.openWriter(size * count, newSize * count);
for (int i = size; i < newSize; i++) {
w.write(nullValue, count);
}
w.flush();
}
return store;
}
@Override
public <W extends Integer> void setStore(int position, Store<W> store) {
int from = 0;
int to = checkSetStore(position, store);
if (store instanceof RangeStore<?>) {
RangeStore<W> range = (RangeStore<W>) store;
store = range.store;
from = range.from;
to = range.to;
}
if (store instanceof ArbitraryStore) {
bits.setStore(position * count, ((ArbitraryStore) store).bits.range(from * count, to * count));
} else {
setStoreImpl(position, store, from, to);
}
}
@Override
int range() {
return range;
}
@Override
int setImpl(int index, int value) {
int position = index * count;
int v = (int) bits.getBits(position, count);
bits.setBits(position, value, count);
return v;
}
@Override
int getImpl(int index) {
return (int) bits.getBits(index * count, count);
}
@Override
void fillImpl(int value) {
writeFill(bits, value);
}
@Override
void fillImpl(int from, int to, int value) {
writeFill(bits.range(from * count, to * count), value);
}
@Override
void checkImpl(int value) {
if (value < 0) throw new IllegalArgumentException("negative value");
if (value >= range) throw new IllegalArgumentException("value too large");
}
private int checkedValue(Integer value) {
if (value == null) {
if (nullValue < 0) StoreType.failNull();
return nullValue;
}
checkImpl(value);
return value;
}
private void writeFill(BitStore bits, int value) {
if (value == 0) {
bits.clear();
} else if (value == (1 << count) - 1) {
bits.fill();
} else {
int length = bits.size() / count;
BitWriter w = bits.openWriter();
for (int i = 0; i < length; i++) {
w.write(value, count);
}
w.flush();
}
}
}
// nullable stores
interface NullSmallStorage extends Storage<Integer> {
@Override default public StoreType<Integer> type() { return StoreType.INT; }
}
static class ZeroOrNullStore extends AbstractStore<Integer> implements StoreInts {
private static final Integer ZERO = 0;
private final int size;
private final BitStore bits;
ZeroOrNullStore(int size, Integer initialValue) {
this.size = size;
bits = Bits.store(size);
if (initialValue != null) {
bits.setAll(true);
}
}
ZeroOrNullStore(BitStore bits) {
this.size = bits.size();
this.bits = bits;
}
@Override
public StoreType<Integer> type() {
return StoreType.INT;
}
public int size() {
return size;
}
public Class<Integer> valueType() {
return Integer.class;
}
@Override
public Integer get(int index) {
checkIndex(index);
return bits.getBit(index) ? 0 : null;
}
@Override
public boolean isNull(int index) {
checkIndex(index);
return !bits.getBit(index);
}
@Override
public Integer set(int index, Integer value) {
checkIndex(index);
boolean v = checkedValue(value);
return bits.getThenSetBit(index, v) ? 0 : null;
}
@Override
public boolean isSettable(Object value) {
return value == null || ZERO.equals(value);
}
@Override
public void clear() {
bits.clear();
}
@Override
public BitStore population() {
return bits.immutableView();
}
@Override
public void fill(Integer value) {
bits.setAll(checkedValue(value));
}
@Override
public Store<Integer> resizedCopy(int newSize) {
return new ZeroOrNullStore(Bits.resizedCopyOf(bits, newSize, false));
}
@Override
public <W extends Integer> void setStore(int position, Store<W> store) {
int from = 0;
int to = checkSetStore(position, store);
if (store instanceof RangeStore<?>) {
RangeStore<W> range = (RangeStore<W>) store;
store = range.store;
from = range.from;
to = range.to;
}
if (store instanceof ZeroOrNullStore) {
bits.setStore(position, ((ZeroOrNullStore) store).bits.range(from, to));
} else {
setStoreImpl(position, store, from, to);
}
}
@Override
public boolean isMutable() { return bits.isMutable(); }
@Override
public Store<Integer> mutableCopy() { return new ZeroOrNullStore(bits.mutableCopy()); }
@Override
public Store<Integer> immutableCopy() { return new ZeroOrNullStore(bits.immutableCopy()); }
@Override
public Store<Integer> immutableView() { return new ZeroOrNullStore(bits.immutable()); }
@Override
public void transpose(int i, int j) {
bits.permute().transpose(i, j);
}
// store ints
@Override
public boolean isInt(int index) {
return !isNull(index);
}
@Override
public int getInt(int index) {
checkIndex(index);
if (!bits.getBit(index)) throw new RuntimeException("null, not an int");
return 0;
}
@Override
public void setInt(int index, int value) {
checkIndex(index);
if (value != 0) throw new IllegalArgumentException("value not zero");
bits.setBit(index, true);
}
// private helper methods
private void checkIndex(int index) {
if (index < 0) throw new IllegalArgumentException("negative index");
if (index >= size) throw new IllegalArgumentException("index too large");
}
private boolean checkedValue(Integer value) {
if (value == null) return false;
if (value == 0) return true;
throw new IllegalArgumentException("value not null or zero");
}
}
private static class NullableStore extends AbstractStore<Integer> implements StoreInts {
private final SmallValueStore wrapped;
NullableStore(SmallValueStore wrapped) {
this.wrapped = wrapped;
}
@Override
public StoreType<Integer> type() {
return StoreType.INT;
}
@Override
public int size() {
return wrapped.size;
}
@Override
public Integer get(int index) {
wrapped.checkIndex(index);
return unwrap(wrapped.getImpl(index));
}
@Override
public boolean isNull(int index) {
wrapped.checkIndex(index);
return wrapped.getImpl(index) == 0;
}
@Override
public Integer set(int index, Integer value) {
wrapped.checkIndex(index);
return unwrap( wrapped.setImpl(index, wrap(value)) );
}
@Override
public boolean isSettable(Object value) {
if (value == null) return true;
if (!(value instanceof Integer)) return false;
int i = ((Integer) value) + 1;
return i >= 1 && i < wrapped.range();
}
@Override
public void clear() {
wrapped.fillImpl(0);
}
@Override
public void fill(Integer value) {
wrapped.fillImpl(wrap(value));
}
@Override
public Store<Integer> resizedCopy(int newSize) {
return new NullableStore(wrapped.resizedCopy(newSize));
}
@Override
public <W extends Integer> void setStore(int position, Store<W> store) {
if (store instanceof NullableStore) {
wrapped.setStore(position, ((NullableStore) store).wrapped);
} else {
super.setStore(position, store);
}
}
@Override
public boolean isMutable() {
return wrapped.isMutable();
}
@Override
public Store<Integer> mutableCopy() {
return new NullableStore(wrapped.mutableCopy());
}
@Override
public Store<Integer> immutableCopy() {
return new NullableStore(wrapped.immutableCopy());
}
@Override
public Store<Integer> immutableView() {
return new NullableStore(wrapped.immutableView());
}
@Override
public void transpose(int i, int j) {
wrapped.transpose(i, j);
}
// store ints
@Override
public boolean isInt(int index) {
return !isNull(index);
}
@Override
public int getInt(int index) {
wrapped.checkIndex(index);
int value = wrapped.getImpl(index);
if (value == 0) throw new RuntimeException("null, not an int");
return value - 1;
}
@Override
public void setInt(int index, int value) {
if (!wrapped.isMutable()) throw new IllegalStateException("immutable");
wrapped.checkIndex(index);
wrapped.setImpl(index, wrapImpl(value));
}
// private helper methods
private Integer unwrap(int value) {
return value == 0 ? null : value - 1;
}
private int wrap(Integer value) {
return value == null ? 0 : wrapImpl(value);
}
private int wrapImpl(int value) {
if (value < 0) throw new IllegalArgumentException("negative value");
if (++value >= wrapped.range()) throw new IllegalArgumentException("value too large");
return value;
}
}
}
| |
/*
* $Id: CommandLinkRenderer.java 473327 2006-11-10 12:59:22Z niallp $
*
* 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.struts.faces.renderer;
import java.io.IOException;
import java.util.Iterator;
import javax.faces.component.NamingContainer;
import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.component.UIForm;
import javax.faces.component.UIParameter;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.ActionEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ModuleConfig;
/**
* <p><code>Renderer</code> implementation for the <code>commandLink</code>
* tag from the <em>Struts-Faces Integration Library</em>.</p>
*
* @version $Rev: 473327 $ $Date: 2006-11-10 13:59:22 +0100 (Ven, 10 nov 2006) $
*/
public class CommandLinkRenderer extends AbstractRenderer {
// -------------------------------------------------------- Static Variables
/**
* <p>Token for private names.</p>
*/
private static final String TOKEN =
"org_apache_struts_faces_renderer_CommandLinkRenderer";
/**
* <p>The <code>Log</code> instance for this class.</p>
*/
private static Log log = LogFactory.getLog(CommandLinkRenderer.class);
// ---------------------------------------------------------- Public Methods
/**
* <p>Perform setup processing that will be required for decoding the
* incoming request.</p>
*
* @param context FacesContext for the request we are processing
* @param component UIComponent to be processed
*
* @exception NullPointerException if <code>context</code>
* or <code>component</code> is null
*/
public void decode(FacesContext context, UIComponent component) {
// Implement spec requirements on NullPointerException
if ((context == null) || (component == null)) {
throw new NullPointerException();
}
// Skip this component if it is not relevant
if (!component.isRendered() || isDisabled(component) ||
isReadOnly(component)) {
return;
}
// Set up variables we will need
UIForm form = null;
UIComponent parent = component.getParent();
while (parent != null) {
if (parent instanceof UIForm) {
form = (UIForm) parent;
break;
}
parent = parent.getParent();
}
if (form == null) {
log.warn("CommandLinkComponent not nested inside UIForm, ignored");
return;
}
// Was this the component that submitted this form?
String paramId = TOKEN;
String value = (String)
context.getExternalContext().getRequestParameterMap().get(paramId);
if ((value == null) || !value.equals(component.getClientId(context))) {
if (log.isTraceEnabled()) {
log.trace("decode(" + component.getId() + ") --> not active");
}
return;
}
// Queue an ActionEvent from this component
if (log.isTraceEnabled()) {
log.trace("decode(" + component.getId() + ") --> queueEvent()");
}
component.queueEvent(new ActionEvent(component));
}
private static String passThrough[] =
{ "accesskey", "charset", "dir", "hreflang", "lang", "onblur",
/* "onclick", */ "ondblclick", "onfocus", "onkeydown",
"onkeypress", "onkeyup", "onmousedown", "onmousemove",
"onmouseout", "onmouseover", "onmouseup", "rel", "rev",
"style", "tabindex", "target", "title", "type" };
/**
* <p>Render the beginning of a hyperlink to submit this form.</p>
*
* @param context FacesContext for the request we are processing
* @param component UIComponent to be rendered
* @param writer ResponseWriter we are rendering to
*
* @exception IOException if an input/output error occurs while rendering
* @exception NullPointerException if <code>context</code>
* or <code>component</code> is null
*/
public void renderStart(FacesContext context, UIComponent component,
ResponseWriter writer)
throws IOException {
// Skip this component if it is not relevant
if (!component.isRendered() || isDisabled(component) ||
isReadOnly(component)) {
return;
}
// Set up variables we will need
UIForm form = null;
UIComponent parent = component.getParent();
while (parent != null) {
if (parent instanceof UIForm) {
form = (UIForm) parent;
break;
}
parent = parent.getParent();
}
if (form == null) {
log.warn("CommandLinkComponent not nested inside UIForm, ignored");
return;
}
String formClientId = form.getClientId(context);
// If this is the first nested command link inside this form,
// render a hidden variable to identify which link did the submit
String key = formClientId + NamingContainer.SEPARATOR_CHAR + TOKEN;
if (context.getExternalContext().getRequestMap().get(key) == null) {
writer.startElement("input", null);
writer.writeAttribute("name", TOKEN, null);
writer.writeAttribute("type", "hidden", null);
writer.writeAttribute("value", "", null);
writer.endElement("input");
context.getExternalContext().getRequestMap().put
(key, Boolean.TRUE);
}
// Render the beginning of this hyperlink
writer.startElement("a", component);
}
/**
* <p>Render the attributes of a hyperlink to submit this form.</p>
*
* @param context FacesContext for the request we are processing
* @param component UIComponent to be rendered
* @param writer ResponseWriter we are rendering to
*
* @exception IOException if an input/output error occurs while rendering
* @exception NullPointerException if <code>context</code>
* or <code>component</code> is null
*/
public void renderAttributes(FacesContext context, UIComponent component,
ResponseWriter writer)
throws IOException {
// Skip this component if it is not relevant
if (!component.isRendered() || isDisabled(component) ||
isReadOnly(component)) {
return;
}
// Set up variables we will need
UIComponent form = null;
UIComponent parent = component.getParent();
while (parent != null) {
if (parent instanceof UIForm ||
"org.apache.myfaces.trinidad.Form".equals(parent.getFamily()) ||
"oracle.adf.Form".equals(parent.getFamily())) {
form = parent;
break;
}
parent = parent.getParent();
}
if (form == null) {
log.warn("CommandLinkComponent not nested inside UIForm, ignored");
return;
}
String formClientId = form.getClientId(context);
// Render the attributes of this hyperlink
if (component.getId() != null) {
writer.writeAttribute("id", component.getClientId(context), "id");
}
writer.writeAttribute("href", "#", null);
String styleClass = (String)
component.getAttributes().get("styleClass");
if (styleClass != null) {
writer.writeAttribute("class", styleClass, "styleClass");
}
renderPassThrough(context, component, writer, passThrough);
// Render the JavaScript content of the "onclick" element
StringBuffer sb = new StringBuffer();
sb.append("document.forms['");
sb.append(formClientId);
sb.append("']['");
sb.append(TOKEN);
sb.append("'].value='");
sb.append(component.getClientId(context));
sb.append("';");
Iterator kids = component.getChildren().iterator();
while (kids.hasNext()) {
UIComponent kid = (UIComponent) kids.next();
if (!(kid instanceof UIParameter)) {
continue;
}
sb.append("document.forms['");
sb.append(formClientId);
sb.append("']['");
sb.append((String) kid.getAttributes().get("name"));
sb.append("'].value='");
sb.append((String) kid.getAttributes().get("value"));
sb.append("';");
}
sb.append("document.forms['");
sb.append(formClientId);
sb.append("'].submit(); return false;");
writer.writeAttribute("onclick", sb.toString(), null);
// Render the component value as the hyperlink text
Object value = component.getAttributes().get("value");
if (value != null) {
if (value instanceof String) {
writer.write((String) value);
} else {
writer.write(value.toString());
}
}
}
/**
* <p>Render the end of a hyperlink to submit this form.</p>
*
* @param context FacesContext for the request we are processing
* @param component UIComponent to be rendered
* @param writer ResponseWriter we are rendering to
*
* @exception IOException if an input/output error occurs while rendering
* @exception NullPointerException if <code>context</code>
* or <code>component</code> is null
*/
public void renderEnd(FacesContext context, UIComponent component,
ResponseWriter writer)
throws IOException {
// Skip this component if it is not relevant
if (!component.isRendered() || isDisabled(component) ||
isReadOnly(component)) {
return;
}
// Render the beginning of this hyperlink
writer.endElement("a");
}
}
| |
/**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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 the following location:
*
* 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.jasig.portal.layout;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.commons.lang.Validate;
import org.jasig.portal.layout.om.IStylesheetUserPreferences;
import org.jasig.portal.utils.Populator;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
/**
* Stylesheet user preferences setup for memory or serialized storage. All APIs and returned objects are thread safe.
*
* @author Eric Dalquist
*/
public class StylesheetUserPreferencesImpl implements IStylesheetUserPreferences, Serializable {
private static final long serialVersionUID = 1L;
private final ConcurrentMap<String, String> outputProperties = new ConcurrentHashMap<String, String>();
private final ConcurrentMap<String, String> parameters = new ConcurrentHashMap<String, String>();
//NodeId -> Name -> Value
private final ConcurrentMap<String, ConcurrentMap<String, String>> layoutAttributes = new ConcurrentHashMap<String, ConcurrentMap<String,String>>();
@Override
public long getId() {
return -1;
}
@Override
public String getOutputProperty(String name) {
Validate.notEmpty(name, "name cannot be null");
return this.outputProperties.get(name);
}
@Override
public String removeOutputProperty(String name) {
Validate.notEmpty(name, "name cannot be null");
return this.outputProperties.remove(name);
}
@Override
public String getStylesheetParameter(String name) {
Validate.notEmpty(name, "name cannot be null");
return this.parameters.get(name);
}
@Override
public String setStylesheetParameter(String name, String value) {
Validate.notEmpty(name, "name cannot be null");
Validate.notEmpty(value, "value cannot be null");
return this.parameters.put(name, value);
}
@Override
public String removeStylesheetParameter(String name) {
Validate.notEmpty(name, "name cannot be null");
return this.parameters.remove(name);
}
@Override
public <P extends Populator<String, String>> P populateStylesheetParameters(P stylesheetParameters) {
stylesheetParameters.putAll(this.parameters);
return stylesheetParameters;
}
@Override
public String getLayoutAttribute(String nodeId, String name) {
Validate.notEmpty(nodeId, "nodeId cannot be null");
Validate.notEmpty(name, "name cannot be null");
final Map<String, String> nodeAttributes = this.layoutAttributes.get(nodeId);
if (nodeAttributes == null) {
return null;
}
return nodeAttributes.get(name);
}
@Override
public String setLayoutAttribute(String nodeId, String name, String value) {
Validate.notEmpty(nodeId, "nodeId cannot be null");
Validate.notEmpty(name, "name cannot be null");
Validate.notEmpty(value, "value cannot be null");
ConcurrentMap<String, String> nodeAttributes;
synchronized (this.layoutAttributes) {
nodeAttributes = this.layoutAttributes.get(nodeId);
if (nodeAttributes == null) {
nodeAttributes = new ConcurrentHashMap<String, String>();
this.layoutAttributes.put(nodeId, nodeAttributes);
}
}
return nodeAttributes.put(name, value);
}
/* (non-Javadoc)
* @see org.jasig.portal.layout.om.IStylesheetUserPreferences#removeLayoutAttribute(java.lang.String, java.lang.String)
*/
@Override
public String removeLayoutAttribute(String nodeId, String name) {
Validate.notEmpty(nodeId, "nodeId cannot be null");
Validate.notEmpty(name, "name cannot be null");
final Map<String, String> nodeAttributes = this.layoutAttributes.get(nodeId);
if (nodeAttributes == null) {
return null;
}
return nodeAttributes.remove(name);
}
@Override
public <P extends Populator<String, String>> P populateLayoutAttributes(String nodeId, P layoutAttributes) {
Validate.notEmpty(nodeId, "nodeId cannot be null");
final Map<String, String> nodeAttributes = this.layoutAttributes.get(nodeId);
if (nodeAttributes != null) {
layoutAttributes.putAll(nodeAttributes);
}
return layoutAttributes;
}
@Override
public Map<String, String> getAllNodesAndValuesForAttribute(String name) {
Validate.notEmpty(name, "name cannot be null");
final Builder<String, String> result = ImmutableMap.builder();
for (final Entry<String, ConcurrentMap<String, String>> layoutNodeAttributesEntry : this.layoutAttributes.entrySet()) {
final ConcurrentMap<String, String> layoutNodeAttributes = layoutNodeAttributesEntry.getValue();
final String value = layoutNodeAttributes.get(name);
if (value != null) {
final String nodeId = layoutNodeAttributesEntry.getKey();
result.put(nodeId, value);
}
}
return result.build();
}
@Override
public Collection<String> getAllLayoutAttributeNodeIds() {
return Collections.unmodifiableSet(this.layoutAttributes.keySet());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.layoutAttributes == null) ? 0 : this.layoutAttributes.hashCode());
result = prime * result + ((this.outputProperties == null) ? 0 : this.outputProperties.hashCode());
result = prime * result + ((this.parameters == null) ? 0 : this.parameters.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StylesheetUserPreferencesImpl other = (StylesheetUserPreferencesImpl) obj;
if (this.layoutAttributes == null) {
if (other.layoutAttributes != null)
return false;
}
else if (!this.layoutAttributes.equals(other.layoutAttributes))
return false;
if (this.outputProperties == null) {
if (other.outputProperties != null)
return false;
}
else if (!this.outputProperties.equals(other.outputProperties))
return false;
if (this.parameters == null) {
if (other.parameters != null)
return false;
}
else if (!this.parameters.equals(other.parameters))
return false;
return true;
}
@Override
public String toString() {
return "StylesheetUserPreferencesImpl [outputProperties=" + this.outputProperties
+ ", parameters=" + this.parameters + ", layoutAttributes=" + this.layoutAttributes + "]";
}
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.indices.recovery;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.ElasticsearchTimeoutException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.IndexShardClosedException;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.threadpool.ThreadPool;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* This class holds a collection of all on going recoveries on the current node (i.e., the node is the target node
* of those recoveries). The class is used to guarantee concurrent semantics such that once a recoveries was done/cancelled/failed
* no other thread will be able to find it. Last, the {@link RecoveryRef} inner class verifies that recovery temporary files
* and store will only be cleared once on going usage is finished.
*/
public class RecoveriesCollection {
/** This is the single source of truth for ongoing recoveries. If it's not here, it was canceled or done */
private final ConcurrentMap<Long, RecoveryTarget> onGoingRecoveries = ConcurrentCollections.newConcurrentMap();
private final Logger logger;
private final ThreadPool threadPool;
public RecoveriesCollection(Logger logger, ThreadPool threadPool) {
this.logger = logger;
this.threadPool = threadPool;
}
/**
* Starts are new recovery for the given shard, source node and state
*
* @return the id of the new recovery.
*/
public long startRecovery(IndexShard indexShard, DiscoveryNode sourceNode,
PeerRecoveryTargetService.RecoveryListener listener, TimeValue activityTimeout) {
RecoveryTarget recoveryTarget = new RecoveryTarget(indexShard, sourceNode, listener);
startRecoveryInternal(recoveryTarget, activityTimeout);
return recoveryTarget.recoveryId();
}
private void startRecoveryInternal(RecoveryTarget recoveryTarget, TimeValue activityTimeout) {
RecoveryTarget existingTarget = onGoingRecoveries.putIfAbsent(recoveryTarget.recoveryId(), recoveryTarget);
assert existingTarget == null : "found two RecoveryStatus instances with the same id";
logger.trace("{} started recovery from {}, id [{}]", recoveryTarget.shardId(), recoveryTarget.sourceNode(),
recoveryTarget.recoveryId());
threadPool.schedule(new RecoveryMonitor(recoveryTarget.recoveryId(), recoveryTarget.lastAccessTime(), activityTimeout),
activityTimeout, ThreadPool.Names.GENERIC);
}
/**
* Resets the recovery and performs a recovery restart on the currently recovering index shard
*
* @see IndexShard#performRecoveryRestart()
* @return newly created RecoveryTarget
*/
public RecoveryTarget resetRecovery(final long recoveryId, final TimeValue activityTimeout) {
RecoveryTarget oldRecoveryTarget = null;
final RecoveryTarget newRecoveryTarget;
try {
synchronized (onGoingRecoveries) {
// swap recovery targets in a synchronized block to ensure that the newly added recovery target is picked up by
// cancelRecoveriesForShard whenever the old recovery target is picked up
oldRecoveryTarget = onGoingRecoveries.remove(recoveryId);
if (oldRecoveryTarget == null) {
return null;
}
newRecoveryTarget = oldRecoveryTarget.retryCopy();
startRecoveryInternal(newRecoveryTarget, activityTimeout);
}
// Closes the current recovery target
boolean successfulReset = oldRecoveryTarget.resetRecovery(newRecoveryTarget.cancellableThreads());
if (successfulReset) {
logger.trace("{} restarted recovery from {}, id [{}], previous id [{}]", newRecoveryTarget.shardId(),
newRecoveryTarget.sourceNode(), newRecoveryTarget.recoveryId(), oldRecoveryTarget.recoveryId());
return newRecoveryTarget;
} else {
logger.trace("{} recovery could not be reset as it is already cancelled, recovery from {}, id [{}], previous id [{}]",
newRecoveryTarget.shardId(), newRecoveryTarget.sourceNode(), newRecoveryTarget.recoveryId(),
oldRecoveryTarget.recoveryId());
cancelRecovery(newRecoveryTarget.recoveryId(), "recovery cancelled during reset");
return null;
}
} catch (Exception e) {
// fail shard to be safe
oldRecoveryTarget.notifyListener(new RecoveryFailedException(oldRecoveryTarget.state(), "failed to retry recovery", e), true);
return null;
}
}
public RecoveryTarget getRecoveryTarget(long id) {
return onGoingRecoveries.get(id);
}
/**
* gets the {@link RecoveryTarget } for a given id. The RecoveryStatus returned has it's ref count already incremented
* to make sure it's safe to use. However, you must call {@link RecoveryTarget#decRef()} when you are done with it, typically
* by using this method in a try-with-resources clause.
* <p>
* Returns null if recovery is not found
*/
public RecoveryRef getRecovery(long id) {
RecoveryTarget status = onGoingRecoveries.get(id);
if (status != null && status.tryIncRef()) {
return new RecoveryRef(status);
}
return null;
}
/** Similar to {@link #getRecovery(long)} but throws an exception if no recovery is found */
public RecoveryRef getRecoverySafe(long id, ShardId shardId) {
RecoveryRef recoveryRef = getRecovery(id);
if (recoveryRef == null) {
throw new IndexShardClosedException(shardId);
}
assert recoveryRef.target().shardId().equals(shardId);
return recoveryRef;
}
/** cancel the recovery with the given id (if found) and remove it from the recovery collection */
public boolean cancelRecovery(long id, String reason) {
RecoveryTarget removed = onGoingRecoveries.remove(id);
boolean cancelled = false;
if (removed != null) {
logger.trace("{} canceled recovery from {}, id [{}] (reason [{}])",
removed.shardId(), removed.sourceNode(), removed.recoveryId(), reason);
removed.cancel(reason);
cancelled = true;
}
return cancelled;
}
/**
* fail the recovery with the given id (if found) and remove it from the recovery collection
*
* @param id id of the recovery to fail
* @param e exception with reason for the failure
* @param sendShardFailure true a shard failed message should be sent to the master
*/
public void failRecovery(long id, RecoveryFailedException e, boolean sendShardFailure) {
RecoveryTarget removed = onGoingRecoveries.remove(id);
if (removed != null) {
logger.trace("{} failing recovery from {}, id [{}]. Send shard failure: [{}]", removed.shardId(), removed.sourceNode(),
removed.recoveryId(), sendShardFailure);
removed.fail(e, sendShardFailure);
}
}
/** mark the recovery with the given id as done (if found) */
public void markRecoveryAsDone(long id) {
RecoveryTarget removed = onGoingRecoveries.remove(id);
if (removed != null) {
logger.trace("{} marking recovery from {} as done, id [{}]", removed.shardId(), removed.sourceNode(), removed.recoveryId());
removed.markAsDone();
}
}
/** the number of ongoing recoveries */
public int size() {
return onGoingRecoveries.size();
}
/**
* cancel all ongoing recoveries for the given shard
*
* @param reason reason for cancellation
* @param shardId shardId for which to cancel recoveries
* @return true if a recovery was cancelled
*/
public boolean cancelRecoveriesForShard(ShardId shardId, String reason) {
boolean cancelled = false;
List<RecoveryTarget> matchedRecoveries = new ArrayList<>();
synchronized (onGoingRecoveries) {
for (Iterator<RecoveryTarget> it = onGoingRecoveries.values().iterator(); it.hasNext(); ) {
RecoveryTarget status = it.next();
if (status.shardId().equals(shardId)) {
matchedRecoveries.add(status);
it.remove();
}
}
}
for (RecoveryTarget removed : matchedRecoveries) {
logger.trace("{} canceled recovery from {}, id [{}] (reason [{}])",
removed.shardId(), removed.sourceNode(), removed.recoveryId(), reason);
removed.cancel(reason);
cancelled = true;
}
return cancelled;
}
/**
* a reference to {@link RecoveryTarget}, which implements {@link AutoCloseable}. closing the reference
* causes {@link RecoveryTarget#decRef()} to be called. This makes sure that the underlying resources
* will not be freed until {@link RecoveryRef#close()} is called.
*/
public static class RecoveryRef implements AutoCloseable {
private final RecoveryTarget status;
private final AtomicBoolean closed = new AtomicBoolean(false);
/**
* Important: {@link RecoveryTarget#tryIncRef()} should
* be *successfully* called on status before
*/
public RecoveryRef(RecoveryTarget status) {
this.status = status;
this.status.setLastAccessTime();
}
@Override
public void close() {
if (closed.compareAndSet(false, true)) {
status.decRef();
}
}
public RecoveryTarget target() {
return status;
}
}
private class RecoveryMonitor extends AbstractRunnable {
private final long recoveryId;
private final TimeValue checkInterval;
private volatile long lastSeenAccessTime;
private RecoveryMonitor(long recoveryId, long lastSeenAccessTime, TimeValue checkInterval) {
this.recoveryId = recoveryId;
this.checkInterval = checkInterval;
this.lastSeenAccessTime = lastSeenAccessTime;
}
@Override
public void onFailure(Exception e) {
logger.error(() -> new ParameterizedMessage("unexpected error while monitoring recovery [{}]", recoveryId), e);
}
@Override
protected void doRun() throws Exception {
RecoveryTarget status = onGoingRecoveries.get(recoveryId);
if (status == null) {
logger.trace("[monitor] no status found for [{}], shutting down", recoveryId);
return;
}
long accessTime = status.lastAccessTime();
if (accessTime == lastSeenAccessTime) {
String message = "no activity after [" + checkInterval + "]";
failRecovery(recoveryId,
new RecoveryFailedException(status.state(), message, new ElasticsearchTimeoutException(message)),
true // to be safe, we don't know what go stuck
);
return;
}
lastSeenAccessTime = accessTime;
logger.trace("[monitor] rescheduling check for [{}]. last access time is [{}]", recoveryId, lastSeenAccessTime);
threadPool.schedule(this, checkInterval, ThreadPool.Names.GENERIC);
}
}
}
| |
package org.codemonkey.simplejavamail;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Mailing tool aimed for simplicity, for sending e-mails of any complexity. This includes e-mails with plain text and/or html content,
* embedded images and separate attachments, SMTP, SMTPS / SSL and SMTP + SSL<br />
* <br />
* This mailing tool abstracts the javax.mail API to a higher level easy to use API. For public use, this tool only works with {@link Email}
* instances. <br />
* <br />
* The e-mail message structure is built to work with all e-mail clients and has been tested with many different webclients as well as some
* mainstream client applications such as MS Outlook or Mozilla Thunderbird.<br />
* <br />
* Technically, the resulting email structure is a follows:<br />
*
* <pre>
* - root
* - related
* - alternative
* - mail text
* - mail html text
* - embedded images
* - attachments
* </pre>
*
* <br />
* Usage example:<br />
*
* <pre>
* Email email = new Email();
* email.setFromAddress("lollypop", "lolly.pop@somemail.com");
* email.addRecipient("Sugar Cae", "sugar.cane@candystore.org", RecipientType.TO);
* email.setText("We should meet up!!");
* email.setTextHTML("<b>We should meet up!</b>");
* email.setSubject("Hey");
* new Mailer(preconfiguredMailSession).sendMail(email);
* // or:
* new Mailer("smtp.someserver.com", 25, "username", "password").sendMail(email);
* </pre>
*
* @author Benny Bottema
* @see MimeEmailMessageWrapper
* @see Email
*/
public class Mailer {
private static final Logger logger = LoggerFactory.getLogger(Mailer.class);
/**
* Used to actually send the email. This session can come from being passed in the default constructor, or made by <code>Mailer</code>
* directly, when no <code>Session</code> instance was provided.
*
* @see #Mailer(Session)
* @see #Mailer(String, int, String, String, TransportStrategy)
*/
private final Session session;
/**
* The transport protocol strategy enum that actually handles the session configuration. Session configuration meaning setting the right
* properties for the appropriate transport type (ie. <em>"mail.smtp.host"</em> for SMTP, <em>"mail.smtps.host"</em> for SMTPS).
*/
private TransportStrategy transportStrategy;
/**
* Email address restriction flags set either by constructor or overridden by getter by user.
*
* @see EmailAddressValidationCriteria
*/
private EmailAddressValidationCriteria emailAddressValidationCriteria;
/**
* Default constructor, stores the given mail session for later use. Assumes that *all* properties used to make a connection are
* configured (host, port, authentication and transport protocol settings).
* <p>
* Also defines a default email address validation criteria object, which remains true to RFC 2822, meaning allowing both domain
* literals and quoted identifiers (see {@link EmailAddressValidationCriteria#EmailAddressValidationCriteria(boolean, boolean)}).
*
* @param session A preconfigured mail {@link Session} object with which a {@link Message} can be produced.
*/
public Mailer(final Session session) {
this.session = session;
this.emailAddressValidationCriteria = new EmailAddressValidationCriteria(true, true);
}
/**
* Overloaded constructor which produces a new {@link Session} on the fly. Use this if you don't have a mail session configured in your
* web container, or Spring context etc.
* <p>
* Also defines a default email address validation criteria object, which remains true to RFC 2822, meaning allowing both domain
* literals and quoted identifiers (see {@link EmailAddressValidationCriteria#EmailAddressValidationCriteria(boolean, boolean)}).
*
* @param host The address URL of the SMTP server to be used.
* @param port The port of the SMTP server.
* @param username An optional username, may be <code>null</code>.
* @param password An optional password, may be <code>null</code>, but only if username is <code>null</code> as well.
* @param transportStrategy The transport protocol configuration type for handling SSL or TLS (or vanilla SMTP)
*/
public Mailer(final String host, final int port, final String username, final String password, final TransportStrategy transportStrategy) {
// we're doing these validations manually instead of using Apache Commons to avoid another dependency
if (host == null || "".equals(host.trim())) {
throw new RuntimeException("Can't send an email without host");
} else if ((password != null && !"".equals(password.trim())) && (username == null || "".equals(username.trim()))) {
throw new RuntimeException("Can't have a password without username");
}
this.transportStrategy = transportStrategy;
this.session = createMailSession(host, port, username, password);
this.emailAddressValidationCriteria = new EmailAddressValidationCriteria(true, true);
}
/**
* Actually instantiates and configures the {@link Session} instance. Delegates resolving transport protocol specific properties to the
* {@link #transportStrategy} in two ways:
* <ol>
* <li>request an initial property list which the strategy may pre-populate</li>
* <li>by requesting the property names according to the respective transport protocol it handles (for the host property name it would
* be <em>"mail.smtp.host"</em> for SMTP and <em>"mail.smtps.host"</em> for SMTPS)</li>
* </ol>
*
* @param host The address URL of the SMTP server to be used.
* @param port The port of the SMTP server.
* @param username An optional username, may be <code>null</code>.
* @param password An optional password, may be <code>null</code>.
* @return A fully configured <code>Session</code> instance complete with transport protocol settings.
* @see TransportStrategy#generateProperties()
* @see TransportStrategy#propertyNameHost()
* @see TransportStrategy#propertyNamePort()
* @see TransportStrategy#propertyNameUsername()
* @see TransportStrategy#propertyNameAuthenticate()
*/
public Session createMailSession(final String host, final int port, final String username, final String password) {
Properties props = transportStrategy.generateProperties();
props.put(transportStrategy.propertyNameHost(), host);
props.put(transportStrategy.propertyNamePort(), String.valueOf(port));
if (username != null) {
props.put(transportStrategy.propertyNameUsername(), username);
}
if (password != null) {
props.put(transportStrategy.propertyNameAuthenticate(), "true");
return Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
} else {
return Session.getInstance(props);
}
}
/**
* Overloaded constructor which produces a new {@link Session} on the fly, using default vanilla SMTP transport protocol.
*
* @see #Mailer(String, int, String, String, TransportStrategy)
*/
public Mailer(final String host, final int port, final String username, final String password) {
this(host, port, username, password, TransportStrategy.SMTP_SSL);
}
/**
* Actually sets {@link Session#setDebug(boolean)} so that it generate debug information.
*/
public void setDebug(boolean debug) {
session.setDebug(debug);
}
/**
* Processes an {@link Email} instance into a completely configured {@link Message}.
* <p>
* Sends the Sun JavaMail {@link Message} object using {@link Session#getTransport()}. It will call {@link Transport#connect()} assuming
* all connection details have been configured in the provided {@link Session} instance.
* <p>
* Performs a call to {@link Message#saveChanges()} as the Sun JavaMail API indicates it is needed to configure the message headers and
* providing a message id.
*
* @param email The information for the email to be sent.
* @throws MailException Can be thrown if an email isn't validating correctly, or some other problem occurs during connection, sending
* etc.
* @see #validate(Email)
* @see #prepareMessage(Email, MimeMultipart)
* @see #setRecipients(Email, Message)
* @see #setTexts(Email, MimeMultipart)
* @see #setEmbeddedImages(Email, MimeMultipart)
* @see #setAttachments(Email, MimeMultipart)
*/
public final void sendMail(final Email email)
throws MailException {
if (validate(email)) {
try {
// create new wrapper for each mail being sent (enable sending multiple emails with one mailer)
final MimeEmailMessageWrapper messageRoot = new MimeEmailMessageWrapper();
// fill and send wrapped mime message parts
final Message message = prepareMessage(email, messageRoot.multipartRoot);
setRecipients(email, message);
setTexts(email, messageRoot.multipartAlternativeMessages);
setEmbeddedImages(email, messageRoot.multipartRelated);
setAttachments(email, messageRoot.multipartRoot);
logSession(session, transportStrategy);
message.saveChanges(); // some headers and id's will be set for this specific message
Transport transport = session.getTransport();
transport.connect();
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (final UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
throw new MailException(String.format(MailException.INVALID_ENCODING, e.getMessage()));
} catch (final MessagingException e) {
logger.error(e.getMessage(), e);
throw new MailException(String.format(MailException.GENERIC_ERROR, e.getMessage()), e);
}
}
}
/**
* Simply logs host details, credentials used and whether authentication will take place and finally the transport protocol used.
*/
private void logSession(Session session, TransportStrategy transportStrategy) {
final String logmsg = "starting mail session (host: %s, port: %s, username: %s, authenticate: %s, transport: %s)";
Properties properties = session.getProperties();
logger.debug(String.format(logmsg, properties.get(transportStrategy.propertyNameHost()),
properties.get(transportStrategy.propertyNamePort()), properties.get(transportStrategy.propertyNameUsername()),
properties.get(transportStrategy.propertyNameAuthenticate()), transportStrategy));
}
/**
* Validates an {@link Email} instance. Validation fails if the subject is missing, content is missing, or no recipients are defined.
*
* @param email The email that needs to be configured correctly.
* @return Always <code>true</code> (throws a {@link MailException} exception if validation fails).
* @throws MailException Is being thrown in any of the above causes.
* @see EmailValidationUtil
*/
public boolean validate(final Email email)
throws MailException {
if (email.getText() == null && email.getTextHTML() == null) {
throw new MailException(MailException.MISSING_CONTENT);
} else if (email.getSubject() == null || email.getSubject().equals("")) {
throw new MailException(MailException.MISSING_SUBJECT);
} else if (email.getRecipients().size() == 0) {
throw new MailException(MailException.MISSING_RECIPIENT);
} else if (email.getFromRecipient() == null) {
throw new MailException(MailException.MISSING_SENDER);
} else {
if (!EmailValidationUtil.isValid(email.getFromRecipient().getAddress(), emailAddressValidationCriteria)) {
throw new MailException(String.format(MailException.INVALID_SENDER, email));
}
for (final Recipient recipient : email.getRecipients()) {
if (!EmailValidationUtil.isValid(recipient.getAddress(), emailAddressValidationCriteria)) {
throw new MailException(String.format(MailException.INVALID_RECIPIENT, email));
}
}
}
return true;
}
/**
* Creates a new {@link MimeMessage} instance and prepares it in the email structure, so that it can be filled and send.
*
* @param email The email message from which the subject and From-address are extracted.
* @param multipartRoot The root of the email which holds everything (filled with some email data).
* @return Een geprepareerde {@link Message} instantie, klaar om gevuld en verzonden te worden.
* @throws MessagingException Kan gegooid worden als het message niet goed behandelt wordt.
* @throws UnsupportedEncodingException Zie {@link InternetAddress#InternetAddress(String, String)}.
*/
private Message prepareMessage(final Email email, final MimeMultipart multipartRoot)
throws MessagingException, UnsupportedEncodingException {
final Message message = new MimeMessage(session);
message.setSubject(email.getSubject());
message.setFrom(new InternetAddress(email.getFromRecipient().getAddress(), email.getFromRecipient().getName()));
message.setContent(multipartRoot);
message.setSentDate(new Date());
return message;
}
/**
* Fills the {@link Message} instance with recipients from the {@link Email}.
*
* @param email The message in which the recipients are defined.
* @param message The javax message that needs to be filled with recipients.
* @throws UnsupportedEncodingException See {@link InternetAddress#InternetAddress(String, String)}.
* @throws MessagingException See {@link Message#addRecipient(javax.mail.Message.RecipientType, Address)}
*/
private void setRecipients(final Email email, final Message message)
throws UnsupportedEncodingException, MessagingException {
for (final Recipient recipient : email.getRecipients()) {
final Address address = new InternetAddress(recipient.getAddress(), recipient.getName());
message.addRecipient(recipient.getType(), address);
}
}
/**
* Fills the {@link Message} instance with the content bodies (text and html).
*
* @param email The message in which the content is defined.
* @param multipartAlternativeMessages See {@link MimeMultipart#addBodyPart(BodyPart)}
* @throws MessagingException See {@link BodyPart#setText(String)}, {@link BodyPart#setContent(Object, String)} and
* {@link MimeMultipart#addBodyPart(BodyPart)}.
*/
private void setTexts(final Email email, final MimeMultipart multipartAlternativeMessages)
throws MessagingException {
if (email.getText() != null) {
final MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(email.getText(), "UTF-8");
multipartAlternativeMessages.addBodyPart(messagePart);
}
if (email.getTextHTML() != null) {
final MimeBodyPart messagePartHTML = new MimeBodyPart();
messagePartHTML.setContent(email.getTextHTML(), "text/html; charset=\"UTF-8\"");
multipartAlternativeMessages.addBodyPart(messagePartHTML);
}
}
/**
* Fills the {@link Message} instance with the embedded images from the {@link Email}.
*
* @param email The message in which the embedded images are defined.
* @param multipartRelated The branch in the email structure in which we'll stuff the embedded images.
* @throws MessagingException See {@link MimeMultipart#addBodyPart(BodyPart)} and
* {@link #getBodyPartFromDatasource(AttachmentResource, String)}
*/
private void setEmbeddedImages(final Email email, final MimeMultipart multipartRelated)
throws MessagingException {
for (final AttachmentResource embeddedImage : email.getEmbeddedImages()) {
multipartRelated.addBodyPart(getBodyPartFromDatasource(embeddedImage, Part.INLINE));
}
}
/**
* Fills the {@link Message} instance with the attachments from the {@link Email}.
*
* @param email The message in which the attachments are defined.
* @param multipartRoot The branch in the email structure in which we'll stuff the attachments.
* @throws MessagingException See {@link MimeMultipart#addBodyPart(BodyPart)} and
* {@link #getBodyPartFromDatasource(AttachmentResource, String)}
*/
private void setAttachments(final Email email, final MimeMultipart multipartRoot)
throws MessagingException {
for (final AttachmentResource resource : email.getAttachments()) {
multipartRoot.addBodyPart(getBodyPartFromDatasource(resource, Part.ATTACHMENT));
}
}
/**
* Helper method which generates a {@link BodyPart} from an {@link AttachmentResource} (from its {@link DataSource}) and a disposition
* type ({@link Part#INLINE} or {@link Part#ATTACHMENT}). With this the attachment data can be converted into objects that fit in the
* email structure. <br />
* <br />
* For every attachment and embedded image a header needs to be set.
*
* @param resource An object that describes the attachment and contains the actual content data.
* @param dispositionType The type of attachment, {@link Part#INLINE} or {@link Part#ATTACHMENT} .
* @return An object with the attachment data read for placement in the email structure.
* @throws MessagingException All BodyPart setters.
*/
private BodyPart getBodyPartFromDatasource(final AttachmentResource resource, final String dispositionType)
throws MessagingException {
final BodyPart attachmentPart = new MimeBodyPart();
final DataSource ds = resource.getDataSource();
// setting headers isn't working nicely using the javax mail API, so let's do that manually
attachmentPart.setDataHandler(new DataHandler(resource.getDataSource()));
attachmentPart.setFileName(resource.getName());
attachmentPart.setHeader("Content-Type", ds.getContentType() + "; filename=" + ds.getName() + "; name=" + ds.getName());
attachmentPart.setHeader("Content-ID", String.format("<%s>", ds.getName()));
attachmentPart.setDisposition(dispositionType + "; size=0");
return attachmentPart;
}
/**
* This class conveniently wraps all necessary mimemessage parts that need to be filled with content, attachments etc. The root is
* ultimately sent using JavaMail.<br />
* <br />
* The constructor creates a new email message constructed from {@link MimeMultipart} as follows:
*
* <pre>
* - root
* - related
* - alternative
* - mail tekst
* - mail html tekst
* - embedded images
* - attachments
* </pre>
*
* @author Benny Bottema
*/
private class MimeEmailMessageWrapper {
private final MimeMultipart multipartRoot;
private final MimeMultipart multipartRelated;
private final MimeMultipart multipartAlternativeMessages;
/**
* Creates an email skeleton structure, so that embedded images, attachments and (html) texts are being processed properly.
*/
MimeEmailMessageWrapper() {
multipartRoot = new MimeMultipart("mixed");
final MimeBodyPart contentRelated = new MimeBodyPart();
multipartRelated = new MimeMultipart("related");
final MimeBodyPart contentAlternativeMessages = new MimeBodyPart();
multipartAlternativeMessages = new MimeMultipart("alternative");
try {
// construct mail structure
multipartRoot.addBodyPart(contentRelated);
contentRelated.setContent(multipartRelated);
multipartRelated.addBodyPart(contentAlternativeMessages);
contentAlternativeMessages.setContent(multipartAlternativeMessages);
} catch (final MessagingException e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
}
}
/**
* Overrides the default email address validation restrictions when validating and sending emails using the current <code>Mailer</code>
* instance.
*
* @param emailAddressValidationCriteria Refer to
* {@link EmailAddressValidationCriteria#EmailAddressValidationCriteria(boolean, boolean)}.
*/
public void setEmailAddressValidationCriteria(EmailAddressValidationCriteria emailAddressValidationCriteria) {
this.emailAddressValidationCriteria = emailAddressValidationCriteria;
}
}
| |
/*
* 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.felix.deploymentadmin.spi;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.apache.felix.deploymentadmin.AbstractDeploymentPackage;
import org.apache.felix.deploymentadmin.DeploymentAdminImpl;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.service.deploymentadmin.DeploymentException;
import org.osgi.service.deploymentadmin.DeploymentPackage;
import org.osgi.service.deploymentadmin.spi.DeploymentSession;
import org.osgi.service.log.LogService;
import org.osgi.service.packageadmin.PackageAdmin;
/**
* Represents a running deployment session.
*/
public class DeploymentSessionImpl implements DeploymentSession {
private final AbstractDeploymentPackage m_target;
private final AbstractDeploymentPackage m_source;
private final List m_commands;
private final DeploymentAdminImpl m_admin;
private volatile Command m_currentCommand = null;
private volatile boolean m_cancelled;
public DeploymentSessionImpl(AbstractDeploymentPackage source, AbstractDeploymentPackage target, List commands, DeploymentAdminImpl admin) {
m_source = source;
m_target = target;
m_commands = commands;
m_admin = admin;
}
/**
* Calling this method will cause the commands specified for this session to be executed. the commands will be rolled back if the session is
* canceled or if an exception is caused by one of the commands.
*
* @throws DeploymentException If the session was canceled (<code>DeploymentException.CODE_CANCELLED</code>) or if one of the commands caused an exception (<code>DeploymentException.*</code>)
*/
public void call() throws DeploymentException {
List executedCommands = new ArrayList();
for (Iterator i = m_commands.iterator(); i.hasNext();) {
if (m_cancelled) {
// previous command did not pick up on cancel
rollback(executedCommands);
throw new DeploymentException(DeploymentException.CODE_CANCELLED);
}
m_currentCommand = (Command) i.next();
try {
executedCommands.add(m_currentCommand);
m_currentCommand.execute(this);
}
catch (DeploymentException de) {
rollback(executedCommands);
throw de;
}
}
for (Iterator i = m_commands.iterator(); i.hasNext();) {
((Command) i.next()).commit();
}
m_currentCommand = null;
}
private void rollback(List executedCommands) {
for (ListIterator i = executedCommands.listIterator(executedCommands.size()); i.hasPrevious();) {
Command command = (Command) i.previous();
command.rollback();
}
}
/**
* Cancels the session if it is in progress.
*
* @return true if a session was in progress and now canceled, false otherwise.
*/
public boolean cancel() {
m_cancelled = true;
if (m_currentCommand != null) {
m_currentCommand.cancel();
return true;
}
return false;
}
/**
* Retrieve the base directory of the persistent storage area according to
* OSGi Core R4 6.1.6.10 for the given <code>BundleContext</code>.
*
* @param bundle of which the storage area will be returned
* @return a <code>File</code> that represents the base directory of the
* persistent storage area for the bundle
*/
public File getDataFile(Bundle bundle) {
BundleContext context = null;
try {
// try to find the method in the current class
Method getBundleContext = bundle.getClass().getDeclaredMethod("getBundleContext", null);
getBundleContext.setAccessible(true);
context = (BundleContext) getBundleContext.invoke(bundle, null);
}
catch (Exception e) {
// if we cannot find the method at first, we try again below
}
if (context == null) {
try {
// try to find the method in superclasses
Method getBundleContext = bundle.getClass().getMethod("getBundleContext", null);
getBundleContext.setAccessible(true);
context = (BundleContext) getBundleContext.invoke(bundle, null);
}
catch (Exception e) {
// we still can't find the method, we will throw an exception indicating that below
}
}
File result = null;
if (context != null) {
result = context.getDataFile("");
}
else {
throw new IllegalStateException("Could not retrieve valid bundle context from bundle " + bundle.getSymbolicName());
}
if (result == null) {
throw new IllegalStateException("Could not retrieve base directory for bundle " + bundle.getSymbolicName());
}
return result;
}
public DeploymentPackage getSourceDeploymentPackage() {
return m_source;
}
public DeploymentPackage getTargetDeploymentPackage() {
return m_target;
}
/**
* Returns the bundle context of the bundle this class is part of.
*
* @return The <code>BundleContext</code>.
*/
public BundleContext getBundleContext() {
return m_admin.getBundleContext();
}
/**
* Returns the currently present log service.
*
* @return The <code>LogService</code>.
*/
public LogService getLog() {
return m_admin.getLog();
}
/**
* Returns the currently present package admin.
*
* @return The <code>PackageAdmin</code>
*/
public PackageAdmin getPackageAdmin() {
return m_admin.getPackageAdmin();
}
/**
* Returns the target deployment package as an <code>AbstractDeploymentPackage</code>.
*
* @return The target deployment package of the session.
*/
public AbstractDeploymentPackage getTargetAbstractDeploymentPackage() {
return m_target;
}
/**
* Returns the source deployment package as an <code>AbstractDeploymentPackage</code>.
*
* @return The source deployment packge of the session.
*/
public AbstractDeploymentPackage getSourceAbstractDeploymentPackage() {
return m_source;
}
}
| |
package com.alibaba.mtc;
import com.alibaba.mtc.testmodel.FooMtContextThreadLocal;
import com.alibaba.mtc.testmodel.FooPojo;
import com.alibaba.mtc.testmodel.FooTask;
import com.alibaba.mtc.testmodel.Task;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.AfterClass;
import org.junit.Test;
import static com.alibaba.mtc.Utils.CHILD;
import static com.alibaba.mtc.Utils.PARENT_AFTER_CREATE_MTC_TASK;
import static com.alibaba.mtc.Utils.PARENT_MODIFIED_IN_CHILD;
import static com.alibaba.mtc.Utils.PARENT_UNMODIFIED_IN_CHILD;
import static com.alibaba.mtc.Utils.assertMtContext;
import static com.alibaba.mtc.Utils.copied;
import static com.alibaba.mtc.Utils.createTestMtContexts;
import static com.alibaba.mtc.Utils.expandThreadPool;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* @author Jerry Lee (oldratlee at gmail dot com)
*/
public class MtContextRunnableTest {
static ExecutorService executorService = Executors.newFixedThreadPool(3);
static {
expandThreadPool(executorService);
}
@AfterClass
public static void afterClass() throws Exception {
executorService.shutdown();
}
@Test
public void test_MtContextRunnable_inSameThread() throws Exception {
ConcurrentMap<String, MtContextThreadLocal<String>> mtContexts = createTestMtContexts();
Task task = new Task("1", mtContexts);
MtContextRunnable mtContextRunnable = MtContextRunnable.get(task);
// create after new Task
MtContextThreadLocal<String> after = new MtContextThreadLocal<String>();
after.set(PARENT_AFTER_CREATE_MTC_TASK);
mtContexts.put(PARENT_AFTER_CREATE_MTC_TASK, after);
mtContextRunnable.run();
// child Inheritable
assertMtContext(task.copied,
PARENT_UNMODIFIED_IN_CHILD, PARENT_UNMODIFIED_IN_CHILD,
PARENT_MODIFIED_IN_CHILD + "1", PARENT_MODIFIED_IN_CHILD,
CHILD + "1", CHILD + "1"
);
// child do not effect parent
assertMtContext(copied(mtContexts),
PARENT_UNMODIFIED_IN_CHILD, PARENT_UNMODIFIED_IN_CHILD,
PARENT_MODIFIED_IN_CHILD, PARENT_MODIFIED_IN_CHILD, // restored after call!
PARENT_AFTER_CREATE_MTC_TASK, PARENT_AFTER_CREATE_MTC_TASK
);
}
@Test
public void test_MtContextRunnable_withThread() throws Exception {
ConcurrentMap<String, MtContextThreadLocal<String>> mtContexts = createTestMtContexts();
Task task = new Task("1", mtContexts);
Thread thread1 = new Thread(task);
// create after new Task, won't see parent value in in task!
MtContextThreadLocal<String> after = new MtContextThreadLocal<String>();
after.set(PARENT_AFTER_CREATE_MTC_TASK);
mtContexts.put(PARENT_AFTER_CREATE_MTC_TASK, after);
thread1.start();
thread1.join();
// child Inheritable
assertMtContext(task.copied,
PARENT_UNMODIFIED_IN_CHILD, PARENT_UNMODIFIED_IN_CHILD,
PARENT_MODIFIED_IN_CHILD + "1", PARENT_MODIFIED_IN_CHILD,
CHILD + "1", CHILD + "1"
);
// child do not effect parent
assertMtContext(copied(mtContexts),
PARENT_UNMODIFIED_IN_CHILD, PARENT_UNMODIFIED_IN_CHILD,
PARENT_MODIFIED_IN_CHILD, PARENT_MODIFIED_IN_CHILD,
PARENT_AFTER_CREATE_MTC_TASK, PARENT_AFTER_CREATE_MTC_TASK
);
}
@Test
public void test_MtContextRunnable_withExecutorService() throws Exception {
ConcurrentMap<String, MtContextThreadLocal<String>> mtContexts = createTestMtContexts();
Task task = new Task("1", mtContexts);
MtContextRunnable mtContextRunnable = MtContextRunnable.get(task);
// create after new Task, won't see parent value in in task!
MtContextThreadLocal<String> after = new MtContextThreadLocal<String>();
after.set(PARENT_AFTER_CREATE_MTC_TASK);
mtContexts.put(PARENT_AFTER_CREATE_MTC_TASK, after);
Future<?> submit = executorService.submit(mtContextRunnable);
submit.get();
// child Inheritable
assertMtContext(task.copied,
PARENT_UNMODIFIED_IN_CHILD, PARENT_UNMODIFIED_IN_CHILD,
PARENT_MODIFIED_IN_CHILD + "1", PARENT_MODIFIED_IN_CHILD,
CHILD + "1", CHILD + "1"
);
// child do not effect parent
assertMtContext(copied(mtContexts),
PARENT_UNMODIFIED_IN_CHILD, PARENT_UNMODIFIED_IN_CHILD,
PARENT_MODIFIED_IN_CHILD, PARENT_MODIFIED_IN_CHILD,
PARENT_AFTER_CREATE_MTC_TASK, PARENT_AFTER_CREATE_MTC_TASK
);
}
@Test
public void test_testRemove() throws Exception {
ConcurrentMap<String, MtContextThreadLocal<String>> mtContexts = createTestMtContexts();
// remove MtContextThreadLocal
mtContexts.get(PARENT_UNMODIFIED_IN_CHILD).remove();
Task task = new Task("1", mtContexts);
MtContextRunnable mtContextRunnable = MtContextRunnable.get(task);
// create after new Task, won't see parent value in in task!
MtContextThreadLocal<String> after = new MtContextThreadLocal<String>();
after.set(PARENT_AFTER_CREATE_MTC_TASK);
mtContexts.put(PARENT_AFTER_CREATE_MTC_TASK, after);
Future<?> submit = executorService.submit(mtContextRunnable);
submit.get();
// child Inheritable
assertMtContext(task.copied,
PARENT_MODIFIED_IN_CHILD + "1", PARENT_MODIFIED_IN_CHILD,
CHILD + 1, CHILD + 1
);
// child do not effect parent
assertMtContext(copied(mtContexts),
PARENT_MODIFIED_IN_CHILD, PARENT_MODIFIED_IN_CHILD,
PARENT_AFTER_CREATE_MTC_TASK, PARENT_AFTER_CREATE_MTC_TASK
);
}
@Test
public void test_MtContextRunnable_copyObject() throws Exception {
ConcurrentMap<String, MtContextThreadLocal<FooPojo>> mtContexts =
new ConcurrentHashMap<String, MtContextThreadLocal<FooPojo>>();
MtContextThreadLocal<FooPojo> parent = new FooMtContextThreadLocal();
parent.set(new FooPojo(PARENT_UNMODIFIED_IN_CHILD, 1));
mtContexts.put(PARENT_UNMODIFIED_IN_CHILD, parent);
MtContextThreadLocal<FooPojo> p = new FooMtContextThreadLocal();
p.set(new FooPojo(PARENT_MODIFIED_IN_CHILD, 2));
mtContexts.put(PARENT_MODIFIED_IN_CHILD, p);
FooTask task = new FooTask("1", mtContexts);
MtContextRunnable mtContextRunnable = MtContextRunnable.get(task);
// create after new Task, won't see parent value in in task!
MtContextThreadLocal<FooPojo> after = new FooMtContextThreadLocal();
after.set(new FooPojo(PARENT_AFTER_CREATE_MTC_TASK, 4));
mtContexts.put(PARENT_AFTER_CREATE_MTC_TASK, after);
Future<?> submit = executorService.submit(mtContextRunnable);
submit.get();
// child Inheritable
assertEquals(3, task.copied.size());
assertEquals(new FooPojo(PARENT_UNMODIFIED_IN_CHILD, 1), task.copied.get(PARENT_UNMODIFIED_IN_CHILD));
assertEquals(new FooPojo(PARENT_MODIFIED_IN_CHILD + "1", 2), task.copied.get(PARENT_MODIFIED_IN_CHILD));
assertEquals(new FooPojo(CHILD + 1, 3), task.copied.get(CHILD + 1));
// child do not effect parent
Map<String, Object> copied = copied(mtContexts);
assertEquals(3, copied.size());
assertEquals(new FooPojo(PARENT_UNMODIFIED_IN_CHILD, 1), copied.get(PARENT_UNMODIFIED_IN_CHILD));
assertEquals(new FooPojo(PARENT_MODIFIED_IN_CHILD, 2), copied.get(PARENT_MODIFIED_IN_CHILD));
assertEquals(new FooPojo(PARENT_AFTER_CREATE_MTC_TASK, 4), copied.get(PARENT_AFTER_CREATE_MTC_TASK));
}
@Test
public void test_releaseMtContextAfterRun() throws Exception {
ConcurrentMap<String, MtContextThreadLocal<String>> mtContexts = createTestMtContexts();
Task task = new Task("1", mtContexts);
MtContextRunnable mtContextRunnable = MtContextRunnable.get(task, true);
Future<?> future = executorService.submit(mtContextRunnable);
assertNull(future.get());
future = executorService.submit(mtContextRunnable);
try {
future.get();
fail();
} catch (ExecutionException expected) {
assertThat(expected.getCause(), instanceOf(IllegalStateException.class));
assertThat(expected.getMessage(), containsString("MtContext is released!"));
}
}
@Test
public void test_sameTask() throws Exception {
Task task = new Task("1", null);
MtContextRunnable mtContextRunnable = MtContextRunnable.get(task);
assertSame(task, mtContextRunnable.getRunnable());
}
@Test
public void test_get_idempotent() throws Exception {
MtContextRunnable task = MtContextRunnable.get(new Task("1", null));
try {
MtContextRunnable.get(task);
fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage(), containsString("Already MtContextRunnable"));
}
}
@Test
public void test_get_nullInput() throws Exception {
assertNull(MtContextRunnable.get(null));
}
@Test
public void test_gets() throws Exception {
Task task1 = new Task("1", null);
Task task2 = new Task("1", null);
Runnable task3 = new Task("1", null);
List<MtContextRunnable> taskList = MtContextRunnable.gets(Arrays.asList(task1, task2, null, task3));
assertEquals(4, taskList.size());
assertThat(taskList.get(0), instanceOf(MtContextRunnable.class));
assertThat(taskList.get(1), instanceOf(MtContextRunnable.class));
assertNull(taskList.get(2));
assertThat(taskList.get(3), instanceOf(MtContextRunnable.class));
}
}
| |
package com.example.android.sunshine.wear;
/**
* Created by tsato on 3/17/16.
*/
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.android.sunshine.wear.data.WeatherContract;
/**
* A placeholder fragment containing a simple view.
*/
public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String LOG_TAG = DetailFragment.class.getSimpleName();
static final String DETAIL_URI = "URI";
static final String DETAIL_TRANSITION_ANIMATION = "DTA";
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private String mForecast;
private Uri mUri;
private boolean mTransitionAnimation;
private static final int DETAIL_LOADER = 0;
public static final String[] DETAIL_COLUMNS = {
WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
WeatherContract.WeatherEntry.COLUMN_DATE,
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
WeatherContract.WeatherEntry.COLUMN_HUMIDITY,
WeatherContract.WeatherEntry.COLUMN_PRESSURE,
WeatherContract.WeatherEntry.COLUMN_WIND_SPEED,
WeatherContract.WeatherEntry.COLUMN_DEGREES,
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
// This works because the WeatherProvider returns location data joined with
// weather data, even though they're stored in two different tables.
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING
};
// These indices are tied to DETAIL_COLUMNS. If DETAIL_COLUMNS changes, these
// must change.
public static final int COL_WEATHER_ID = 0;
public static final int COL_WEATHER_DATE = 1;
public static final int COL_WEATHER_DESC = 2;
public static final int COL_WEATHER_MAX_TEMP = 3;
public static final int COL_WEATHER_MIN_TEMP = 4;
public static final int COL_WEATHER_HUMIDITY = 5;
public static final int COL_WEATHER_PRESSURE = 6;
public static final int COL_WEATHER_WIND_SPEED = 7;
public static final int COL_WEATHER_DEGREES = 8;
public static final int COL_WEATHER_CONDITION_ID = 9;
private ImageView mIconView;
private TextView mDateView;
private TextView mDescriptionView;
private TextView mHighTempView;
private TextView mLowTempView;
private TextView mHumidityView;
private TextView mHumidityLabelView;
private TextView mWindView;
private TextView mWindLabelView;
private TextView mPressureView;
private TextView mPressureLabelView;
public DetailFragment() {
setHasOptionsMenu(false);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle arguments = getArguments();
if (arguments != null) {
mUri = arguments.getParcelable(DetailFragment.DETAIL_URI);
mTransitionAnimation = arguments.getBoolean(DetailFragment.DETAIL_TRANSITION_ANIMATION, false);
}
View rootView = inflater.inflate(R.layout.fragment_detail_start, container, false);
mIconView = (ImageView) rootView.findViewById(R.id.detail_icon);
mDateView = (TextView) rootView.findViewById(R.id.detail_date_textview);
mDescriptionView = (TextView) rootView.findViewById(R.id.detail_forecast_textview);
mHighTempView = (TextView) rootView.findViewById(R.id.detail_high_textview);
mLowTempView = (TextView) rootView.findViewById(R.id.detail_low_textview);
mHumidityView = (TextView) rootView.findViewById(R.id.detail_humidity_textview);
mHumidityLabelView = (TextView) rootView.findViewById(R.id.detail_humidity_label_textview);
mWindView = (TextView) rootView.findViewById(R.id.detail_wind_textview);
mWindLabelView = (TextView) rootView.findViewById(R.id.detail_wind_label_textview);
mPressureView = (TextView) rootView.findViewById(R.id.detail_pressure_textview);
mPressureLabelView = (TextView) rootView.findViewById(R.id.detail_pressure_label_textview);
return rootView;
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mForecast + FORECAST_SHARE_HASHTAG);
return shareIntent;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
void onLocationChanged( String newLocation ) {
// replace the uri, since the location has changed
Uri uri = mUri;
if (null != uri) {
long date = WeatherContract.WeatherEntry.getDateFromUri(uri);
Uri updatedUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(newLocation, date);
mUri = updatedUri;
getLoaderManager().restartLoader(DETAIL_LOADER, null, this);
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if ( null != mUri ) {
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(
getActivity(),
mUri,
DETAIL_COLUMNS,
null,
null,
null
);
}
ViewParent vp = getView().getParent();
if ( vp instanceof CardView) {
((View)vp).setVisibility(View.INVISIBLE);
}
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data != null && data.moveToFirst()) {
ViewParent vp = getView().getParent();
if ( vp instanceof CardView ) {
((View)vp).setVisibility(View.VISIBLE);
}
// Read weather condition ID from cursor
int weatherId = data.getInt(COL_WEATHER_CONDITION_ID);
if ( Utility.usingLocalGraphics(getActivity()) ) {
mIconView.setImageResource(Utility.getArtResourceForWeatherCondition(weatherId));
} else {
// Use weather art image
Glide.with(this)
.load(Utility.getArtUrlForWeatherCondition(getActivity(), weatherId))
.error(Utility.getArtResourceForWeatherCondition(weatherId))
.crossFade()
.into(mIconView);
}
// Read date from cursor and update views for day of week and date
long date = data.getLong(COL_WEATHER_DATE);
String dateText = Utility.getFullFriendlyDayString(getActivity(),date);
mDateView.setText(dateText);
// Get description from weather condition ID
String description = Utility.getStringForWeatherCondition(getActivity(), weatherId);
mDescriptionView.setText(description);
mDescriptionView.setContentDescription(getString(R.string.a11y_forecast, description));
// For accessibility, add a content description to the icon field. Because the ImageView
// is independently focusable, it's better to have a description of the image. Using
// null is appropriate when the image is purely decorative or when the image already
// has text describing it in the same UI component.
mIconView.setContentDescription(getString(R.string.a11y_forecast_icon, description));
// Read high temperature from cursor and update view
boolean isMetric = Utility.isMetric(getActivity());
double high = data.getDouble(COL_WEATHER_MAX_TEMP);
String highString = Utility.formatTemperature(getActivity(), high);
mHighTempView.setText(highString);
mHighTempView.setContentDescription(getString(R.string.a11y_high_temp, highString));
// Read low temperature from cursor and update view
double low = data.getDouble(COL_WEATHER_MIN_TEMP);
String lowString = Utility.formatTemperature(getActivity(), low);
mLowTempView.setText(lowString);
mLowTempView.setContentDescription(getString(R.string.a11y_low_temp, lowString));
// Read humidity from cursor and update view
float humidity = data.getFloat(COL_WEATHER_HUMIDITY);
mHumidityView.setText(getActivity().getString(R.string.format_humidity, humidity));
mHumidityView.setContentDescription(getString(R.string.a11y_humidity, mHumidityView.getText()));
mHumidityLabelView.setContentDescription(mHumidityView.getContentDescription());
// Read wind speed and direction from cursor and update view
float windSpeedStr = data.getFloat(COL_WEATHER_WIND_SPEED);
float windDirStr = data.getFloat(COL_WEATHER_DEGREES);
mWindView.setText(Utility.getFormattedWind(getActivity(), windSpeedStr, windDirStr));
mWindView.setContentDescription(getString(R.string.a11y_wind, mWindView.getText()));
mWindLabelView.setContentDescription(mWindView.getContentDescription());
// Read pressure from cursor and update view
float pressure = data.getFloat(COL_WEATHER_PRESSURE);
mPressureView.setText(getString(R.string.format_pressure, pressure));
mPressureView.setContentDescription(getString(R.string.a11y_pressure, mPressureView.getText()));
mPressureLabelView.setContentDescription(mPressureView.getContentDescription());
// We still need this for the share intent
mForecast = String.format("%s - %s - %s/%s", dateText, description, high, low);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) { }
}
| |
/*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxauth.model.config;
import org.apache.commons.lang.StringUtils;
import org.gluu.exception.ConfigurationException;
import org.gluu.oxauth.model.configuration.AppConfiguration;
import org.gluu.oxauth.model.configuration.Configuration;
import org.gluu.oxauth.model.crypto.AbstractCryptoProvider;
import org.gluu.oxauth.model.crypto.CryptoProviderFactory;
import org.gluu.oxauth.model.error.ErrorMessages;
import org.gluu.oxauth.model.error.ErrorResponseFactory;
import org.gluu.oxauth.model.event.CryptoProviderEvent;
import org.gluu.oxauth.model.jwk.JSONWebKey;
import org.gluu.oxauth.service.common.ApplicationFactory;
import org.gluu.oxauth.util.ServerUtil;
import org.gluu.persist.PersistenceEntryManager;
import org.gluu.persist.exception.BasePersistenceException;
import org.gluu.persist.model.PersistenceConfiguration;
import org.gluu.persist.service.PersistanceFactoryService;
import org.gluu.service.cdi.async.Asynchronous;
import org.gluu.service.cdi.event.*;
import org.gluu.service.timer.event.TimerEvent;
import org.gluu.service.timer.schedule.TimerSchedule;
import org.gluu.util.StringHelper;
import org.gluu.util.properties.FileConfiguration;
import org.json.JSONObject;
import org.slf4j.Logger;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import java.io.File;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
/**
* @author Yuriy Zabrovarnyy
* @author Javier Rojas Blum
* @author Yuriy Movchan
* @version June 15, 2016
*/
@ApplicationScoped
public class ConfigurationFactory {
@Inject
private Logger log;
@Inject
private Event<TimerEvent> timerEvent;
@Inject
private Event<AppConfiguration> configurationUpdateEvent;
@Inject
private Event<AbstractCryptoProvider> cryptoProviderEvent;
@Inject
private Event<String> event;
@Inject @Named(ApplicationFactory.PERSISTENCE_ENTRY_MANAGER_NAME)
private Instance<PersistenceEntryManager> persistenceEntryManagerInstance;
@Inject
private PersistanceFactoryService persistanceFactoryService;
@Inject
private Instance<Configuration> configurationInstance;
@Inject
private Instance<AbstractCryptoProvider> abstractCryptoProviderInstance;
public final static String PERSISTENCE_CONFIGUARION_RELOAD_EVENT_TYPE = "persistenceConfigurationReloadEvent";
public final static String BASE_CONFIGUARION_RELOAD_EVENT_TYPE = "baseConfigurationReloadEvent";
private final static int DEFAULT_INTERVAL = 30; // 30 seconds
static {
if (System.getProperty("gluu.base") != null) {
BASE_DIR = System.getProperty("gluu.base");
} else if ((System.getProperty("catalina.base") != null) && (System.getProperty("catalina.base.ignore") == null)) {
BASE_DIR = System.getProperty("catalina.base");
} else if (System.getProperty("catalina.home") != null) {
BASE_DIR = System.getProperty("catalina.home");
} else if (System.getProperty("jboss.home.dir") != null) {
BASE_DIR = System.getProperty("jboss.home.dir");
} else {
BASE_DIR = null;
}
}
private static final String BASE_DIR;
private static final String DIR = BASE_DIR + File.separator + "conf" + File.separator;
private static final String BASE_PROPERTIES_FILE = DIR + "gluu.properties";
private static final String LDAP_PROPERTIES_FILE = "oxauth.properties";
private final String CONFIG_FILE_NAME = "oxauth-config.json";
private final String ERRORS_FILE_NAME = "oxauth-errors.json";
private final String STATIC_CONF_FILE_NAME = "oxauth-static-conf.json";
private final String WEB_KEYS_FILE_NAME = "oxauth-web-keys.json";
private final String SALT_FILE_NAME = "salt";
private String confDir, configFilePath, errorsFilePath, staticConfFilePath, webKeysFilePath, saltFilePath;
private boolean loaded = false;
private FileConfiguration baseConfiguration;
private PersistenceConfiguration persistenceConfiguration;
private AppConfiguration conf;
private StaticConfiguration staticConf;
private WebKeysConfiguration jwks;
private ErrorResponseFactory errorResponseFactory;
private String cryptoConfigurationSalt;
private String contextPath;
private String facesMapping;
private AtomicBoolean isActive;
private long baseConfigurationFileLastModifiedTime;
private long loadedRevision = -1;
private boolean loadedFromLdap = true;
@PostConstruct
public void init() {
this.isActive = new AtomicBoolean(true);
try {
this.persistenceConfiguration = persistanceFactoryService.loadPersistenceConfiguration(LDAP_PROPERTIES_FILE);
loadBaseConfiguration();
this.confDir = confDir();
this.configFilePath = confDir + CONFIG_FILE_NAME;
this.errorsFilePath = confDir + ERRORS_FILE_NAME;
this.staticConfFilePath = confDir + STATIC_CONF_FILE_NAME;
String certsDir = this.baseConfiguration.getString("certsDir");
if (StringHelper.isEmpty(certsDir)) {
certsDir = confDir;
}
this.webKeysFilePath = certsDir + File.separator + WEB_KEYS_FILE_NAME;
this.saltFilePath = confDir + SALT_FILE_NAME;
loadCryptoConfigurationSalt();
} finally {
this.isActive.set(false);
}
}
public void onServletContextActivation(@Observes ServletContext context ) {
this.contextPath = context.getContextPath();
this.facesMapping = "";
ServletRegistration servletRegistration = context.getServletRegistration("Faces Servlet");
if (servletRegistration == null) {
return;
}
String[] mappings = servletRegistration.getMappings().toArray(new String[0]);
if (mappings.length == 0) {
return;
}
this.facesMapping = mappings[0].replaceAll("\\*", "");
}
public void create() {
if (!createFromLdap(true)) {
log.error("Failed to load configuration from LDAP. Please fix it!!!.");
throw new ConfigurationException("Failed to load configuration from LDAP.");
} else {
log.info("Configuration loaded successfully.");
}
}
public void initTimer() {
log.debug("Initializing Configuration Timer");
final int delay = 30;
final int interval = DEFAULT_INTERVAL;
timerEvent.fire(new TimerEvent(new TimerSchedule(delay, interval), new ConfigurationEvent(),
Scheduled.Literal.INSTANCE));
}
@Asynchronous
public void reloadConfigurationTimerEvent(@Observes @Scheduled ConfigurationEvent configurationEvent) {
if (this.isActive.get()) {
return;
}
if (!this.isActive.compareAndSet(false, true)) {
return;
}
try {
reloadConfiguration();
} catch (Throwable ex) {
log.error("Exception happened while reloading application configuration", ex);
} finally {
this.isActive.set(false);
}
}
private void reloadConfiguration() {
// Reload LDAP configuration if needed
PersistenceConfiguration newPersistenceConfiguration = persistanceFactoryService.loadPersistenceConfiguration(LDAP_PROPERTIES_FILE);
if (newPersistenceConfiguration != null) {
if (!StringHelper.equalsIgnoreCase(this.persistenceConfiguration.getFileName(), newPersistenceConfiguration.getFileName()) || (newPersistenceConfiguration.getLastModifiedTime() > this.persistenceConfiguration.getLastModifiedTime())) {
// Reload configuration only if it was modified
this.persistenceConfiguration = newPersistenceConfiguration;
event.select(LdapConfigurationReload.Literal.INSTANCE).fire(PERSISTENCE_CONFIGUARION_RELOAD_EVENT_TYPE);
}
}
// Reload Base configuration if needed
File baseConfiguration = new File(BASE_PROPERTIES_FILE);
if (baseConfiguration.exists()) {
final long lastModified = baseConfiguration.lastModified();
if (lastModified > baseConfigurationFileLastModifiedTime) {
// Reload configuration only if it was modified
loadBaseConfiguration();
event.select(BaseConfigurationReload.Literal.INSTANCE).fire(BASE_CONFIGUARION_RELOAD_EVENT_TYPE);
}
}
if (!loadedFromLdap) {
return;
}
if (!isRevisionIncreased()) {
return;
}
createFromLdap(false);
}
private boolean isRevisionIncreased() {
final Conf conf = loadConfigurationFromLdap("oxRevision");
if (conf == null) {
return false;
}
log.trace("LDAP revision: " + conf.getRevision() + ", server revision:" + loadedRevision);
return conf.getRevision() > this.loadedRevision;
}
private String confDir() {
final String confDir = this.baseConfiguration.getString("confDir", null);
if (StringUtils.isNotBlank(confDir)) {
return confDir;
}
return DIR;
}
public FileConfiguration getBaseConfiguration() {
return baseConfiguration;
}
@Produces
@ApplicationScoped
public PersistenceConfiguration getPersistenceConfiguration() {
return persistenceConfiguration;
}
@Produces
@ApplicationScoped
public AppConfiguration getAppConfiguration() {
return conf;
}
@Produces
@ApplicationScoped
public StaticConfiguration getStaticConfiguration() {
return staticConf;
}
@Produces
@ApplicationScoped
public WebKeysConfiguration getWebKeysConfiguration() {
return jwks;
}
@Produces
@ApplicationScoped
public ErrorResponseFactory getErrorResponseFactory() {
return errorResponseFactory;
}
public BaseDnConfiguration getBaseDn() {
return getStaticConfiguration().getBaseDn();
}
public String getCryptoConfigurationSalt() {
return cryptoConfigurationSalt;
}
private boolean createFromFile() {
boolean result = reloadConfFromFile() && reloadErrorsFromFile() && reloadStaticConfFromFile()
&& reloadWebkeyFromFile();
return result;
}
private boolean reloadWebkeyFromFile() {
final WebKeysConfiguration webKeysFromFile = loadWebKeysFromFile();
if (webKeysFromFile != null) {
log.info("Reloaded web keys from file: " + webKeysFilePath);
jwks = webKeysFromFile;
return true;
} else {
log.error("Failed to load web keys configuration from file: " + webKeysFilePath);
}
return false;
}
private boolean reloadStaticConfFromFile() {
final StaticConfiguration staticConfFromFile = loadStaticConfFromFile();
if (staticConfFromFile != null) {
log.info("Reloaded static conf from file: " + staticConfFilePath);
staticConf = staticConfFromFile;
return true;
} else {
log.error("Failed to load static configuration from file: " + staticConfFilePath);
}
return false;
}
private boolean reloadErrorsFromFile() {
final ErrorMessages errorsFromFile = loadErrorsFromFile();
if (errorsFromFile != null) {
log.info("Reloaded errors from file: " + errorsFilePath);
errorResponseFactory = new ErrorResponseFactory(errorsFromFile, conf);
return true;
} else {
log.error("Failed to load errors from file: " + errorsFilePath);
}
return false;
}
private boolean reloadConfFromFile() {
final AppConfiguration configFromFile = loadConfFromFile();
if (configFromFile != null) {
log.info("Reloaded configuration from file: " + configFilePath);
conf = configFromFile;
return true;
} else {
log.error("Failed to load configuration from file: " + configFilePath);
}
return false;
}
public boolean reloadConfFromLdap() {
if (!isRevisionIncreased()) {
return false;
}
return createFromLdap(false);
}
private boolean createFromLdap(boolean recoverFromFiles) {
log.info("Loading configuration from '{}' DB...", baseConfiguration.getString("persistence.type"));
try {
final Conf c = loadConfigurationFromLdap();
if (c != null) {
init(c);
// Destroy old configuration
if (this.loaded) {
destroy(AppConfiguration.class);
destroy(StaticConfiguration.class);
destroy(WebKeysConfiguration.class);
destroy(ErrorResponseFactory.class);
}
this.loaded = true;
configurationUpdateEvent.select(ConfigurationUpdate.Literal.INSTANCE).fire(conf);
destroyCryptoProviderInstance();
AbstractCryptoProvider newAbstractCryptoProvider = abstractCryptoProviderInstance.get();
cryptoProviderEvent.select(CryptoProviderEvent.Literal.INSTANCE).fire(newAbstractCryptoProvider);
return true;
}
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
if (recoverFromFiles) {
log.info("Unable to find configuration in LDAP, try to load configuration from file system... ");
if (createFromFile()) {
this.loadedFromLdap = false;
return true;
}
}
return false;
}
public void destroy(Class<? extends Configuration> clazz) {
Instance<? extends Configuration> confInstance = configurationInstance.select(clazz);
configurationInstance.destroy(confInstance.get());
}
private void destroyCryptoProviderInstance() {
log.trace("Destroyed crypto provider instance.");
AbstractCryptoProvider abstractCryptoProvider = abstractCryptoProviderInstance.get();
abstractCryptoProviderInstance.destroy(abstractCryptoProvider);
CryptoProviderFactory.reset();
}
private Conf loadConfigurationFromLdap(String... returnAttributes) {
final PersistenceEntryManager ldapManager = persistenceEntryManagerInstance.get();
final String dn = this.baseConfiguration.getString("oxauth_ConfigurationEntryDN");
try {
final Conf conf = ldapManager.find(dn, Conf.class, returnAttributes);
return conf;
} catch (BasePersistenceException ex) {
ex.printStackTrace();
log.error(ex.getMessage());
}
return null;
}
private void init(Conf p_conf) {
initConfigurationConf(p_conf);
this.loadedRevision = p_conf.getRevision();
}
private void initConfigurationConf(Conf p_conf) {
if (p_conf.getDynamic() != null) {
conf = p_conf.getDynamic();
}
if (p_conf.getStatics() != null) {
staticConf = p_conf.getStatics();
}
if (p_conf.getWebKeys() != null) {
jwks = p_conf.getWebKeys();
} else {
generateWebKeys();
}
if (p_conf.getErrors() != null) {
errorResponseFactory = new ErrorResponseFactory(p_conf.getErrors(), p_conf.getDynamic());
}
}
private void generateWebKeys() {
log.info("Failed to load JWKS. Attempting to generate new JWKS...");
String newWebKeys = null;
try {
final AbstractCryptoProvider cryptoProvider = CryptoProviderFactory.getCryptoProvider(getAppConfiguration());
// Generate new JWKS
JSONObject jsonObject = AbstractCryptoProvider.generateJwks(cryptoProvider, getAppConfiguration());
newWebKeys = jsonObject.toString();
// Attempt to load new JWKS
jwks = ServerUtil.createJsonMapper().readValue(newWebKeys, WebKeysConfiguration.class);
// Store new JWKS in LDAP
Conf conf = loadConfigurationFromLdap();
conf.setWebKeys(jwks);
long nextRevision = conf.getRevision() + 1;
conf.setRevision(nextRevision);
final PersistenceEntryManager ldapManager = persistenceEntryManagerInstance.get();
ldapManager.merge(conf);
log.info("Generated new JWKS successfully.");
log.trace("JWKS keys: " + conf.getWebKeys().getKeys().stream().map(JSONWebKey::getKid).collect(Collectors.toList()));
log.trace("KeyStore keys: " + cryptoProvider.getKeys());
} catch (Exception ex2) {
log.error("Failed to re-generate JWKS keys", ex2);
}
}
private AppConfiguration loadConfFromFile() {
try {
return ServerUtil.createJsonMapper().readValue(new File(configFilePath), AppConfiguration.class);
} catch (Exception e) {
log.warn(e.getMessage(), e);
}
return null;
}
private ErrorMessages loadErrorsFromFile() {
try {
return ServerUtil.createJsonMapper().readValue(new File(errorsFilePath), ErrorMessages.class);
} catch (Exception e) {
log.warn(e.getMessage(), e);
}
return null;
}
private StaticConfiguration loadStaticConfFromFile() {
try {
return ServerUtil.createJsonMapper().readValue(new File(staticConfFilePath), StaticConfiguration.class);
} catch (Exception e) {
log.warn(e.getMessage(), e);
}
return null;
}
private WebKeysConfiguration loadWebKeysFromFile() {
try {
return ServerUtil.createJsonMapper().readValue(new File(webKeysFilePath), WebKeysConfiguration.class);
} catch (Exception e) {
log.warn(e.getMessage(), e);
}
return null;
}
private void loadBaseConfiguration() {
this.baseConfiguration = createFileConfiguration(BASE_PROPERTIES_FILE, true);
File baseConfiguration = new File(BASE_PROPERTIES_FILE);
this.baseConfigurationFileLastModifiedTime = baseConfiguration.lastModified();
}
public void loadCryptoConfigurationSalt() {
try {
FileConfiguration cryptoConfiguration = createFileConfiguration(saltFilePath, true);
this.cryptoConfigurationSalt = cryptoConfiguration.getString("encodeSalt");
} catch (Exception ex) {
log.error("Failed to load configuration from {}", saltFilePath, ex);
throw new ConfigurationException("Failed to load configuration from " + saltFilePath, ex);
}
}
private FileConfiguration createFileConfiguration(String fileName, boolean isMandatory) {
try {
FileConfiguration fileConfiguration = new FileConfiguration(fileName);
return fileConfiguration;
} catch (Exception ex) {
if (isMandatory) {
log.error("Failed to load configuration from {}", fileName, ex);
throw new ConfigurationException("Failed to load configuration from " + fileName, ex);
}
}
return null;
}
public String getFacesMapping() {
return facesMapping;
}
public String getContextPath() {
return contextPath;
}
}
| |
// Copyright (c) 2003 Compaq Corporation. All rights reserved.
// Last modified on Wed Oct 17 15:23:57 PDT 2001 by yuanyu
package util;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import tlc2.output.EC;
/** A <code>BufferedDataInputStream</code> is an optimized
combination of a <code>java.io.BufferedInputStream</code>
and a <code>java.io.DataInputStream</code>. It also provides
an <code>atEOF</code> method for detecting end-of-file.<P>
For efficiency, <code>BufferedDataInputStream</code>s are
unmonitored. Hence, it is the client's responsibility to lock
the stream before using it. This requirement is denoted in
the comments of this class by the specification
<TT>REQUIRES LL = SELF</TT>. */
public final class BufferedDataInputStream extends FilterInputStream implements IDataInputStream {
/* protected by SELF */
private byte[] buff; /* buffer of bytes to read */
private int len; /* number of valid bytes in "buff" */
private int curr; /* position of next byte to return */
private byte[] temp; /* temporary array used by various methods */
/* Object invariants:
this.out == null <==> ``stream is closed''
this.buff != null && 0 < this.buff.length
this.len != 0
this.len > 0 <==> 0 <= this.curr < this.len <= this.buff.length
this.len < 0 <==> ``read EOF from underlying stream''
this.temp != null && this.temp.length >= 8
*/
/** Initialize this input stream. The stream will be closed
initially; use the <code>open</code> method below to
open it on an underlying <code>InputStream</code>. */
public BufferedDataInputStream() {
super(null);
this.initFields();
}
/** Open this input stream on the underlying stream <code>is</code>. */
public BufferedDataInputStream(InputStream is) throws IOException {
super(is);
this.initFields();
this.len = this.in.read(this.buff);
Assert.check(this.len != 0, EC.SYSTEM_STREAM_EMPTY);
}
/** Open this input stream on the underlying input stream
<code>new FileInputStream(name)</code>. */
public BufferedDataInputStream(String name) throws IOException {
this(new FileInputStream(name));
}
/** Open this input stream on the underlying input stream
<code>new FileOutputStream(file)</code>. */
public BufferedDataInputStream(File file) throws IOException {
this(new FileInputStream(file));
}
private void initFields() {
this.buff = new byte[8192];
this.curr = 0;
this.temp = new byte[8];
}
/** REQUIRES LL = SELF */
/** Re-open this input stream on <code>is</code>. This method need
not be called on a newly initialized stream, but it can be called
after the stream has been closed to re-open the stream on a
different underlying stream without requiring internal resources
to be re-allocated. */
public void open(InputStream is) throws IOException {
Assert.check(this.in == null, EC.SYSTEM_STREAM_EMPTY);
this.in = is;
this.len = this.in.read(this.buff);
Assert.check(this.len != 0, EC.SYSTEM_STREAM_EMPTY);
}
/** Equivalent to <code>this.open(new FileInputStream(name))</code>. */
public void open(String name) throws IOException {
this.open(new FileInputStream(name));
}
/** REQUIRES LL = SELF */
/** Closes this stream and its underlying stream. */
public void close() throws IOException {
this.in.close();
this.in = null;
}
/** REQUIRES LL = SELF */
/** Returns <code>true</code> iff the stream is exhausted. */
public final boolean atEOF() {
return (this.len < 0);
}
/** REQUIRES LL = SELF */
/** Reads up to <code>b.length</code> bytes into <code>b</code>,
and returns the number of bytes read, or -1 if the stream is
exhausted on entry. */
public final int read(byte[] b) throws IOException {
return this.read(b, 0, b.length);
}
/** REQUIRES LL = SELF */
/** Reads up to <code>n</code> bytes into <code>b</code> starting
at position <code>off</code>, and returns the number of bytes
read, or -1 if the stream is exhausted on entry. */
public final int read(byte[] b, int off, int n) throws IOException {
if (this.len < 0) return -1;
int offInit = off;
while (n > 0 && this.len > 0) {
int toCopy = Math.min(n, this.len - this.curr);
System.arraycopy(this.buff, this.curr, b, off, toCopy);
this.curr += toCopy; off += toCopy; n -= toCopy;
if (this.curr == this.len) {
// refill buffer from underlying input stream
this.len = this.in.read(this.buff);
Assert.check(this.len != 0, EC.SYSTEM_STREAM_EMPTY);
this.curr = 0;
}
}
return off - offInit;
}
/** REQUIRES LL = SELF */
/** Reads <code>b.length</code> bytes into <code>b</code>, or
throws <code>EOFException</code> if the stream contains fewer
than <code>b.length</code> bytes. */
public final void readFully(byte[] b) throws IOException, EOFException {
this.readFully(b, 0, b.length);
}
/** REQUIRES LL = SELF */
/** Reads <code>n</code> bytes into <code>b</code> starting at
position <code>off</code>, or throws <code>EOFException</code>
if the stream contains fewer than <code>n</code> bytes. */
public final void readFully(byte[] b, int off, int n)
throws IOException, EOFException {
while (n > 0) {
int numRead = this.read(b, off, n);
if (numRead < 0) throw new EOFException();
off += numRead; n -= numRead;
}
}
/** REQUIRES LL = SELF */
/** Reads and returns the next byte of this stream, or throws
<code>EOFException</code> if the stream is exhausted. */
public final byte readByte() throws IOException, EOFException {
if (this.len < 0) throw new EOFException();
byte res = this.buff[this.curr++];
if (this.curr == this.len) {
// refill buffer from underlying input stream
this.len = this.in.read(this.buff);
Assert.check(this.len != 0, EC.SYSTEM_STREAM_EMPTY);
this.curr = 0;
}
return res;
}
/** REQUIRES LL = SELF */
/** Reads and returns the next <code>boolean</code> value
encoded in the next byte of this stream, or
throws <code>EOFException</code> if the stream is
exhausted. */
public final boolean readBoolean() throws IOException, EOFException {
return (this.readByte() != 0);
}
/** REQUIRES LL = SELF */
/** Read and return the next <code>short</code> value
encoded in the next two bytes of this stream, or
throw <code>EOFException</code> if the stream contains
fewer than two bytes. */
public final short readShort() throws IOException, EOFException {
this.readFully(this.temp, 0, 2);
return (short) ((temp[0] << 8) | (temp[1] & 0xff));
}
/** REQUIRES LL = SELF */
/** Reads and returns the next <code>int</code> value
encoded in the next four bytes of this stream, or
throws <code>EOFException</code> if the stream contains
fewer than four bytes. */
public final int readInt() throws IOException, EOFException {
this.readFully(this.temp, 0, 4);
int res = temp[0];
res <<= 8; res |= (temp[1] & 0xff);
res <<= 8; res |= (temp[2] & 0xff);
res <<= 8; res |= (temp[3] & 0xff);
return res;
}
/** REQUIRES LL = SELF */
/** Reads and returns the next <code>long</code> value
encoded in the next eight bytes of this stream, or
throws <code>EOFException</code> if the stream contains
fewer than eight bytes. */
public final long readLong() throws IOException, EOFException {
this.readFully(this.temp, 0, 8);
long res = temp[0];
res <<= 8; res |= (temp[1] & 0xff);
res <<= 8; res |= (temp[2] & 0xff);
res <<= 8; res |= (temp[3] & 0xff);
res <<= 8; res |= (temp[4] & 0xff);
res <<= 8; res |= (temp[5] & 0xff);
res <<= 8; res |= (temp[6] & 0xff);
res <<= 8; res |= (temp[7] & 0xff);
return res;
}
/** REQUIRES LL = SELF */
/** Reads and returns the next line of text from this stream, or
<code>null</code> if the stream is exhausted. Any end-of-line
character(s) are not included in the result. A line is termined
by a carriage return character (<code>'\r'</code>), a newline
character (<code>'\n'</code>), a carriage return immediately
followed by a newline, or by the end of the stream. */
public final String readLine() throws IOException {
String res = null;
while (this.len > 0) {
for (int i = this.curr; i < this.len; i++) {
if (this.buff[i] == (byte)'\n' || this.buff[i] == (byte)'\r') {
// remember EOL character
byte eol = this.buff[i];
// create new substring
String s = new String(this.buff, /*offset=*/ this.curr,
/*count=*/ i - this.curr);
if (res == null) res = s; else res += s;
// skip over bytes in stream
this.skip(i + 1 - this.curr);
// skip '\n' if it follows '\r'
if (eol == (byte)'\r' && this.len > 0
&& this.buff[this.curr] == (byte)'\n') {
this.readByte();
}
return res;
}
}
// hit end of buffer -- append rest of buffer to "res"
String s = new String(this.buff, /*offset=*/ this.curr,
/*count=*/ this.len - this.curr);
if (res == null) res = s; else res += s;
// skip over bytes in stream
this.skip(this.len - this.curr);
}
// hit EOF without seeing EOL chars
return res;
}
public final String readString(int n) throws IOException {
char[] b = new char[n];
int off = 0;
while (n > 0) {
if (this.len < 0) throw new EOFException();
int offInit = off;
while (n > 0 && this.len > 0) {
int toCopy = Math.min(n, this.len - this.curr);
for (int i = 0; i < toCopy; i++) {
b[off+i] = (char)this.buff[this.curr+i];
}
this.curr += toCopy; off += toCopy; n -= toCopy;
if (this.curr == this.len) {
// refill buffer from underlying input stream
this.len = this.in.read(this.buff);
Assert.check(this.len != 0, EC.SYSTEM_STREAM_EMPTY);
this.curr = 0;
}
}
int numRead = off - offInit;
off += numRead; n -= numRead;
}
return new String(b);
}
/** REQUIRES LL = SELF */
/** Skips over the next <code>n</code> bytes in this stream,
or throws <code>EOFException</code> if it contains fewer
than <code>n</code> bytes. */
public final void skip(int n) throws IOException, EOFException {
while (this.len > 0 && this.curr + n >= this.len) {
n -= (this.len - this.curr);
// refill buffer from underlying input stream
this.len = this.in.read(this.buff);
Assert.check(this.len != 0, EC.SYSTEM_STREAM_EMPTY);
this.curr = 0;
}
if (n > 0 && this.len < 0) throw new EOFException();
this.curr += n;
Assert.check(this.len < 0 || this.curr < this.len, EC.SYSTEM_INDEX_ERROR);
}
}
| |
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.spongepowered.asm.mixin.transformer.ext.extensions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.spongepowered.asm.logging.ILogger;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.transformer.ClassInfo;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.ClassInfo.SearchType;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Traversal;
import org.spongepowered.asm.mixin.transformer.ext.IExtension;
import org.spongepowered.asm.mixin.transformer.ext.ITargetClassContext;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.SignaturePrinter;
import com.google.common.base.Charsets;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.Files;
/**
* Checks whether interfaces declared on mixin target classes are actually fully
* implemented and generates reports to the console and to files on disk
*/
public class ExtensionCheckInterfaces implements IExtension {
private static final String AUDIT_DIR = "audit";
private static final String IMPL_REPORT_FILENAME = "mixin_implementation_report";
private static final String IMPL_REPORT_CSV_FILENAME = ExtensionCheckInterfaces.IMPL_REPORT_FILENAME + ".csv";
private static final String IMPL_REPORT_TXT_FILENAME = ExtensionCheckInterfaces.IMPL_REPORT_FILENAME + ".txt";
private static final ILogger logger = MixinService.getService().getLogger("mixin");
/**
* CSV Report file
*/
private final File csv;
/**
* Text Report file
*/
private final File report;
/**
* Methods from interfaces that are already in the class before mixins are
* applied.
*/
private final Multimap<ClassInfo, Method> interfaceMethods = HashMultimap.create();
/**
* Strict mode
*/
private boolean strict;
/**
* True once the output dir and csv have been created, not triggered until
* something is written
*/
private boolean started = false;
public ExtensionCheckInterfaces() {
File debugOutputFolder = new File(Constants.DEBUG_OUTPUT_DIR, ExtensionCheckInterfaces.AUDIT_DIR);
this.csv = new File(debugOutputFolder, ExtensionCheckInterfaces.IMPL_REPORT_CSV_FILENAME);
this.report = new File(debugOutputFolder, ExtensionCheckInterfaces.IMPL_REPORT_TXT_FILENAME);
}
/**
* Delayed creation of CSV so the dir doesn't get created when the extension
* is inactive
*/
private void start() {
if (this.started) {
return;
}
this.started = true;
this.csv.getParentFile().mkdirs();
try {
Files.write("Class,Method,Signature,Interface\n", this.csv, Charsets.ISO_8859_1);
} catch (IOException ex) {
// well this sucks
}
try {
String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Files.write("Mixin Implementation Report generated on " + dateTime + "\n", this.report, Charsets.ISO_8859_1);
} catch (IOException ex) {
// hmm :(
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.ext.IExtension#checkActive(
* org.spongepowered.asm.mixin.MixinEnvironment)
*/
@Override
public boolean checkActive(MixinEnvironment environment) {
this.strict = environment.getOption(Option.CHECK_IMPLEMENTS_STRICT);
return environment.getOption(Option.CHECK_IMPLEMENTS);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.IMixinTransformerModule
* #preApply(org.spongepowered.asm.mixin.transformer.TargetClassContext)
*/
@Override
public void preApply(ITargetClassContext context) {
ClassInfo targetClassInfo = context.getClassInfo();
for (Method m : targetClassInfo.getInterfaceMethods(false)) {
this.interfaceMethods.put(targetClassInfo, m);
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.IMixinTransformerModule
* #postApply(org.spongepowered.asm.mixin.transformer.TargetClassContext)
*/
@Override
public void postApply(ITargetClassContext context) {
this.start();
ClassInfo targetClassInfo = context.getClassInfo();
// If the target is abstract and strict mode is not enabled, skip this class
if (targetClassInfo.isAbstract() && !this.strict) {
ExtensionCheckInterfaces.logger.info("{} is skipping abstract target {}", this.getClass().getSimpleName(), context);
return;
}
String className = targetClassInfo.getName().replace('/', '.');
int missingMethodCount = 0;
PrettyPrinter printer = new PrettyPrinter();
printer.add("Class: %s", className).hr();
printer.add("%-32s %-47s %s", "Return Type", "Missing Method", "From Interface").hr();
Set<Method> interfaceMethods = targetClassInfo.getInterfaceMethods(true);
Set<Method> implementedMethods = new HashSet<Method>(targetClassInfo.getSuperClass().getInterfaceMethods(true));
implementedMethods.addAll(this.interfaceMethods.removeAll(targetClassInfo));
for (Method method : interfaceMethods) {
Method found = targetClassInfo.findMethodInHierarchy(method.getName(), method.getDesc(), SearchType.ALL_CLASSES, Traversal.ALL);
// If method IS found and IS implemented, then do nothing (don't print an error)
if (found != null && !found.isAbstract()) {
continue;
}
// Don't blame the subclass for not implementing methods that it does not need to implement.
if (implementedMethods.contains(method)) {
continue;
}
if (missingMethodCount > 0) {
printer.add();
}
SignaturePrinter signaturePrinter = new SignaturePrinter(method.getName(), method.getDesc()).setModifiers("");
String iface = method.getOwner().getName().replace('/', '.');
missingMethodCount++;
printer.add("%-32s%s", signaturePrinter.getReturnType(), signaturePrinter);
printer.add("%-80s %s", "", iface);
this.appendToCSVReport(className, method, iface);
}
if (missingMethodCount > 0) {
printer.hr().add("%82s%s: %d", "", "Total unimplemented", missingMethodCount);
printer.print(System.err);
this.appendToTextReport(printer);
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.ext.IExtension
* #export(org.spongepowered.asm.mixin.MixinEnvironment,
* java.lang.String, boolean, org.objectweb.asm.tree.ClassNode)
*/
@Override
public void export(MixinEnvironment env, String name, boolean force, ClassNode classNode) {
}
private void appendToCSVReport(String className, Method method, String iface) {
try {
Files.append(String.format("%s,%s,%s,%s\n", className, method.getName(), method.getDesc(), iface), this.csv, Charsets.ISO_8859_1);
} catch (IOException ex) {
// Not the end of the world
}
}
private void appendToTextReport(PrettyPrinter printer) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(this.report, true);
PrintStream stream = new PrintStream(fos);
stream.print("\n");
printer.print(stream);
} catch (Exception ex) {
// never mind
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ex) {
ExtensionCheckInterfaces.logger.catching(ex);
}
}
}
}
}
| |
/*
* =========================================================================
* Copyright (c) 2002-2014 Pivotal Software, Inc. All Rights Reserved.
* This product is protected by U.S. and international copyright
* and intellectual property laws. Pivotal products are covered by
* more patents listed at http://www.pivotal.io/patents.
* ========================================================================
*/
package com.gemstone.gemfire.management.internal.cli.commands;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyStore;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.ExitShellRequest;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.internal.ClassPathLoader;
import com.gemstone.gemfire.internal.DSFIDFactory;
import com.gemstone.gemfire.internal.lang.Initializer;
import com.gemstone.gemfire.internal.lang.StringUtils;
import com.gemstone.gemfire.internal.lang.SystemUtils;
import com.gemstone.gemfire.internal.util.IOUtils;
import com.gemstone.gemfire.internal.util.PasswordUtil;
import com.gemstone.gemfire.management.cli.CliMetaData;
import com.gemstone.gemfire.management.cli.ConverterHint;
import com.gemstone.gemfire.management.cli.Result;
import com.gemstone.gemfire.management.internal.JmxManagerLocatorRequest;
import com.gemstone.gemfire.management.internal.JmxManagerLocatorResponse;
import com.gemstone.gemfire.management.internal.SSLUtil;
import com.gemstone.gemfire.management.internal.cli.CliUtil;
import com.gemstone.gemfire.management.internal.cli.GfshParser;
import com.gemstone.gemfire.management.internal.cli.LogWrapper;
import com.gemstone.gemfire.management.internal.cli.annotation.CliArgument;
import com.gemstone.gemfire.management.internal.cli.converters.ConnectionEndpointConverter;
import com.gemstone.gemfire.management.internal.cli.domain.ConnectToLocatorResult;
import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
import com.gemstone.gemfire.management.internal.cli.result.ErrorResultData;
import com.gemstone.gemfire.management.internal.cli.result.InfoResultData;
import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
import com.gemstone.gemfire.management.internal.cli.shell.JMXConnectionException;
import com.gemstone.gemfire.management.internal.cli.shell.JmxOperationInvoker;
import com.gemstone.gemfire.management.internal.cli.shell.OperationInvoker;
import com.gemstone.gemfire.management.internal.cli.shell.jline.GfshHistory;
import com.gemstone.gemfire.management.internal.cli.util.CauseFinder;
import com.gemstone.gemfire.management.internal.cli.util.ConnectionEndpoint;
import com.gemstone.gemfire.management.internal.web.domain.LinkIndex;
import com.gemstone.gemfire.management.internal.web.http.support.SimpleHttpRequester;
import com.gemstone.gemfire.management.internal.web.shell.HttpOperationInvoker;
import com.gemstone.gemfire.management.internal.web.shell.RestHttpOperationInvoker;
/**
* @author Abhishek Chaudhari
*
* @since 7.0
*/
public class ShellCommands implements CommandMarker {
private Gfsh getGfsh() {
return Gfsh.getCurrentInstance();
}
@CliCommand(value = { CliStrings.EXIT, "quit" }, help = CliStrings.EXIT__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH})
public ExitShellRequest exit() throws IOException {
Gfsh gfshInstance = getGfsh();
gfshInstance.stop();
ExitShellRequest exitShellRequest = gfshInstance.getExitShellRequest();
if (exitShellRequest == null) {
// shouldn't really happen, but we'll fallback to this anyway
exitShellRequest = ExitShellRequest.NORMAL_EXIT;
}
return exitShellRequest;
}
// millis that connect --locator will wait for a response from the locator.
private final static int CONNECT_LOCATOR_TIMEOUT_MS = 60000; // see bug 45971
public static int getConnectLocatorTimeoutInMS() {
return ShellCommands.CONNECT_LOCATOR_TIMEOUT_MS;
}
@CliCommand(value = { CliStrings.CONNECT }, help = CliStrings.CONNECT__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_JMX, CliStrings.TOPIC_GEMFIRE_MANAGER})
public Result connect(
@CliOption(key = { CliStrings.CONNECT__LOCATOR },
unspecifiedDefaultValue = ConnectionEndpointConverter.DEFAULT_LOCATOR_ENDPOINTS,
optionContext = ConnectionEndpoint.LOCATOR_OPTION_CONTEXT,
help = CliStrings.CONNECT__LOCATOR__HELP) ConnectionEndpoint locatorTcpHostPort,
@CliOption(key = { CliStrings.CONNECT__JMX_MANAGER },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
optionContext = ConnectionEndpoint.JMXMANAGER_OPTION_CONTEXT,
help = CliStrings.CONNECT__JMX_MANAGER__HELP) ConnectionEndpoint memberRmiHostPort,
@CliOption(key = { CliStrings.CONNECT__USE_HTTP },
mandatory = false,
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.CONNECT__USE_HTTP__HELP) boolean useHttp,
@CliOption(key = { CliStrings.CONNECT__URL },
mandatory = false,
unspecifiedDefaultValue = CliStrings.CONNECT__DEFAULT_BASE_URL,
help = CliStrings.CONNECT__URL__HELP) String url,
@CliOption(key = { CliStrings.CONNECT__USERNAME },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__USERNAME__HELP) String userName,
@CliOption(key = { CliStrings.CONNECT__PASSWORD },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__PASSWORD__HELP) String password,
@CliOption(key = { CliStrings.CONNECT__KEY_STORE },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__KEY_STORE__HELP) String keystore,
@CliOption(key = { CliStrings.CONNECT__KEY_STORE_PASSWORD },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__KEY_STORE_PASSWORD__HELP) String keystorePassword,
@CliOption(key = { CliStrings.CONNECT__TRUST_STORE },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__TRUST_STORE__HELP) String truststore,
@CliOption(key = { CliStrings.CONNECT__TRUST_STORE_PASSWORD },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__TRUST_STORE_PASSWORD__HELP) String truststorePassword,
@CliOption(key = { CliStrings.CONNECT__SSL_CIPHERS },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__SSL_CIPHERS__HELP) String sslCiphers,
@CliOption(key = { CliStrings.CONNECT__SSL_PROTOCOLS },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__SSL_PROTOCOLS__HELP) String sslProtocols,
@CliOption(key = CliStrings.CONNECT__SECURITY_PROPERTIES,
optionContext = ConverterHint.FILE_PATHSTRING,
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__SECURITY_PROPERTIES__HELP) final String gfSecurityPropertiesPath,
@CliOption(key = { CliStrings.CONNECT__USE_SSL },
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.CONNECT__USE_SSL__HELP) final boolean useSsl)
{
Result result;
String passwordToUse = password;
String keystoreToUse = keystore;
String keystorePasswordToUse = keystorePassword;
String truststoreToUse = truststore;
String truststorePasswordToUse = truststorePassword;
String sslCiphersToUse = sslCiphers;
String sslProtocolsToUse = sslProtocols;
// TODO shouldn't the condition be (getGfsh() != null && getGfsh().isConnectedAndReady())?
// otherwise, we have potential NullPointerException on the line with getGfsh().getOperationInvoker()
//if (getGfsh() == null || getGfsh().isConnectedAndReady()) {
if (getGfsh() != null && getGfsh().isConnectedAndReady()) {
try {
result = ResultBuilder.createInfoResult("Already connected to: " + getGfsh().getOperationInvoker().toString());
} catch (Exception e) {
result = ResultBuilder.buildResult(ResultBuilder.createErrorResultData().setErrorCode(
ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage()));
}
} else if (useHttp) {
try{
final Map<String, String> sslConfigProps = this.readSSLConfiguration(useSsl, keystoreToUse,keystorePasswordToUse,
truststoreToUse, truststorePasswordToUse, sslCiphersToUse, sslProtocolsToUse, gfSecurityPropertiesPath);
if (useSsl) {
configureHttpsURLConnection(sslConfigProps);
if (url.startsWith("http:")) {
url = url.replace("http:", "https:");
}
}
LogWrapper.getInstance().warning(String.format("Sending HTTP request for Link Index at (%1$s)...", url.concat("/index")));
LinkIndex linkIndex = new SimpleHttpRequester(CONNECT_LOCATOR_TIMEOUT_MS).get(url.concat("/index"), LinkIndex.class);
LogWrapper.getInstance().warning(String.format("Received Link Index (%1$s)", linkIndex.toString()));
Gfsh gemfireShell = getGfsh();
HttpOperationInvoker operationInvoker = new RestHttpOperationInvoker(linkIndex, gemfireShell, url);
Initializer.init(operationInvoker);
gemfireShell.setOperationInvoker(operationInvoker);
LogWrapper.getInstance().info(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, operationInvoker.toString()));
Gfsh.redirectInternalJavaLoggers();
result = ResultBuilder.createInfoResult(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, operationInvoker.toString()));
} catch (IOException ioe) {
String errorMessage = ioe.getMessage();
result = ResultBuilder.createConnectionErrorResult(errorMessage);
ioe.printStackTrace();
} catch (Exception e) {
String errorMessage = e.getMessage();
result = ResultBuilder.createConnectionErrorResult(errorMessage);
e.printStackTrace();
}
} else {
boolean isConnectingViaLocator = false;
InfoResultData infoResultData = ResultBuilder.createInfoResultData();
ConnectionEndpoint hostPortToConnect = null;
try {
Gfsh gfshInstance = getGfsh();
// JMX Authentication Config
if (userName != null && userName.length() > 0) {
if (passwordToUse == null || passwordToUse.length() == 0) {
passwordToUse = gfshInstance.readWithMask("jmx password: ", '*');
}
if (passwordToUse == null || passwordToUse.length() == 0) {
throw new IllegalArgumentException(CliStrings.CONNECT__MSG__JMX_PASSWORD_MUST_BE_SPECIFIED);
}
}
final Map<String, String> sslConfigProps = this.readSSLConfiguration(useSsl, keystoreToUse,keystorePasswordToUse,
truststoreToUse, truststorePasswordToUse, sslCiphersToUse, sslProtocolsToUse, gfSecurityPropertiesPath);
if (memberRmiHostPort != null) {
hostPortToConnect = memberRmiHostPort;
Gfsh.println(CliStrings.format(CliStrings.CONNECT__MSG__CONNECTING_TO_MANAGER_AT_0, new Object[] {memberRmiHostPort.toString(false)}));
} else {
isConnectingViaLocator = true;
hostPortToConnect = locatorTcpHostPort;
Gfsh.println(CliStrings.format(CliStrings.CONNECT__MSG__CONNECTING_TO_LOCATOR_AT_0, new Object[] {locatorTcpHostPort.toString(false)}));
// Props required to configure a SocketCreator with SSL.
// Used for gfsh->locator connection & not needed for gfsh->manager connection
if (useSsl || !sslConfigProps.isEmpty()) {
//Fix for 51266 : Added an check for cluster-ssl-enabled proeprty
if(!sslConfigProps.containsKey(DistributionConfig.CLUSTER_SSL_ENABLED_NAME))
sslConfigProps.put(DistributionConfig.SSL_ENABLED_NAME, String.valueOf(true));
sslConfigProps.put(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
sslConfigProps.put(DistributionConfig.LOCATORS_NAME, "");
String sslInfoLogMsg = "Connecting to Locator via SSL.";
if (useSsl) {
sslInfoLogMsg = CliStrings.CONNECT__USE_SSL + " is set to true. " + sslInfoLogMsg;
}
gfshInstance.logToFile(sslInfoLogMsg, null);
}
ConnectToLocatorResult connectToLocatorResult = connectToLocator(locatorTcpHostPort.getHost(), locatorTcpHostPort.getPort(), CONNECT_LOCATOR_TIMEOUT_MS, sslConfigProps);
memberRmiHostPort = connectToLocatorResult.getMemberEndpoint();
hostPortToConnect = memberRmiHostPort;
Gfsh.printlnErr(connectToLocatorResult.getResultMessage());
// when locator is configured to use SSL (ssl-enabled=true) but manager is not (jmx-manager-ssl=false)
if ((useSsl || !sslConfigProps.isEmpty()) && !connectToLocatorResult.isJmxManagerSslEnabled()) {
gfshInstance.logInfo(CliStrings.CONNECT__USE_SSL + " is set to true. But JMX Manager doesn't support SSL, connecting without SSL.", null);
sslConfigProps.clear();
}
}
if (!sslConfigProps.isEmpty()) {
gfshInstance.logToFile("Connecting to manager via SSL.", null);
}
JmxOperationInvoker operationInvoker = new JmxOperationInvoker(memberRmiHostPort.getHost(), memberRmiHostPort.getPort(), userName, passwordToUse, sslConfigProps);
gfshInstance.setOperationInvoker(operationInvoker);
infoResultData.addLine(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, memberRmiHostPort.toString(false)));
LogWrapper.getInstance().info(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, memberRmiHostPort.toString(false)));
result = ResultBuilder.buildResult(infoResultData);
} catch (Exception e) {
// TODO - Abhishek: Refactor to use catch blocks for instanceof checks
Gfsh gfshInstance = Gfsh.getCurrentInstance();
String errorMessage = e.getMessage();
boolean logAsFine = false;
if (CauseFinder.indexOfCause(e, javax.naming.ServiceUnavailableException.class, false) != -1) {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__SERVICE_UNAVAILABLE_ERROR, hostPortToConnect.toString(false));
} else if (e instanceof JMXConnectionException) {
JMXConnectionException jce = (JMXConnectionException)e;
if (jce.getExceptionType() == JMXConnectionException.MANAGER_NOT_FOUND_EXCEPTION) {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__SERVICE_UNAVAILABLE_ERROR, hostPortToConnect.toString(false));
}
} else if ((e instanceof ConnectException) && isConnectingViaLocator) {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__COULD_NOT_CONNECT_TO_LOCATOR_0, hostPortToConnect.toString(false));
} else if ( (e instanceof IllegalStateException) && isConnectingViaLocator) {
Throwable causeByType = CauseFinder.causeByType(e, ClassCastException.class, false);
if (causeByType != null) {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__COULD_NOT_CONNECT_TO_LOCATOR_0_POSSIBLY_SSL_CONFIG_ERROR,
new Object[] { hostPortToConnect.toString(false)});
if (gfshInstance.isLoggingEnabled()) {
errorMessage += " "+ getGfshLogsCheckMessage(gfshInstance.getLogFilePath());
}
} else if (errorMessage == null) {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__COULD_NOT_CONNECT_TO_LOCATOR_0, locatorTcpHostPort.toString(false));
if (gfshInstance.isLoggingEnabled()) {
errorMessage += " "+ getGfshLogsCheckMessage(gfshInstance.getLogFilePath());
}
}
} else if (e instanceof IOException) {
Throwable causeByType = CauseFinder.causeByType(e, java.rmi.ConnectIOException.class, false);
if (causeByType != null) {
// TODO - Abhishek : Is there a better way to know about a specific cause?
if (String.valueOf(causeByType.getMessage()).contains("non-JRMP server")) {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__COULD_NOT_CONNECT_TO_MANAGER_0_POSSIBLY_SSL_CONFIG_ERROR,
new Object[] { memberRmiHostPort.toString(false)});
logAsFine = true;
} else {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__ERROR, new Object[] {memberRmiHostPort.toString(false), ""});
}
if (gfshInstance.isLoggingEnabled()) {
errorMessage += " "+ getGfshLogsCheckMessage(gfshInstance.getLogFilePath());
}
}
} else if (e instanceof SecurityException) {
// the default exception message is clear enough
String msgPart = StringUtils.isBlank(userName) && StringUtils.isBlank(passwordToUse) ? "" : "appropriate ";
errorMessage += ". Please specify "+msgPart+"values for --"+CliStrings.CONNECT__USERNAME+" and --"+CliStrings.CONNECT__PASSWORD;
} else{
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__ERROR, hostPortToConnect.toString(false), errorMessage);
}
result = ResultBuilder.createConnectionErrorResult(errorMessage);
if (logAsFine) {
LogWrapper.getInstance().fine(e.getMessage(), e);
} else {
LogWrapper.getInstance().severe(e.getMessage(), e);
}
}
Gfsh.redirectInternalJavaLoggers();
}
return result;
}
private void configureHttpsURLConnection(Map<String, String> sslConfigProps) throws Exception {
String keystoreToUse = sslConfigProps.get(Gfsh.SSL_KEYSTORE);
String keystorePasswordToUse = sslConfigProps.get(Gfsh.SSL_KEYSTORE_PASSWORD);
String truststoreToUse = sslConfigProps.get(Gfsh.SSL_TRUSTSTORE);
String truststorePasswordToUse = sslConfigProps.get(Gfsh.SSL_TRUSTSTORE_PASSWORD);
// Ciphers are not passed to HttpsURLConnection. Could not find a clean way
// to pass this attribute to socket layer (see #51645)
String sslCiphersToUse = sslConfigProps.get(DistributionConfig.CLUSTER_SSL_CIPHERS_NAME);
String sslProtocolsToUse = sslConfigProps.get(DistributionConfig.CLUSTER_SSL_PROTOCOLS_NAME);
//Commenting the code to set cipher suites in GFSH rest connect (see #51645)
/*
if(sslCiphersToUse != null){
System.setProperty("https.cipherSuites", sslCiphersToUse);
}
*/
FileInputStream keyStoreStream = null;
FileInputStream trustStoreStream = null;
try{
KeyManagerFactory keyManagerFactory = null;
if (!StringUtils.isBlank(keystoreToUse)) {
KeyStore clientKeys = KeyStore.getInstance("JKS");
keyStoreStream = new FileInputStream(keystoreToUse);
clientKeys.load(keyStoreStream, keystorePasswordToUse.toCharArray());
keyManagerFactory = KeyManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientKeys, keystorePasswordToUse.toCharArray());
}
// load server public key
TrustManagerFactory trustManagerFactory = null;
if (!StringUtils.isBlank(truststoreToUse)) {
KeyStore serverPub = KeyStore.getInstance("JKS");
trustStoreStream = new FileInputStream(truststoreToUse);
serverPub.load(trustStoreStream, truststorePasswordToUse.toCharArray());
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(serverPub);
}
SSLContext ssl = SSLContext.getInstance(SSLUtil.getSSLAlgo(SSLUtil.readArray(sslProtocolsToUse)));
ssl.init(keyManagerFactory != null ? keyManagerFactory.getKeyManagers() : null,
trustManagerFactory != null ? trustManagerFactory.getTrustManagers() : null, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
}finally{
if(keyStoreStream != null){
keyStoreStream.close();
}
if(trustStoreStream != null ){
trustStoreStream.close();
}
}
}
/**
* Common code to read SSL information. Used by JMX, Locator & HTTP mode connect
*/
private Map<String, String> readSSLConfiguration(boolean useSsl, String keystoreToUse, String keystorePasswordToUse,
String truststoreToUse, String truststorePasswordToUse, String sslCiphersToUse, String sslProtocolsToUse,
String gfSecurityPropertiesPath) throws IOException {
Gfsh gfshInstance = getGfsh();
final Map<String, String> sslConfigProps = new LinkedHashMap<String, String>();
// JMX SSL Config 1:
// First from gfsecurity properties file if it's specified OR
// if the default gfsecurity.properties exists useSsl==true
if (useSsl || gfSecurityPropertiesPath != null) {
// reference to hold resolved gfSecurityPropertiesPath
String gfSecurityPropertiesPathToUse = CliUtil.resolvePathname(gfSecurityPropertiesPath);
URL gfSecurityPropertiesUrl = null;
// Case 1: User has specified gfSecurity properties file
if (!StringUtils.isBlank(gfSecurityPropertiesPathToUse)) {
// User specified gfSecurity properties doesn't exist
if (!IOUtils.isExistingPathname(gfSecurityPropertiesPathToUse)) {
gfshInstance.printAsSevere(CliStrings.format(CliStrings.GEMFIRE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, "Security ", gfSecurityPropertiesPathToUse));
} else {
gfSecurityPropertiesUrl = new File(gfSecurityPropertiesPathToUse).toURI().toURL();
}
} else if (useSsl && gfSecurityPropertiesPath == null) {
// Case 2: User has specified to useSsl but hasn't specified
// gfSecurity properties file. Use default "gfsecurity.properties"
// in current dir, user's home or classpath
gfSecurityPropertiesUrl = getFileUrl("gfsecurity.properties");
}
// if 'gfSecurityPropertiesPath' OR gfsecurity.properties has resolvable path
if (gfSecurityPropertiesUrl != null) {
gfshInstance.logToFile("Using security properties file : "
+ CliUtil.decodeWithDefaultCharSet(gfSecurityPropertiesUrl.getPath()), null);
Map<String, String> gfsecurityProps = loadPropertiesFromURL(gfSecurityPropertiesUrl);
// command line options (if any) would override props in gfsecurity.properties
sslConfigProps.putAll(gfsecurityProps);
}
}
int numTimesPrompted = 0;
/*
* Using do-while here for a case when --use-ssl=true is specified but
* no SSL options were specified & there was no gfsecurity properties
* specified or readable in default gfsh directory.
*
* NOTE: 2nd round of prompting is done only when sslConfigProps map is
* empty & useSsl is true - so we won't over-write any previous values.
*/
do {
// JMX SSL Config 2: Now read the options
if (numTimesPrompted > 0) {
Gfsh.println("Please specify these SSL Configuration properties: ");
}
if (numTimesPrompted > 0) {
//NOTE: sslConfigProps map was empty
keystoreToUse = readText(gfshInstance, CliStrings.CONNECT__KEY_STORE + ": ");
}
if (keystoreToUse != null && keystoreToUse.length() > 0) {
if (keystorePasswordToUse == null || keystorePasswordToUse.length() == 0) {
// Check whether specified in gfsecurity props earlier
keystorePasswordToUse = sslConfigProps.get(Gfsh.SSL_KEYSTORE_PASSWORD);
if (keystorePasswordToUse == null || keystorePasswordToUse.length() == 0) {
// not even in properties file, prompt user for it
keystorePasswordToUse = readPassword(gfshInstance, CliStrings.CONNECT__KEY_STORE_PASSWORD + ": ");
sslConfigProps.put(Gfsh.SSL_KEYSTORE_PASSWORD, keystorePasswordToUse);
}
}else{//For cases where password is already part of command option
sslConfigProps.put(Gfsh.SSL_KEYSTORE_PASSWORD, keystorePasswordToUse);
}
sslConfigProps.put(Gfsh.SSL_KEYSTORE, keystoreToUse);
}
if (numTimesPrompted > 0) {
truststoreToUse = readText(gfshInstance, CliStrings.CONNECT__TRUST_STORE + ": ");
}
if (truststoreToUse != null && truststoreToUse.length() > 0) {
if (truststorePasswordToUse == null || truststorePasswordToUse.length() == 0) {
// Check whether specified in gfsecurity props earlier?
truststorePasswordToUse = sslConfigProps.get(Gfsh.SSL_TRUSTSTORE_PASSWORD);
if (truststorePasswordToUse == null || truststorePasswordToUse.length() == 0) {
// not even in properties file, prompt user for it
truststorePasswordToUse = readPassword(gfshInstance, CliStrings.CONNECT__TRUST_STORE_PASSWORD + ": ");
sslConfigProps.put(Gfsh.SSL_TRUSTSTORE_PASSWORD, truststorePasswordToUse);
}
}else{//For cases where password is already part of command option
sslConfigProps.put(Gfsh.SSL_TRUSTSTORE_PASSWORD, truststorePasswordToUse);
}
sslConfigProps.put(Gfsh.SSL_TRUSTSTORE, truststoreToUse);
}
if (numTimesPrompted > 0) {
sslCiphersToUse = readText(gfshInstance, CliStrings.CONNECT__SSL_CIPHERS + ": ");
}
if (sslCiphersToUse != null && sslCiphersToUse.length() > 0) {
//sslConfigProps.put(DistributionConfig.CLUSTER_SSL_CIPHERS_NAME, sslCiphersToUse);
sslConfigProps.put(Gfsh.SSL_ENABLED_CIPHERS, sslCiphersToUse);
}
if (numTimesPrompted > 0) {
sslProtocolsToUse = readText(gfshInstance, CliStrings.CONNECT__SSL_PROTOCOLS + ": ");
}
if (sslProtocolsToUse != null && sslProtocolsToUse.length() > 0) {
//sslConfigProps.put(DistributionConfig.CLUSTER_SSL_PROTOCOLS_NAME, sslProtocolsToUse);
sslConfigProps.put(Gfsh.SSL_ENABLED_PROTOCOLS, sslProtocolsToUse);
}
// SSL is required to be used but no SSL config found
} while(useSsl && sslConfigProps.isEmpty() && (0 == numTimesPrompted++) && !gfshInstance.isQuietMode());
return sslConfigProps;
}
private static String getGfshLogsCheckMessage(String logFilePath) {
return CliStrings.format(CliStrings.GFSH__PLEASE_CHECK_LOGS_AT_0, logFilePath);
}
private String readText(Gfsh gfsh, String textToPrompt) throws IOException {
if (!gfsh.isHeadlessMode() || !gfsh.isQuietMode()) {
return gfsh.interact(textToPrompt);
} else {
return null;
}
}
private String readPassword(Gfsh gfsh, String textToPrompt) throws IOException {
if (!gfsh.isHeadlessMode() || !gfsh.isQuietMode()) {
return gfsh.readWithMask(textToPrompt, '*');
} else {
return null;
}
}
/* package-private */ static Map<String, String> loadPropertiesFromURL(URL gfSecurityPropertiesUrl) {
Map<String, String> propsMap = Collections.emptyMap();
if (gfSecurityPropertiesUrl != null) {
InputStream inputStream = null;
try {
Properties props = new Properties();
inputStream = gfSecurityPropertiesUrl.openStream();
props.load(inputStream);
if (!props.isEmpty()) {
Set<String> jmxSpecificProps = new HashSet<String>();
propsMap = new LinkedHashMap<String, String>();
Set<Entry<Object, Object>> entrySet = props.entrySet();
for (Entry<Object, Object> entry : entrySet) {
String key = (String)entry.getKey();
if (key.endsWith(DistributionConfig.JMX_SSL_PROPS_SUFFIX)) {
key = key.substring(0, key.length() - DistributionConfig.JMX_SSL_PROPS_SUFFIX.length());
jmxSpecificProps.add(key);
propsMap.put(key, (String)entry.getValue());
} else if (!jmxSpecificProps.contains(key)) {// Prefer properties ending with "-jmx" over default SSL props.
propsMap.put(key, (String)entry.getValue());
}
}
props.clear();
jmxSpecificProps.clear();
}
} catch (IOException io) {
throw new RuntimeException(CliStrings.format(
CliStrings.CONNECT__MSG__COULD_NOT_READ_CONFIG_FROM_0,
CliUtil.decodeWithDefaultCharSet(gfSecurityPropertiesUrl.getPath())), io);
} finally {
IOUtils.close(inputStream);
}
}
return propsMap;
}
// Copied from DistributedSystem.java
private static URL getFileUrl(String fileName) {
File file = new File(fileName);
if (file.exists()) {
try {
return IOUtils.tryGetCanonicalFileElseGetAbsoluteFile(file).toURI().toURL();
} catch (MalformedURLException ignore) {
}
}
file = new File(System.getProperty("user.home"), fileName);
if (file.exists()) {
try {
return IOUtils.tryGetCanonicalFileElseGetAbsoluteFile(file).toURI().toURL();
} catch (MalformedURLException ignore) {
}
}
return ClassPathLoader.getLatest().getResource(ShellCommands.class, fileName);
}
public static ConnectToLocatorResult connectToLocator(String host, int port, int timeout, Map<String, String> props)
throws IOException
{
// register DSFID types first; invoked explicitly so that all message type
// initializations do not happen in first deserialization on a possibly
// "precious" thread
DSFIDFactory.registerTypes();
JmxManagerLocatorResponse locatorResponse = JmxManagerLocatorRequest.send(host, port, timeout, props);
if (StringUtils.isBlank(locatorResponse.getHost()) || locatorResponse.getPort() == 0) {
Throwable locatorResponseException = locatorResponse.getException();
String exceptionMessage = CliStrings.CONNECT__MSG__LOCATOR_COULD_NOT_FIND_MANAGER;
if (locatorResponseException != null) {
String locatorResponseExceptionMessage = locatorResponseException.getMessage();
locatorResponseExceptionMessage = (!StringUtils.isBlank(locatorResponseExceptionMessage)
? locatorResponseExceptionMessage : locatorResponseException.toString());
exceptionMessage = "Exception caused JMX Manager startup to fail because: '"
.concat(locatorResponseExceptionMessage).concat("'");
}
throw new IllegalStateException(exceptionMessage, locatorResponseException);
}
ConnectionEndpoint memberEndpoint = new ConnectionEndpoint(locatorResponse.getHost(), locatorResponse.getPort());
String resultMessage = CliStrings.format(CliStrings.CONNECT__MSG__CONNECTING_TO_MANAGER_AT_0,
memberEndpoint.toString(false));
return new ConnectToLocatorResult(memberEndpoint, resultMessage, locatorResponse.isJmxManagerSslEnabled());
}
@CliCommand(value = { CliStrings.DISCONNECT }, help = CliStrings.DISCONNECT__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_JMX, CliStrings.TOPIC_GEMFIRE_MANAGER})
public Result disconnect() {
Result result = null;
if (getGfsh() != null && !getGfsh().isConnectedAndReady()) {
result = ResultBuilder.createInfoResult("Not connected.");
} else {
InfoResultData infoResultData = ResultBuilder.createInfoResultData();
try {
Gfsh gfshInstance = getGfsh();
if (gfshInstance.isConnectedAndReady()) {
OperationInvoker operationInvoker = gfshInstance.getOperationInvoker();
Gfsh.println("Disconnecting from: " + operationInvoker);
operationInvoker.stop();
infoResultData.addLine(CliStrings
.format(CliStrings.DISCONNECT__MSG__DISCONNECTED, operationInvoker.toString()));
LogWrapper.getInstance().info(CliStrings.format(CliStrings.DISCONNECT__MSG__DISCONNECTED, operationInvoker.toString()));
gfshInstance.setPromptPath(com.gemstone.gemfire.management.internal.cli.converters.RegionPathConverter.DEFAULT_APP_CONTEXT_PATH);
} else {
infoResultData.addLine(CliStrings.DISCONNECT__MSG__NOTCONNECTED);
}
result = ResultBuilder.buildResult(infoResultData);
} catch (Exception e) {
result = ResultBuilder.createConnectionErrorResult(CliStrings.format(CliStrings.DISCONNECT__MSG__ERROR, e.getMessage()));
}
}
return result;
}
@CliCommand(value = {CliStrings.DESCRIBE_CONNECTION}, help = CliStrings.DESCRIBE_CONNECTION__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_JMX})
public Result describeConnection() {
Result result = null;
try {
TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
Gfsh gfshInstance = getGfsh();
if (gfshInstance.isConnectedAndReady()) {
OperationInvoker operationInvoker = gfshInstance.getOperationInvoker();
// tabularResultData.accumulate("Monitored GemFire DS", operationInvoker.toString());
tabularResultData.accumulate("Connection Endpoints", operationInvoker.toString());
} else {
tabularResultData.accumulate("Connection Endpoints", "Not connected");
}
result = ResultBuilder.buildResult(tabularResultData);
} catch (Exception e) {
ErrorResultData errorResultData =
ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
.addLine(e.getMessage());
result = ResultBuilder.buildResult(errorResultData);
}
return result;
}
@CliCommand(value = { CliStrings.ECHO }, help = CliStrings.ECHO__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result echo(
@CliOption(key = {CliStrings.ECHO__STR, ""},
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
specifiedDefaultValue = "",
mandatory = true,
help = CliStrings.ECHO__STR__HELP) String stringToEcho) {
Result result = null;
if(stringToEcho.equals("$*")){
Gfsh gfshInstance = getGfsh();
Map<String, String> envMap = gfshInstance.getEnv();
Set< Entry<String, String> > setEnvMap = envMap.entrySet();
TabularResultData resultData = buildResultForEcho(setEnvMap);
result = ResultBuilder.buildResult(resultData);
} else {
result = ResultBuilder.createInfoResult(stringToEcho);
}
return result;
}
TabularResultData buildResultForEcho(Set< Entry<String, String> > propertyMap){
TabularResultData resultData = ResultBuilder.createTabularResultData();
Iterator <Entry<String, String>> it = propertyMap.iterator();
while(it.hasNext()){
Entry<String, String> setEntry = it.next();
resultData.accumulate("Property", setEntry.getKey());
resultData.accumulate("Value", String.valueOf(setEntry.getValue()));
}
return resultData;
}
@CliCommand(value = { CliStrings.SET_VARIABLE }, help = CliStrings.SET_VARIABLE__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result setVariable(
@CliOption(key = CliStrings.SET_VARIABLE__VAR,
mandatory=true,
help = CliStrings.SET_VARIABLE__VAR__HELP)
String var,
@CliOption(key = CliStrings.SET_VARIABLE__VALUE,
mandatory=true,
help = CliStrings.SET_VARIABLE__VALUE__HELP)
String value) {
Result result = null;
try {
getGfsh().setEnvProperty(var, String.valueOf(value));
result = ResultBuilder.createInfoResult("Value for variable "+var+" is now: "+value+".");
} catch (IllegalArgumentException e) {
ErrorResultData errorResultData = ResultBuilder.createErrorResultData();
errorResultData.addLine(e.getMessage());
result = ResultBuilder.buildResult(errorResultData);
}
return result;
}
//Enable when "use region" command is required. See #46110
// @CliCommand(value = { CliStrings.USE_REGION }, help = CliStrings.USE_REGION__HELP)
// @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_REGION})
// public Result useRegion(
// @CliArgument(name = CliStrings.USE_REGION__REGION,
// unspecifiedDefaultValue = "/",
// argumentContext = CliStrings.PARAM_CONTEXT_REGIONPATH,
// help = CliStrings.USE_REGION__REGION__HELP)
// String toRegion) {
// Gfsh gfsh = Gfsh.getCurrentInstance();
//
// gfsh.setPromptPath(toRegion);
// return ResultBuilder.createInfoResult("");
// }
@CliCommand(value = { CliStrings.DEBUG }, help = CliStrings.DEBUG__HELP)
@CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_DEBUG_UTIL })
public Result debug(
@CliOption(key = CliStrings.DEBUG__STATE,
unspecifiedDefaultValue = "OFF",
mandatory = true,
optionContext = "debug",
help = CliStrings.DEBUG__STATE__HELP)
String state) {
Gfsh gfshInstance = Gfsh.getCurrentInstance();
if (gfshInstance != null) {
// Handle state
if (state.equalsIgnoreCase("ON")) {
gfshInstance.setDebug(true);
} else if(state.equalsIgnoreCase("OFF")){
gfshInstance.setDebug(false);
}else{
return ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.DEBUG__MSG_0_INVALID_STATE_VALUE,state)) ;
}
} else {
ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(
CliStrings.ECHO__MSG__NO_GFSH_INSTANCE);
return ResultBuilder.buildResult(errorResultData);
}
return ResultBuilder.createInfoResult(CliStrings.DEBUG__MSG_DEBUG_STATE_IS + state );
}
@CliCommand(value = CliStrings.HISTORY, help = CliStrings.HISTORY__HELP)
@CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GFSH })
public Result history(
@CliOption(key = { CliStrings.HISTORY__FILE }, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.HISTORY__FILE__HELP)
String saveHistoryTo,
@CliOption(key = { CliStrings.HISTORY__CLEAR }, specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false", help = CliStrings.HISTORY__CLEAR__HELP) Boolean clearHistory) {
//process clear history
if (clearHistory ) {
return executeClearHistory();
}else {
//Process file option
Gfsh gfsh = Gfsh.getCurrentInstance();
ErrorResultData errorResultData = null;
StringBuilder contents = new StringBuilder();
Writer output = null;
int historySize = gfsh.getHistorySize();
String historySizeString = String.valueOf(historySize);
int historySizeWordLength = historySizeString.length();
GfshHistory gfshHistory = gfsh.getGfshHistory();
List<?> gfshHistoryList = gfshHistory.getHistoryList();
Iterator<?> it = gfshHistoryList.iterator();
boolean flagForLineNumbers = (saveHistoryTo != null && saveHistoryTo
.length() > 0) ? false : true;
long lineNumber = 0;
while (it.hasNext()) {
String line = (String) it.next();
if (line.isEmpty() == false) {
if (flagForLineNumbers) {
lineNumber++;
contents.append(String.format("%" + historySizeWordLength + "s ",
lineNumber));
}
contents.append(line);
contents.append(GfshParser.LINE_SEPARATOR);
}
}
try {
// write to a user file
if (saveHistoryTo != null && saveHistoryTo.length() > 0) {
File saveHistoryToFile = new File(saveHistoryTo);
output = new BufferedWriter(new FileWriter(saveHistoryToFile));
if (!saveHistoryToFile.exists()) {
errorResultData = ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
.addLine(CliStrings.HISTORY__MSG__FILE_DOES_NOT_EXISTS);
return ResultBuilder.buildResult(errorResultData);
}
if (!saveHistoryToFile.isFile()) {
errorResultData = ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
.addLine(CliStrings.HISTORY__MSG__FILE_SHOULD_NOT_BE_DIRECTORY);
return ResultBuilder.buildResult(errorResultData);
}
if (!saveHistoryToFile.canWrite()) {
errorResultData = ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
.addLine(CliStrings.HISTORY__MSG__FILE_CANNOT_BE_WRITTEN);
return ResultBuilder.buildResult(errorResultData);
}
output.write(contents.toString());
}
} catch (IOException ex) {
return ResultBuilder.createInfoResult("File error " + ex.getMessage()
+ " for file " + saveHistoryTo);
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
errorResultData = ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
.addLine("exception in closing file");
return ResultBuilder.buildResult(errorResultData);
}
}
if (saveHistoryTo != null && saveHistoryTo.length() > 0) {
// since written to file no need to display the content
return ResultBuilder.createInfoResult("Wrote successfully to file "
+ saveHistoryTo);
} else {
return ResultBuilder.createInfoResult(contents.toString());
}
}
}
Result executeClearHistory(){
try{
Gfsh gfsh = Gfsh.getCurrentInstance();
GfshHistory gfshHistory = gfsh.getGfshHistory();
gfshHistory.clear();
}catch(Exception e){
LogWrapper.getInstance().info(CliUtil.stackTraceAsString(e) );
return ResultBuilder.createGemFireErrorResult("Exception occured while clearing history " + e.getMessage());
}
return ResultBuilder.createInfoResult(CliStrings.HISTORY__MSG__CLEARED_HISTORY);
}
@CliCommand(value = { CliStrings.RUN }, help = CliStrings.RUN__HELP)
@CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result executeScript(
@CliOption(key = CliStrings.RUN__FILE,
optionContext = ConverterHint.FILE,
mandatory = true,
help = CliStrings.RUN__FILE__HELP)
File file,
@CliOption(key = { CliStrings.RUN__QUIET },
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.RUN__QUIET__HELP)
boolean quiet,
@CliOption(key = { CliStrings.RUN__CONTINUEONERROR },
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.RUN__CONTINUEONERROR__HELP)
boolean continueOnError) {
Result result = null;
Gfsh gfsh = Gfsh.getCurrentInstance();
try {
result = gfsh.executeScript(file, quiet, continueOnError);
} catch (IllegalArgumentException e) {
result = ResultBuilder.createShellClientErrorResult(e.getMessage());
} // let CommandProcessingException go to the caller
return result;
}
@CliCommand(value = CliStrings.ENCRYPT, help = CliStrings.ENCRYPT__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEMFIRE_DEBUG_UTIL})
public Result encryptPassword(
@CliOption(key = CliStrings.ENCRYPT_STRING,
help = CliStrings.ENCRYPT_STRING__HELP,
mandatory = true)
String stringToEncrypt) {
return ResultBuilder.createInfoResult(PasswordUtil.encrypt(stringToEncrypt, false/*echo*/));
}
@CliCommand(value = { CliStrings.VERSION }, help = CliStrings.VERSION__HELP)
@CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result version(
@CliOption(key = { CliStrings.VERSION__FULL },
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.VERSION__FULL__HELP)
boolean full) {
Gfsh gfsh = Gfsh.getCurrentInstance();
return ResultBuilder.createInfoResult(gfsh.getVersion(full));
}
@CliCommand(value = { CliStrings.SLEEP }, help = CliStrings.SLEEP__HELP)
@CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result sleep(
@CliOption(key = { CliStrings.SLEEP__TIME },
unspecifiedDefaultValue = "3",
help = CliStrings.SLEEP__TIME__HELP)
double time) {
try {
LogWrapper.getInstance().fine("Sleeping for " + time + "seconds.");
Thread.sleep( Math.round(time * 1000) );
} catch (InterruptedException ignorable) {}
return ResultBuilder.createInfoResult("");
}
@CliCommand(value = { CliStrings.SH }, help = CliStrings.SH__HELP)
@CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result sh(
@CliArgument(name = CliStrings.SH__COMMAND,
mandatory = true,
help = CliStrings.SH__COMMAND__HELP)
String command,
@CliOption(key = CliStrings.SH__USE_CONSOLE,
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.SH__USE_CONSOLE__HELP)
boolean useConsole) {
Result result = null;
try {
result = ResultBuilder.buildResult(executeCommand(Gfsh.getCurrentInstance(), command, useConsole));
} catch (IllegalStateException e) {
result = ResultBuilder.createUserErrorResult(e.getMessage());
LogWrapper.getInstance().warning("Unable to execute command \"" + command + "\". Reason:" + e.getMessage() + ".");
} catch (IOException e) {
result = ResultBuilder.createUserErrorResult(e.getMessage());
LogWrapper.getInstance().warning("Unable to execute command \"" + command + "\". Reason:" + e.getMessage() + ".");
}
return result;
}
private static InfoResultData executeCommand(Gfsh gfsh, String userCommand, boolean useConsole) throws IOException {
InfoResultData infoResultData = ResultBuilder.createInfoResultData();
String cmdToExecute = userCommand;
String cmdExecutor = "/bin/sh";
String cmdExecutorOpt = "-c";
if (SystemUtils.isWindows()) {
cmdExecutor = "cmd";
cmdExecutorOpt = "/c";
} else if (useConsole) {
cmdToExecute = cmdToExecute + " </dev/tty >/dev/tty";
}
String[] commandArray = { cmdExecutor, cmdExecutorOpt, cmdToExecute };
ProcessBuilder builder = new ProcessBuilder();
builder.command(commandArray);
builder.directory();
builder.redirectErrorStream();
Process proc = builder.start();
BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String lineRead = "";
while ((lineRead = input.readLine()) != null) {
infoResultData.addLine(lineRead);
}
proc.getOutputStream().close();
try {
if (proc.waitFor() != 0) {
gfsh.logWarning("The command '" + userCommand + "' did not complete successfully", null);
}
} catch (final InterruptedException e) {
throw new IllegalStateException(e);
}
return infoResultData;
}
@CliAvailabilityIndicator({CliStrings.CONNECT, CliStrings.DISCONNECT, CliStrings.DESCRIBE_CONNECTION})
public boolean isAvailable() {
return true;
}
}
| |
package org.belle.topit.visio.base.events;
import com4j.*;
/**
* Visio Windows Event Interface
*/
@IID("{000D0B01-0000-0000-C000-000000000046}")
public abstract class EWindows {
// Methods:
/**
* @param window Mandatory test.IVWindow parameter.
*/
@DISPID(32769)
public void windowOpened(
org.belle.topit.visio.base.IVWindow window) {
throw new UnsupportedOperationException();
}
/**
* @param window Mandatory test.IVWindow parameter.
*/
@DISPID(701)
public void selectionChanged(
org.belle.topit.visio.base.IVWindow window) {
throw new UnsupportedOperationException();
}
/**
* @param window Mandatory test.IVWindow parameter.
*/
@DISPID(16385)
public void beforeWindowClosed(
org.belle.topit.visio.base.IVWindow window) {
throw new UnsupportedOperationException();
}
/**
* @param window Mandatory test.IVWindow parameter.
*/
@DISPID(4224)
public void windowActivated(
org.belle.topit.visio.base.IVWindow window) {
throw new UnsupportedOperationException();
}
/**
* @param window Mandatory test.IVWindow parameter.
*/
@DISPID(702)
public void beforeWindowSelDelete(
org.belle.topit.visio.base.IVWindow window) {
throw new UnsupportedOperationException();
}
/**
* @param window Mandatory test.IVWindow parameter.
*/
@DISPID(703)
public void beforeWindowPageTurn(
org.belle.topit.visio.base.IVWindow window) {
throw new UnsupportedOperationException();
}
/**
* @param window Mandatory test.IVWindow parameter.
*/
@DISPID(704)
public void windowTurnedToPage(
org.belle.topit.visio.base.IVWindow window) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Fires after a window's size or position changes
* </p>
* @param window Mandatory test.IVWindow parameter.
*/
@DISPID(8193)
public void windowChanged(
org.belle.topit.visio.base.IVWindow window) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Fires after scroll or zoom in a drawing window
* </p>
* @param window Mandatory test.IVWindow parameter.
*/
@DISPID(705)
public void viewChanged(
org.belle.topit.visio.base.IVWindow window) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Cancel close of window? T:Yes F:No
* </p>
* @param window Mandatory test.IVWindow parameter.
* @return Returns a value of type void
*/
@DISPID(706)
public void queryCancelWindowClose(
org.belle.topit.visio.base.IVWindow window) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Window close operation was canceled.
* </p>
* @param window Mandatory test.IVWindow parameter.
*/
@DISPID(707)
public void windowCloseCanceled(
org.belle.topit.visio.base.IVWindow window) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Called when keystroke message received for Addon window. True return indicates message was handled.
* </p>
* @param msg Mandatory test.IVMSGWrap parameter.
* @return Returns a value of type void
*/
@DISPID(708)
public void onKeystrokeMessageForAddon(
org.belle.topit.visio.base.IVMSGWrap msg) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Called when mousedown message received for window. If you set CancelDefault to True then Visio will not process this message.
* </p>
* @param button Mandatory int parameter.
* @param keyButtonState Mandatory int parameter.
* @param x Mandatory double parameter.
* @param y Mandatory double parameter.
* @param cancelDefault Mandatory Holder<Boolean> parameter.
*/
@DISPID(709)
public void mouseDown(
int button,
int keyButtonState,
double x,
double y,
Holder<Boolean> cancelDefault) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Called when mousemove message received for window. If you set CancelDefault to True then Visio will not process this message.
* </p>
* @param button Mandatory int parameter.
* @param keyButtonState Mandatory int parameter.
* @param x Mandatory double parameter.
* @param y Mandatory double parameter.
* @param cancelDefault Mandatory Holder<Boolean> parameter.
*/
@DISPID(710)
public void mouseMove(
int button,
int keyButtonState,
double x,
double y,
Holder<Boolean> cancelDefault) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Called when mouseup message received for window. If you set CancelDefault to True then Visio will not process this message.
* </p>
* @param button Mandatory int parameter.
* @param keyButtonState Mandatory int parameter.
* @param x Mandatory double parameter.
* @param y Mandatory double parameter.
* @param cancelDefault Mandatory Holder<Boolean> parameter.
*/
@DISPID(711)
public void mouseUp(
int button,
int keyButtonState,
double x,
double y,
Holder<Boolean> cancelDefault) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Called when keydown message received for window. If you set CancelDefault to True then Visio will not process this message.
* </p>
* @param keyCode Mandatory int parameter.
* @param keyButtonState Mandatory int parameter.
* @param cancelDefault Mandatory Holder<Boolean> parameter.
*/
@DISPID(712)
public void keyDown(
int keyCode,
int keyButtonState,
Holder<Boolean> cancelDefault) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Called when keypress message received for window. If you set CancelDefault to True then Visio will not process this message.
* </p>
* @param keyAscii Mandatory int parameter.
* @param cancelDefault Mandatory Holder<Boolean> parameter.
*/
@DISPID(713)
public void keyPress(
int keyAscii,
Holder<Boolean> cancelDefault) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Called when keyup message received for window. If you set CancelDefault to True then Visio will not process this message.
* </p>
* @param keyCode Mandatory int parameter.
* @param keyButtonState Mandatory int parameter.
* @param cancelDefault Mandatory Holder<Boolean> parameter.
*/
@DISPID(714)
public void keyUp(
int keyCode,
int keyButtonState,
Holder<Boolean> cancelDefault) {
throw new UnsupportedOperationException();
}
// Properties:
}
| |
/*
* Copyright (C) 2016 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.android.exoplayer2;
import android.annotation.TargetApi;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.MediaCodec;
import android.support.annotation.IntDef;
import android.view.Surface;
import com.google.android.exoplayer2.util.Util;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.UUID;
/**
* Defines constants used by the library.
*/
public final class C {
private C() {}
/**
* Special constant representing a time corresponding to the end of a source. Suitable for use in
* any time base.
*/
public static final long TIME_END_OF_SOURCE = Long.MIN_VALUE;
/**
* Special constant representing an unset or unknown time or duration. Suitable for use in any
* time base.
*/
public static final long TIME_UNSET = Long.MIN_VALUE + 1;
/**
* Represents an unset or unknown index.
*/
public static final int INDEX_UNSET = -1;
/**
* Represents an unset or unknown position.
*/
public static final int POSITION_UNSET = -1;
/**
* Represents an unset or unknown length.
*/
public static final int LENGTH_UNSET = -1;
/**
* The number of microseconds in one second.
*/
public static final long MICROS_PER_SECOND = 1000000L;
/**
* The number of nanoseconds in one second.
*/
public static final long NANOS_PER_SECOND = 1000000000L;
/**
* The name of the UTF-8 charset.
*/
public static final String UTF8_NAME = "UTF-8";
/**
* Crypto modes for a codec.
*/
@Retention(RetentionPolicy.SOURCE)
@IntDef({CRYPTO_MODE_UNENCRYPTED, CRYPTO_MODE_AES_CTR, CRYPTO_MODE_AES_CBC})
public @interface CryptoMode {}
/**
* @see MediaCodec#CRYPTO_MODE_UNENCRYPTED
*/
@SuppressWarnings("InlinedApi")
public static final int CRYPTO_MODE_UNENCRYPTED = MediaCodec.CRYPTO_MODE_UNENCRYPTED;
/**
* @see MediaCodec#CRYPTO_MODE_AES_CTR
*/
@SuppressWarnings("InlinedApi")
public static final int CRYPTO_MODE_AES_CTR = MediaCodec.CRYPTO_MODE_AES_CTR;
/**
* @see MediaCodec#CRYPTO_MODE_AES_CBC
*/
@SuppressWarnings("InlinedApi")
public static final int CRYPTO_MODE_AES_CBC = MediaCodec.CRYPTO_MODE_AES_CBC;
/**
* Represents an unset {@link android.media.AudioTrack} session identifier. Equal to
* {@link AudioManager#AUDIO_SESSION_ID_GENERATE}.
*/
@SuppressWarnings("InlinedApi")
public static final int AUDIO_SESSION_ID_UNSET = AudioManager.AUDIO_SESSION_ID_GENERATE;
/**
* Represents an audio encoding, or an invalid or unset value.
*/
@Retention(RetentionPolicy.SOURCE)
@IntDef({Format.NO_VALUE, ENCODING_INVALID, ENCODING_PCM_8BIT, ENCODING_PCM_16BIT,
ENCODING_PCM_24BIT, ENCODING_PCM_32BIT, ENCODING_AC3, ENCODING_E_AC3, ENCODING_DTS,
ENCODING_DTS_HD})
public @interface Encoding {}
/**
* Represents a PCM audio encoding, or an invalid or unset value.
*/
@Retention(RetentionPolicy.SOURCE)
@IntDef({Format.NO_VALUE, ENCODING_INVALID, ENCODING_PCM_8BIT, ENCODING_PCM_16BIT,
ENCODING_PCM_24BIT, ENCODING_PCM_32BIT})
public @interface PcmEncoding {}
/**
* @see AudioFormat#ENCODING_INVALID
*/
public static final int ENCODING_INVALID = AudioFormat.ENCODING_INVALID;
/**
* @see AudioFormat#ENCODING_PCM_8BIT
*/
public static final int ENCODING_PCM_8BIT = AudioFormat.ENCODING_PCM_8BIT;
/**
* @see AudioFormat#ENCODING_PCM_16BIT
*/
public static final int ENCODING_PCM_16BIT = AudioFormat.ENCODING_PCM_16BIT;
/**
* PCM encoding with 24 bits per sample.
*/
public static final int ENCODING_PCM_24BIT = 0x80000000;
/**
* PCM encoding with 32 bits per sample.
*/
public static final int ENCODING_PCM_32BIT = 0x40000000;
/**
* @see AudioFormat#ENCODING_AC3
*/
@SuppressWarnings("InlinedApi")
public static final int ENCODING_AC3 = AudioFormat.ENCODING_AC3;
/**
* @see AudioFormat#ENCODING_E_AC3
*/
@SuppressWarnings("InlinedApi")
public static final int ENCODING_E_AC3 = AudioFormat.ENCODING_E_AC3;
/**
* @see AudioFormat#ENCODING_DTS
*/
@SuppressWarnings("InlinedApi")
public static final int ENCODING_DTS = AudioFormat.ENCODING_DTS;
/**
* @see AudioFormat#ENCODING_DTS_HD
*/
@SuppressWarnings("InlinedApi")
public static final int ENCODING_DTS_HD = AudioFormat.ENCODING_DTS_HD;
/**
* @see AudioFormat#CHANNEL_OUT_7POINT1_SURROUND
*/
@SuppressWarnings({"InlinedApi", "deprecation"})
public static final int CHANNEL_OUT_7POINT1_SURROUND = Util.SDK_INT < 23
? AudioFormat.CHANNEL_OUT_7POINT1 : AudioFormat.CHANNEL_OUT_7POINT1_SURROUND;
/**
* Stream types for an {@link android.media.AudioTrack}.
*/
@Retention(RetentionPolicy.SOURCE)
@IntDef({STREAM_TYPE_ALARM, STREAM_TYPE_MUSIC, STREAM_TYPE_NOTIFICATION, STREAM_TYPE_RING,
STREAM_TYPE_SYSTEM, STREAM_TYPE_VOICE_CALL})
public @interface StreamType {}
/**
* @see AudioManager#STREAM_ALARM
*/
public static final int STREAM_TYPE_ALARM = AudioManager.STREAM_ALARM;
/**
* @see AudioManager#STREAM_MUSIC
*/
public static final int STREAM_TYPE_MUSIC = AudioManager.STREAM_MUSIC;
/**
* @see AudioManager#STREAM_NOTIFICATION
*/
public static final int STREAM_TYPE_NOTIFICATION = AudioManager.STREAM_NOTIFICATION;
/**
* @see AudioManager#STREAM_RING
*/
public static final int STREAM_TYPE_RING = AudioManager.STREAM_RING;
/**
* @see AudioManager#STREAM_SYSTEM
*/
public static final int STREAM_TYPE_SYSTEM = AudioManager.STREAM_SYSTEM;
/**
* @see AudioManager#STREAM_VOICE_CALL
*/
public static final int STREAM_TYPE_VOICE_CALL = AudioManager.STREAM_VOICE_CALL;
/**
* The default stream type used by audio renderers.
*/
public static final int STREAM_TYPE_DEFAULT = STREAM_TYPE_MUSIC;
/**
* Flags which can apply to a buffer containing a media sample.
*/
@Retention(RetentionPolicy.SOURCE)
@IntDef(flag = true, value = {BUFFER_FLAG_KEY_FRAME, BUFFER_FLAG_END_OF_STREAM,
BUFFER_FLAG_ENCRYPTED, BUFFER_FLAG_DECODE_ONLY})
public @interface BufferFlags {}
/**
* Indicates that a buffer holds a synchronization sample.
*/
@SuppressWarnings("InlinedApi")
public static final int BUFFER_FLAG_KEY_FRAME = MediaCodec.BUFFER_FLAG_KEY_FRAME;
/**
* Flag for empty buffers that signal that the end of the stream was reached.
*/
@SuppressWarnings("InlinedApi")
public static final int BUFFER_FLAG_END_OF_STREAM = MediaCodec.BUFFER_FLAG_END_OF_STREAM;
/**
* Indicates that a buffer is (at least partially) encrypted.
*/
public static final int BUFFER_FLAG_ENCRYPTED = 0x40000000;
/**
* Indicates that a buffer should be decoded but not rendered.
*/
public static final int BUFFER_FLAG_DECODE_ONLY = 0x80000000;
/**
* Video scaling modes for {@link MediaCodec}-based {@link Renderer}s.
*/
@Retention(RetentionPolicy.SOURCE)
@IntDef(value = {VIDEO_SCALING_MODE_SCALE_TO_FIT, VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING})
public @interface VideoScalingMode {}
/**
* @see MediaCodec#VIDEO_SCALING_MODE_SCALE_TO_FIT
*/
@SuppressWarnings("InlinedApi")
public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT =
MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT;
/**
* @see MediaCodec#VIDEO_SCALING_MODE_SCALE_TO_FIT
*/
@SuppressWarnings("InlinedApi")
public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING =
MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING;
/**
* A default video scaling mode for {@link MediaCodec}-based {@link Renderer}s.
*/
public static final int VIDEO_SCALING_MODE_DEFAULT = VIDEO_SCALING_MODE_SCALE_TO_FIT;
/**
* Track selection flags.
*/
@Retention(RetentionPolicy.SOURCE)
@IntDef(flag = true, value = {SELECTION_FLAG_DEFAULT, SELECTION_FLAG_FORCED,
SELECTION_FLAG_AUTOSELECT})
public @interface SelectionFlags {}
/**
* Indicates that the track should be selected if user preferences do not state otherwise.
*/
public static final int SELECTION_FLAG_DEFAULT = 1;
/**
* Indicates that the track must be displayed. Only applies to text tracks.
*/
public static final int SELECTION_FLAG_FORCED = 2;
/**
* Indicates that the player may choose to play the track in absence of an explicit user
* preference.
*/
public static final int SELECTION_FLAG_AUTOSELECT = 4;
/**
* Represents a streaming or other media type.
*/
@Retention(RetentionPolicy.SOURCE)
@IntDef({TYPE_DASH, TYPE_SS, TYPE_HLS, TYPE_OTHER})
public @interface ContentType {}
/**
* Value returned by {@link Util#inferContentType(String)} for DASH manifests.
*/
public static final int TYPE_DASH = 0;
/**
* Value returned by {@link Util#inferContentType(String)} for Smooth Streaming manifests.
*/
public static final int TYPE_SS = 1;
/**
* Value returned by {@link Util#inferContentType(String)} for HLS manifests.
*/
public static final int TYPE_HLS = 2;
/**
* Value returned by {@link Util#inferContentType(String)} for files other than DASH, HLS or
* Smooth Streaming manifests.
*/
public static final int TYPE_OTHER = 3;
/**
* A return value for methods where the end of an input was encountered.
*/
public static final int RESULT_END_OF_INPUT = -1;
/**
* A return value for methods where the length of parsed data exceeds the maximum length allowed.
*/
public static final int RESULT_MAX_LENGTH_EXCEEDED = -2;
/**
* A return value for methods where nothing was read.
*/
public static final int RESULT_NOTHING_READ = -3;
/**
* A return value for methods where a buffer was read.
*/
public static final int RESULT_BUFFER_READ = -4;
/**
* A return value for methods where a format was read.
*/
public static final int RESULT_FORMAT_READ = -5;
/**
* A data type constant for data of unknown or unspecified type.
*/
public static final int DATA_TYPE_UNKNOWN = 0;
/**
* A data type constant for media, typically containing media samples.
*/
public static final int DATA_TYPE_MEDIA = 1;
/**
* A data type constant for media, typically containing only initialization data.
*/
public static final int DATA_TYPE_MEDIA_INITIALIZATION = 2;
/**
* A data type constant for drm or encryption data.
*/
public static final int DATA_TYPE_DRM = 3;
/**
* A data type constant for a manifest file.
*/
public static final int DATA_TYPE_MANIFEST = 4;
/**
* A data type constant for time synchronization data.
*/
public static final int DATA_TYPE_TIME_SYNCHRONIZATION = 5;
/**
* Applications or extensions may define custom {@code DATA_TYPE_*} constants greater than or
* equal to this value.
*/
public static final int DATA_TYPE_CUSTOM_BASE = 10000;
/**
* A type constant for tracks of unknown type.
*/
public static final int TRACK_TYPE_UNKNOWN = -1;
/**
* A type constant for tracks of some default type, where the type itself is unknown.
*/
public static final int TRACK_TYPE_DEFAULT = 0;
/**
* A type constant for audio tracks.
*/
public static final int TRACK_TYPE_AUDIO = 1;
/**
* A type constant for video tracks.
*/
public static final int TRACK_TYPE_VIDEO = 2;
/**
* A type constant for text tracks.
*/
public static final int TRACK_TYPE_TEXT = 3;
/**
* A type constant for metadata tracks.
*/
public static final int TRACK_TYPE_METADATA = 4;
/**
* Applications or extensions may define custom {@code TRACK_TYPE_*} constants greater than or
* equal to this value.
*/
public static final int TRACK_TYPE_CUSTOM_BASE = 10000;
/**
* A selection reason constant for selections whose reasons are unknown or unspecified.
*/
public static final int SELECTION_REASON_UNKNOWN = 0;
/**
* A selection reason constant for an initial track selection.
*/
public static final int SELECTION_REASON_INITIAL = 1;
/**
* A selection reason constant for an manual (i.e. user initiated) track selection.
*/
public static final int SELECTION_REASON_MANUAL = 2;
/**
* A selection reason constant for an adaptive track selection.
*/
public static final int SELECTION_REASON_ADAPTIVE = 3;
/**
* A selection reason constant for a trick play track selection.
*/
public static final int SELECTION_REASON_TRICK_PLAY = 4;
/**
* Applications or extensions may define custom {@code SELECTION_REASON_*} constants greater than
* or equal to this value.
*/
public static final int SELECTION_REASON_CUSTOM_BASE = 10000;
/**
* A default size in bytes for an individual allocation that forms part of a larger buffer.
*/
public static final int DEFAULT_BUFFER_SEGMENT_SIZE = 64 * 1024;
/**
* A default size in bytes for a video buffer.
*/
public static final int DEFAULT_VIDEO_BUFFER_SIZE = 200 * DEFAULT_BUFFER_SEGMENT_SIZE;
/**
* A default size in bytes for an audio buffer.
*/
public static final int DEFAULT_AUDIO_BUFFER_SIZE = 54 * DEFAULT_BUFFER_SEGMENT_SIZE;
/**
* A default size in bytes for a text buffer.
*/
public static final int DEFAULT_TEXT_BUFFER_SIZE = 2 * DEFAULT_BUFFER_SEGMENT_SIZE;
/**
* A default size in bytes for a metadata buffer.
*/
public static final int DEFAULT_METADATA_BUFFER_SIZE = 2 * DEFAULT_BUFFER_SEGMENT_SIZE;
/**
* A default size in bytes for a muxed buffer (e.g. containing video, audio and text).
*/
public static final int DEFAULT_MUXED_BUFFER_SIZE = DEFAULT_VIDEO_BUFFER_SIZE
+ DEFAULT_AUDIO_BUFFER_SIZE + DEFAULT_TEXT_BUFFER_SIZE;
/**
* The Nil UUID as defined by
* <a href="https://tools.ietf.org/html/rfc4122#section-4.1.7">RFC4122</a>.
*/
public static final UUID UUID_NIL = new UUID(0L, 0L);
/**
* UUID for the Widevine DRM scheme.
* <p></p>
* Widevine is supported on Android devices running Android 4.3 (API Level 18) and up.
*/
public static final UUID WIDEVINE_UUID = new UUID(0xEDEF8BA979D64ACEL, 0xA3C827DCD51D21EDL);
/**
* UUID for the PlayReady DRM scheme.
* <p>
* PlayReady is supported on all AndroidTV devices. Note that most other Android devices do not
* provide PlayReady support.
*/
public static final UUID PLAYREADY_UUID = new UUID(0x9A04F07998404286L, 0xAB92E65BE0885F95L);
/**
* The type of a message that can be passed to a video {@link Renderer} via
* {@link ExoPlayer#sendMessages} or {@link ExoPlayer#blockingSendMessages}. The message object
* should be the target {@link Surface}, or null.
*/
public static final int MSG_SET_SURFACE = 1;
/**
* A type of a message that can be passed to an audio {@link Renderer} via
* {@link ExoPlayer#sendMessages} or {@link ExoPlayer#blockingSendMessages}. The message object
* should be a {@link Float} with 0 being silence and 1 being unity gain.
*/
public static final int MSG_SET_VOLUME = 2;
/**
* A type of a message that can be passed to an audio {@link Renderer} via
* {@link ExoPlayer#sendMessages} or {@link ExoPlayer#blockingSendMessages}. The message object
* should be a {@link android.media.PlaybackParams}, or null, which will be used to configure the
* underlying {@link android.media.AudioTrack}. The message object should not be modified by the
* caller after it has been passed
*/
public static final int MSG_SET_PLAYBACK_PARAMS = 3;
/**
* A type of a message that can be passed to an audio {@link Renderer} via
* {@link ExoPlayer#sendMessages} or {@link ExoPlayer#blockingSendMessages}. The message object
* should be one of the integer stream types in {@link C.StreamType}, and will specify the stream
* type of the underlying {@link android.media.AudioTrack}. See also
* {@link android.media.AudioTrack#AudioTrack(int, int, int, int, int, int)}. If the stream type
* is not set, audio renderers use {@link #STREAM_TYPE_DEFAULT}.
* <p>
* Note that when the stream type changes, the AudioTrack must be reinitialized, which can
* introduce a brief gap in audio output. Note also that tracks in the same audio session must
* share the same routing, so a new audio session id will be generated.
*/
public static final int MSG_SET_STREAM_TYPE = 4;
/**
* The type of a message that can be passed to a {@link MediaCodec}-based video {@link Renderer}
* via {@link ExoPlayer#sendMessages} or {@link ExoPlayer#blockingSendMessages}. The message
* object should be one of the integer scaling modes in {@link C.VideoScalingMode}.
* <p>
* Note that the scaling mode only applies if the {@link Surface} targeted by the renderer is
* owned by a {@link android.view.SurfaceView}.
*/
public static final int MSG_SET_SCALING_MODE = 5;
/**
* Applications or extensions may define custom {@code MSG_*} constants greater than or equal to
* this value.
*/
public static final int MSG_CUSTOM_BASE = 10000;
/**
* The stereo mode for 360/3D/VR videos.
*/
@Retention(RetentionPolicy.SOURCE)
@IntDef({
Format.NO_VALUE,
STEREO_MODE_MONO,
STEREO_MODE_TOP_BOTTOM,
STEREO_MODE_LEFT_RIGHT,
STEREO_MODE_STEREO_MESH
})
public @interface StereoMode {}
/**
* Indicates Monoscopic stereo layout, used with 360/3D/VR videos.
*/
public static final int STEREO_MODE_MONO = 0;
/**
* Indicates Top-Bottom stereo layout, used with 360/3D/VR videos.
*/
public static final int STEREO_MODE_TOP_BOTTOM = 1;
/**
* Indicates Left-Right stereo layout, used with 360/3D/VR videos.
*/
public static final int STEREO_MODE_LEFT_RIGHT = 2;
/**
* Indicates a stereo layout where the left and right eyes have separate meshes,
* used with 360/3D/VR videos.
*/
public static final int STEREO_MODE_STEREO_MESH = 3;
/**
* Converts a time in microseconds to the corresponding time in milliseconds, preserving
* {@link #TIME_UNSET} values.
*
* @param timeUs The time in microseconds.
* @return The corresponding time in milliseconds.
*/
public static long usToMs(long timeUs) {
return timeUs == TIME_UNSET ? TIME_UNSET : (timeUs / 1000);
}
/**
* Converts a time in milliseconds to the corresponding time in microseconds, preserving
* {@link #TIME_UNSET} values.
*
* @param timeMs The time in milliseconds.
* @return The corresponding time in microseconds.
*/
public static long msToUs(long timeMs) {
return timeMs == TIME_UNSET ? TIME_UNSET : (timeMs * 1000);
}
/**
* Returns a newly generated {@link android.media.AudioTrack} session identifier.
*/
@TargetApi(21)
public static int generateAudioSessionIdV21(Context context) {
return ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE))
.generateAudioSessionId();
}
}
| |
/*******************************************************************************
* Copyright (c) 2014 eBay Software Foundation.
*
* 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.ostara.cmd.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class FileUtils {
public static String getTempIODir() {
return getTempIODir(false);
}
public static String getTempIODir(boolean createFolder) {
String folderPath = System.getProperty("java.io.tmpdir") + "/" + System.currentTimeMillis();
if (createFolder) {
new File(folderPath).mkdirs();
}
return folderPath;
}
public static void copy(InputStream is, OutputStream os) throws IOException {
byte[] content = new byte[4096];
try {
while (true) {
int size = is.read(content);
if (size == -1) {
break;
} else {
os.write(content, 0, size);
}
}
} finally {
try{is.close();} catch(Throwable e){};
try{os.close();} catch(Throwable e){};
}
}
public static void writeFile(String fileName, String text, String characterEncoding)
throws UnsupportedEncodingException, FileNotFoundException, IOException {
FileOutputStream fos;
byte[] buf = text.getBytes(characterEncoding);
int numWritten;
fos = new FileOutputStream(fileName);
numWritten = 0;
fos.write(buf, numWritten, buf.length);
fos.close();
}
public static String readFile(String fileName, String characterEncoding) throws UnsupportedEncodingException,
FileNotFoundException, IOException {
FileInputStream fis;
InputStreamReader isr;
StringBuilder sb = new StringBuilder(75000);
char[] buf = new char[4096];
int numRead;
fis = new FileInputStream(fileName);
isr = new InputStreamReader(fis, characterEncoding);
do {
numRead = isr.read(buf, 0, buf.length);
if (numRead > 0) {
sb.append(buf, 0, numRead);
}
} while (numRead >= 0);
isr.close();
fis.close();
return sb.toString();
}
/** This does a binary file copy
*/
public static void copyFile(final String sourceFile, final String destinationFile) throws IOException {
final FileInputStream fis = new FileInputStream(sourceFile);
final FileOutputStream fos = new FileOutputStream(destinationFile);
try {
final byte[] buffer = new byte[4096];
int numBytesRead;
do {
numBytesRead = fis.read(buffer);
if (numBytesRead > 0) {
fos.write(buffer, 0, numBytesRead);
}
} while (numBytesRead >= 0);
} finally {
try {
fos.flush();
} finally {
try {
fos.close();
} finally {
fis.close();
}
}
}
}
/** This is a convenience method thread reads an input stream into a
* List<String>
*
* @param inputStream
* @return
* @throws IOException
*/
public static List<String> readLines(final InputStream inputStream) throws IOException {
final String text = readStream(inputStream);
StringTokenizer tokenizer = new StringTokenizer(text, "\n\r");
List<String> list = new ArrayList<String>();
while (tokenizer.hasMoreElements()) {
final String line = tokenizer.nextToken();
list.add(line);
}
return list;
}
public static String readStream(final InputStream inputStream, boolean autoClose) throws IOException {
try {
return readStream(inputStream);
} finally {
if(autoClose) {
try {inputStream.close();} catch(Throwable e){};
}
}
}
/** This is a convienence method to read text from an input stream into a
* string. It will use the default encoding of the OS.
* It call the underlying readString(InputStreamReader)
*
* @param inputStream - InputStream
* @return String - the text that was read in
* @throws IOException
*/
public static String readStream(final InputStream inputStream) throws IOException {
final InputStreamReader isr = new InputStreamReader(inputStream);
try {
return readStream(isr);
} finally {
isr.close();
}
}
/** This is a convienence method to read text from a stream into a string.
* The transfer buffer is 4k and the initial string buffer is 75k. If
* this causes a problem, write your own routine.
*
* @param isr - InputStreamReader
* @return String - the text that was read in
* @throws IOException
*/
public static String readStream(final InputStreamReader isr) throws IOException {
StringBuilder sb = new StringBuilder(75000);
char[] buf = new char[4096];
int numRead;
do {
numRead = isr.read(buf, 0, buf.length);
if (numRead > 0) {
sb.append(buf, 0, numRead);
}
} while (numRead >= 0);
final String result = sb.toString();
return result;
}
/**
* Answers the String value of the specified resourceName. The resourceName
* is looked for in the calling methods Class space.
* @param resourceName
* @return String value of the resource
* @throws IOException
*/
// public static String getResourceAsString(String resourceName)
// throws IOException
// {
// return getResourceAsString(CallerIntrospector.getCaller(), resourceName) ;
// }
/**
* Answers the String value of the specified resourceName. The resourceName
* is looked for in the calling methods Class space. If an IOException
* occurs, null is returned.
* @param resourceName
* @return String value of the resource
*/
// public static String getResourceString(String resourceName) {
// return getResourceString(CallerIntrospector.getCaller(), resourceName) ;
// }
// public static String getResourceString(Class<?> clz, String resourceName) {
// try {
// return getResourceAsString(clz, resourceName) ;
// }
// catch(IOException e) {
// return null ;
// }
// }
// public static String getResourceAsString(Class<?> clz, String resourceName)
// throws IOException
// {
// final InputStream is = clz.getResourceAsStream(resourceName) ;
// final byte bytes[] = new byte[4096] ;
// final RopeBuffer buffer = new RopeBuffer() ;
// while(true) {
// int bytesRead = is.read(bytes) ;
// String thisChunk = new String(bytes, 0, bytesRead) ;
// buffer.append(thisChunk) ;
// if (bytesRead < 4096) {
// break ;
// }
// }
// return buffer.toString() ;
// }
/** This is a convienence method to read text from a stream into a string.
* The transfer buffer is 4k and the initial string buffer is 75k. If
* this causes a problem, write your own routine.
*
* @param isr - InputStreamReader
* @return String - the text that was read in
* @throws IOException
*/
public static boolean isDirectoryWithFiles(String directory) {
if (directory == null || directory.trim().length() == 0)
return false;
File dir = new File(directory);
if (dir.isDirectory()) {
String[] files = dir.list();
if (files != null && files.length > 0)
return true;
}
return false;
}
//
// Helper Class(es)
//
private final static class CallerIntrospector extends SecurityManager {
static CallerIntrospector instance = new CallerIntrospector();
static Class<?> getCaller() {
return instance.getClassContext()[2];
}
}
}
| |
package com.lsu.vizeq;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.util.Random;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TableRow;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
public class ProfileActivity extends BackableActivity implements OnItemSelectedListener, UseSearchResults {
public String mColor;
Spinner spinner;
LinearLayout customSearchLayout;
OnClickListener submitListener;
ActionBar actionBar;
ProgressBar progress;
public MyApplication myapp;
OnTouchListener rowTap;
AsyncHttpClient searchClient = new AsyncHttpClient();
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// An item was selected. You can retrieve the selected item using parent.getItemAtPosition(pos)
spinner.setSelection(pos);
SharedPreferences memory = getSharedPreferences("VizEQ", MODE_PRIVATE);
mColor = (String) parent.getItemAtPosition(pos);
SharedPreferences.Editor saver = memory.edit();
saver.putString("color", mColor);
saver.putInt("colorPos", pos);
saver.commit();
Log.d("Color", "item selected");
actionBar = getActionBar();
int posi = memory.getInt("colorPos", -1);
if (posi != -1)
{
VizEQ.numRand = posi;
if (VizEQ.numRand == 0){
Random r = new Random();
VizEQ.numRand = r.nextInt(5) + 1;
}
switch (VizEQ.numRand)
{
case 1:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Red)));
VizEQ.colorScheme = getResources().getColor(R.color.Red);
break;
case 2:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Green)));
VizEQ.colorScheme = getResources().getColor(R.color.Green);
break;
case 3:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Blue)));
VizEQ.colorScheme = getResources().getColor(R.color.Blue);
break;
case 4:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Purple)));
VizEQ.colorScheme = getResources().getColor(R.color.Purple);
break;
case 5:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Orange)));
VizEQ.colorScheme = getResources().getColor(R.color.Orange);
break;
}
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
Log.d("Color", "Nothing Selected");
actionBar = getActionBar();
SharedPreferences memory = getSharedPreferences("VizEQ", MODE_PRIVATE);
int posi = memory.getInt("colorPos", -1);
spinner.setSelection(posi);
if (posi > 0)
{
VizEQ.numRand = posi;
switch (VizEQ.numRand)
{
case 1:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Red)));
break;
case 2:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Green)));
break;
case 3:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Blue)));
break;
case 4:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Purple)));
break;
case 5:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Orange)));
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
actionBar = getActionBar();
progress = (ProgressBar)findViewById(R.id.spinner2);
myapp = (MyApplication) this.getApplicationContext();
EditText et = (EditText) this.findViewById(R.id.ProfileUsername);
SharedPreferences memory = getSharedPreferences("VizEQ",MODE_PRIVATE);
String userName = memory.getString("username", "");
if(userName.equals("")) et.setHint("Enter username");
else et.setText(userName);
refreshQueue();
int posi = memory.getInt("colorPos", -1);
if (posi > 0) VizEQ.numRand = posi;
switch (VizEQ.numRand)
{
case 1:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Red)));
break;
case 2:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Green)));
break;
case 3:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Blue)));
break;
case 4:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Purple)));
break;
case 5:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Orange)));
break;
}
customSearchLayout = (LinearLayout) findViewById(R.id.customSearchLayout);
final EditText searchText = (EditText) findViewById(R.id.CustomSearchField);
TabHost tabhost = (TabHost) findViewById(android.R.id.tabhost);
tabhost.setup();
TabSpec ts = tabhost.newTabSpec("tab01");
ts.setContent(R.id.tab01);
ts.setIndicator("Search");
tabhost.addTab(ts);
ts = tabhost.newTabSpec("tab02");
ts.setContent(R.id.tab02);
ts.setIndicator("My Requests");
tabhost.addTab(ts);
ts = tabhost.newTabSpec("tab03");
ts.setContent(R.id.tab03);
ts.setIndicator("Profile");
tabhost.addTab(ts);
Button submit = (Button)findViewById(R.id.SubmitCustomList);
submit.setOnClickListener(submitListener);
//Animation an = new Animation();
// Color Spinner
spinner = (Spinner) findViewById(R.id.colorspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.color_spinner, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener(this);
spinner.setAdapter(adapter);
if (posi == -1) posi = 0;
spinner.setSelection(posi);
Switch camFlash = (Switch) findViewById(R.id.CamFlash);
Switch bgFlash = (Switch) findViewById(R.id.BGFlash);
camFlash.setChecked(memory.getBoolean("cameraFlash", true));
bgFlash.setChecked(memory.getBoolean("backgroundFlash", true));
final SharedPreferences.Editor saver = memory.edit();
camFlash.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
MyApplication.doFlash = isChecked;
saver.putBoolean("cameraFlash", isChecked);
saver.commit();
}
});
bgFlash.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
MyApplication.doBackground = isChecked;
saver.putBoolean("backgroundFlash", isChecked);
saver.commit();
}
});
rowTap = new OnTouchListener()
{
@Override
public boolean onTouch(View arg0, MotionEvent arg1)
{
if (arg1.getAction() == MotionEvent.ACTION_DOWN)
{
TableRow row = (TableRow)arg0;
row.setBackgroundColor(Color.BLUE);
return true;
}
else if (arg1.getAction() == MotionEvent.ACTION_UP)
{
final TrackRow row = (TrackRow)arg0;
row.setBackgroundColor(row.originalColor);
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this);
builder.setMessage(R.string.RequestPrompt)
.setPositiveButton("Add to queue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
myapp.queue.add(0, row.getTrack());
refreshQueue();
customSearchLayout.removeView(row);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
//builder.create();
builder.show();
return true;
}
else if (arg1.getAction() == MotionEvent.ACTION_CANCEL)
{
TrackRow row = (TrackRow)arg0;
row.setBackgroundColor(row.originalColor);
return true;
}
return false;
}
};
findViewById(R.id.SearchOK).setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0)
{
customSearchLayout.removeAllViews();
String strSearch;
searchText.clearFocus();
progress.setVisibility(View.VISIBLE);
try
{
strSearch = URLEncoder.encode(searchText.getText().toString(), "UTF-8");
} catch (UnsupportedEncodingException e1)
{
strSearch = searchText.getText().toString().replace(' ', '+');
e1.printStackTrace();
}
final String search = strSearch;
final SearchProvider searchProvider = new SearchProvider(ProfileActivity.this);
searchProvider.SearchForTrack(search, ProfileActivity.this);
}
});
findViewById(R.id.SubmitCustomList).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if(!isNetworkAvailable())
{
noNetworkNotification();
}
else if(myapp.hostAddress == null)
{
noHostNotification();
}
else
{
sendRequest();
}
}
});
}
public void updateName(View view)
{
EditText et = (EditText) findViewById(R.id.ProfileUsername);
myapp.myName = et.getText().toString();
if (!et.getText().toString().equals("Enter username")){
System.out.print(et.getText().toString());
SharedPreferences memory = getSharedPreferences("VizEQ", MODE_PRIVATE);
SharedPreferences.Editor saver = memory.edit();
saver.putString("username", et.getText().toString());
saver.commit();
}
}
public void noNetworkNotification()
{
//Log.d("Contact Server", "Name already in use");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("No network connection").setCancelable(false)
.setPositiveButton("ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void noHostNotification()
{
//Log.d("Contact Server", "Name already in use");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You haven't joined a party yet. :(").setCancelable(false)
.setPositiveButton("ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
});
AlertDialog alert = builder.create();
alert.show();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public void sendRequest()
{
new Thread(new Runnable()
{
@Override
public void run()
{
DatagramSocket sendSocket;
try
{
sendSocket = new DatagramSocket();
//make a packet containing all elements with newlines between each
for (int j = 0; j < myapp.queue.size(); j++)
{
// Log.d("SendRequestTask", "Sending: "+myapp.queue.get(j).mTrack);
byte[] requestHeader = "request\n".getBytes();
byte[] backslashN = "\n".getBytes();
byte[] albumBytes = myapp.queue.get(j).mAlbum.getBytes();
byte[] artistBytes = myapp.queue.get(j).mArtist.getBytes();
byte[] requesterBytes = myapp.myName.getBytes(); //myapp.queue.get(j).mRequester.getBytes(); //NO
byte[] trackBytes= myapp.queue.get(j).mTrack.getBytes();
byte[] uriBytes = myapp.queue.get(j).mUri.getBytes();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(requestHeader);
outputStream.write(albumBytes);
outputStream.write(backslashN);
outputStream.write(artistBytes);
outputStream.write(backslashN);
outputStream.write(requesterBytes);
outputStream.write(backslashN);
outputStream.write(trackBytes);
outputStream.write(backslashN);
outputStream.write(uriBytes);
outputStream.write(backslashN);
byte[] sendData = outputStream.toByteArray();
InetAddress ip = RoleActivity.myapp.hostAddress;
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, 7770);
sendSocket.send(sendPacket);
}
sendSocket.close();
myapp.queue.clear();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread(new Runnable()
{
@Override
public void run() {
refreshQueue();
}
});
}
}).start();
}
public void refreshQueue()
{
LinearLayout queueTab = (LinearLayout) findViewById(R.id.profile_queue);
queueTab.removeAllViews(); //remove everything that's there
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
// Log.d("refreshQueue", "refreshing");
/*---color stuff---*/
//Calculate start and end colors
int startColor = 0;
int endColor = 0;
SharedPreferences memory = getSharedPreferences("VizEQ",MODE_PRIVATE);
int posi = memory.getInt("colorPos", -1);
if (posi > 0) VizEQ.numRand = posi;
switch (VizEQ.numRand)
{
case 1:
startColor = getResources().getColor(R.color.Red); //203, 32, 38
endColor = Color.rgb(203+50, 32+90, 38+90);
break;
case 2:
startColor = getResources().getColor(R.color.Green);//100, 153, 64
endColor = Color.rgb(100+90, 153+90, 64+90);
break;
case 3:
startColor = getResources().getColor(R.color.Blue); //0, 153, 204
endColor = Color.rgb(0+90, 153+90, 204+50);
break;
case 4:
startColor = getResources().getColor(R.color.Purple); //155, 105, 172
endColor = Color.rgb(155+70, 105+70, 172+70);
break;
case 5:
startColor = getResources().getColor(R.color.Orange); //245, 146, 30
endColor = Color.rgb(245, 146+90, 30+90);
break;
}
int redStart = Color.red(startColor);
int redEnd = Color.red(endColor);
int addRed = (redEnd - redStart)/15;
int greenStart = Color.green(startColor);
int greenEnd = Color.green(endColor);
int addGreen = (greenEnd - greenStart)/15;
int blueStart = Color.blue(startColor);
int blueEnd = Color.blue(endColor);
int addBlue = (blueEnd - blueStart)/15;
/*---queue stuff---*/
for(int i=0; i<myapp.queue.size(); i++)
{
TrackRow queueRow = new TrackRow(this.getBaseContext(), myapp.queue.get(i).mTrack, myapp.queue.get(i).mAlbum, myapp.queue.get(i).mArtist, myapp.queue.get(i).mUri, myapp.queue.get(i).mThumbnail);
queueRow.setOnTouchListener(null);
int r,g,b;
if (i>15)
{
r = redEnd;
g = greenEnd;
b = blueEnd;
}
else
{
r = redStart + addRed * i;
g = greenStart + addGreen * i;
b = blueStart + addBlue * i;
}
queueRow.setBackgroundColor(Color.argb(255, r, g, b));
params.setMargins(0, 2, 0, 2);
queueTab.addView(queueRow, params);
// Log.d("refresh queue", "adding row to tab");
}
}
public void NoConnectionNotification()
{
// Log.d("Contact Server", "Error connecting");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Unable to search - no network connection").setCancelable(false)
.setPositiveButton("ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
});
AlertDialog alert = builder.create();
alert.show();
}
@Override
public void useResults(SearchResults searchResults)
{
progress.setVisibility(Spinner.GONE);
if (searchResults.mConnectionError) {
NoConnectionNotification();
return;
}
if (searchResults.mJsonError) {
return;
}
if (searchResults.mResults.length == 0) {
final TextView noResults = new TextView(ProfileActivity.this);
noResults.setText("There are no results.");
customSearchLayout.addView(noResults);
return;
}
//Calculate start and end colors
int startColor = 0;
int endColor = 0;
SharedPreferences memory = getSharedPreferences("VizEQ",MODE_PRIVATE);
int posi = memory.getInt("colorPos", -1);
if (posi > 0) VizEQ.numRand = posi;
switch (VizEQ.numRand)
{
case 1:
startColor = getResources().getColor(R.color.Red); //203, 32, 38
endColor = Color.rgb(203+50, 32+90, 38+90);
break;
case 2:
startColor = getResources().getColor(R.color.Green);//100, 153, 64
endColor = Color.rgb(100+90, 153+90, 64+90);
break;
case 3:
startColor = getResources().getColor(R.color.Blue); //0, 153, 204
endColor = Color.rgb(0+90, 153+90, 204+50);
break;
case 4:
startColor = getResources().getColor(R.color.Purple); //155, 105, 172
endColor = Color.rgb(155+70, 105+70, 172+70);
break;
case 5:
startColor = getResources().getColor(R.color.Orange); //245, 146, 30
endColor = Color.rgb(245, 146+90, 30+90);
break;
}
int redStart = Color.red(startColor);
int redEnd = Color.red(endColor);
int addRed = (redEnd - redStart)/15;
int greenStart = Color.green(startColor);
int greenEnd = Color.green(endColor);
int addGreen = (greenEnd - greenStart)/15;
int blueStart = Color.blue(startColor);
int blueEnd = Color.blue(endColor);
int addBlue = (blueEnd - blueStart)/15;
for (int i = 0; i < searchResults.mResults.length; i++)
{
TrackRow tableRowToAdd = searchResults.mResults[i];
tableRowToAdd.setBackgroundColor(Color.argb(255, redStart, greenStart, blueStart));
tableRowToAdd.originalColor = (Color.argb(255, redStart, greenStart, blueStart));
tableRowToAdd.setOnTouchListener(rowTap);
if (redStart + addRed < 255 && i < 16) redStart += addRed;
if (greenStart + addGreen < 255 && i < 16) greenStart += addGreen;
if (blueStart + addBlue < 255 && i < 16) blueStart += addBlue;
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 2, 0, 2);
customSearchLayout.addView(tableRowToAdd, params);
}
}
}
| |
/*
* Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved.
*/
package jsystem.treeui.sobrows;
import jsystem.treeui.sobrows.Options.Access;
import jsystem.utils.StringUtils;
/**
* A class member. Use as method parameter as well.
*
* @author guy.arieli
*
*/
public class Member implements CodeElement {
/**
* The member access public/private ...
*/
private Access access = Access.NO;
/**
* The name of the member
*/
private String name = null;
/**
* The type of the member
*/
private String type = null;
/**
* the default value of the member
*/
private String value = null;
/**
* diterminate if the member is an array
*/
private boolean isArray = false;
/**
* Init a member to be used as a class field
*
* @param name
* the member name
* @param type
* the member type
* @param value
* the member default value
* @param access
* the access of the member
*/
public Member(String name, String type, String value, Access access) {
this.name = name;
this.type = type;
this.value = value;
this.access = access;
}
/**
* Init a member to be used as parameter to method
*
* @param name
* the nember name
* @param type
* the member type
*/
public Member(String name, String type) {
this.name = name;
this.type = type;
}
public Member() {
// default constractor
}
/**
* @return the member as a string (public int index = 0 ...)
*/
public String toString() {
return Options.getAccessString(access) + type + ((isArray) ? "[]" : "") + " " + name
+ ((value == null) ? "" : " = " + value) + ";";
}
/**
*
* @return the string of method parameter (int index).
*/
public String toParameterString() {
return type + ((isArray) ? "[]" : "") + " " + name;
}
/**
*
* @return the member access
*/
public Access getAccess() {
return access;
}
/**
* Set the member access see Options class
*
* @param access
*/
public void setAccess(Access access) {
this.access = access;
}
/**
* Get the member name
*
* @return the member name
*/
public String getName() {
return name;
}
/**
* Set the member name
*
* @param name
* the member name
*/
public void setName(String name) {
this.name = name;
}
/**
* Get the member type
*
* @return the member type
*/
public String getType() {
return type;
}
/**
* Set the member type
*
* @param type
* the member type
*/
public void setType(String type) {
this.type = type;
}
/**
* Get the member defulat value
*
* @return member value
*/
public String getValue() {
return value;
}
/**
* Set the member defualt value
*
* @param value
*/
public void setValue(String value) {
this.value = value;
}
/**
* Add to overall code
*/
public void addToCode(Code code) {
code.addLine(toString());
}
/**
* Get a setter method for this member
*
* @return a setter method
*/
public Method getSetter() {
Method m = new Method();
m.setAccess(Access.PUBLIC);
m.setJavadoc("set the " + name);
m.setMethodName("set" + StringUtils.firstCharToUpper(name));
m.setMethodCode("this." + name + " = " + name + ";");
m.addParameter(this);
m.setReturnType("void");
m.setThrowsName(null);
// m.setReturnArray(isArray);
return m;
}
/**
* Get a getter method for this member
*
* @return a getter method
*/
public Method getGetter() {
Method m = new Method();
m.setAccess(Access.PUBLIC);
m.setJavadoc("get the " + name);
m.setMethodName("get" + StringUtils.firstCharToUpper(name));
m.setMethodCode("return " + name + ";");
m.setReturnType(type);
m.setThrowsName(null);
m.setReturnArray(isArray);
return m;
}
/**
* Is member an array
*
* @return true if member is an array
*/
public boolean isArray() {
return isArray;
}
/**
* Set the member array status
*
* @param isArray
*/
public void setArray(boolean isArray) {
this.isArray = isArray;
}
}
| |
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.pricer.fxopt;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import org.joda.beans.Bean;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.ImmutableConstructor;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.opengamma.strata.basics.currency.CurrencyPair;
import com.opengamma.strata.basics.date.DayCount;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.data.MarketDataName;
import com.opengamma.strata.market.ValueType;
import com.opengamma.strata.market.curve.Curve;
import com.opengamma.strata.market.curve.CurveInfoType;
import com.opengamma.strata.market.curve.Curves;
import com.opengamma.strata.market.curve.InterpolatedNodalCurve;
import com.opengamma.strata.market.param.CurrencyParameterSensitivities;
import com.opengamma.strata.market.param.CurrencyParameterSensitivity;
import com.opengamma.strata.market.param.ParameterMetadata;
import com.opengamma.strata.market.param.ParameterPerturbation;
import com.opengamma.strata.market.param.UnitParameterSensitivity;
import com.opengamma.strata.market.sensitivity.PointSensitivities;
import com.opengamma.strata.market.sensitivity.PointSensitivity;
import com.opengamma.strata.pricer.impl.option.BlackFormulaRepository;
import com.opengamma.strata.product.common.PutCall;
/**
* Volatility for FX options in the log-normal or Black model based on a curve.
* <p>
* The volatility is represented by a curve on the expiry and the volatility
* is flat along the strike direction.
*/
@BeanDefinition
public final class BlackFxOptionFlatVolatilities
implements BlackFxOptionVolatilities, ImmutableBean, Serializable {
/**
* The currency pair that the volatilities are for.
*/
@PropertyDefinition(validate = "notNull", overrideGet = true)
private final CurrencyPair currencyPair;
/**
* The valuation date-time.
* All data items in this provider is calibrated for this date-time.
*/
@PropertyDefinition(validate = "notNull", overrideGet = true)
private final ZonedDateTime valuationDateTime;
/**
* The Black volatility curve.
* <p>
* The x-values represent the expiry year-fraction.
* The metadata of the curve must define a day count.
*/
@PropertyDefinition(validate = "notNull")
private final Curve curve;
/**
* The day count convention of the curve.
*/
private final DayCount dayCount; // cached, not a property
//-------------------------------------------------------------------------
/**
* Obtains an instance from an expiry-volatility curve and the date-time for which it is valid.
* <p>
* The curve is specified by an instance of {@link Curve}, such as {@link InterpolatedNodalCurve}.
* The curve must contain the correct metadata:
* <ul>
* <li>The x-value type must be {@link ValueType#YEAR_FRACTION}
* <li>The y-value type must be {@link ValueType#BLACK_VOLATILITY}
* <li>The day count must be set in the additional information using {@link CurveInfoType#DAY_COUNT}
* </ul>
* Suitable curve metadata can be created using
* {@link Curves#blackVolatilityByExpiry(String, DayCount)}.
*
* @param currencyPair the currency pair
* @param valuationDateTime the valuation date-time
* @param curve the volatility curve
* @return the volatilities
*/
public static BlackFxOptionFlatVolatilities of(
CurrencyPair currencyPair,
ZonedDateTime valuationDateTime,
Curve curve) {
return new BlackFxOptionFlatVolatilities(currencyPair, valuationDateTime, curve);
}
@ImmutableConstructor
private BlackFxOptionFlatVolatilities(
CurrencyPair currencyPair,
ZonedDateTime valuationDateTime,
Curve curve) {
ArgChecker.notNull(currencyPair, "currencyPair");
ArgChecker.notNull(valuationDateTime, "valuationDateTime");
ArgChecker.notNull(curve, "curve");
curve.getMetadata().getXValueType().checkEquals(
ValueType.YEAR_FRACTION, "Incorrect x-value type for Black volatilities");
curve.getMetadata().getYValueType().checkEquals(
ValueType.BLACK_VOLATILITY, "Incorrect y-value type for Black volatilities");
DayCount dayCount = curve.getMetadata().findInfo(CurveInfoType.DAY_COUNT)
.orElseThrow(() -> new IllegalArgumentException("Incorrect curve metadata, missing DayCount"));
this.currencyPair = currencyPair;
this.valuationDateTime = valuationDateTime;
this.curve = curve;
this.dayCount = dayCount;
}
//-------------------------------------------------------------------------
@Override
public FxOptionVolatilitiesName getName() {
return FxOptionVolatilitiesName.of(curve.getName().getName());
}
@Override
public <T> Optional<T> findData(MarketDataName<T> name) {
if (curve.getName().equals(name)) {
return Optional.of(name.getMarketDataType().cast(curve));
}
return Optional.empty();
}
@Override
public int getParameterCount() {
return curve.getParameterCount();
}
@Override
public double getParameter(int parameterIndex) {
return curve.getParameter(parameterIndex);
}
@Override
public ParameterMetadata getParameterMetadata(int parameterIndex) {
return curve.getParameterMetadata(parameterIndex);
}
@Override
public BlackFxOptionFlatVolatilities withParameter(int parameterIndex, double newValue) {
return new BlackFxOptionFlatVolatilities(
currencyPair, valuationDateTime, curve.withParameter(parameterIndex, newValue));
}
@Override
public BlackFxOptionFlatVolatilities withPerturbation(ParameterPerturbation perturbation) {
return new BlackFxOptionFlatVolatilities(
currencyPair, valuationDateTime, curve.withPerturbation(perturbation));
}
//-------------------------------------------------------------------------
@Override
public double volatility(CurrencyPair currencyPair, double expiry, double strike, double forward) {
return curve.yValue(expiry);
}
@Override
public CurrencyParameterSensitivities parameterSensitivity(PointSensitivities pointSensitivities) {
CurrencyParameterSensitivities sens = CurrencyParameterSensitivities.empty();
for (PointSensitivity point : pointSensitivities.getSensitivities()) {
if (point instanceof FxOptionSensitivity) {
FxOptionSensitivity pt = (FxOptionSensitivity) point;
if (pt.getVolatilitiesName().equals(getName())) {
sens = sens.combinedWith(parameterSensitivity(pt));
}
}
}
return sens;
}
private CurrencyParameterSensitivity parameterSensitivity(FxOptionSensitivity point) {
double expiry = point.getExpiry();
UnitParameterSensitivity unitSens = curve.yValueParameterSensitivity(expiry);
return unitSens.multipliedBy(point.getCurrency(), point.getSensitivity());
}
//-------------------------------------------------------------------------
@Override
public double price(double expiry, PutCall putCall, double strike, double forward, double volatility) {
return BlackFormulaRepository.price(forward, strike, expiry, volatility, putCall.isCall());
}
//-------------------------------------------------------------------------
@Override
public double relativeTime(ZonedDateTime dateTime) {
ArgChecker.notNull(dateTime, "dateTime");
LocalDate valuationDate = valuationDateTime.toLocalDate();
LocalDate date = dateTime.toLocalDate();
return dayCount.relativeYearFraction(valuationDate, date);
}
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
/**
* The meta-bean for {@code BlackFxOptionFlatVolatilities}.
* @return the meta-bean, not null
*/
public static BlackFxOptionFlatVolatilities.Meta meta() {
return BlackFxOptionFlatVolatilities.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(BlackFxOptionFlatVolatilities.Meta.INSTANCE);
}
/**
* The serialization version id.
*/
private static final long serialVersionUID = 1L;
/**
* Returns a builder used to create an instance of the bean.
* @return the builder, not null
*/
public static BlackFxOptionFlatVolatilities.Builder builder() {
return new BlackFxOptionFlatVolatilities.Builder();
}
@Override
public BlackFxOptionFlatVolatilities.Meta metaBean() {
return BlackFxOptionFlatVolatilities.Meta.INSTANCE;
}
@Override
public <R> Property<R> property(String propertyName) {
return metaBean().<R>metaProperty(propertyName).createProperty(this);
}
@Override
public Set<String> propertyNames() {
return metaBean().metaPropertyMap().keySet();
}
//-----------------------------------------------------------------------
/**
* Gets the currency pair that the volatilities are for.
* @return the value of the property, not null
*/
@Override
public CurrencyPair getCurrencyPair() {
return currencyPair;
}
//-----------------------------------------------------------------------
/**
* Gets the valuation date-time.
* All data items in this provider is calibrated for this date-time.
* @return the value of the property, not null
*/
@Override
public ZonedDateTime getValuationDateTime() {
return valuationDateTime;
}
//-----------------------------------------------------------------------
/**
* Gets the Black volatility curve.
* <p>
* The x-values represent the expiry year-fraction.
* The metadata of the curve must define a day count.
* @return the value of the property, not null
*/
public Curve getCurve() {
return curve;
}
//-----------------------------------------------------------------------
/**
* Returns a builder that allows this bean to be mutated.
* @return the mutable builder, not null
*/
public Builder toBuilder() {
return new Builder(this);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
BlackFxOptionFlatVolatilities other = (BlackFxOptionFlatVolatilities) obj;
return JodaBeanUtils.equal(currencyPair, other.currencyPair) &&
JodaBeanUtils.equal(valuationDateTime, other.valuationDateTime) &&
JodaBeanUtils.equal(curve, other.curve);
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash = hash * 31 + JodaBeanUtils.hashCode(currencyPair);
hash = hash * 31 + JodaBeanUtils.hashCode(valuationDateTime);
hash = hash * 31 + JodaBeanUtils.hashCode(curve);
return hash;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(128);
buf.append("BlackFxOptionFlatVolatilities{");
buf.append("currencyPair").append('=').append(currencyPair).append(',').append(' ');
buf.append("valuationDateTime").append('=').append(valuationDateTime).append(',').append(' ');
buf.append("curve").append('=').append(JodaBeanUtils.toString(curve));
buf.append('}');
return buf.toString();
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code BlackFxOptionFlatVolatilities}.
*/
public static final class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code currencyPair} property.
*/
private final MetaProperty<CurrencyPair> currencyPair = DirectMetaProperty.ofImmutable(
this, "currencyPair", BlackFxOptionFlatVolatilities.class, CurrencyPair.class);
/**
* The meta-property for the {@code valuationDateTime} property.
*/
private final MetaProperty<ZonedDateTime> valuationDateTime = DirectMetaProperty.ofImmutable(
this, "valuationDateTime", BlackFxOptionFlatVolatilities.class, ZonedDateTime.class);
/**
* The meta-property for the {@code curve} property.
*/
private final MetaProperty<Curve> curve = DirectMetaProperty.ofImmutable(
this, "curve", BlackFxOptionFlatVolatilities.class, Curve.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"currencyPair",
"valuationDateTime",
"curve");
/**
* Restricted constructor.
*/
private Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case 1005147787: // currencyPair
return currencyPair;
case -949589828: // valuationDateTime
return valuationDateTime;
case 95027439: // curve
return curve;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BlackFxOptionFlatVolatilities.Builder builder() {
return new BlackFxOptionFlatVolatilities.Builder();
}
@Override
public Class<? extends BlackFxOptionFlatVolatilities> beanType() {
return BlackFxOptionFlatVolatilities.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code currencyPair} property.
* @return the meta-property, not null
*/
public MetaProperty<CurrencyPair> currencyPair() {
return currencyPair;
}
/**
* The meta-property for the {@code valuationDateTime} property.
* @return the meta-property, not null
*/
public MetaProperty<ZonedDateTime> valuationDateTime() {
return valuationDateTime;
}
/**
* The meta-property for the {@code curve} property.
* @return the meta-property, not null
*/
public MetaProperty<Curve> curve() {
return curve;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case 1005147787: // currencyPair
return ((BlackFxOptionFlatVolatilities) bean).getCurrencyPair();
case -949589828: // valuationDateTime
return ((BlackFxOptionFlatVolatilities) bean).getValuationDateTime();
case 95027439: // curve
return ((BlackFxOptionFlatVolatilities) bean).getCurve();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
metaProperty(propertyName);
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
}
}
//-----------------------------------------------------------------------
/**
* The bean-builder for {@code BlackFxOptionFlatVolatilities}.
*/
public static final class Builder extends DirectFieldsBeanBuilder<BlackFxOptionFlatVolatilities> {
private CurrencyPair currencyPair;
private ZonedDateTime valuationDateTime;
private Curve curve;
/**
* Restricted constructor.
*/
private Builder() {
}
/**
* Restricted copy constructor.
* @param beanToCopy the bean to copy from, not null
*/
private Builder(BlackFxOptionFlatVolatilities beanToCopy) {
this.currencyPair = beanToCopy.getCurrencyPair();
this.valuationDateTime = beanToCopy.getValuationDateTime();
this.curve = beanToCopy.getCurve();
}
//-----------------------------------------------------------------------
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
case 1005147787: // currencyPair
return currencyPair;
case -949589828: // valuationDateTime
return valuationDateTime;
case 95027439: // curve
return curve;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
}
@Override
public Builder set(String propertyName, Object newValue) {
switch (propertyName.hashCode()) {
case 1005147787: // currencyPair
this.currencyPair = (CurrencyPair) newValue;
break;
case -949589828: // valuationDateTime
this.valuationDateTime = (ZonedDateTime) newValue;
break;
case 95027439: // curve
this.curve = (Curve) newValue;
break;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
return this;
}
@Override
public Builder set(MetaProperty<?> property, Object value) {
super.set(property, value);
return this;
}
@Override
public Builder setString(String propertyName, String value) {
setString(meta().metaProperty(propertyName), value);
return this;
}
@Override
public Builder setString(MetaProperty<?> property, String value) {
super.setString(property, value);
return this;
}
@Override
public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
super.setAll(propertyValueMap);
return this;
}
@Override
public BlackFxOptionFlatVolatilities build() {
return new BlackFxOptionFlatVolatilities(
currencyPair,
valuationDateTime,
curve);
}
//-----------------------------------------------------------------------
/**
* Sets the currency pair that the volatilities are for.
* @param currencyPair the new value, not null
* @return this, for chaining, not null
*/
public Builder currencyPair(CurrencyPair currencyPair) {
JodaBeanUtils.notNull(currencyPair, "currencyPair");
this.currencyPair = currencyPair;
return this;
}
/**
* Sets the valuation date-time.
* All data items in this provider is calibrated for this date-time.
* @param valuationDateTime the new value, not null
* @return this, for chaining, not null
*/
public Builder valuationDateTime(ZonedDateTime valuationDateTime) {
JodaBeanUtils.notNull(valuationDateTime, "valuationDateTime");
this.valuationDateTime = valuationDateTime;
return this;
}
/**
* Sets the Black volatility curve.
* <p>
* The x-values represent the expiry year-fraction.
* The metadata of the curve must define a day count.
* @param curve the new value, not null
* @return this, for chaining, not null
*/
public Builder curve(Curve curve) {
JodaBeanUtils.notNull(curve, "curve");
this.curve = curve;
return this;
}
//-----------------------------------------------------------------------
@Override
public String toString() {
StringBuilder buf = new StringBuilder(128);
buf.append("BlackFxOptionFlatVolatilities.Builder{");
buf.append("currencyPair").append('=').append(JodaBeanUtils.toString(currencyPair)).append(',').append(' ');
buf.append("valuationDateTime").append('=').append(JodaBeanUtils.toString(valuationDateTime)).append(',').append(' ');
buf.append("curve").append('=').append(JodaBeanUtils.toString(curve));
buf.append('}');
return buf.toString();
}
}
///CLOVER:ON
//-------------------------- AUTOGENERATED END --------------------------
}
| |
/*
* 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.ignite.jdbc.thin;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.binary.BinaryMarshaller;
import org.apache.ignite.internal.jdbc.thin.JdbcThinConnection;
import org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo;
import org.apache.ignite.internal.jdbc.thin.JdbcThinUtils;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.GridTestUtils;
import org.jetbrains.annotations.NotNull;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.Callable;
/**
* Connection test.
*/
public class JdbcThinConnectionSelfTest extends JdbcThinAbstractSelfTest {
/** IP finder. */
private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
cfg.setCacheConfiguration(cacheConfiguration(DEFAULT_CACHE_NAME));
TcpDiscoverySpi disco = new TcpDiscoverySpi();
disco.setIpFinder(IP_FINDER);
cfg.setDiscoverySpi(disco);
cfg.setMarshaller(new BinaryMarshaller());
return cfg;
}
/**
* @param name Cache name.
* @return Cache configuration.
* @throws Exception In case of error.
*/
private CacheConfiguration cacheConfiguration(@NotNull String name) throws Exception {
CacheConfiguration cfg = defaultCacheConfiguration();
cfg.setName(name);
return cfg;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
super.beforeTestsStarted();
startGridsMultiThreaded(2);
}
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
stopAllGrids();
}
/**
* @throws Exception If failed.
*/
@SuppressWarnings({"EmptyTryBlock", "unused"})
public void testDefaults() throws Exception {
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1")) {
// No-op.
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1/")) {
// No-op.
}
}
/**
* Test invalid endpoint.
*
* @throws Exception If failed.
*/
public void testInvalidEndpoint() throws Exception {
assertInvalid("jdbc:ignite:thin://", "Host name is empty");
assertInvalid("jdbc:ignite:thin://:10000", "Host name is empty");
assertInvalid("jdbc:ignite:thin:// :10000", "Host name is empty");
assertInvalid("jdbc:ignite:thin://127.0.0.1:-1", "Invalid port");
assertInvalid("jdbc:ignite:thin://127.0.0.1:0", "Invalid port");
assertInvalid("jdbc:ignite:thin://127.0.0.1:100000", "Invalid port");
}
/**
* Test invalid socket buffer sizes.
*
* @throws Exception If failed.
*/
public void testSocketBuffers() throws Exception {
assertInvalid("jdbc:ignite:thin://127.0.0.1?socketSendBuffer=-1",
"Property cannot be negative [name=" + JdbcThinUtils.PARAM_SOCK_SND_BUF);
assertInvalid("jdbc:ignite:thin://127.0.0.1?socketReceiveBuffer=-1",
"Property cannot be negative [name=" + JdbcThinUtils.PARAM_SOCK_RCV_BUF);
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1")) {
assertEquals(0, io(conn).socketSendBuffer());
assertEquals(0, io(conn).socketReceiveBuffer());
}
// Note that SO_* options are hints, so we check that value is equals to either what we set or to default.
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?socketSendBuffer=1024")) {
assertEquals(1024, io(conn).socketSendBuffer());
assertEquals(0, io(conn).socketReceiveBuffer());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?socketReceiveBuffer=1024")) {
assertEquals(0, io(conn).socketSendBuffer());
assertEquals(1024, io(conn).socketReceiveBuffer());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?" +
"socketSendBuffer=1024&socketReceiveBuffer=2048")) {
assertEquals(1024, io(conn).socketSendBuffer());
assertEquals(2048, io(conn).socketReceiveBuffer());
}
}
/**
* Test SQL hints.
*
* @throws Exception If failed.
*/
public void testSqlHints() throws Exception {
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1")) {
assertFalse(io(conn).distributedJoins());
assertFalse(io(conn).enforceJoinOrder());
assertFalse(io(conn).collocated());
assertFalse(io(conn).replicatedOnly());
assertFalse(io(conn).lazy());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?distributedJoins=true")) {
assertTrue(io(conn).distributedJoins());
assertFalse(io(conn).enforceJoinOrder());
assertFalse(io(conn).collocated());
assertFalse(io(conn).replicatedOnly());
assertFalse(io(conn).lazy());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?enforceJoinOrder=true")) {
assertFalse(io(conn).distributedJoins());
assertTrue(io(conn).enforceJoinOrder());
assertFalse(io(conn).collocated());
assertFalse(io(conn).replicatedOnly());
assertFalse(io(conn).lazy());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?collocated=true")) {
assertFalse(io(conn).distributedJoins());
assertFalse(io(conn).enforceJoinOrder());
assertTrue(io(conn).collocated());
assertFalse(io(conn).replicatedOnly());
assertFalse(io(conn).lazy());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?replicatedOnly=true")) {
assertFalse(io(conn).distributedJoins());
assertFalse(io(conn).enforceJoinOrder());
assertFalse(io(conn).collocated());
assertTrue(io(conn).replicatedOnly());
assertFalse(io(conn).lazy());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?lazy=true")) {
assertFalse(io(conn).distributedJoins());
assertFalse(io(conn).enforceJoinOrder());
assertFalse(io(conn).collocated());
assertFalse(io(conn).replicatedOnly());
assertTrue(io(conn).lazy());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?distributedJoins=true&" +
"enforceJoinOrder=true&collocated=true&replicatedOnly=true&lazy=true")) {
assertTrue(io(conn).distributedJoins());
assertTrue(io(conn).enforceJoinOrder());
assertTrue(io(conn).collocated());
assertTrue(io(conn).replicatedOnly());
assertTrue(io(conn).lazy());
}
}
/**
* Test TCP no delay property handling.
*
* @throws Exception If failed.
*/
public void testTcpNoDelay() throws Exception {
assertInvalid("jdbc:ignite:thin://127.0.0.1?tcpNoDelay=0",
"Failed to parse boolean property [name=" + JdbcThinUtils.PARAM_TCP_NO_DELAY);
assertInvalid("jdbc:ignite:thin://127.0.0.1?tcpNoDelay=1",
"Failed to parse boolean property [name=" + JdbcThinUtils.PARAM_TCP_NO_DELAY);
assertInvalid("jdbc:ignite:thin://127.0.0.1?tcpNoDelay=false1",
"Failed to parse boolean property [name=" + JdbcThinUtils.PARAM_TCP_NO_DELAY);
assertInvalid("jdbc:ignite:thin://127.0.0.1?tcpNoDelay=true1",
"Failed to parse boolean property [name=" + JdbcThinUtils.PARAM_TCP_NO_DELAY);
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1")) {
assertTrue(io(conn).tcpNoDelay());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?tcpNoDelay=true")) {
assertTrue(io(conn).tcpNoDelay());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?tcpNoDelay=True")) {
assertTrue(io(conn).tcpNoDelay());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?tcpNoDelay=false")) {
assertFalse(io(conn).tcpNoDelay());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1?tcpNoDelay=False")) {
assertFalse(io(conn).tcpNoDelay());
}
}
/**
* Test autoCloseServerCursor property handling.
*
* @throws Exception If failed.
*/
public void testAutoCloseServerCursorProperty() throws Exception {
String url = "jdbc:ignite:thin://127.0.0.1?" + JdbcThinUtils.PARAM_AUTO_CLOSE_SERVER_CURSOR;
String err = "Failed to parse boolean property [name=" + JdbcThinUtils.PARAM_AUTO_CLOSE_SERVER_CURSOR;
assertInvalid(url + "=0", err);
assertInvalid(url + "=1", err);
assertInvalid(url + "=false1", err);
assertInvalid(url + "=true1", err);
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1")) {
assertFalse(io(conn).autoCloseServerCursor());
}
try (Connection conn = DriverManager.getConnection(url + "=true")) {
assertTrue(io(conn).autoCloseServerCursor());
}
try (Connection conn = DriverManager.getConnection(url + "=True")) {
assertTrue(io(conn).autoCloseServerCursor());
}
try (Connection conn = DriverManager.getConnection(url + "=false")) {
assertFalse(io(conn).autoCloseServerCursor());
}
try (Connection conn = DriverManager.getConnection(url + "=False")) {
assertFalse(io(conn).autoCloseServerCursor());
}
}
/**
* Test schema property in URL.
*
* @throws Exception If failed.
*/
public void testSchema() throws Exception {
assertInvalid("jdbc:ignite:thin://127.0.0.1/qwe/qwe",
"Invalid URL format (only schema name is allowed in URL path parameter 'host:port[/schemaName]')" );
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1/public")) {
assertEquals("Invalid schema", "public", conn.getSchema());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1/" + DEFAULT_CACHE_NAME)) {
assertEquals("Invalid schema", DEFAULT_CACHE_NAME, conn.getSchema());
}
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1/_not_exist_schema_")) {
assertEquals("Invalid schema", "_not_exist_schema_", conn.getSchema());
}
}
/**
* Get client socket for connection.
*
* @param conn Connection.
* @return Socket.
* @throws Exception If failed.
*/
private static JdbcThinTcpIo io(Connection conn) throws Exception {
JdbcThinConnection conn0 = conn.unwrap(JdbcThinConnection.class);
return conn0.io();
}
/**
* Assert that provided URL is invalid.
*
* @param url URL.
* @param errMsg Error message.
*/
@SuppressWarnings("ThrowableNotThrown")
private void assertInvalid(final String url, String errMsg) {
GridTestUtils.assertThrowsAnyCause(log, new Callable<Void>() {
@Override public Void call() throws Exception {
DriverManager.getConnection(url);
return null;
}
}, SQLException.class, errMsg);
}
/**
* @throws Exception If failed.
*/
@SuppressWarnings("ThrowableNotThrown")
public void testClose() throws Exception {
final Connection conn;
try (Connection conn0 = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1")) {
conn = conn0;
assert conn != null;
assert !conn.isClosed();
}
assert conn.isClosed();
assert !conn.isValid(2): "Connection must be closed";
GridTestUtils.assertThrows(log, new Callable<Object>() {
@Override public Object call() throws Exception {
conn.isValid(-2);
return null;
}
}, SQLException.class, "Invalid timeout");
}
}
| |
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.dumptruckman.minecraft.chunky.bukkit.test.utils;
import com.dumptruckman.minecraft.chunky.bukkit.ChunkyBukkit;
import com.dumptruckman.minecraft.pluginbase.plugin.AbstractBukkitPlugin;
import com.dumptruckman.minecraft.pluginbase.util.FileUtils;
import junit.framework.Assert;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import org.mockito.Matchers;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.MockGateway;
import java.io.File;
import java.lang.reflect.Field;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
public class TestInstanceCreator {
private AbstractBukkitPlugin plugin;
private Server mockServer;
private CommandSender commandSender;
public static final File pluginDirectory = new File("bin/test/server/plugins/plugintest");
public static final File serverDirectory = new File("bin/test/server");
public static final File worldsDirectory = new File("bin/test/server");
public boolean setUp() {
FileUtils.deleteFolder(serverDirectory);
try {
pluginDirectory.mkdirs();
Assert.assertTrue(pluginDirectory.exists());
MockGateway.MOCK_STANDARD_METHODS = false;
plugin = PowerMockito.spy(new ChunkyBukkit());
// Let's let all MV files go to bin/test
doReturn(pluginDirectory).when(plugin).getDataFolder();
// Return a fake PDF file.
PluginDescriptionFile pdf = new PluginDescriptionFile("Chunky", "1.0",
"com.dumptruckman.minecraft.chunky.bukkit.ChunkyBukkit");
doReturn(pdf).when(plugin).getDescription();
doReturn(true).when(plugin).isEnabled();
plugin.setServerFolder(serverDirectory);
// Add Core to the list of loaded plugins
JavaPlugin[] plugins = new JavaPlugin[] { plugin };
// Mock the Plugin Manager
PluginManager mockPluginManager = PowerMockito.mock(PluginManager.class);
when(mockPluginManager.getPlugins()).thenReturn(plugins);
when(mockPluginManager.getPlugin("Chunky")).thenReturn(plugin);
when(mockPluginManager.getPermission(anyString())).thenReturn(null);
// Make some fake folders to fool the fake MV into thinking these worlds exist
File worldNormalFile = new File(plugin.getServerFolder(), "world");
Util.log("Creating world-folder: " + worldNormalFile.getAbsolutePath());
worldNormalFile.mkdirs();
File worldNetherFile = new File(plugin.getServerFolder(), "world_nether");
Util.log("Creating world-folder: " + worldNetherFile.getAbsolutePath());
worldNetherFile.mkdirs();
File worldSkylandsFile = new File(plugin.getServerFolder(), "world_the_end");
Util.log("Creating world-folder: " + worldSkylandsFile.getAbsolutePath());
worldSkylandsFile.mkdirs();
// Initialize the Mock server.
mockServer = mock(Server.class);
when(mockServer.getName()).thenReturn("TestBukkit");
Logger.getLogger("Minecraft").setParent(Util.logger);
when(mockServer.getLogger()).thenReturn(Util.logger);
when(mockServer.getWorldContainer()).thenReturn(worldsDirectory);
// Give the server some worlds
when(mockServer.getWorld(anyString())).thenAnswer(new Answer<World>() {
public World answer(InvocationOnMock invocation) throws Throwable {
String arg;
try {
arg = (String) invocation.getArguments()[0];
} catch (Exception e) {
return null;
}
return MockWorldFactory.getWorld(arg);
}
});
when(mockServer.getWorlds()).thenAnswer(new Answer<List<World>>() {
public List<World> answer(InvocationOnMock invocation) throws Throwable {
return MockWorldFactory.getWorlds();
}
});
when(mockServer.getPluginManager()).thenReturn(mockPluginManager);
when(mockServer.createWorld(Matchers.isA(WorldCreator.class))).thenAnswer(
new Answer<World>() {
public World answer(InvocationOnMock invocation) throws Throwable {
WorldCreator arg;
try {
arg = (WorldCreator) invocation.getArguments()[0];
} catch (Exception e) {
return null;
}
// Add special case for creating null worlds.
// Not sure I like doing it this way, but this is a special case
if (arg.name().equalsIgnoreCase("nullworld")) {
return MockWorldFactory.makeNewNullMockWorld(arg.name(), arg.environment(), arg.type());
}
return MockWorldFactory.makeNewMockWorld(arg.name(), arg.environment(), arg.type());
}
});
when(mockServer.unloadWorld(anyString(), anyBoolean())).thenReturn(true);
// add mock scheduler
BukkitScheduler mockScheduler = mock(BukkitScheduler.class);
when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class), anyLong())).
thenAnswer(new Answer<Integer>() {
public Integer answer(InvocationOnMock invocation) throws Throwable {
Runnable arg;
try {
arg = (Runnable) invocation.getArguments()[1];
} catch (Exception e) {
return null;
}
arg.run();
return null;
}});
when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class))).
thenAnswer(new Answer<Integer>() {
public Integer answer(InvocationOnMock invocation) throws Throwable {
Runnable arg;
try {
arg = (Runnable) invocation.getArguments()[1];
} catch (Exception e) {
return null;
}
arg.run();
return null;
}});
when(mockServer.getScheduler()).thenReturn(mockScheduler);
// Set server
Field serverfield = JavaPlugin.class.getDeclaredField("server");
serverfield.setAccessible(true);
serverfield.set(plugin, mockServer);
/*
// Set worldManager
WorldManager wm = PowerMockito.spy(new WorldManager(core));
Field worldmanagerfield = MultiverseCore.class.getDeclaredField("worldManager");
worldmanagerfield.setAccessible(true);
worldmanagerfield.set(core, wm);
// Set playerListener
MVPlayerListener pl = PowerMockito.spy(new MVPlayerListener(core));
Field playerlistenerfield = MultiverseCore.class.getDeclaredField("playerListener");
playerlistenerfield.setAccessible(true);
playerlistenerfield.set(core, pl);
// Set entityListener
MVEntityListener el = PowerMockito.spy(new MVEntityListener(core));
Field entitylistenerfield = MultiverseCore.class.getDeclaredField("entityListener");
entitylistenerfield.setAccessible(true);
entitylistenerfield.set(core, el);
// Set weatherListener
MVWeatherListener wl = PowerMockito.spy(new MVWeatherListener(core));
Field weatherlistenerfield = MultiverseCore.class.getDeclaredField("weatherListener");
weatherlistenerfield.setAccessible(true);
weatherlistenerfield.set(core, wl);
*/
// Init our command sender
final Logger commandSenderLogger = Logger.getLogger("CommandSender");
commandSenderLogger.setParent(Util.logger);
commandSender = mock(CommandSender.class);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) throws Throwable {
commandSenderLogger.info(ChatColor.stripColor((String) invocation.getArguments()[0]));
return null;
}}).when(commandSender).sendMessage(anyString());
when(commandSender.getServer()).thenReturn(mockServer);
when(commandSender.getName()).thenReturn("MockCommandSender");
when(commandSender.isPermissionSet(anyString())).thenReturn(true);
when(commandSender.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true);
when(commandSender.hasPermission(anyString())).thenReturn(true);
when(commandSender.hasPermission(Matchers.isA(Permission.class))).thenReturn(true);
when(commandSender.addAttachment(plugin)).thenReturn(null);
when(commandSender.isOp()).thenReturn(true);
Bukkit.setServer(mockServer);
// Load Multiverse Core
plugin.onLoad();
// Enable it.
plugin.onEnable();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public boolean tearDown() {
/*
List<MultiverseWorld> worlds = new ArrayList<MultiverseWorld>(core.getMVWorldManager()
.getMVWorlds());
for (MultiverseWorld world : worlds) {
core.getMVWorldManager().deleteWorld(world.getName());
}
*/
try {
Field serverField = Bukkit.class.getDeclaredField("server");
serverField.setAccessible(true);
serverField.set(Class.forName("org.bukkit.Bukkit"), null);
} catch (Exception e) {
Util.log(Level.SEVERE,
"Error while trying to unregister the server from Bukkit. Has Bukkit changed?");
e.printStackTrace();
Assert.fail(e.getMessage());
return false;
}
//FileUtils.deleteFolder(serverDirectory);
MockWorldFactory.clearWorlds();
return true;
}
public AbstractBukkitPlugin getPlugin() {
return this.plugin;
}
public Server getServer() {
return this.mockServer;
}
public CommandSender getCommandSender() {
return commandSender;
}
}
| |
/*
* Copyright (C) 2011 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.android.scenegraph;
import java.lang.Math;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import com.android.scenegraph.Float4Param;
import com.android.scenegraph.MatrixTransform;
import com.android.scenegraph.SceneManager;
import com.android.scenegraph.ShaderParam;
import com.android.scenegraph.TransformParam;
import android.content.res.Resources;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.Element.DataType;
import android.renderscript.Matrix4f;
import android.renderscript.Mesh;
import android.renderscript.ProgramFragment;
import android.renderscript.ProgramStore;
import android.renderscript.ProgramVertex;
import android.renderscript.RenderScriptGL;
import android.util.Log;
/**
* @hide
*/
public class Renderable extends RenderableBase {
HashMap<String, ShaderParam> mSourceParams;
RenderState mRenderState;
Transform mTransform;
String mMeshName;
String mMeshIndexName;
public String mMaterialName;
ScriptField_Renderable_s mField;
ScriptField_Renderable_s.Item mData;
public Renderable() {
mSourceParams = new HashMap<String, ShaderParam>();
mData = new ScriptField_Renderable_s.Item();
}
public void setCullType(int cull) {
mData.cullType = cull;
}
public void setRenderState(RenderState renderState) {
mRenderState = renderState;
if (mField != null) {
RenderScriptGL rs = SceneManager.getRS();
updateFieldItem(rs);
mField.set(mData, 0, true);
}
}
public void setMesh(Mesh mesh) {
mData.mesh = mesh;
if (mField != null) {
mField.set_mesh(0, mData.mesh, true);
}
}
public void setMesh(String mesh, String indexName) {
mMeshName = mesh;
mMeshIndexName = indexName;
}
public void setMaterialName(String name) {
mMaterialName = name;
}
public Transform getTransform() {
return mTransform;
}
public void setTransform(Transform t) {
mTransform = t;
if (mField != null) {
RenderScriptGL rs = SceneManager.getRS();
updateFieldItem(rs);
mField.set(mData, 0, true);
}
}
public void appendSourceParams(ShaderParam p) {
mSourceParams.put(p.getParamName(), p);
// Possibly lift this restriction later
if (mField != null) {
throw new RuntimeException("Can't add source params to objects that are rendering");
}
}
public void resolveMeshData(Mesh mesh) {
mData.mesh = mesh;
if (mData.mesh == null) {
Log.v("DRAWABLE: ", "*** NO MESH *** " + mMeshName);
return;
}
int subIndexCount = mData.mesh.getPrimitiveCount();
if (subIndexCount == 1 || mMeshIndexName == null) {
mData.meshIndex = 0;
} else {
for (int i = 0; i < subIndexCount; i ++) {
if (mData.mesh.getIndexSetAllocation(i).getName().equals(mMeshIndexName)) {
mData.meshIndex = i;
break;
}
}
}
if (mField != null) {
mField.set(mData, 0, true);
}
}
void updateTextures(RenderScriptGL rs) {
Iterator<ShaderParam> allParamsIter = mSourceParams.values().iterator();
int paramIndex = 0;
while (allParamsIter.hasNext()) {
ShaderParam sp = allParamsIter.next();
if (sp instanceof TextureParam) {
TextureParam p = (TextureParam)sp;
TextureBase tex = p.getTexture();
if (tex != null) {
mData.pf_textures[paramIndex++] = tex.getRsData(false).getAllocation();
}
}
}
ProgramFragment pf = mRenderState.mFragment.mProgram;
mData.pf_num_textures = pf != null ? Math.min(pf.getTextureCount(), paramIndex) : 0;
if (mField != null) {
mField.set_pf_textures(0, mData.pf_textures, true);
mField.set_pf_num_textures(0, mData.pf_num_textures, true);
}
}
public void setVisible(boolean vis) {
mData.cullType = vis ? 0 : 2;
if (mField != null) {
mField.set_cullType(0, mData.cullType, true);
}
}
ScriptField_Renderable_s getRsField(RenderScriptGL rs, Resources res) {
if (mField != null) {
return mField;
}
updateFieldItem(rs);
updateTextures(rs);
mField = new ScriptField_Renderable_s(rs, 1);
mField.set(mData, 0, true);
return mField;
}
void updateVertexConstants(RenderScriptGL rs) {
Allocation pvParams = null, vertexConstants = null;
VertexShader pv = mRenderState.mVertex;
if (pv != null && pv.getObjectConstants() != null) {
vertexConstants = Allocation.createTyped(rs, pv.getObjectConstants());
Element vertexConst = vertexConstants.getType().getElement();
pvParams = ShaderParam.fillInParams(vertexConst, mSourceParams,
mTransform).getAllocation();
}
mData.pv_const = vertexConstants;
mData.pv_constParams = pvParams;
}
void updateFragmentConstants(RenderScriptGL rs) {
Allocation pfParams = null, fragmentConstants = null;
FragmentShader pf = mRenderState.mFragment;
if (pf != null && pf.getObjectConstants() != null) {
fragmentConstants = Allocation.createTyped(rs, pf.getObjectConstants());
Element fragmentConst = fragmentConstants.getType().getElement();
pfParams = ShaderParam.fillInParams(fragmentConst, mSourceParams,
mTransform).getAllocation();
}
mData.pf_const = fragmentConstants;
mData.pf_constParams = pfParams;
}
void updateFieldItem(RenderScriptGL rs) {
if (mRenderState == null) {
mRenderState = SceneManager.getDefaultState();
}
if (mTransform == null) {
mTransform = SceneManager.getDefaultTransform();
}
updateVertexConstants(rs);
updateFragmentConstants(rs);
mData.transformMatrix = mTransform.getRSData().getAllocation();
mData.name = getNameAlloc(rs);
mData.render_state = mRenderState.getRSData().getAllocation();
mData.bVolInitialized = 0;
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.test.client.transport;
import org.elasticsearch.action.admin.cluster.node.liveness.LivenessResponse;
import org.elasticsearch.action.admin.cluster.node.liveness.TransportLivenessAction;
import org.elasticsearch.action.admin.cluster.state.ClusterStateAction;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.CheckedBiConsumer;
import org.elasticsearch.common.component.Lifecycle;
import org.elasticsearch.common.component.LifecycleListener;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.ConnectTransportException;
import org.elasticsearch.transport.ConnectionProfile;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestOptions;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.transport.TransportResponseHandler;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.transport.TransportStats;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
abstract class FailAndRetryMockTransport<Response extends TransportResponse> implements Transport {
private final Random random;
private final ClusterName clusterName;
private boolean connectMode = true;
private TransportService transportService;
private final AtomicInteger connectTransportExceptions = new AtomicInteger();
private final AtomicInteger failures = new AtomicInteger();
private final AtomicInteger successes = new AtomicInteger();
private final Set<DiscoveryNode> triedNodes = new CopyOnWriteArraySet<>();
private final AtomicLong requestId = new AtomicLong();
FailAndRetryMockTransport(Random random, ClusterName clusterName) {
this.random = new Random(random.nextLong());
this.clusterName = clusterName;
}
protected abstract ClusterState getMockClusterState(DiscoveryNode node);
@Override
public Connection getConnection(DiscoveryNode node) {
return new Connection() {
@Override
public DiscoveryNode getNode() {
return node;
}
@Override
public void sendRequest(long requestId, String action, TransportRequest request, TransportRequestOptions options)
throws IOException, TransportException {
//we make sure that nodes get added to the connected ones when calling addTransportAddress, by returning proper nodes info
if (connectMode) {
if (TransportLivenessAction.NAME.equals(action)) {
TransportResponseHandler transportResponseHandler = transportService.onResponseReceived(requestId);
transportResponseHandler.handleResponse(new LivenessResponse(ClusterName.CLUSTER_NAME_SETTING.
getDefault(Settings.EMPTY),
node));
} else if (ClusterStateAction.NAME.equals(action)) {
TransportResponseHandler transportResponseHandler = transportService.onResponseReceived(requestId);
ClusterState clusterState = getMockClusterState(node);
transportResponseHandler.handleResponse(new ClusterStateResponse(clusterName, clusterState, 0L));
} else {
throw new UnsupportedOperationException("Mock transport does not understand action " + action);
}
return;
}
//once nodes are connected we'll just return errors for each sendRequest call
triedNodes.add(node);
if (random.nextInt(100) > 10) {
connectTransportExceptions.incrementAndGet();
throw new ConnectTransportException(node, "node not available");
} else {
if (random.nextBoolean()) {
failures.incrementAndGet();
//throw whatever exception that is not a subclass of ConnectTransportException
throw new IllegalStateException();
} else {
TransportResponseHandler transportResponseHandler = transportService.onResponseReceived(requestId);
if (random.nextBoolean()) {
successes.incrementAndGet();
transportResponseHandler.handleResponse(newResponse());
} else {
failures.incrementAndGet();
transportResponseHandler.handleException(new TransportException("transport exception"));
}
}
}
}
@Override
public void close() throws IOException {
}
};
}
@Override
public Connection openConnection(DiscoveryNode node, ConnectionProfile profile) throws IOException {
return getConnection(node);
}
protected abstract Response newResponse();
public void endConnectMode() {
this.connectMode = false;
}
public int connectTransportExceptions() {
return connectTransportExceptions.get();
}
public int failures() {
return failures.get();
}
public int successes() {
return successes.get();
}
public Set<DiscoveryNode> triedNodes() {
return triedNodes;
}
@Override
public void setTransportService(TransportService transportServiceAdapter) {
this.transportService = transportServiceAdapter;
}
@Override
public BoundTransportAddress boundAddress() {
return null;
}
@Override
public TransportAddress[] addressesFromString(String address, int perAddressLimit) throws UnknownHostException {
throw new UnsupportedOperationException();
}
@Override
public boolean nodeConnected(DiscoveryNode node) {
return false;
}
@Override
public void connectToNode(DiscoveryNode node, ConnectionProfile connectionProfile,
CheckedBiConsumer<Connection, ConnectionProfile, IOException> connectionValidator)
throws ConnectTransportException {
}
@Override
public void disconnectFromNode(DiscoveryNode node) {
}
@Override
public Lifecycle.State lifecycleState() {
return null;
}
@Override
public void addLifecycleListener(LifecycleListener listener) {
throw new UnsupportedOperationException();
}
@Override
public void removeLifecycleListener(LifecycleListener listener) {
throw new UnsupportedOperationException();
}
@Override
public void start() {}
@Override
public void stop() {}
@Override
public void close() {}
@Override
public Map<String, BoundTransportAddress> profileBoundAddresses() {
return Collections.emptyMap();
}
@Override
public long newRequestId() {
return requestId.incrementAndGet();
}
@Override
public TransportStats getStats() {
throw new UnsupportedOperationException();
}
}
| |
/*
* This file is part of the DITA Open Toolkit project.
* See the accompanying license.txt file for applicable licenses.
*/
/*
* (c) Copyright IBM Corp. 2007 All Rights Reserved.
*/
package org.dita.dost.writer;
import org.dita.dost.exception.DITAOTException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import java.io.File;
import java.net.URI;
import java.util.Map;
import static org.dita.dost.util.Constants.*;
import static org.dita.dost.util.URLUtils.*;
import static org.dita.dost.util.FileUtils.*;
import static org.dita.dost.util.XMLUtils.addOrSetAttribute;
/**
* TopicRefWriter which updates the linking elements' value according to the
* mapping table.
*/
public final class TopicRefWriter extends AbstractXMLFilter {
private Map<URI, URI> changeTable = null;
private Map<URI, URI> conflictTable = null;
private File currentFileDir = null;
/** Using for rectify relative path of xml */
private String fixpath = null;
@Override
public void write(final File outputFilename) throws DITAOTException {
setCurrentFile(outputFilename.toURI());
currentFileDir = outputFilename.getParentFile();
super.write(outputFilename);
}
/**
* Set up class.
*
* @param conflictTable conflictTable
*/
public void setup(final Map<URI, URI> conflictTable) {
for (final Map.Entry<URI, URI> e: changeTable.entrySet()) {
assert e.getKey().isAbsolute();
assert e.getValue().isAbsolute();
}
this.conflictTable = conflictTable;
}
public void setChangeTable(final Map<URI, URI> changeTable) {
assert changeTable != null && !changeTable.isEmpty();
for (final Map.Entry<URI, URI> e: changeTable.entrySet()) {
assert e.getKey().isAbsolute();
assert e.getValue().isAbsolute();
}
this.changeTable = changeTable;
}
public void setFixpath(final String fixpath) {
assert fixpath == null || !(toFile(fixpath).isAbsolute());
this.fixpath = fixpath;
}
@Override
public void processingInstruction(final String target, String data) throws SAXException {
if (fixpath != null && target.equals(PI_WORKDIR_TARGET)) {
final String tmp = fixpath.substring(0, fixpath.lastIndexOf(SLASH));
if (!data.endsWith(tmp)) {
data = data + File.separator + tmp;
}
} else if (fixpath != null && target.equals(PI_WORKDIR_TARGET_URI)) {
final String tmp = fixpath.substring(0, fixpath.lastIndexOf(URI_SEPARATOR) + 1);
if (!data.endsWith(tmp)) {
data = data + tmp;
}
}
getContentHandler().processingInstruction(target, data);
}
@Override
public void startElement(final String uri, final String localName, final String qName, final Attributes atts)
throws SAXException {
Attributes as = atts;
if (TOPIC_OBJECT.matches(atts)) {
final String data = atts.getValue(ATTRIBUTE_NAME_DATA);
if (data != null) {
final AttributesImpl res = new AttributesImpl(atts);
addOrSetAttribute(res, ATTRIBUTE_NAME_DATA, updateData(data));
as = res;
}
} else {
final String href = atts.getValue(ATTRIBUTE_NAME_HREF);
if (href != null) {
final AttributesImpl res = new AttributesImpl(atts);
addOrSetAttribute(res, ATTRIBUTE_NAME_HREF, updateHref(as));
as = res;
}
}
getContentHandler().startElement(uri, localName, qName, as);
}
/**
* Check whether the attributes contains references
*
* @param atts element attributes
* @return {@code true} if local DITA reference, otherwise {@code false}
*/
private boolean isLocalDita(final Attributes atts) {
final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS);
if (classValue == null
|| (TOPIC_IMAGE.matches(classValue))) {
return false;
}
String scopeValue = atts.getValue(ATTRIBUTE_NAME_SCOPE);
if (scopeValue == null) {
scopeValue = ATTR_SCOPE_VALUE_LOCAL;
}
String formatValue = atts.getValue(ATTRIBUTE_NAME_FORMAT);
if (formatValue == null) {
formatValue = ATTR_FORMAT_VALUE_DITA;
}
return scopeValue.equals(ATTR_SCOPE_VALUE_LOCAL) && formatValue.equals(ATTR_FORMAT_VALUE_DITA);
}
private String updateData(final String origValue) {
String hrefValue = origValue;
if (fixpath != null && hrefValue.startsWith(fixpath)) {
hrefValue = hrefValue.substring(fixpath.length());
}
return hrefValue;
}
private String updateHref(final Attributes atts) {
// FIXME should be URI
String hrefValue = atts.getValue(ATTRIBUTE_NAME_HREF);
if (hrefValue == null) {
return null;
}
if (fixpath != null && hrefValue.startsWith(fixpath)) {
hrefValue = hrefValue.substring(fixpath.length());
}
if (changeTable == null || changeTable.isEmpty()) {
return hrefValue;
}
if (isLocalDita(atts)) {
// replace the href value if it's referenced topic is extracted.
final URI rootPathName = currentFile;
URI changeTargetkey = stripFragment(currentFileDir.toURI().resolve(hrefValue));
URI changeTarget = changeTable.get(changeTargetkey);
final String topicID = getTopicID(toURI(hrefValue));
if (topicID != null) {
changeTargetkey = setFragment(changeTargetkey, topicID);
final URI changeTarget_with_elemt = changeTable.get(changeTargetkey);
if (changeTarget_with_elemt != null) {
changeTarget = changeTarget_with_elemt;
}
}
final String elementID = getElementID(hrefValue);
final String pathtoElem = getFragment(hrefValue, "");
if (changeTarget == null || changeTarget.toString().isEmpty()) {
URI absolutePath = toURI(resolveTopic(currentFileDir, hrefValue));
absolutePath = setElementID(absolutePath, null);
changeTarget = changeTable.get(absolutePath);
}
if (changeTarget == null) {
return hrefValue;// no change
} else {
final URI conTarget = conflictTable.get(stripFragment(changeTarget));
logger.debug("Update " + changeTarget + " to " + conTarget);
if (conTarget != null && !conTarget.toString().isEmpty()) {
final URI p = getRelativePath(rootPathName, conTarget);
if (elementID == null) {
return setFragment(p, getElementID(changeTarget.toString())).toString();
} else {
if (conTarget.getFragment() != null) {
if (!pathtoElem.contains(SLASH)) {
return p.toString();
} else {
return setElementID(p, elementID).toString();
}
} else {
return setFragment(p, pathtoElem).toString();
}
}
} else {
final URI p = getRelativePath(rootPathName, changeTarget);
if (elementID == null) {
return p.toString();
} else {
if (changeTarget.getFragment() != null) {
if (!pathtoElem.contains(SLASH)) {
return p.toString();
} else {
return setElementID(p, elementID).toString();
}
} else {
return setFragment(p, pathtoElem).toString();
}
}
}
}
}
return hrefValue;
}
/**
* Retrieve the element ID from the path. If there is no element ID, return topic ID.
*
* @param relativePath
* @return String
*/
private String getElementID(final String relativePath) {
final String fragment = getFragment(relativePath);
if (fragment != null) {
if (fragment.lastIndexOf(SLASH) != -1) {
return fragment.substring(fragment.lastIndexOf(SLASH) + 1);
} else {
return fragment;
}
}
return null;
}
}
| |
/*
* Copyright 2000-2011 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.refactoring.move.moveClassesOrPackages;
import com.intellij.CommonBundle;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.JavaProjectRootsUtil;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.file.JavaDirectoryServiceImpl;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.JavaRefactoringSettings;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.move.MoveCallback;
import com.intellij.refactoring.move.MoveHandlerDelegate;
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil;
import com.intellij.refactoring.rename.JavaVetoRenameCondition;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.RadioUpDownListener;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.HashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.Arrays;
public class JavaMoveClassesOrPackagesHandler extends MoveHandlerDelegate {
private static final Logger LOG = Logger.getInstance("#" + JavaMoveClassesOrPackagesHandler.class.getName());
private static final JavaVetoRenameCondition VETO_RENAME_CONDITION = new JavaVetoRenameCondition();
public static boolean isPackageOrDirectory(final PsiElement element) {
if (element instanceof PsiPackage) return true;
return element instanceof PsiDirectory && JavaDirectoryService.getInstance().getPackage((PsiDirectory)element) != null;
}
public static boolean isReferenceInAnonymousClass(@Nullable final PsiReference reference) {
if (reference instanceof PsiJavaCodeReferenceElement &&
((PsiJavaCodeReferenceElement)reference).getParent() instanceof PsiAnonymousClass) {
return true;
}
return false;
}
@Override
public boolean canMove(PsiElement[] elements, @Nullable PsiElement targetContainer) {
for (PsiElement element : elements) {
if (!isPackageOrDirectory(element) && invalid4Move(element)) return false;
}
return super.canMove(elements, targetContainer);
}
public static boolean invalid4Move(PsiElement element) {
PsiFile parentFile;
if (element instanceof PsiClassOwner) {
final PsiClass[] classes = ((PsiClassOwner)element).getClasses();
if (classes.length == 0) return true;
for (PsiClass aClass : classes) {
if (aClass instanceof PsiSyntheticClass) return true;
}
parentFile = (PsiFile)element;
}
else {
if (element instanceof PsiSyntheticClass) return true;
if (!(element instanceof PsiClass)) return true;
if (element instanceof PsiAnonymousClass) return true;
if (((PsiClass)element).getContainingClass() != null) return true;
parentFile = element.getContainingFile();
}
return parentFile instanceof PsiJavaFile && JavaProjectRootsUtil.isOutsideJavaSourceRoot(parentFile);
}
@Override
public boolean isValidTarget(PsiElement psiElement, PsiElement[] sources) {
if (isPackageOrDirectory(psiElement)) return true;
boolean areAllClasses = true;
for (PsiElement source : sources) {
areAllClasses &= !isPackageOrDirectory(source) && !invalid4Move(source);
}
return areAllClasses && psiElement instanceof PsiClass;
}
public PsiElement[] adjustForMove(final Project project, final PsiElement[] sourceElements, final PsiElement targetElement) {
return MoveClassesOrPackagesImpl.adjustForMove(project,sourceElements, targetElement);
}
public void doMove(final Project project, final PsiElement[] elements, final PsiElement targetContainer, final MoveCallback callback) {
final PsiDirectory[] directories = new PsiDirectory[elements.length];
final String prompt = getPromptToMoveDirectoryLibrariesSafe(elements);
if (prompt != null) {
System.arraycopy(elements, 0, directories, 0, directories.length);
moveDirectoriesLibrariesSafe(project, targetContainer, callback, directories, prompt);
return;
}
if (canMoveOrRearrangePackages(elements) ) {
System.arraycopy(elements, 0, directories, 0, directories.length);
SelectMoveOrRearrangePackageDialog dialog = new SelectMoveOrRearrangePackageDialog(project, directories, targetContainer == null);
dialog.show();
if (!dialog.isOK()) return;
if (dialog.isPackageRearrageSelected()) {
MoveClassesOrPackagesImpl.doRearrangePackage(project, directories);
return;
}
if (dialog.isMoveDirectory()) {
moveAsDirectory(project, targetContainer, callback, directories);
return;
}
}
final PsiElement[] adjustedElements = MoveClassesOrPackagesImpl.adjustForMove(project, elements, targetContainer);
if (adjustedElements == null) return;
if (targetContainer instanceof PsiDirectory) {
if (CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, Arrays.asList(adjustedElements), true)) {
if (!packageHasMultipleDirectoriesInModule(project, (PsiDirectory)targetContainer)) {
createMoveClassesOrPackagesToNewDirectoryDialog((PsiDirectory)targetContainer, adjustedElements, callback).show();
return;
}
}
}
doMoveWithMoveClassesDialog(project, adjustedElements, targetContainer, callback);
}
protected void doMoveWithMoveClassesDialog(final Project project,
PsiElement[] adjustedElements,
PsiElement initialTargetElement,
final MoveCallback moveCallback) {
MoveClassesOrPackagesImpl.doMove(project, adjustedElements, initialTargetElement, moveCallback);
}
private static void moveDirectoriesLibrariesSafe(Project project,
PsiElement targetContainer,
MoveCallback callback,
PsiDirectory[] directories,
String prompt) {
final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directories[0]);
LOG.assertTrue(aPackage != null);
final PsiDirectory[] projectDirectories = aPackage.getDirectories(GlobalSearchScope.projectScope(project));
if (projectDirectories.length > 1) {
int ret = Messages
.showYesNoCancelDialog(project, prompt + " or all directories in project?", RefactoringBundle.message("warning.title"),
RefactoringBundle.message("move.current.directory"),
RefactoringBundle.message("move.directories"),
CommonBundle.getCancelButtonText(), Messages.getWarningIcon());
if (ret == 0) {
moveAsDirectory(project, targetContainer, callback, directories);
}
else if (ret == 1) {
moveAsDirectory(project, targetContainer, callback, projectDirectories);
}
}
else if (Messages.showOkCancelDialog(project, prompt + "?", RefactoringBundle.message("warning.title"),
Messages.getWarningIcon()) == DialogWrapper.OK_EXIT_CODE) {
moveAsDirectory(project, targetContainer, callback, directories);
}
}
@NotNull
protected DialogWrapper createMoveClassesOrPackagesToNewDirectoryDialog(@NotNull final PsiDirectory directory,
PsiElement[] elementsToMove,
final MoveCallback moveCallback) {
return new MoveClassesOrPackagesToNewDirectoryDialog(directory, elementsToMove, moveCallback);
}
private static void moveAsDirectory(Project project,
PsiElement targetContainer,
final MoveCallback callback,
final PsiDirectory[] directories) {
if (targetContainer instanceof PsiDirectory) {
final JavaRefactoringSettings refactoringSettings = JavaRefactoringSettings.getInstance();
final MoveDirectoryWithClassesProcessor processor =
new MoveDirectoryWithClassesProcessor(project, directories, (PsiDirectory)targetContainer,
refactoringSettings.RENAME_SEARCH_IN_COMMENTS_FOR_PACKAGE,
refactoringSettings.RENAME_SEARCH_IN_COMMENTS_FOR_PACKAGE, true, callback);
processor.setPrepareSuccessfulSwingThreadCallback(new Runnable() {
@Override
public void run() {
}
});
processor.run();
}
else {
final boolean containsJava = hasJavaFiles(directories[0]);
if (!containsJava) {
MoveFilesOrDirectoriesUtil.doMove(project, new PsiElement[]{directories[0]}, new PsiElement[]{targetContainer}, callback);
return;
}
final MoveClassesOrPackagesToNewDirectoryDialog dlg =
new MoveClassesOrPackagesToNewDirectoryDialog(directories[0], new PsiElement[0], false, callback) {
@Override
protected void performRefactoring(Project project,
final PsiDirectory targetDirectory,
PsiPackage aPackage,
boolean searchInComments,
boolean searchForTextOccurences) {
try {
for (PsiDirectory dir: directories) {
MoveFilesOrDirectoriesUtil.checkIfMoveIntoSelf(dir, targetDirectory);
}
}
catch (IncorrectOperationException e) {
Messages.showErrorDialog(project, e.getMessage(), RefactoringBundle.message("cannot.move"));
return;
}
final MoveDirectoryWithClassesProcessor processor =
new MoveDirectoryWithClassesProcessor(project, directories, targetDirectory, searchInComments, searchForTextOccurences,
true, callback);
processor.setPrepareSuccessfulSwingThreadCallback(new Runnable() {
@Override
public void run() {
}
});
processor.run();
}
};
dlg.show();
}
}
public static boolean hasJavaFiles(PsiDirectory directory) {
final boolean [] containsJava = new boolean[]{false};
directory.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitElement(PsiElement element) {
if (containsJava[0]) return;
if (element instanceof PsiDirectory) {
super.visitElement(element);
}
}
@Override
public void visitFile(PsiFile file) {
containsJava[0] = file instanceof PsiJavaFile;
}
});
return containsJava[0];
}
@Override
public PsiElement adjustTargetForMove(DataContext dataContext, PsiElement targetContainer) {
if (targetContainer instanceof PsiPackage) {
final Module module = LangDataKeys.TARGET_MODULE.getData(dataContext);
if (module != null) {
final PsiDirectory[] directories = ((PsiPackage)targetContainer).getDirectories(GlobalSearchScope.moduleScope(module));
if (directories.length == 1) {
return directories[0];
}
}
}
return super.adjustTargetForMove(dataContext, targetContainer);
}
public static boolean packageHasMultipleDirectoriesInModule(Project project, PsiDirectory targetElement) {
final PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(targetElement);
if (psiPackage != null) {
final Module module = ModuleUtilCore.findModuleForFile(targetElement.getVirtualFile(), project);
if (module != null) {
if (psiPackage.getDirectories(GlobalSearchScope.moduleScope(module)).length > 1) return true;
}
}
return false;
}
@Nullable
private static String getPromptToMoveDirectoryLibrariesSafe(PsiElement[] elements) {
if (elements.length == 0 || elements.length > 1) return null;
final Project project = elements[0].getProject();
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
if (!(elements[0] instanceof PsiDirectory)) return null;
final PsiDirectory directory = ((PsiDirectory)elements[0]);
if (RefactoringUtil.isSourceRoot(directory)) {
return null;
}
final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory);
if (aPackage == null) return null;
if ("".equals(aPackage.getQualifiedName())) return null;
final PsiDirectory[] directories = aPackage.getDirectories();
boolean inLib = false;
for (PsiDirectory psiDirectory : directories) {
inLib |= !fileIndex.isInContent(psiDirectory.getVirtualFile());
}
return inLib ? "Package \'" +
aPackage.getName() +
"\' contains directories in libraries which cannot be moved. Do you want to move current directory" : null;
}
private static boolean canMoveOrRearrangePackages(PsiElement[] elements) {
if (elements.length == 0) return false;
final Project project = elements[0].getProject();
if (JavaProjectRootsUtil.getSuitableDestinationSourceRoots(project).size() == 1) {
return false;
}
for (PsiElement element : elements) {
if (!(element instanceof PsiDirectory)) return false;
final PsiDirectory directory = ((PsiDirectory)element);
if (RefactoringUtil.isSourceRoot(directory)) {
return false;
}
final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory);
if (aPackage == null) return false;
if (aPackage.getQualifiedName().isEmpty()) return false;
final VirtualFile sourceRootForFile = ProjectRootManager.getInstance(element.getProject()).getFileIndex()
.getSourceRootForFile(directory.getVirtualFile());
if (sourceRootForFile == null) return false;
}
return true;
}
public static boolean hasPackages(PsiDirectory directory) {
if (JavaDirectoryService.getInstance().getPackage(directory) != null) {
return true;
}
return false;
}
private static class SelectMoveOrRearrangePackageDialog extends DialogWrapper {
private JRadioButton myRbMovePackage;
private JRadioButton myRbRearrangePackage;
private JRadioButton myRbMoveDirectory;
private final PsiDirectory[] myDirectories;
private final boolean myRearrangePackagesEnabled;
public SelectMoveOrRearrangePackageDialog(Project project, PsiDirectory[] directories) {
this(project, directories, true);
}
public SelectMoveOrRearrangePackageDialog(Project project, PsiDirectory[] directories, boolean rearrangePackagesEnabled) {
super(project, true);
myDirectories = directories;
myRearrangePackagesEnabled = rearrangePackagesEnabled;
setTitle(RefactoringBundle.message("select.refactoring.title"));
init();
}
protected JComponent createNorthPanel() {
return new JLabel(RefactoringBundle.message("what.would.you.like.to.do"));
}
public JComponent getPreferredFocusedComponent() {
return myRbMovePackage;
}
protected String getDimensionServiceKey() {
return "#com.intellij.refactoring.move.MoveHandler.SelectRefactoringDialog";
}
protected JComponent createCenterPanel() {
JPanel panel = new JPanel(new BorderLayout());
final HashSet<String> packages = new HashSet<String>();
for (PsiDirectory directory : myDirectories) {
packages.add(JavaDirectoryService.getInstance().getPackage(directory).getQualifiedName());
}
final String moveDescription;
LOG.assertTrue(myDirectories.length > 0);
LOG.assertTrue(packages.size() > 0);
if (packages.size() > 1) {
moveDescription = RefactoringBundle.message("move.packages.to.another.package", packages.size());
}
else {
final String qName = packages.iterator().next();
moveDescription = RefactoringBundle.message("move.package.to.another.package", qName);
}
myRbMovePackage = new JRadioButton();
myRbMovePackage.setText(moveDescription);
myRbMovePackage.setSelected(true);
final String rearrangeDescription;
if (myDirectories.length > 1) {
rearrangeDescription = RefactoringBundle.message("move.directories.to.another.source.root", myDirectories.length);
}
else {
rearrangeDescription = RefactoringBundle.message("move.directory.to.another.source.root", myDirectories[0].getVirtualFile().getPresentableUrl());
}
myRbRearrangePackage = new JRadioButton();
myRbRearrangePackage.setText(rearrangeDescription);
myRbRearrangePackage.setVisible(myRearrangePackagesEnabled);
final String moveDirectoryDescription;
if (myDirectories.length > 1) {
moveDirectoryDescription = "Move everything from " + myDirectories.length + " directories to another directory";
}
else {
moveDirectoryDescription = "Move everything from " + myDirectories[0].getVirtualFile().getPresentableUrl() + " to another directory";
}
myRbMoveDirectory = new JRadioButton();
myRbMoveDirectory.setMnemonic('e');
myRbMoveDirectory.setText(moveDirectoryDescription);
ButtonGroup gr = new ButtonGroup();
gr.add(myRbMovePackage);
gr.add(myRbRearrangePackage);
gr.add(myRbMoveDirectory);
if (myRearrangePackagesEnabled) {
new RadioUpDownListener(myRbMovePackage, myRbRearrangePackage, myRbMoveDirectory);
} else {
new RadioUpDownListener(myRbMovePackage, myRbMoveDirectory);
}
Box box = Box.createVerticalBox();
box.add(Box.createVerticalStrut(5));
box.add(myRbMovePackage);
box.add(myRbRearrangePackage);
box.add(myRbMoveDirectory);
panel.add(box, BorderLayout.CENTER);
return panel;
}
public boolean isPackageRearrageSelected() {
return myRbRearrangePackage.isSelected();
}
public boolean isMoveDirectory() {
return myRbMoveDirectory.isSelected();
}
}
public boolean tryToMove(final PsiElement element, final Project project, final DataContext dataContext, final PsiReference reference,
final Editor editor) {
if (isPackageOrDirectory(element)) return false;
if (isReferenceInAnonymousClass(reference)) return false;
if (!invalid4Move(element)) {
final PsiElement initialTargetElement = LangDataKeys.TARGET_PSI_ELEMENT.getData(dataContext);
PsiElement[] adjustedElements = adjustForMove(project, new PsiElement[]{element}, initialTargetElement);
if (adjustedElements == null) {
return true;
}
doMoveWithMoveClassesDialog(project, adjustedElements, initialTargetElement, null);
return true;
}
return false;
}
@Override
public boolean isMoveRedundant(PsiElement source, PsiElement target) {
if (target instanceof PsiDirectory && source instanceof PsiClass) {
try {
JavaDirectoryServiceImpl.checkCreateClassOrInterface((PsiDirectory)target, ((PsiClass)source).getName());
}
catch (IncorrectOperationException e) {
return true;
}
}
if (target instanceof PsiDirectory && source instanceof PsiDirectory) {
final PsiPackage aPackage = JavaDirectoryServiceImpl.getInstance().getPackage((PsiDirectory)source);
if (aPackage != null && !MoveClassesOrPackagesImpl.checkNesting(target.getProject(), aPackage, target, false)) return true;
}
return super.isMoveRedundant(source, target);
}
}
| |
/*
* Copyright 2005 Ryan Bloom
* 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 net.rkbloom.logdriver;
import net.rkbloom.logdriver.util.TypeConverter;
import org.apache.log4j.Logger;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Map;
import java.util.TreeMap;
/**
* LogCallableStatement
* @version $Rev$
*/
public class LogCallableStatement implements CallableStatement {
private CallableStatement embedded;
private Connection conn;
private String sql;
private Map<Object, Object> bindParams;
private Map<Object, Object> outParams;
private static Logger log = Logger.getLogger(LogCallableStatement.class);
public LogCallableStatement(CallableStatement cs, Connection c, String s) {
embedded = cs;
conn = c;
sql = s;
// we want to have the bind parameters print out in order
// otherwise it is difficult to match the parameters with
// the question marks (?) in the query.
bindParams = new TreeMap<Object, Object>();
outParams = new TreeMap<Object, Object>();
}
// This looks useless, but it isn't. I have centralized the logging in
// this class so that I can easily replace all of the '?'s with the actual
// values.
private void logStatement() {
logStatement(sql);
}
private void logStatement(String sql) {
String replaceBind = System.getProperty("replace.bindParams", "0");
if (replaceBind.equals("1") || replaceBind.equals("true")) {
String logStr = sql;
int i = 1;
while (logStr.indexOf('?') >= 0) {
logStr = logStr.replaceFirst("\\?",
bindParams.get(new Integer(i++)).toString());
}
log.debug("executing CallableStatement: " + logStr);
return;
}
log.debug("executing CallableStatement: '" + sql + "' with bind " +
"parameters: " + bindParams + " out parameters: " + outParams);
}
/**
* {@inheritDoc}
*/
public void addBatch() throws SQLException {
logStatement();
embedded.addBatch();
}
/**
* {@inheritDoc}
*/
public void addBatch(String sql) throws SQLException {
logStatement(sql);
embedded.addBatch(sql);
}
/**
* {@inheritDoc}
*/
public void cancel() throws SQLException {
embedded.cancel();
}
/**
* {@inheritDoc}
*/
public void clearBatch() throws SQLException {
embedded.clearBatch();
}
/**
* {@inheritDoc}
*/
public void clearParameters() throws SQLException {
embedded.clearParameters();
bindParams.clear();
}
/**
* {@inheritDoc}
*/
public void clearWarnings() throws SQLException {
embedded.clearWarnings();
}
/**
* {@inheritDoc}
*/
public void close() throws SQLException {
embedded.close();
}
/**
* {@inheritDoc}
*/
public boolean execute() throws SQLException {
logStatement();
return embedded.execute();
}
/**
* {@inheritDoc}
*/
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
logStatement(sql);
return embedded.execute(sql, autoGeneratedKeys);
}
/**
* {@inheritDoc}
*/
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
logStatement(sql);
return embedded.execute(sql, columnIndexes);
}
/**
* {@inheritDoc}
*/
public boolean execute(String sql, String[] columnNames) throws SQLException {
logStatement(sql);
return embedded.execute(sql, columnNames);
}
/**
* {@inheritDoc}
*/
public boolean execute(String sql) throws SQLException {
logStatement(sql);
return embedded.execute(sql);
}
/**
* {@inheritDoc}
*/
public int[] executeBatch() throws SQLException {
logStatement();
return embedded.executeBatch();
}
/**
* {@inheritDoc}
*/
public ResultSet executeQuery() throws SQLException {
logStatement();
return embedded.executeQuery();
}
/**
* {@inheritDoc}
*/
public ResultSet executeQuery(String sql) throws SQLException {
logStatement(sql);
return embedded.executeQuery(sql);
}
/**
* {@inheritDoc}
*/
public int executeUpdate() throws SQLException {
logStatement();
return embedded.executeUpdate();
}
/**
* {@inheritDoc}
*/
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
logStatement(sql);
return embedded.executeUpdate(sql, autoGeneratedKeys);
}
/**
* {@inheritDoc}
*/
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
logStatement(sql);
return embedded.executeUpdate(sql, columnIndexes);
}
/**
* {@inheritDoc}
*/
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
logStatement(sql);
return embedded.executeUpdate(sql, columnNames);
}
/**
* {@inheritDoc}
*/
public int executeUpdate(String sql) throws SQLException {
logStatement(sql);
return embedded.executeUpdate(sql);
}
/**
* {@inheritDoc}
*/
public Connection getConnection() throws SQLException {
return conn;
}
/**
* {@inheritDoc}
*/
public int getFetchDirection() throws SQLException {
return embedded.getFetchDirection();
}
/**
* {@inheritDoc}
*/
public int getFetchSize() throws SQLException {
return embedded.getFetchSize();
}
/**
* {@inheritDoc}
*/
public ResultSet getGeneratedKeys() throws SQLException {
return embedded.getGeneratedKeys();
}
/**
* {@inheritDoc}
*/
public int getMaxFieldSize() throws SQLException {
return embedded.getMaxFieldSize();
}
/**
* {@inheritDoc}
*/
public int getMaxRows() throws SQLException {
return embedded.getMaxRows();
}
/**
* {@inheritDoc}
*/
public ResultSetMetaData getMetaData() throws SQLException {
return embedded.getMetaData();
}
/**
* {@inheritDoc}
*/
public boolean getMoreResults() throws SQLException {
return embedded.getMoreResults();
}
/**
* {@inheritDoc}
*/
public boolean getMoreResults(int current) throws SQLException {
return embedded.getMoreResults(current);
}
/**
* {@inheritDoc}
*/
public ParameterMetaData getParameterMetaData() throws SQLException {
return embedded.getParameterMetaData();
}
/**
* {@inheritDoc}
*/
public int getQueryTimeout() throws SQLException {
return embedded.getQueryTimeout();
}
/**
* {@inheritDoc}
*/
public ResultSet getResultSet() throws SQLException {
return embedded.getResultSet();
}
/**
* {@inheritDoc}
*/
public int getResultSetConcurrency() throws SQLException {
return embedded.getResultSetConcurrency();
}
/**
* {@inheritDoc}
*/
public int getResultSetHoldability() throws SQLException {
return embedded.getResultSetHoldability();
}
/**
* {@inheritDoc}
*/
public int getResultSetType() throws SQLException {
return embedded.getResultSetType();
}
/**
* {@inheritDoc}
*/
public int getUpdateCount() throws SQLException {
return embedded.getUpdateCount();
}
/**
* {@inheritDoc}
*/
public SQLWarning getWarnings() throws SQLException {
return embedded.getWarnings();
}
/**
* {@inheritDoc}
*/
public void setArray(int i, Array x) throws SQLException {
embedded.setArray(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setAsciiStream(int i, InputStream x, int length) throws SQLException {
embedded.setAsciiStream(i, x, length);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setBigDecimal(int i, BigDecimal x) throws SQLException {
embedded.setBigDecimal(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setBinaryStream(int i, InputStream x, int length) throws SQLException {
embedded.setBinaryStream(i, x, length);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setBlob(int i, Blob x) throws SQLException {
embedded.setBlob(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setBoolean(int i, boolean x) throws SQLException {
embedded.setBoolean(i, x);
bindParams.put(new Integer(i), new Boolean(x));
}
/**
* {@inheritDoc}
*/
public void setByte(int i, byte x) throws SQLException {
embedded.setByte(i, x);
bindParams.put(new Integer(i), new Byte(x));
}
/**
* {@inheritDoc}
*/
public void setBytes(int i, byte[] x) throws SQLException {
embedded.setBytes(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setCharacterStream(int i, Reader reader, int length) throws SQLException {
embedded.setCharacterStream(i, reader, length);
bindParams.put(new Integer(i), reader);
}
/**
* {@inheritDoc}
*/
public void setClob(int i, Clob x) throws SQLException {
embedded.setClob(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setCursorName(String name) throws SQLException {
embedded.setCursorName(name);
}
/**
* {@inheritDoc}
*/
public void setDate(int i, Date x, Calendar cal) throws SQLException {
embedded.setDate(i, x, cal);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setDate(int i, Date x) throws SQLException {
embedded.setDate(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setDouble(int i, double x) throws SQLException {
embedded.setDouble(i, x);
bindParams.put(new Integer(i), new Double(x));
}
/**
* {@inheritDoc}
*/
public void setEscapeProcessing(boolean enable) throws SQLException {
embedded.setEscapeProcessing(enable);
}
/**
* {@inheritDoc}
*/
public void setFetchDirection(int direction) throws SQLException {
embedded.setFetchDirection(direction);
}
/**
* {@inheritDoc}
*/
public void setFetchSize(int rows) throws SQLException {
embedded.setFetchSize(rows);
}
/**
* {@inheritDoc}
*/
public void setFloat(int i, float x) throws SQLException {
embedded.setFloat(i, x);
bindParams.put(new Integer(i), new Float(x));
}
/**
* {@inheritDoc}
*/
public void setInt(int i, int x) throws SQLException {
embedded.setInt(i, x);
bindParams.put(new Integer(i), new Integer(x));
}
/**
* {@inheritDoc}
*/
public void setLong(int i, long x) throws SQLException {
embedded.setLong(i, x);
bindParams.put(new Integer(i), new Long(x));
}
/**
* {@inheritDoc}
*/
public void setMaxFieldSize(int max) throws SQLException {
embedded.setMaxFieldSize(max);
}
/**
* {@inheritDoc}
*/
public void setMaxRows(int max) throws SQLException {
embedded.setMaxRows(max);
}
/**
* {@inheritDoc}
*/
public void setNull(int paramIndex, int sqlType, String typeName) throws SQLException {
embedded.setNull(paramIndex, sqlType, typeName);
}
/**
* {@inheritDoc}
*/
public void setNull(int i, int sqlType) throws SQLException {
embedded.setNull(i, sqlType);
}
/**
* {@inheritDoc}
*/
public void setObject(int i, Object x, int targetSqlType, int scale) throws SQLException {
embedded.setObject(i, x, targetSqlType, scale);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setObject(int i, Object x, int targetSqlType) throws SQLException {
embedded.setObject(i, x, targetSqlType);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setObject(int i, Object x) throws SQLException {
embedded.setObject(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setQueryTimeout(int seconds) throws SQLException {
embedded.setQueryTimeout(seconds);
}
/**
* {@inheritDoc}
*/
public void setRef(int i, Ref x) throws SQLException {
embedded.setRef(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setShort(int i, short x) throws SQLException {
embedded.setShort(i, x);
bindParams.put(new Integer(i), new Short(x));
}
/**
* {@inheritDoc}
*/
public void setString(int i, String x) throws SQLException {
embedded.setString(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setTime(int i, Time x, Calendar cal) throws SQLException {
embedded.setTime(i, x, cal);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setTime(int i, Time x) throws SQLException {
embedded.setTime(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setTimestamp(int i, Timestamp x, Calendar cal) throws SQLException {
embedded.setTimestamp(i, x, cal);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setTimestamp(int i, Timestamp x) throws SQLException {
embedded.setTimestamp(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
* @deprecated
*/
public void setUnicodeStream(int i, InputStream x, int length) throws SQLException {
embedded.setUnicodeStream(i, x, length);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setURL(int i, URL x) throws SQLException {
embedded.setURL(i, x);
bindParams.put(new Integer(i), x);
}
// Prepared Statement methods
/**
* {@inheritDoc}
*/
public void registerOutParameter(int i, int sqlType)
throws SQLException {
embedded.registerOutParameter(i, sqlType);
outParams.put(new Integer(i),
new OutParamMetadata(sqlType));
}
/**
* {@inheritDoc}
*/
public void registerOutParameter(int i, int sqlType,
int scale) throws SQLException {
embedded.registerOutParameter(i, sqlType, scale);
outParams.put(new Integer(i),
new OutParamMetadata(sqlType, scale));
}
/**
* {@inheritDoc}
*/
public boolean wasNull() throws SQLException {
return embedded.wasNull();
}
/**
* {@inheritDoc}
*/
public String getString(int i) throws SQLException {
return embedded.getString(i);
}
/**
* {@inheritDoc}
*/
public boolean getBoolean(int i) throws SQLException {
return embedded.getBoolean(i);
}
/**
* {@inheritDoc}
*/
public byte getByte(int i) throws SQLException {
return embedded.getByte(i);
}
/**
* {@inheritDoc}
*/
public short getShort(int i) throws SQLException {
return embedded.getShort(i);
}
/**
* {@inheritDoc}
*/
public int getInt(int i) throws SQLException {
return embedded.getInt(i);
}
/**
* {@inheritDoc}
*/
public long getLong(int i) throws SQLException {
return embedded.getLong(i);
}
/**
* {@inheritDoc}
*/
public float getFloat(int i) throws SQLException {
return embedded.getFloat(i);
}
/**
* {@inheritDoc}
*/
public double getDouble(int i) throws SQLException {
return embedded.getDouble(i);
}
/**
* {@inheritDoc}
*/
public BigDecimal getBigDecimal(int i, int scale)
throws SQLException {
return embedded.getBigDecimal(i);
}
/**
* {@inheritDoc}
*/
public byte[] getBytes(int i) throws SQLException {
return embedded.getBytes(i);
}
/**
* {@inheritDoc}
*/
public Date getDate(int i) throws SQLException {
return embedded.getDate(i);
}
/**
* {@inheritDoc}
*/
public Time getTime(int i) throws SQLException {
return embedded.getTime(i);
}
/**
* {@inheritDoc}
*/
public Timestamp getTimestamp(int i) throws SQLException {
return embedded.getTimestamp(i);
}
/**
* {@inheritDoc}
*/
public Object getObject(int i) throws SQLException {
return embedded.getObject(i);
}
/**
* {@inheritDoc}
*/
public BigDecimal getBigDecimal(int i) throws SQLException {
return embedded.getBigDecimal(i);
}
/**
* {@inheritDoc}
*/
public Ref getRef(int i) throws SQLException {
return embedded.getRef(i);
}
/**
* {@inheritDoc}
*/
public Blob getBlob(int i) throws SQLException {
return embedded.getBlob(i);
}
/**
* {@inheritDoc}
*/
public Clob getClob(int i) throws SQLException {
return embedded.getClob(i);
}
/**
* {@inheritDoc}
*/
public Array getArray(int i) throws SQLException {
return embedded.getArray(i);
}
/**
* {@inheritDoc}
*/
public Date getDate(int i, Calendar cal)
throws SQLException {
return embedded.getDate(i, cal);
}
/**
* {@inheritDoc}
*/
public Time getTime(int i, Calendar cal)
throws SQLException {
return embedded.getTime(i, cal);
}
/**
* {@inheritDoc}
*/
public Timestamp getTimestamp(int i, Calendar cal)
throws SQLException {
return embedded.getTimestamp(i, cal);
}
/**
* {@inheritDoc}
*/
public void registerOutParameter(int paramIndex, int sqlType,
String typeName) throws SQLException {
embedded.registerOutParameter(paramIndex, sqlType, typeName);
outParams.put(new Integer(paramIndex),
new OutParamMetadata(sqlType, typeName));
}
/**
* {@inheritDoc}
*/
public void registerOutParameter(String name, int sqlType)
throws SQLException {
embedded.registerOutParameter(name, sqlType);
outParams.put(name, new OutParamMetadata(sqlType));
}
/**
* {@inheritDoc}
*/
public void registerOutParameter(String name, int sqlType,
int scale) throws SQLException {
embedded.registerOutParameter(name, sqlType, scale);
outParams.put(name, new OutParamMetadata(sqlType, scale));
}
/**
* {@inheritDoc}
*/
public void registerOutParameter(String name, int sqlType,
String typeName) throws SQLException {
embedded.registerOutParameter(name, sqlType, typeName);
outParams.put(name, new OutParamMetadata(sqlType, typeName));
}
/**
* {@inheritDoc}
*/
public URL getURL(int i) throws SQLException {
return embedded.getURL(i);
}
/**
* {@inheritDoc}
*/
public void setURL(String name, URL val) throws SQLException {
embedded.setURL(name, val);
bindParams.put(name, val);
}
/**
* {@inheritDoc}
*/
public void setNull(String name, int sqlType)
throws SQLException {
embedded.setNull(name, sqlType);
bindParams.put(name, null);
}
/**
* {@inheritDoc}
*/
public void setBoolean(String name, boolean x)
throws SQLException {
embedded.setBoolean(name, x);
bindParams.put(name, new Boolean(x));
}
/**
* {@inheritDoc}
*/
public void setByte(String name, byte x) throws SQLException {
embedded.setByte(name, x);
bindParams.put(name, new Byte(x));
}
/**
* {@inheritDoc}
*/
public void setShort(String name, short x) throws SQLException {
embedded.setShort(name, x);
bindParams.put(name, new Short(x));
}
/**
* {@inheritDoc}
*/
public void setInt(String name, int x) throws SQLException {
embedded.setInt(name, x);
bindParams.put(name, new Integer(x));
}
/**
* {@inheritDoc}
*/
public void setLong(String name, long x) throws SQLException {
embedded.setLong(name, x);
bindParams.put(name, new Long(x));
}
/**
* {@inheritDoc}
*/
public void setFloat(String name, float x) throws SQLException {
embedded.setFloat(name, x);
bindParams.put(name, new Float(x));
}
/**
* {@inheritDoc}
*/
public void setDouble(String name, double x)
throws SQLException {
embedded.setDouble(name, x);
bindParams.put(name, new Double(x));
}
/**
* {@inheritDoc}
*/
public void setBigDecimal(String name, BigDecimal x)
throws SQLException {
embedded.setBigDecimal(name, x);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setString(String name, String x)
throws SQLException {
embedded.setString(name, x);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setBytes(String name, byte[] x)
throws SQLException {
embedded.setBytes(name, x);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setDate(String name, Date x) throws SQLException {
embedded.setDate(name, x);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setTime(String name, Time x) throws SQLException {
embedded.setTime(name, x);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setTimestamp(String name, Timestamp x)
throws SQLException {
embedded.setTimestamp(name, x);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setAsciiStream(String name, InputStream x,
int length) throws SQLException {
embedded.setAsciiStream(name, x, length);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setBinaryStream(String name, InputStream x,
int length) throws SQLException {
embedded.setBinaryStream(name, x, length);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setObject(String name, Object x,
int targetSqlType, int scale) throws SQLException {
embedded.setObject(name, x, targetSqlType);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setObject(String name, Object x,
int targetSqlType) throws SQLException {
embedded.setObject(name, x, targetSqlType);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setObject(String name, Object x)
throws SQLException {
embedded.setObject(name, x);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setCharacterStream(String name, Reader reader,
int length) throws SQLException {
embedded.setCharacterStream(name, reader, length);
bindParams.put(name, reader);
}
/**
* {@inheritDoc}
*/
public void setDate(String name, Date x, Calendar cal)
throws SQLException {
embedded.setDate(name, x, cal);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setTime(String name, Time x, Calendar cal)
throws SQLException {
embedded.setTime(name, x, cal);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setTimestamp(String name, Timestamp x,
Calendar cal) throws SQLException {
embedded.setTimestamp(name, x, cal);
bindParams.put(name, x);
}
/**
* {@inheritDoc}
*/
public void setNull(String name, int sqlType, String typeName)
throws SQLException {
embedded.setNull(name, sqlType, typeName);
bindParams.put(name, null);
}
/**
* {@inheritDoc}
*/
public String getString(String name) throws SQLException {
return embedded.getString(name);
}
/**
* {@inheritDoc}
*/
public boolean getBoolean(String name) throws SQLException {
return embedded.getBoolean(name);
}
/**
* {@inheritDoc}
*/
public byte getByte(String name) throws SQLException {
return embedded.getByte(name);
}
/**
* {@inheritDoc}
*/
public short getShort(String name) throws SQLException {
return embedded.getShort(name);
}
/**
* {@inheritDoc}
*/
public int getInt(String name) throws SQLException {
return embedded.getInt(name);
}
/**
* {@inheritDoc}
*/
public long getLong(String name) throws SQLException {
return embedded.getLong(name);
}
/**
* {@inheritDoc}
*/
public float getFloat(String name) throws SQLException {
return embedded.getFloat(name);
}
/**
* {@inheritDoc}
*/
public double getDouble(String name) throws SQLException {
return embedded.getDouble(name);
}
/**
* {@inheritDoc}
*/
public byte[] getBytes(String name) throws SQLException {
return embedded.getBytes(name);
}
/**
* {@inheritDoc}
*/
public Date getDate(String name) throws SQLException {
return embedded.getDate(name);
}
/**
* {@inheritDoc}
*/
public Time getTime(String name) throws SQLException {
return embedded.getTime(name);
}
/**
* {@inheritDoc}
*/
public Timestamp getTimestamp(String name) throws SQLException {
return embedded.getTimestamp(name);
}
/**
* {@inheritDoc}
*/
public Object getObject(String name) throws SQLException {
return embedded.getObject(name);
}
/**
* {@inheritDoc}
*/
public BigDecimal getBigDecimal(String name) throws SQLException {
return embedded.getBigDecimal(name);
}
/**
* {@inheritDoc}
*/
public Ref getRef(String name) throws SQLException {
return embedded.getRef(name);
}
/**
* {@inheritDoc}
*/
public Blob getBlob(String name) throws SQLException {
return embedded.getBlob(name);
}
/**
* {@inheritDoc}
*/
public Clob getClob(String name) throws SQLException {
return embedded.getClob(name);
}
/**
* {@inheritDoc}
*/
public Array getArray(String name) throws SQLException {
return embedded.getArray(name);
}
/**
* {@inheritDoc}
*/
public Date getDate(String name, Calendar cal)
throws SQLException {
return embedded.getDate(name, cal);
}
/**
* {@inheritDoc}
*/
public Time getTime(String name, Calendar cal)
throws SQLException {
return embedded.getTime(name, cal);
}
/**
* {@inheritDoc}
*/
public Timestamp getTimestamp(String name, Calendar cal)
throws SQLException {
return embedded.getTimestamp(name, cal);
}
/**
* {@inheritDoc}
*/
public URL getURL(String name) throws SQLException {
return embedded.getURL(name);
}
/**
* Represents the meta information about a Out parameter.
* OutParamMetadata
* @version $Rev$
*/
class OutParamMetadata {
private int type;
private int scale;
private String typeName;
public static final int NO_SCALE = -1;
public static final String NONE = "NONE";
/**
* Default contructor
* @param t the SQL type code defined by <code>java.sql.Types</code>.
* @param s the desired number of digits to the right of the
* decimal point. It must be greater than or equal to zero.
* @param tName the fully-qualified name of an SQL structured type
*/
public OutParamMetadata(int t, int s, String tName) {
type = t;
scale = s;
typeName = tName;
}
/**
* Constructs metadata with a Typename
* @param t the SQL type code defined by <code>java.sql.Types</code>.
* @param tName the fully-qualified name of an SQL structured type
*/
public OutParamMetadata(int t, String tName) {
this(t, NO_SCALE, tName);
}
/**
* Constructs metadata with a Typename
* @param t the SQL type code defined by <code>java.sql.Types</code>.
* @param s the desired number of digits to the right of the
* decimal point. It must be greater than or equal to zero.
*/
public OutParamMetadata(int t, int s) {
this(t, s, NONE);
}
/**
* Constructs metadata with a Typename
* @param t the SQL type code defined by <code>java.sql.Types</code>.
*/
public OutParamMetadata(int t) {
this(t, NO_SCALE, NONE);
}
/**
* @return Returns the scale.
*/
public int getScale() {
return scale;
}
/**
* @return Returns the type.
*/
public int getType() {
return type;
}
/**
* @return Returns the typeName.
*/
public String getTypeName() {
return typeName;
}
public String toString() {
return "type: " + TypeConverter.convert(type) + " scale: " + scale +
" type name: " + typeName;
}
}
public Object getObject(int i, Map<String, Class<?>> map)
throws SQLException {
return embedded.getObject(i, map);
}
public Object getObject(String name, Map<String, Class<?>> map)
throws SQLException {
return embedded.getObject(name, map);
}
public RowId getRowId(int i) throws SQLException {
return embedded.getRowId(i);
}
public RowId getRowId(String name) throws SQLException {
return embedded.getRowId(name);
}
public void setRowId(String name, RowId x) throws SQLException {
embedded.setRowId(name, x);
}
public void setNString(String name, String value) throws SQLException {
embedded.setNString(name, value);
}
public void setNCharacterStream(String name, Reader reader,
long length) throws SQLException {
embedded.setNCharacterStream(name, reader, length);
}
public void setNClob(String name, NClob value) throws SQLException {
embedded.setNClob(name, value);
}
public void setClob(String name, Reader reader, long length)
throws SQLException {
embedded.setClob(name, reader, length);
}
public void setBlob(String name, InputStream input, long length)
throws SQLException {
embedded.setBlob(name, input, length);
}
public void setNClob(String name, Reader reader, long length)
throws SQLException {
embedded.setNClob(name, reader, length);
}
public NClob getNClob(int i) throws SQLException {
return embedded.getNClob(i);
}
public NClob getNClob(String name) throws SQLException {
return embedded.getNClob(name);
}
public void setSQLXML(String name, SQLXML xmlObject)
throws SQLException {
embedded.setSQLXML(name, xmlObject);
}
public SQLXML getSQLXML(int i) throws SQLException {
return embedded.getSQLXML(i);
}
public SQLXML getSQLXML(String name) throws SQLException {
return embedded.getSQLXML(name);
}
public String getNString(int i) throws SQLException {
return embedded.getNString(i);
}
public String getNString(String name) throws SQLException {
return embedded.getNString(name);
}
public Reader getNCharacterStream(int i) throws SQLException {
return embedded.getNCharacterStream(i);
}
public Reader getNCharacterStream(String name) throws SQLException {
return embedded.getNCharacterStream(name);
}
public Reader getCharacterStream(int i) throws SQLException {
return embedded.getCharacterStream(i);
}
public Reader getCharacterStream(String name) throws SQLException {
return embedded.getCharacterStream(name);
}
public void setBlob(String name, Blob x) throws SQLException {
embedded.setBlob(name, x);
}
public void setClob(String name, Clob x) throws SQLException {
embedded.setClob(name, x);
}
public void setAsciiStream(String name, InputStream input, long length)
throws SQLException {
embedded.setAsciiStream(name, input, length);
}
public void setBinaryStream(String name, InputStream input, long length)
throws SQLException {
embedded.setBinaryStream(name, input, length);
}
public void setCharacterStream(String name, Reader reader,
long length) throws SQLException {
embedded.setCharacterStream(name, reader);
}
public void setAsciiStream(String name, InputStream input)
throws SQLException {
embedded.setAsciiStream(name, input);
}
public void setBinaryStream(String name, InputStream input)
throws SQLException {
embedded.setBinaryStream(name, input);
}
public void setCharacterStream(String name, Reader reader)
throws SQLException {
embedded.setCharacterStream(name, reader);
}
public void setNCharacterStream(String name, Reader reader)
throws SQLException {
embedded.setNCharacterStream(name, reader);
}
public void setClob(String name, Reader reader) throws SQLException {
embedded.setClob(name, reader);
}
public void setBlob(String name, InputStream input) throws SQLException {
embedded.setBlob(name, input);
}
public void setNClob(String name, Reader reader)
throws SQLException {
embedded.setNClob(name, reader);
}
public <T> T getObject(int i, Class<T> type)
throws SQLException {
return embedded.getObject(i, type);
}
public <T> T getObject(String name, Class<T> type)
throws SQLException {
return embedded.getObject(name, type);
}
public void setRowId(int i, RowId x) throws SQLException {
embedded.setRowId(i, x);
}
public void setNString(int i, String value)
throws SQLException {
embedded.setNString(i, value);
}
public void setNCharacterStream(int i, Reader reader, long length)
throws SQLException {
embedded.setNCharacterStream(i, reader, length);
}
public void setNClob(int i, NClob value) throws SQLException {
embedded.setNClob(i, value);
}
public void setClob(int i, Reader reader, long length)
throws SQLException {
embedded.setClob(i, reader, length);
}
public void setBlob(int i, InputStream input, long length)
throws SQLException {
embedded.setBlob(i, input, length);
}
public void setNClob(int i, Reader reader, long length)
throws SQLException {
embedded.setNClob(i, reader, length);
}
public void setSQLXML(int i, SQLXML xmlObject)
throws SQLException {
embedded.setSQLXML(i, xmlObject);
}
public void setAsciiStream(int i, InputStream input, long length)
throws SQLException {
embedded.setAsciiStream(i, input, length);
}
public void setBinaryStream(int i, InputStream input, long length)
throws SQLException {
embedded.setBinaryStream(i, input, length);
}
public void setCharacterStream(int i, Reader reader, long length)
throws SQLException {
embedded.setCharacterStream(i, reader, length);
}
public void setAsciiStream(int i, InputStream input) throws SQLException {
embedded.setAsciiStream(i, input);
}
public void setBinaryStream(int i, InputStream input) throws SQLException {
embedded.setBinaryStream(i, input);
}
public void setCharacterStream(int i, Reader reader) throws SQLException {
embedded.setCharacterStream(i, reader);
}
public void setNCharacterStream(int i, Reader reader) throws SQLException {
embedded.setNCharacterStream(i, reader);
}
public void setClob(int i, Reader reader) throws SQLException {
embedded.setClob(i, reader);
}
public void setBlob(int i, InputStream input) throws SQLException {
embedded.setBlob(i, input);
}
public void setNClob(int i, Reader reader) throws SQLException {
embedded.setNClob(i, reader);
}
public boolean isClosed() throws SQLException {
return embedded.isClosed();
}
public void setPoolable(boolean poolable) throws SQLException {
embedded.setPoolable(poolable);
}
public boolean isPoolable() throws SQLException {
return embedded.isPoolable();
}
public void closeOnCompletion() throws SQLException {
embedded.closeOnCompletion();
}
public boolean isCloseOnCompletion() throws SQLException {
return embedded.isCloseOnCompletion();
}
public <T> T unwrap(Class<T> iface) throws SQLException {
return embedded.unwrap(iface);
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return embedded.isWrapperFor(iface);
}
}
| |
/*
* 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.parquet.avro;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;
import java.util.Arrays;
import java.util.Collections;
import org.apache.avro.Schema;
import org.apache.hadoop.conf.Configuration;
import org.codehaus.jackson.node.NullNode;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.parquet.schema.MessageType;
import org.apache.parquet.schema.MessageTypeParser;
import static org.junit.Assert.assertEquals;
public class TestAvroSchemaConverter {
private static final Configuration NEW_BEHAVIOR = new Configuration(false);
@BeforeClass
public static void setupConf() {
NEW_BEHAVIOR.setBoolean("parquet.avro.add-list-element-records", false);
NEW_BEHAVIOR.setBoolean("parquet.avro.write-old-list-structure", false);
}
public static final String ALL_PARQUET_SCHEMA =
"message org.apache.parquet.avro.myrecord {\n" +
" required boolean myboolean;\n" +
" required int32 myint;\n" +
" required int64 mylong;\n" +
" required float myfloat;\n" +
" required double mydouble;\n" +
" required binary mybytes;\n" +
" required binary mystring (UTF8);\n" +
" required group mynestedrecord {\n" +
" required int32 mynestedint;\n" +
" }\n" +
" required binary myenum (ENUM);\n" +
" required group myarray (LIST) {\n" +
" repeated int32 array;\n" +
" }\n" +
" optional group myoptionalarray (LIST) {\n" +
" repeated int32 array;\n" +
" }\n" +
" required group myarrayofoptional (LIST) {\n" +
" repeated group list {\n" +
" optional int32 element;\n" +
" }\n" +
" }\n" +
" required group myrecordarray (LIST) {\n" +
" repeated group array {\n" +
" required int32 a;\n" +
" required int32 b;\n" +
" }\n" +
" }\n" +
" required group mymap (MAP) {\n" +
" repeated group map (MAP_KEY_VALUE) {\n" +
" required binary key (UTF8);\n" +
" required int32 value;\n" +
" }\n" +
" }\n" +
" required fixed_len_byte_array(1) myfixed;\n" +
"}\n";
private void testAvroToParquetConversion(
Schema avroSchema, String schemaString) throws Exception {
testAvroToParquetConversion(new Configuration(false), avroSchema, schemaString);
}
private void testAvroToParquetConversion(
Configuration conf, Schema avroSchema, String schemaString)
throws Exception {
AvroSchemaConverter avroSchemaConverter = new AvroSchemaConverter(conf);
MessageType schema = avroSchemaConverter.convert(avroSchema);
MessageType expectedMT = MessageTypeParser.parseMessageType(schemaString);
assertEquals("converting " + schema + " to " + schemaString, expectedMT.toString(),
schema.toString());
}
private void testParquetToAvroConversion(
Schema avroSchema, String schemaString) throws Exception {
testParquetToAvroConversion(new Configuration(false), avroSchema, schemaString);
}
private void testParquetToAvroConversion(
Configuration conf, Schema avroSchema, String schemaString)
throws Exception {
AvroSchemaConverter avroSchemaConverter = new AvroSchemaConverter(conf);
Schema schema = avroSchemaConverter.convert(MessageTypeParser.parseMessageType
(schemaString));
assertEquals("converting " + schemaString + " to " + avroSchema, avroSchema.toString(),
schema.toString());
}
private void testRoundTripConversion(
Schema avroSchema, String schemaString) throws Exception {
testRoundTripConversion(new Configuration(), avroSchema, schemaString);
}
private void testRoundTripConversion(
Configuration conf, Schema avroSchema, String schemaString)
throws Exception {
AvroSchemaConverter avroSchemaConverter = new AvroSchemaConverter(conf);
MessageType schema = avroSchemaConverter.convert(avroSchema);
MessageType expectedMT = MessageTypeParser.parseMessageType(schemaString);
assertEquals("converting " + schema + " to " + schemaString, expectedMT.toString(),
schema.toString());
Schema convertedAvroSchema = avroSchemaConverter.convert(expectedMT);
assertEquals("converting " + expectedMT + " to " + avroSchema.toString(true),
avroSchema.toString(), convertedAvroSchema.toString());
}
@Test(expected = IllegalArgumentException.class)
public void testTopLevelMustBeARecord() {
new AvroSchemaConverter().convert(Schema.create(Schema.Type.INT));
}
@Test
public void testAllTypes() throws Exception {
Schema schema = new Schema.Parser().parse(
Resources.getResource("all.avsc").openStream());
testAvroToParquetConversion(
NEW_BEHAVIOR, schema,
"message org.apache.parquet.avro.myrecord {\n" +
// Avro nulls are not encoded, unless they are null unions
" required boolean myboolean;\n" +
" required int32 myint;\n" +
" required int64 mylong;\n" +
" required float myfloat;\n" +
" required double mydouble;\n" +
" required binary mybytes;\n" +
" required binary mystring (UTF8);\n" +
" required group mynestedrecord {\n" +
" required int32 mynestedint;\n" +
" }\n" +
" required binary myenum (ENUM);\n" +
" required group myarray (LIST) {\n" +
" repeated group list {\n" +
" required int32 element;\n" +
" }\n" +
" }\n" +
" required group myemptyarray (LIST) {\n" +
" repeated group list {\n" +
" required int32 element;\n" +
" }\n" +
" }\n" +
" optional group myoptionalarray (LIST) {\n" +
" repeated group list {\n" +
" required int32 element;\n" +
" }\n" +
" }\n" +
" required group myarrayofoptional (LIST) {\n" +
" repeated group list {\n" +
" optional int32 element;\n" +
" }\n" +
" }\n" +
" required group mymap (MAP) {\n" +
" repeated group map (MAP_KEY_VALUE) {\n" +
" required binary key (UTF8);\n" +
" required int32 value;\n" +
" }\n" +
" }\n" +
" required group myemptymap (MAP) {\n" +
" repeated group map (MAP_KEY_VALUE) {\n" +
" required binary key (UTF8);\n" +
" required int32 value;\n" +
" }\n" +
" }\n" +
" required fixed_len_byte_array(1) myfixed;\n" +
"}\n");
}
@Test
public void testAllTypesOldListBehavior() throws Exception {
Schema schema = new Schema.Parser().parse(
Resources.getResource("all.avsc").openStream());
testAvroToParquetConversion(
schema,
"message org.apache.parquet.avro.myrecord {\n" +
// Avro nulls are not encoded, unless they are null unions
" required boolean myboolean;\n" +
" required int32 myint;\n" +
" required int64 mylong;\n" +
" required float myfloat;\n" +
" required double mydouble;\n" +
" required binary mybytes;\n" +
" required binary mystring (UTF8);\n" +
" required group mynestedrecord {\n" +
" required int32 mynestedint;\n" +
" }\n" +
" required binary myenum (ENUM);\n" +
" required group myarray (LIST) {\n" +
" repeated int32 array;\n" +
" }\n" +
" required group myemptyarray (LIST) {\n" +
" repeated int32 array;\n" +
" }\n" +
" optional group myoptionalarray (LIST) {\n" +
" repeated int32 array;\n" +
" }\n" +
" required group myarrayofoptional (LIST) {\n" +
" repeated int32 array;\n" +
" }\n" +
" required group mymap (MAP) {\n" +
" repeated group map (MAP_KEY_VALUE) {\n" +
" required binary key (UTF8);\n" +
" required int32 value;\n" +
" }\n" +
" }\n" +
" required group myemptymap (MAP) {\n" +
" repeated group map (MAP_KEY_VALUE) {\n" +
" required binary key (UTF8);\n" +
" required int32 value;\n" +
" }\n" +
" }\n" +
" required fixed_len_byte_array(1) myfixed;\n" +
"}\n");
}
@Test
public void testAllTypesParquetToAvro() throws Exception {
Schema schema = new Schema.Parser().parse(
Resources.getResource("allFromParquetNewBehavior.avsc").openStream());
// Cannot use round-trip assertion because enum is lost
testParquetToAvroConversion(NEW_BEHAVIOR, schema, ALL_PARQUET_SCHEMA);
}
@Test
public void testAllTypesParquetToAvroOldBehavior() throws Exception {
Schema schema = new Schema.Parser().parse(
Resources.getResource("allFromParquetOldBehavior.avsc").openStream());
// Cannot use round-trip assertion because enum is lost
testParquetToAvroConversion(schema, ALL_PARQUET_SCHEMA);
}
@Test(expected = IllegalArgumentException.class)
public void testParquetMapWithNonStringKeyFails() throws Exception {
MessageType parquetSchema = MessageTypeParser.parseMessageType(
"message myrecord {\n" +
" required group mymap (MAP) {\n" +
" repeated group map (MAP_KEY_VALUE) {\n" +
" required int32 key;\n" +
" required int32 value;\n" +
" }\n" +
" }\n" +
"}\n"
);
new AvroSchemaConverter().convert(parquetSchema);
}
@Test
public void testOptionalFields() throws Exception {
Schema schema = Schema.createRecord("record1", null, null, false);
Schema optionalInt = optional(Schema.create(Schema.Type.INT));
schema.setFields(Arrays.asList(
new Schema.Field("myint", optionalInt, null, NullNode.getInstance())
));
testRoundTripConversion(
schema,
"message record1 {\n" +
" optional int32 myint;\n" +
"}\n");
}
@Test
public void testOptionalMapValue() throws Exception {
Schema schema = Schema.createRecord("record1", null, null, false);
Schema optionalIntMap = Schema.createMap(optional(Schema.create(Schema.Type.INT)));
schema.setFields(Arrays.asList(
new Schema.Field("myintmap", optionalIntMap, null, null)
));
testRoundTripConversion(
schema,
"message record1 {\n" +
" required group myintmap (MAP) {\n" +
" repeated group map (MAP_KEY_VALUE) {\n" +
" required binary key (UTF8);\n" +
" optional int32 value;\n" +
" }\n" +
" }\n" +
"}\n");
}
@Test
public void testOptionalArrayElement() throws Exception {
Schema schema = Schema.createRecord("record1", null, null, false);
Schema optionalIntArray = Schema.createArray(optional(Schema.create(Schema.Type.INT)));
schema.setFields(Arrays.asList(
new Schema.Field("myintarray", optionalIntArray, null, null)
));
testRoundTripConversion(
NEW_BEHAVIOR, schema,
"message record1 {\n" +
" required group myintarray (LIST) {\n" +
" repeated group list {\n" +
" optional int32 element;\n" +
" }\n" +
" }\n" +
"}\n");
}
@Test
public void testUnionOfTwoTypes() throws Exception {
Schema schema = Schema.createRecord("record2", null, null, false);
Schema multipleTypes = Schema.createUnion(Arrays.asList(Schema.create(Schema.Type
.NULL),
Schema.create(Schema.Type.INT),
Schema.create(Schema.Type.FLOAT)));
schema.setFields(Arrays.asList(
new Schema.Field("myunion", multipleTypes, null, NullNode.getInstance())));
// Avro union is modelled using optional data members of the different
// types. This does not translate back into an Avro union
testAvroToParquetConversion(
schema,
"message record2 {\n" +
" optional group myunion {\n" +
" optional int32 member0;\n" +
" optional float member1;\n" +
" }\n" +
"}\n");
}
@Test
public void testArrayOfOptionalRecords() throws Exception {
Schema innerRecord = Schema.createRecord("element", null, null, false);
Schema optionalString = optional(Schema.create(Schema.Type.STRING));
innerRecord.setFields(Lists.newArrayList(
new Schema.Field("s1", optionalString, null, NullNode.getInstance()),
new Schema.Field("s2", optionalString, null, NullNode.getInstance())
));
Schema schema = Schema.createRecord("HasArray", null, null, false);
schema.setFields(Lists.newArrayList(
new Schema.Field("myarray", Schema.createArray(optional(innerRecord)),
null, null)
));
System.err.println("Avro schema: " + schema.toString(true));
testRoundTripConversion(NEW_BEHAVIOR, schema, "message HasArray {\n" +
" required group myarray (LIST) {\n" +
" repeated group list {\n" +
" optional group element {\n" +
" optional binary s1 (UTF8);\n" +
" optional binary s2 (UTF8);\n" +
" }\n" +
" }\n" +
" }\n" +
"}\n");
}
@Test
public void testArrayOfOptionalRecordsOldBehavior() throws Exception {
Schema innerRecord = Schema.createRecord("InnerRecord", null, null, false);
Schema optionalString = optional(Schema.create(Schema.Type.STRING));
innerRecord.setFields(Lists.newArrayList(
new Schema.Field("s1", optionalString, null, NullNode.getInstance()),
new Schema.Field("s2", optionalString, null, NullNode.getInstance())
));
Schema schema = Schema.createRecord("HasArray", null, null, false);
schema.setFields(Lists.newArrayList(
new Schema.Field("myarray", Schema.createArray(optional(innerRecord)),
null, null)
));
System.err.println("Avro schema: " + schema.toString(true));
// Cannot use round-trip assertion because InnerRecord optional is removed
testAvroToParquetConversion(schema, "message HasArray {\n" +
" required group myarray (LIST) {\n" +
" repeated group array {\n" +
" optional binary s1 (UTF8);\n" +
" optional binary s2 (UTF8);\n" +
" }\n" +
" }\n" +
"}\n");
}
@Test
public void testOldAvroListOfLists() throws Exception {
Schema listOfLists = optional(Schema.createArray(Schema.createArray(
Schema.create(Schema.Type.INT))));
Schema schema = Schema.createRecord("AvroCompatListInList", null, null, false);
schema.setFields(Lists.newArrayList(
new Schema.Field("listOfLists", listOfLists, null, NullNode.getInstance())
));
System.err.println("Avro schema: " + schema.toString(true));
testRoundTripConversion(schema,
"message AvroCompatListInList {\n" +
" optional group listOfLists (LIST) {\n" +
" repeated group array (LIST) {\n" +
" repeated int32 array;\n" +
" }\n" +
" }\n" +
"}");
// Cannot use round-trip assertion because 3-level representation is used
testParquetToAvroConversion(NEW_BEHAVIOR, schema,
"message AvroCompatListInList {\n" +
" optional group listOfLists (LIST) {\n" +
" repeated group array (LIST) {\n" +
" repeated int32 array;\n" +
" }\n" +
" }\n" +
"}");
}
@Test
public void testOldThriftListOfLists() throws Exception {
Schema listOfLists = optional(Schema.createArray(Schema.createArray(
Schema.create(Schema.Type.INT))));
Schema schema = Schema.createRecord("ThriftCompatListInList", null, null, false);
schema.setFields(Lists.newArrayList(
new Schema.Field("listOfLists", listOfLists, null, NullNode.getInstance())
));
System.err.println("Avro schema: " + schema.toString(true));
// Cannot use round-trip assertion because repeated group names differ
testParquetToAvroConversion(schema,
"message ThriftCompatListInList {\n" +
" optional group listOfLists (LIST) {\n" +
" repeated group listOfLists_tuple (LIST) {\n" +
" repeated int32 listOfLists_tuple_tuple;\n" +
" }\n" +
" }\n" +
"}");
// Cannot use round-trip assertion because 3-level representation is used
testParquetToAvroConversion(NEW_BEHAVIOR, schema,
"message ThriftCompatListInList {\n" +
" optional group listOfLists (LIST) {\n" +
" repeated group listOfLists_tuple (LIST) {\n" +
" repeated int32 listOfLists_tuple_tuple;\n" +
" }\n" +
" }\n" +
"}");
}
@Test
public void testUnknownTwoLevelListOfLists() throws Exception {
// This tests the case where we don't detect a 2-level list by the repeated
// group's name, but it must be 2-level because the repeated group doesn't
// contain an optional or repeated element as required for 3-level lists
Schema listOfLists = optional(Schema.createArray(Schema.createArray(
Schema.create(Schema.Type.INT))));
Schema schema = Schema.createRecord("UnknownTwoLevelListInList", null, null, false);
schema.setFields(Lists.newArrayList(
new Schema.Field("listOfLists", listOfLists, null, NullNode.getInstance())
));
System.err.println("Avro schema: " + schema.toString(true));
// Cannot use round-trip assertion because repeated group names differ
testParquetToAvroConversion(schema,
"message UnknownTwoLevelListInList {\n" +
" optional group listOfLists (LIST) {\n" +
" repeated group mylist (LIST) {\n" +
" repeated int32 innerlist;\n" +
" }\n" +
" }\n" +
"}");
// Cannot use round-trip assertion because 3-level representation is used
testParquetToAvroConversion(NEW_BEHAVIOR, schema,
"message UnknownTwoLevelListInList {\n" +
" optional group listOfLists (LIST) {\n" +
" repeated group mylist (LIST) {\n" +
" repeated int32 innerlist;\n" +
" }\n" +
" }\n" +
"}");
}
@Test
public void testParquetMapWithoutMapKeyValueAnnotation() throws Exception {
Schema schema = Schema.createRecord("myrecord", null, null, false);
Schema map = Schema.createMap(Schema.create(Schema.Type.INT));
schema.setFields(Collections.singletonList(new Schema.Field("mymap", map, null, null)));
String parquetSchema =
"message myrecord {\n" +
" required group mymap (MAP) {\n" +
" repeated group map {\n" +
" required binary key (UTF8);\n" +
" required int32 value;\n" +
" }\n" +
" }\n" +
"}\n";
testParquetToAvroConversion(schema, parquetSchema);
testParquetToAvroConversion(NEW_BEHAVIOR, schema, parquetSchema);
}
public static Schema optional(Schema original) {
return Schema.createUnion(Lists.newArrayList(
Schema.create(Schema.Type.NULL),
original));
}
}
| |
/*
* 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.prestosql.sql.rewrite;
import com.google.common.collect.ImmutableList;
import io.prestosql.Session;
import io.prestosql.execution.warnings.WarningCollector;
import io.prestosql.metadata.Metadata;
import io.prestosql.metadata.QualifiedObjectName;
import io.prestosql.metadata.TableHandle;
import io.prestosql.metadata.TableMetadata;
import io.prestosql.security.AccessControl;
import io.prestosql.spi.connector.ColumnHandle;
import io.prestosql.spi.connector.ColumnMetadata;
import io.prestosql.spi.connector.Constraint;
import io.prestosql.spi.statistics.ColumnStatistics;
import io.prestosql.spi.statistics.DoubleRange;
import io.prestosql.spi.statistics.Estimate;
import io.prestosql.spi.statistics.TableStatistics;
import io.prestosql.spi.type.BigintType;
import io.prestosql.spi.type.DecimalType;
import io.prestosql.spi.type.DoubleType;
import io.prestosql.spi.type.IntegerType;
import io.prestosql.spi.type.RealType;
import io.prestosql.spi.type.SmallintType;
import io.prestosql.spi.type.TinyintType;
import io.prestosql.spi.type.Type;
import io.prestosql.sql.QueryUtil;
import io.prestosql.sql.analyzer.QueryExplainer;
import io.prestosql.sql.analyzer.SemanticException;
import io.prestosql.sql.parser.SqlParser;
import io.prestosql.sql.planner.Plan;
import io.prestosql.sql.planner.plan.FilterNode;
import io.prestosql.sql.planner.plan.TableScanNode;
import io.prestosql.sql.tree.AllColumns;
import io.prestosql.sql.tree.AstVisitor;
import io.prestosql.sql.tree.Cast;
import io.prestosql.sql.tree.DoubleLiteral;
import io.prestosql.sql.tree.Expression;
import io.prestosql.sql.tree.Node;
import io.prestosql.sql.tree.NullLiteral;
import io.prestosql.sql.tree.QualifiedName;
import io.prestosql.sql.tree.Query;
import io.prestosql.sql.tree.QuerySpecification;
import io.prestosql.sql.tree.Row;
import io.prestosql.sql.tree.SelectItem;
import io.prestosql.sql.tree.ShowStats;
import io.prestosql.sql.tree.Statement;
import io.prestosql.sql.tree.StringLiteral;
import io.prestosql.sql.tree.Table;
import io.prestosql.sql.tree.TableSubquery;
import io.prestosql.sql.tree.Values;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.prestosql.metadata.MetadataUtil.createQualifiedObjectName;
import static io.prestosql.spi.type.DateType.DATE;
import static io.prestosql.spi.type.StandardTypes.DOUBLE;
import static io.prestosql.spi.type.StandardTypes.VARCHAR;
import static io.prestosql.sql.QueryUtil.aliased;
import static io.prestosql.sql.QueryUtil.selectAll;
import static io.prestosql.sql.QueryUtil.simpleQuery;
import static io.prestosql.sql.analyzer.SemanticErrorCode.MISSING_TABLE;
import static io.prestosql.sql.analyzer.SemanticErrorCode.NOT_SUPPORTED;
import static io.prestosql.sql.planner.optimizations.PlanNodeSearcher.searchFrom;
import static java.lang.Math.round;
import static java.util.Objects.requireNonNull;
public class ShowStatsRewrite
implements StatementRewrite.Rewrite
{
private static final Expression NULL_DOUBLE = new Cast(new NullLiteral(), DOUBLE);
private static final Expression NULL_VARCHAR = new Cast(new NullLiteral(), VARCHAR);
@Override
public Statement rewrite(Session session, Metadata metadata, SqlParser parser, Optional<QueryExplainer> queryExplainer, Statement node, List<Expression> parameters, AccessControl accessControl, WarningCollector warningCollector)
{
return (Statement) new Visitor(metadata, session, parameters, queryExplainer, warningCollector).process(node, null);
}
private static class Visitor
extends AstVisitor<Node, Void>
{
private final Metadata metadata;
private final Session session;
private final List<Expression> parameters;
private final Optional<QueryExplainer> queryExplainer;
private final WarningCollector warningCollector;
public Visitor(Metadata metadata, Session session, List<Expression> parameters, Optional<QueryExplainer> queryExplainer, WarningCollector warningCollector)
{
this.metadata = requireNonNull(metadata, "metadata is null");
this.session = requireNonNull(session, "session is null");
this.parameters = requireNonNull(parameters, "parameters is null");
this.queryExplainer = requireNonNull(queryExplainer, "queryExplainer is null");
this.warningCollector = requireNonNull(warningCollector, "warningCollector is null");
}
@Override
protected Node visitShowStats(ShowStats node, Void context)
{
checkState(queryExplainer.isPresent(), "Query explainer must be provided for SHOW STATS SELECT");
if (node.getRelation() instanceof TableSubquery) {
Query query = ((TableSubquery) node.getRelation()).getQuery();
QuerySpecification specification = (QuerySpecification) query.getQueryBody();
Plan plan = queryExplainer.get().getLogicalPlan(session, new Query(Optional.empty(), specification, Optional.empty(), Optional.empty()), parameters, warningCollector);
validateShowStatsSubquery(node, query, specification, plan);
Table table = (Table) specification.getFrom().get();
Constraint<ColumnHandle> constraint = getConstraint(plan);
return rewriteShowStats(node, table, constraint);
}
else if (node.getRelation() instanceof Table) {
Table table = (Table) node.getRelation();
return rewriteShowStats(node, table, Constraint.alwaysTrue());
}
else {
throw new IllegalArgumentException("Expected either TableSubquery or Table as relation");
}
}
private void validateShowStatsSubquery(ShowStats node, Query query, QuerySpecification querySpecification, Plan plan)
{
// The following properties of SELECT subquery are required:
// - only one relation in FROM
// - only predicates that can be pushed down can be in the where clause
// - no group by
// - no having
// - no set quantifier
Optional<FilterNode> filterNode = searchFrom(plan.getRoot())
.where(FilterNode.class::isInstance)
.findSingle();
check(!filterNode.isPresent(), node, "Only predicates that can be pushed down are supported in the SHOW STATS WHERE clause");
check(querySpecification.getFrom().isPresent(), node, "There must be exactly one table in query passed to SHOW STATS SELECT clause");
check(querySpecification.getFrom().get() instanceof Table, node, "There must be exactly one table in query passed to SHOW STATS SELECT clause");
check(!query.getWith().isPresent(), node, "WITH is not supported by SHOW STATS SELECT clause");
check(!querySpecification.getOrderBy().isPresent(), node, "ORDER BY is not supported in SHOW STATS SELECT clause");
check(!querySpecification.getLimit().isPresent(), node, "LIMIT is not supported by SHOW STATS SELECT clause");
check(!querySpecification.getHaving().isPresent(), node, "HAVING is not supported in SHOW STATS SELECT clause");
check(!querySpecification.getGroupBy().isPresent(), node, "GROUP BY is not supported in SHOW STATS SELECT clause");
check(!querySpecification.getSelect().isDistinct(), node, "DISTINCT is not supported by SHOW STATS SELECT clause");
List<SelectItem> selectItems = querySpecification.getSelect().getSelectItems();
check(selectItems.size() == 1 && selectItems.get(0) instanceof AllColumns, node, "Only SELECT * is supported in SHOW STATS SELECT clause");
}
private Node rewriteShowStats(ShowStats node, Table table, Constraint<ColumnHandle> constraint)
{
TableHandle tableHandle = getTableHandle(node, table.getName());
TableStatistics tableStatistics = metadata.getTableStatistics(session, tableHandle, constraint);
List<String> statsColumnNames = buildColumnsNames();
List<SelectItem> selectItems = buildSelectItems(statsColumnNames);
TableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle);
Map<String, ColumnHandle> columnHandles = metadata.getColumnHandles(session, tableHandle);
List<Expression> resultRows = buildStatisticsRows(tableMetadata, columnHandles, tableStatistics);
return simpleQuery(selectAll(selectItems),
aliased(new Values(resultRows),
"table_stats_for_" + table.getName(),
statsColumnNames));
}
private static void check(boolean condition, ShowStats node, String message)
{
if (!condition) {
throw new SemanticException(NOT_SUPPORTED, node, message);
}
}
@Override
protected Node visitNode(Node node, Void context)
{
return node;
}
private Constraint<ColumnHandle> getConstraint(Plan plan)
{
Optional<TableScanNode> scanNode = searchFrom(plan.getRoot())
.where(TableScanNode.class::isInstance)
.findSingle();
if (!scanNode.isPresent()) {
return Constraint.alwaysFalse();
}
return new Constraint<>(scanNode.get().getCurrentConstraint());
}
private TableHandle getTableHandle(ShowStats node, QualifiedName table)
{
QualifiedObjectName qualifiedTableName = createQualifiedObjectName(session, node, table);
return metadata.getTableHandle(session, qualifiedTableName)
.orElseThrow(() -> new SemanticException(MISSING_TABLE, node, "Table %s not found", table));
}
private static List<String> buildColumnsNames()
{
return ImmutableList.<String>builder()
.add("column_name")
.add("data_size")
.add("distinct_values_count")
.add("nulls_fraction")
.add("row_count")
.add("low_value")
.add("high_value")
.build();
}
private static List<SelectItem> buildSelectItems(List<String> columnNames)
{
return columnNames.stream()
.map(QueryUtil::unaliasedName)
.collect(toImmutableList());
}
private List<Expression> buildStatisticsRows(TableMetadata tableMetadata, Map<String, ColumnHandle> columnHandles, TableStatistics tableStatistics)
{
ImmutableList.Builder<Expression> rowsBuilder = ImmutableList.builder();
for (ColumnMetadata columnMetadata : tableMetadata.getColumns()) {
if (columnMetadata.isHidden()) {
continue;
}
String columnName = columnMetadata.getName();
Type columnType = columnMetadata.getType();
ColumnHandle columnHandle = columnHandles.get(columnName);
ColumnStatistics columnStatistics = tableStatistics.getColumnStatistics().get(columnHandle);
if (columnStatistics != null) {
rowsBuilder.add(createColumnStatsRow(columnName, columnType, columnStatistics));
}
else {
rowsBuilder.add(createEmptyColumnStatsRow(columnName));
}
}
// Stats for whole table
rowsBuilder.add(createTableStatsRow(tableStatistics));
return rowsBuilder.build();
}
private Row createColumnStatsRow(String columnName, Type type, ColumnStatistics columnStatistics)
{
ImmutableList.Builder<Expression> rowValues = ImmutableList.builder();
rowValues.add(new StringLiteral(columnName));
rowValues.add(createEstimateRepresentation(columnStatistics.getDataSize()));
rowValues.add(createEstimateRepresentation(columnStatistics.getDistinctValuesCount()));
rowValues.add(createEstimateRepresentation(columnStatistics.getNullsFraction()));
rowValues.add(NULL_DOUBLE);
rowValues.add(toStringLiteral(type, columnStatistics.getRange().map(DoubleRange::getMin)));
rowValues.add(toStringLiteral(type, columnStatistics.getRange().map(DoubleRange::getMax)));
return new Row(rowValues.build());
}
private Expression createEmptyColumnStatsRow(String columnName)
{
ImmutableList.Builder<Expression> rowValues = ImmutableList.builder();
rowValues.add(new StringLiteral(columnName));
rowValues.add(NULL_DOUBLE);
rowValues.add(NULL_DOUBLE);
rowValues.add(NULL_DOUBLE);
rowValues.add(NULL_DOUBLE);
rowValues.add(NULL_VARCHAR);
rowValues.add(NULL_VARCHAR);
return new Row(rowValues.build());
}
private static Row createTableStatsRow(TableStatistics tableStatistics)
{
ImmutableList.Builder<Expression> rowValues = ImmutableList.builder();
rowValues.add(NULL_VARCHAR);
rowValues.add(NULL_DOUBLE);
rowValues.add(NULL_DOUBLE);
rowValues.add(NULL_DOUBLE);
rowValues.add(createEstimateRepresentation(tableStatistics.getRowCount()));
rowValues.add(NULL_VARCHAR);
rowValues.add(NULL_VARCHAR);
return new Row(rowValues.build());
}
private static Expression createEstimateRepresentation(Estimate estimate)
{
if (estimate.isUnknown()) {
return NULL_DOUBLE;
}
return new DoubleLiteral(Double.toString(estimate.getValue()));
}
private static Expression toStringLiteral(Type type, Optional<Double> optionalValue)
{
return optionalValue.map(value -> toStringLiteral(type, value)).orElse(NULL_VARCHAR);
}
private static Expression toStringLiteral(Type type, double value)
{
if (type.equals(BigintType.BIGINT) || type.equals(IntegerType.INTEGER) || type.equals(SmallintType.SMALLINT) || type.equals(TinyintType.TINYINT)) {
return new StringLiteral(Long.toString(round(value)));
}
if (type.equals(DoubleType.DOUBLE) || type instanceof DecimalType) {
return new StringLiteral(Double.toString(value));
}
if (type.equals(RealType.REAL)) {
return new StringLiteral(Float.toString((float) value));
}
if (type.equals(DATE)) {
return new StringLiteral(LocalDate.ofEpochDay(round(value)).toString());
}
throw new IllegalArgumentException("Unexpected type: " + type);
}
}
}
| |
/*
* 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.sysml.runtime.matrix.data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.math3.random.Well1024a;
import org.apache.sysml.hops.DataGenOp;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.util.NormalPRNGenerator;
import org.apache.sysml.runtime.util.PRNGenerator;
import org.apache.sysml.runtime.util.PoissonPRNGenerator;
import org.apache.sysml.runtime.util.UniformPRNGenerator;
/**
*
*/
public class LibMatrixDatagen
{
protected static final Log LOG = LogFactory.getLog(LibMatrixDatagen.class.getName());
public static final String RAND_PDF_UNIFORM = "uniform";
public static final String RAND_PDF_NORMAL = "normal";
public static final String RAND_PDF_POISSON = "poisson";
private LibMatrixDatagen() {
//prevent instantiation via private constructor
}
/**
*
* @param min
* @param max
* @param sparsity
* @param pdf
* @return
*/
public static boolean isShortcutRandOperation( double min, double max, double sparsity, String pdf )
{
return pdf.equalsIgnoreCase(RAND_PDF_UNIFORM)
&& ( ( min == 0.0 && max == 0.0 ) //all zeros
||( sparsity==1.0d && min == max )); //equal values
}
/**
*
* @param seq_from
* @param seq_to
* @param seq_incr
* @return
*/
public static double updateSeqIncr(double seq_from, double seq_to, double seq_incr) {
//handle default 1 to -1 for special case of from>to
return (seq_from>seq_to && seq_incr==1)? -1 : seq_incr;
}
/**
* A matrix of random numbers is generated by using multiple seeds, one for each
* block. Such block-level seeds are produced via Well equidistributed long-period linear
* generator (Well1024a). For a given seed, this function sets up the block-level seeds.
*
* This function is invoked from both CP (RandCPInstruction.processInstruction())
* as well as MR (RandMR.java while setting up the Rand job).
*
* @param seed
* @return
*/
public static Well1024a setupSeedsForRand(long seed)
{
long lSeed = (seed == DataGenOp.UNSPECIFIED_SEED ? DataGenOp.generateRandomSeed() : seed);
LOG.trace("Setting up RandSeeds with initial seed = "+lSeed+".");
Random random=new Random(lSeed);
Well1024a bigrand=new Well1024a();
//random.setSeed(lSeed);
int[] seeds=new int[32];
for(int s=0; s<seeds.length; s++)
seeds[s]=random.nextInt();
bigrand.setSeed(seeds);
return bigrand;
}
/**
*
* @param nrow
* @param ncol
* @param brlen
* @param bclen
* @param sparsity
* @return
* @throws DMLRuntimeException
*/
public static long[] computeNNZperBlock(long nrow, long ncol, int brlen, int bclen, double sparsity) throws DMLRuntimeException {
int numBlocks = (int) (Math.ceil((double)nrow/brlen) * Math.ceil((double)ncol/bclen));
//System.out.println("nrow=" + nrow + ", brlen=" + brlen + ", ncol="+ncol+", bclen=" + bclen + "::: " + Math.ceil(nrow/brlen));
// CURRENT:
// Total #of NNZ is set to the expected value (nrow*ncol*sparsity).
// TODO:
// Instead of using the expected value, one should actually
// treat NNZ as a random variable and accordingly generate a random value.
long nnz = (long) Math.ceil (nrow * (ncol*sparsity));
//System.out.println("Number of blocks = " + numBlocks + "; NNZ = " + nnz);
if ( numBlocks > Integer.MAX_VALUE ) {
throw new DMLRuntimeException("A random matrix of size [" + nrow + "," + ncol + "] can not be created. Number of blocks (" + numBlocks + ") exceeds the maximum integer size. Try to increase the block size.");
}
// Compute block-level NNZ
long[] ret = new long[numBlocks];
Arrays.fill(ret, 0);
if ( nnz < numBlocks ) {
// Ultra-sparse matrix
// generate the number of blocks with at least one non-zero
// = a random number between [1,nnz]
Random runif = new Random(System.nanoTime());
int numNZBlocks = 1;
if(nnz-1 > 0)
numNZBlocks += runif.nextInt((int)(nnz-1)); // To avoid exception from random.nextInt(0)
// distribute non-zeros across numNZBlocks
// compute proportions for each nzblock
// - divide (0,1] interval into numNZBlocks portions of random size
double[] blockNNZproportions = new double[numNZBlocks];
runif.setSeed(System.nanoTime());
for(int i=0; i < numNZBlocks-1; i++) {
blockNNZproportions[i] = runif.nextDouble();
}
blockNNZproportions[numNZBlocks-1] = 1;
// sort the values in ascending order
Arrays.sort(blockNNZproportions);
// compute actual number of non zeros per block according to proportions
long actualnnz = 0;
int bid;
runif.setSeed(System.nanoTime());
for(int i=0; i < numNZBlocks; i++) {
bid = -1;
do {
bid = runif.nextInt(numBlocks);
} while( ret[bid] != 0);
double prop = (i==0 ? blockNNZproportions[i]: (blockNNZproportions[i] - blockNNZproportions[i-1]));
ret[bid] = (long)Math.floor(prop * nnz);
actualnnz += ret[bid];
}
// Code to make sure exact number of non-zeros are generated
while (actualnnz < nnz) {
bid = runif.nextInt(numBlocks);
ret[bid]++;
actualnnz++;
}
}
else {
int bid = 0;
//long actualnnz = 0;
for(long r = 0; r < nrow; r += brlen) {
long curBlockRowSize = Math.min(brlen, (nrow - r));
for(long c = 0; c < ncol; c += bclen)
{
long curBlockColSize = Math.min(bclen, (ncol - c));
ret[bid] = (long) (curBlockRowSize * curBlockColSize * sparsity);
//actualnnz += ret[bid];
bid++;
}
}
}
return ret;
}
/**
*
* @param pdf
* @param r
* @param c
* @param rpb
* @param cpb
* @param sp
* @param min
* @param max
* @param distParams
* @return
* @throws DMLRuntimeException
*/
public static RandomMatrixGenerator createRandomMatrixGenerator(String pdf, int r, int c, int rpb, int cpb, double sp, double min, double max, String distParams)
throws DMLRuntimeException
{
RandomMatrixGenerator rgen = null;
if ( pdf.equalsIgnoreCase(RAND_PDF_UNIFORM))
rgen = new RandomMatrixGenerator(pdf, r, c, rpb, cpb, sp, min, max);
else if ( pdf.equalsIgnoreCase(RAND_PDF_NORMAL))
rgen = new RandomMatrixGenerator(pdf, r, c, rpb, cpb, sp);
else if ( pdf.equalsIgnoreCase(RAND_PDF_POISSON))
{
double mean = Double.NaN;
try {
mean = Double.parseDouble(distParams);
} catch(NumberFormatException e) {
throw new DMLRuntimeException("Failed to parse Poisson distribution parameter: " + distParams);
}
rgen = new RandomMatrixGenerator(pdf, r, c, rpb, cpb, sp, min, max, mean);
}
else
throw new DMLRuntimeException("Unsupported probability distribution \"" + pdf + "\" in rand() -- it must be one of \"uniform\", \"normal\", or \"poisson\"");
return rgen;
}
/**
* Function to generate a matrix of random numbers. This is invoked both
* from CP as well as from MR. In case of CP, it generates an entire matrix
* block-by-block. A <code>bigrand</code> is passed so that block-level
* seeds are generated internally. In case of MR, it generates a single
* block for given block-level seed <code>bSeed</code>.
*
* When pdf="uniform", cell values are drawn from uniform distribution in
* range <code>[min,max]</code>.
*
* When pdf="normal", cell values are drawn from standard normal
* distribution N(0,1). The range of generated values will always be
* (-Inf,+Inf).
*
* @param rows
* @param cols
* @param rowsInBlock
* @param colsInBlock
* @param sparsity
* @param min
* @param max
* @param bigrand
* @param bSeed
* @return
* @throws DMLRuntimeException
*/
public static void generateRandomMatrix( MatrixBlock out, RandomMatrixGenerator rgen, long[] nnzInBlocks,
Well1024a bigrand, long bSeed )
throws DMLRuntimeException
{
boolean invokedFromCP = true;
if(bigrand == null && nnzInBlocks!=null)
invokedFromCP = false;
/*
* Setup min and max for distributions other than "uniform". Min and Max
* are set up in such a way that the usual logic of
* (max-min)*prng.nextDouble() is still valid. This is done primarily to
* share the same code across different distributions.
*/
double min=0, max=1;
if ( rgen._pdf.equalsIgnoreCase(RAND_PDF_UNIFORM) ) {
min=rgen._min;
max=rgen._max;
}
int rows = rgen._rows;
int cols = rgen._cols;
int rpb = rgen._rowsPerBlock;
int cpb = rgen._colsPerBlock;
double sparsity = rgen._sparsity;
// sanity check valid dimensions and sparsity
checkMatrixDimensionsAndSparsity(rows, cols, sparsity);
// Determine the sparsity of output matrix
// if invoked from CP: estimated NNZ is for entire matrix (nnz=0, if 0 initialized)
// if invoked from MR: estimated NNZ is for one block
final long estnnz = (invokedFromCP ? ((min==0.0 && max==0.0)? 0 : (long)(sparsity * rows * cols))
: nnzInBlocks[0]);
boolean lsparse = MatrixBlock.evalSparseFormatInMemory( rows, cols, estnnz );
out.reset(rows, cols, lsparse);
// Special case shortcuts for efficiency
if ( rgen._pdf.equalsIgnoreCase(RAND_PDF_UNIFORM)) {
//specific cases for efficiency
if ( min == 0.0 && max == 0.0 ) { //all zeros
// nothing to do here
out.nonZeros = 0;
return;
}
else if( !out.sparse && sparsity==1.0d && (min == max //equal values, dense
|| (Double.isNaN(min) && Double.isNaN(max))) ) //min == max == NaN
{
out.init(min, out.rlen, out.clen);
return;
}
}
// Allocate memory
if ( out.sparse ) {
//note: individual sparse rows are allocated on demand,
//for consistency with memory estimates and prevent OOMs.
out.allocateSparseRowsBlock();
}
else{
out.allocateDenseBlock();
}
int nrb = (int) Math.ceil((double)rows/rpb);
int ncb = (int) Math.ceil((double)cols/cpb);
long[] seeds = null;
if ( invokedFromCP )
seeds = generateSeedsForCP(bigrand, nrb, ncb);
genRandomNumbers(invokedFromCP, 0, nrb, out, rgen, nnzInBlocks, bSeed, seeds);
out.recomputeNonZeros();
}
/**
* Function to generate a matrix of random numbers. This is invoked both
* from CP as well as from MR. In case of CP, it generates an entire matrix
* block-by-block. A <code>bigrand</code> is passed so that block-level
* seeds are generated internally. In case of MR, it generates a single
* block for given block-level seed <code>bSeed</code>.
*
* When pdf="uniform", cell values are drawn from uniform distribution in
* range <code>[min,max]</code>.
*
* When pdf="normal", cell values are drawn from standard normal
* distribution N(0,1). The range of generated values will always be
* (-Inf,+Inf).
*
* @param rows
* @param cols
* @param rowsInBlock
* @param colsInBlock
* @param sparsity
* @param min
* @param max
* @param bigrand
* @param bSeed
* @return
* @throws DMLRuntimeException
*/
public static void generateRandomMatrix( MatrixBlock out, RandomMatrixGenerator rgen, long[] nnzInBlocks,
Well1024a bigrand, long bSeed, int k )
throws DMLRuntimeException
{
int rows = rgen._rows;
int cols = rgen._cols;
int rpb = rgen._rowsPerBlock;
int cpb = rgen._colsPerBlock;
double sparsity = rgen._sparsity;
if (rows == 1) {
generateRandomMatrix(out, rgen, nnzInBlocks, bigrand, bSeed);
return;
}
boolean invokedFromCP = true;
if(bigrand == null && nnzInBlocks!=null)
invokedFromCP = false;
// sanity check valid dimensions and sparsity
checkMatrixDimensionsAndSparsity(rows, cols, sparsity);
/*
* Setup min and max for distributions other than "uniform". Min and Max
* are set up in such a way that the usual logic of
* (max-min)*prng.nextDouble() is still valid. This is done primarily to
* share the same code across different distributions.
*/
double min=0, max=1;
if ( rgen._pdf.equalsIgnoreCase(RAND_PDF_UNIFORM) ) {
min=rgen._min;
max=rgen._max;
}
// Determine the sparsity of output matrix
// if invoked from CP: estimated NNZ is for entire matrix (nnz=0, if 0 initialized)
// if invoked from MR: estimated NNZ is for one block
final long estnnz = (invokedFromCP ? ((min==0.0 && max==0.0)? 0 : (long)(sparsity * rows * cols))
: nnzInBlocks[0]);
boolean lsparse = MatrixBlock.evalSparseFormatInMemory( rows, cols, estnnz );
out.reset(rows, cols, lsparse);
// Special case shortcuts for efficiency
if ( rgen._pdf.equalsIgnoreCase(RAND_PDF_UNIFORM)) {
//specific cases for efficiency
if ( min == 0.0 && max == 0.0 ) { //all zeros
// nothing to do here
out.nonZeros = 0;
return;
}
else if( !out.sparse && sparsity==1.0d && min == max ) //equal values
{
out.init(min, out.rlen, out.clen);
return;
}
}
// Allocate memory
if ( out.sparse ) {
//note: individual sparse rows are allocated on demand,
//for consistency with memory estimates and prevent OOMs.
out.allocateSparseRowsBlock();
}
else{
out.allocateDenseBlock();
}
int nrb = (int) Math.ceil((double)rows/rpb);
int ncb = (int) Math.ceil((double)cols/cpb);
try
{
ExecutorService pool = Executors.newFixedThreadPool(k);
ArrayList<RandTask> tasks = new ArrayList<RandTask>();
int blklen = ((int)(Math.ceil((double)nrb/k)));
for( int i=0; i<k & i*blklen<nrb; i++ ) {
long[] seeds = generateSeedsForCP(bigrand, blklen, ncb);
tasks.add(new RandTask(invokedFromCP, i*blklen, Math.min((i+1)*blklen, nrb),
out, rgen, nnzInBlocks, bSeed, seeds) );
}
pool.invokeAll(tasks);
pool.shutdown();
//early error notify in case not all tasks successful
for(RandTask rt : tasks)
if( !rt.getReturnCode() )
throw new DMLRuntimeException("RandGen task failed: " + rt.getErrMsg());
}
catch (Exception e) {
throw new DMLRuntimeException(e);
}
out.recomputeNonZeros();
}
/**
* Method to generate a sequence according to the given parameters. The
* generated sequence is always in dense format.
*
* Both end points specified <code>from</code> and <code>to</code> must be
* included in the generated sequence i.e., [from,to] both inclusive. Note
* that, <code>to</code> is included only if (to-from) is perfectly
* divisible by <code>incr</code>.
*
* For example, seq(0,1,0.5) generates (0.0 0.5 1.0)
* whereas seq(0,1,0.6) generates (0.0 0.6) but not (0.0 0.6 1.0)
*
* @param from
* @param to
* @param incr
* @return
* @throws DMLRuntimeException
*/
public static void generateSequence(MatrixBlock out, double from, double to, double incr)
throws DMLRuntimeException
{
boolean neg = (from > to);
if (neg != (incr < 0))
throw new DMLRuntimeException("Wrong sign for the increment in a call to seq(): from="+from+", to="+to+ ", incr="+incr);
int rows = 1 + (int)Math.floor((to-from)/incr);
int cols = 1;
out.sparse = false; // sequence matrix is always dense
out.reset(rows, cols, out.sparse);
out.allocateDenseBlock();
//System.out.println(System.nanoTime() + ": MatrixBlockDSM.seq(): seq("+from+","+to+","+incr+") rows = " + rows);
double[] c = out.denseBlock;
c[0] = from;
for(int i=1; i < rows; i++) {
from += incr;
c[i] = from;
}
out.recomputeNonZeros();
//System.out.println(System.nanoTime() + ": end of seq()");
}
/**
* Generates a sample of size <code>size</code> from a range of values [1,range].
* <code>replace</code> defines if sampling is done with or without replacement.
*
* @param ec
* @return
* @throws DMLRuntimeException
*/
public static void generateSample(MatrixBlock out, long range, int size, boolean replace, long seed)
throws DMLRuntimeException
{
//set meta data and allocate dense block
out.reset(size, 1, false);
out.allocateDenseBlock();
seed = (seed == -1 ? System.nanoTime() : seed);
if ( !replace )
{
// reservoir sampling
for(int i=1; i <= size; i++)
out.setValueDenseUnsafe(i-1, 0, i );
Random rand = new Random(seed);
for(int i=size+1; i <= range; i++)
{
if(rand.nextInt(i) < size)
out.setValueDenseUnsafe( rand.nextInt(size), 0, i );
}
// randomize the sample (Algorithm P from Knuth's ACP)
// -- needed especially when the differnce between range and size is small)
double tmp;
int idx;
for(int i=size-1; i >= 1; i--)
{
idx = rand.nextInt(i);
// swap i^th and idx^th entries
tmp = out.getValueDenseUnsafe(idx, 0);
out.setValueDenseUnsafe(idx, 0, out.getValueDenseUnsafe(i, 0));
out.setValueDenseUnsafe(i, 0, tmp);
}
}
else
{
Random r = new Random(seed);
for(int i=0; i < size; i++)
out.setValueDenseUnsafe(i, 0, 1+nextLong(r, range) );
}
out.recomputeNonZeros();
out.examSparsity();
}
/**
*
* @param bigrand
* @param nrb
* @param ncb
* @return
*/
private static long[] generateSeedsForCP(Well1024a bigrand, int nrb, int ncb)
{
int numBlocks = nrb * ncb;
long[] seeds = new long[numBlocks];
for (int l = 0; l < numBlocks; l++ ) {
// case of CP: generate a block-level seed from matrix-level Well1024a seed
seeds[l] = bigrand.nextLong();
}
return seeds;
}
/**
*
* @param invokedFromCP
* @param rl
* @param ru
* @param out
* @param rgen
* @param nnzInBlocks
* @param bSeed
* @param seeds
* @throws DMLRuntimeException
*/
private static void genRandomNumbers(boolean invokedFromCP, int rl, int ru, MatrixBlock out, RandomMatrixGenerator rgen, long[] nnzInBlocks, long bSeed, long[] seeds)
throws DMLRuntimeException
{
int rows = rgen._rows;
int cols = rgen._cols;
int rpb = rgen._rowsPerBlock;
int cpb = rgen._colsPerBlock;
double sparsity = rgen._sparsity;
PRNGenerator valuePRNG = rgen._valuePRNG;
double min=0, max=1;
if ( rgen._pdf.equalsIgnoreCase(RAND_PDF_UNIFORM) ) {
min=rgen._min;
max=rgen._max;
}
double range = max - min;
final int clen = out.clen;
final int estimatedNNzsPerRow = out.estimatedNNzsPerRow;
int nrb = (int) Math.ceil((double)rows/rpb);
int ncb = (int) Math.ceil((double)cols/cpb);
int blockrows, blockcols, rowoffset, coloffset;
int blockID = rl*ncb;
int counter = 0;
// Setup Pseudo Random Number Generator for cell values based on 'pdf'.
if (valuePRNG == null) {
if ( rgen._pdf.equalsIgnoreCase(RAND_PDF_UNIFORM))
valuePRNG = new UniformPRNGenerator();
else if ( rgen._pdf.equalsIgnoreCase(RAND_PDF_NORMAL))
valuePRNG = new NormalPRNGenerator();
else if ( rgen._pdf.equalsIgnoreCase(RAND_PDF_POISSON))
valuePRNG = new PoissonPRNGenerator();
else
throw new DMLRuntimeException("Unsupported distribution function for Rand: " + rgen._pdf);
}
// loop through row-block indices
for(int rbi=rl; rbi < ru; rbi++) {
blockrows = (rbi == nrb-1 ? (rows-rbi*rpb) : rpb);
rowoffset = rbi*rpb;
// loop through column-block indices
for(int cbj=0; cbj < ncb; cbj++, blockID++) {
blockcols = (cbj == ncb-1 ? (cols-cbj*cpb) : cpb);
coloffset = cbj*cpb;
// Generate a block (rbi,cbj)
// select the appropriate block-level seed
long seed = -1;
if ( !invokedFromCP ) {
// case of MR: simply use the passed-in value
seed = bSeed;
}
else {
// case of CP: generate a block-level seed from matrix-level Well1024a seed
seed = seeds[counter++]; //bigrand.nextLong();
}
// Initialize the PRNGenerator for cell values
valuePRNG.setSeed(seed);
// Initialize the PRNGenerator for determining cells that contain a non-zero value
// Note that, "pdf" parameter applies only to cell values and the individual cells
// are always selected uniformly at random.
UniformPRNGenerator nnzPRNG = new UniformPRNGenerator(seed);
// block-level sparsity, which may differ from overall sparsity in the matrix.
// (e.g., border blocks may fall under skinny matrix turn point, in CP this would be
// irrelevant but we need to ensure consistency with MR)
boolean localSparse = MatrixBlock.evalSparseFormatInMemory(blockrows, blockcols, nnzInBlocks[blockID] ); //(long)(sparsity*blockrows*blockcols));
if ( localSparse ) {
SparseRow[] c = out.sparseRows;
int idx = 0; // takes values in range [1, brlen*bclen] (both ends including)
int ridx=0, cidx=0; // idx translates into (ridx, cidx) entry within the block
int skip = -1;
double p = sparsity;
// Prob [k-1 zeros before a nonzero] = Prob [k-1 < log(uniform)/log(1-p) < k] = p*(1-p)^(k-1), where p=sparsity
double log1mp = Math.log(1-p);
long blocksize = blockrows*blockcols;
while(idx < blocksize) {
skip = (int) Math.ceil( Math.log(nnzPRNG.nextDouble())/log1mp )-1;
idx = idx+skip+1;
if ( idx > blocksize)
break;
// translate idx into (r,c) within the block
ridx = (idx-1)/blockcols;
cidx = (idx-1)%blockcols;
double val = min + (range * valuePRNG.nextDouble());
if( c[rowoffset+ridx]==null )
c[rowoffset+ridx]=new SparseRow(estimatedNNzsPerRow, clen);
c[rowoffset+ridx].append(coloffset+cidx, val);
}
}
else {
if (sparsity == 1.0) {
double[] c = out.denseBlock;
for(int ii=0; ii < blockrows; ii++) {
for(int jj=0, index = ((ii+rowoffset)*cols)+coloffset; jj < blockcols; jj++, index++) {
c[index] = min + (range * valuePRNG.nextDouble());
}
}
}
else {
if (out.sparse ) {
/* This case evaluated only when this function is invoked from CP.
* In this case:
* sparse=true -> entire matrix is in sparse format and hence denseBlock=null
* localSparse=false -> local block is dense, and hence on MR side a denseBlock will be allocated
* i.e., we need to generate data in a dense-style but set values in sparseRows
*
*/
// In this case, entire matrix is in sparse format but the current block is dense
SparseRow[] c = out.sparseRows;
for(int ii=0; ii < blockrows; ii++) {
for(int jj=0; jj < blockcols; jj++) {
if(nnzPRNG.nextDouble() <= sparsity) {
double val = min + (range * valuePRNG.nextDouble());
if( c[ii+rowoffset]==null )
c[ii+rowoffset]=new SparseRow(estimatedNNzsPerRow, clen);
c[ii+rowoffset].append(jj+coloffset, val);
}
}
}
}
else {
double[] c = out.denseBlock;
for(int ii=0; ii < blockrows; ii++) {
for(int jj=0, index = ((ii+rowoffset)*cols)+coloffset; jj < blockcols; jj++, index++) {
if(nnzPRNG.nextDouble() <= sparsity) {
c[index] = min + (range * valuePRNG.nextDouble());
}
}
}
}
}
} // sparse or dense
} // cbj
} // rbi
}
/**
*
* @param rows
* @param cols
* @param sp
* @throws DMLRuntimeException
*/
private static void checkMatrixDimensionsAndSparsity(int rows, int cols, double sp)
throws DMLRuntimeException
{
if( rows <= 0 || cols <= 0 || sp < 0 || sp > 1)
throw new DMLRuntimeException("Invalid matrix characteristics: "+rows+"x"+cols+", "+sp);
}
// modified version of java.util.nextInt
private static long nextLong(Random r, long n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
//if ((n & -n) == n) // i.e., n is a power of 2
// return ((n * (long)r.nextLong()) >> 31);
long bits, val;
do {
bits = (r.nextLong() << 1) >>> 1;
val = bits % n;
} while (bits - val + (n-1) < 0L);
return val;
}
/**
*
*
*/
private static class RandTask implements Callable<Object>
{
private boolean _rc = true;
private String _errMsg = null;
private boolean _invokedFromCP = true;
private int _rl = 0;
private int _ru = 0;
private MatrixBlock _out = null;
private RandomMatrixGenerator _rgen = new RandomMatrixGenerator();
private long[] _nnzInBlocks = null;
private long _bSeed = 0;
private long[] _seeds = null;
public RandTask(boolean invokedFromCP, int rl, int ru, MatrixBlock out, RandomMatrixGenerator rgen, long[] nnzInBlocks, long bSeed, long[] seeds) throws DMLRuntimeException
{
_invokedFromCP = invokedFromCP;
_rl = rl;
_ru = ru;
_out = out;
_rgen.init(rgen._pdf, rgen._rows, rgen._cols, rgen._rowsPerBlock, rgen._colsPerBlock, rgen._sparsity, rgen._min, rgen._max, rgen._mean);
_nnzInBlocks = nnzInBlocks;
_bSeed = bSeed;
_seeds = seeds;
}
public boolean getReturnCode() {
return _rc;
}
public String getErrMsg() {
return _errMsg;
}
@Override
public Object call() throws Exception
{
genRandomNumbers(_invokedFromCP, _rl, _ru, _out, _rgen, _nnzInBlocks, _bSeed, _seeds);
return null;
}
}
}
| |
package com.lartek.wagecalculator20;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Statistics extends Activity {
private int statMonth;
private int statYear;
private EditText statDateOutput;
private EditText statHoursOutput;
private EditText statResultOutput;
private RadioButton monthYear;
private RadioButton justYear;
private Button plusButton;
private Button minusButton;
private TextView repDate;
private TextView repHours;
private TextView repRate;
private TextView repResult;
private List<WorkDay> workdays;
private DatabaseHandler db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statistics_layout);
statDateOutput = (EditText) findViewById(R.id.statDate);
statHoursOutput = (EditText) findViewById(R.id.statHoursField);
statResultOutput = (EditText) findViewById(R.id.statResultField);
monthYear = (RadioButton) findViewById(R.id.radio0);
justYear = (RadioButton) findViewById(R.id.radio1);
plusButton = (Button) findViewById(R.id.plusBtn);
minusButton = (Button) findViewById(R.id.minusBtn);
repDate = (TextView) findViewById(R.id.reportDate);
repHours = (TextView) findViewById(R.id.reportHours);
repRate = (TextView) findViewById(R.id.reportRate);
repResult = (TextView) findViewById(R.id.reportResult);
statHoursOutput.setFocusable(false);
statResultOutput.setFocusable(false);
statDateOutput.setFocusable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
final Spinner spinner = (Spinner) findViewById(R.id.monthSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.monthArray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
monthYear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
displayStat();
}
});
justYear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
displayStat();
}
});
statSetCurrentDate();
displayStat();
spinner.setSelection(statMonth);
statDateOutput.setText(String.valueOf(statYear));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
statMonth = spinner.getSelectedItemPosition();
displayStat();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
displayStat();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.statistics, menu);
return true;
}
public void statSetCurrentDate() {
final Calendar cal = Calendar.getInstance();
statYear = cal.get(Calendar.YEAR);
statMonth = cal.get(Calendar.MONTH);
return;
}
private void displayStat(){
repDate.setText("");
repHours.setText("");
repRate.setText("");
repResult.setText("");
List<WorkDay> displayList;
if (monthYear.isChecked()) {
displayList = getListByMonth();
}
else {
displayList = getListByYear();
}
double thisHours = 0;
double thisResult = 0;
for (WorkDay cn : displayList) {
thisHours += cn.hours;
thisResult += cn.result;
makeReportLine(cn);
}
statHoursOutput.setText(String.valueOf(thisHours));
statResultOutput.setText(String.valueOf(thisResult));
return;
}
public void plus(View view) {
statYear += 1;
statDateOutput.setText(String.valueOf(statYear));
displayStat();
return;
}
public void minus(View view) {
statYear -= 1;
statDateOutput.setText(String.valueOf(statYear));
displayStat();
return;
}
public void makeReportLine(WorkDay wd) {
repDate.append(String.valueOf(wd.day) + "/" + String.valueOf(wd.month + 1) + "/" + String.valueOf(wd.year) + "\n");
repHours.append(String.valueOf(wd.hours) + "\n");
repRate.append(String.valueOf(wd.rate) + "\n");
repResult.append(String.valueOf(wd.result) + "\n");
}
public List<WorkDay> getListByMonth() {
List<WorkDay> byMonth = new LinkedList<WorkDay>();
db = new DatabaseHandler(this);
List<WorkDay> workdays = db.getAllWorkDays();
for (WorkDay cn : workdays) {
if (cn.month == statMonth && cn.year == statYear) {
byMonth.add(cn);
}
}
Collections.sort(byMonth);
return byMonth;
}
public List<WorkDay> getListByYear() {
List<WorkDay> byYear = new LinkedList<WorkDay>();
db = new DatabaseHandler(this);
List<WorkDay> workdays = db.getAllWorkDays();
for (WorkDay cn : workdays) {
if (cn.year == statYear) {
byYear.add(cn);
}
}
Collections.sort(byYear);
return byYear;
}
public void gotToDeleteScreen(View view) {
Intent intent = new Intent(this, Delete.class);
startActivity(intent);
return;
}
public void gotToFromTo (View view) {
Intent intent = new Intent(this, FromTo.class);
startActivity(intent);
return;
}
}
| |
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver14;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import org.jboss.netty.buffer.ChannelBuffer;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFOxmIpv6NdSllVer14 implements OFOxmIpv6NdSll {
private static final Logger logger = LoggerFactory.getLogger(OFOxmIpv6NdSllVer14.class);
// version: 1.4
final static byte WIRE_VERSION = 5;
final static int LENGTH = 10;
private final static MacAddress DEFAULT_VALUE = MacAddress.NONE;
// OF message fields
private final MacAddress value;
//
// Immutable default instance
final static OFOxmIpv6NdSllVer14 DEFAULT = new OFOxmIpv6NdSllVer14(
DEFAULT_VALUE
);
// package private constructor - used by readers, builders, and factory
OFOxmIpv6NdSllVer14(MacAddress value) {
if(value == null) {
throw new NullPointerException("OFOxmIpv6NdSllVer14: property value cannot be null");
}
this.value = value;
}
// Accessors for OF message fields
@Override
public long getTypeLen() {
return 0x80004006L;
}
@Override
public MacAddress getValue() {
return value;
}
@Override
public MatchField<MacAddress> getMatchField() {
return MatchField.IPV6_ND_SLL;
}
@Override
public boolean isMasked() {
return false;
}
public OFOxm<MacAddress> getCanonical() {
// exact match OXM is always canonical
return this;
}
@Override
public MacAddress getMask()throws UnsupportedOperationException {
throw new UnsupportedOperationException("Property mask not supported in version 1.4");
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
public OFOxmIpv6NdSll.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFOxmIpv6NdSll.Builder {
final OFOxmIpv6NdSllVer14 parentMessage;
// OF message fields
private boolean valueSet;
private MacAddress value;
BuilderWithParent(OFOxmIpv6NdSllVer14 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public long getTypeLen() {
return 0x80004006L;
}
@Override
public MacAddress getValue() {
return value;
}
@Override
public OFOxmIpv6NdSll.Builder setValue(MacAddress value) {
this.value = value;
this.valueSet = true;
return this;
}
@Override
public MatchField<MacAddress> getMatchField() {
return MatchField.IPV6_ND_SLL;
}
@Override
public boolean isMasked() {
return false;
}
@Override
public OFOxm<MacAddress> getCanonical()throws UnsupportedOperationException {
throw new UnsupportedOperationException("Property canonical not supported in version 1.4");
}
@Override
public MacAddress getMask()throws UnsupportedOperationException {
throw new UnsupportedOperationException("Property mask not supported in version 1.4");
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
@Override
public OFOxmIpv6NdSll build() {
MacAddress value = this.valueSet ? this.value : parentMessage.value;
if(value == null)
throw new NullPointerException("Property value must not be null");
//
return new OFOxmIpv6NdSllVer14(
value
);
}
}
static class Builder implements OFOxmIpv6NdSll.Builder {
// OF message fields
private boolean valueSet;
private MacAddress value;
@Override
public long getTypeLen() {
return 0x80004006L;
}
@Override
public MacAddress getValue() {
return value;
}
@Override
public OFOxmIpv6NdSll.Builder setValue(MacAddress value) {
this.value = value;
this.valueSet = true;
return this;
}
@Override
public MatchField<MacAddress> getMatchField() {
return MatchField.IPV6_ND_SLL;
}
@Override
public boolean isMasked() {
return false;
}
@Override
public OFOxm<MacAddress> getCanonical()throws UnsupportedOperationException {
throw new UnsupportedOperationException("Property canonical not supported in version 1.4");
}
@Override
public MacAddress getMask()throws UnsupportedOperationException {
throw new UnsupportedOperationException("Property mask not supported in version 1.4");
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
//
@Override
public OFOxmIpv6NdSll build() {
MacAddress value = this.valueSet ? this.value : DEFAULT_VALUE;
if(value == null)
throw new NullPointerException("Property value must not be null");
return new OFOxmIpv6NdSllVer14(
value
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFOxmIpv6NdSll> {
@Override
public OFOxmIpv6NdSll readFrom(ChannelBuffer bb) throws OFParseError {
// fixed value property typeLen == 0x80004006L
int typeLen = bb.readInt();
if(typeLen != (int) 0x80004006)
throw new OFParseError("Wrong typeLen: Expected=0x80004006L(0x80004006L), got="+typeLen);
MacAddress value = MacAddress.read6Bytes(bb);
OFOxmIpv6NdSllVer14 oxmIpv6NdSllVer14 = new OFOxmIpv6NdSllVer14(
value
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", oxmIpv6NdSllVer14);
return oxmIpv6NdSllVer14;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFOxmIpv6NdSllVer14Funnel FUNNEL = new OFOxmIpv6NdSllVer14Funnel();
static class OFOxmIpv6NdSllVer14Funnel implements Funnel<OFOxmIpv6NdSllVer14> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFOxmIpv6NdSllVer14 message, PrimitiveSink sink) {
// fixed value property typeLen = 0x80004006L
sink.putInt((int) 0x80004006);
message.value.putTo(sink);
}
}
public void writeTo(ChannelBuffer bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFOxmIpv6NdSllVer14> {
@Override
public void write(ChannelBuffer bb, OFOxmIpv6NdSllVer14 message) {
// fixed value property typeLen = 0x80004006L
bb.writeInt((int) 0x80004006);
message.value.write6Bytes(bb);
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFOxmIpv6NdSllVer14(");
b.append("value=").append(value);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFOxmIpv6NdSllVer14 other = (OFOxmIpv6NdSllVer14) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
}
| |
/**
*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "[]"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright 2016 Alibaba Group
*
* 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.taobao.weex.http;
import android.os.Looper;
import android.telecom.Call;
import com.taobao.weex.WXSDKInstanceTest;
import com.taobao.weex.adapter.DefaultWXHttpAdapter;
import com.taobao.weex.adapter.IWXHttpAdapter;
import com.taobao.weex.bridge.JSCallback;
import com.taobao.weex.bridge.WXBridgeManager;
import com.taobao.weex.common.WXRequest;
import com.taobao.weex.common.WXResponse;
import com.taobao.weex.common.WXThread;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.robolectric.RobolectricTestRunner;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.mockito.Mockito.*;
import static junit.framework.Assert.*;
/**
* Created by sospartan on 5/24/16.
*/
@RunWith(RobolectricTestRunner.class)
@PrepareForTest({WXStreamModule.class, IWXHttpAdapter.class})
public class WXStreamModuleTest {
@Before
public void setup() throws Exception{
}
private WXResponse successResponse(){
WXResponse resp = new WXResponse();
resp.data = "data";
resp.statusCode = "200";
return resp;
}
static class Callback implements JSCallback{
Map<String, Object> mData;
@Override
public void invoke(Object data) {
mData = (Map<String,Object>)data;
}
@Override
public void invokeAndKeepAlive(Object data) {
mData = (Map<String,Object>)data;
}
}
@Test
public void testFetchInvaildOptions() throws Exception{
IWXHttpAdapter adapter = new IWXHttpAdapter() {
@Override
public void sendRequest(WXRequest request, OnHttpListener listener) {
listener.onHttpFinish(successResponse());
}
};
WXStreamModule streamModule = new WXStreamModule(adapter);
Callback cb = new Callback();
streamModule.fetch("",cb,null);
assert !(boolean)cb.mData.get("ok");
}
private WXStreamModule createModule(IWXHttpAdapter adapter){
WXStreamModule m = new WXStreamModule(adapter);
m.mWXSDKInstance = WXSDKInstanceTest.createInstance();
return m;
}
@Test
public void testFetchSuccessFinish() throws Exception{
IWXHttpAdapter adapter = new IWXHttpAdapter() {
@Override
public void sendRequest(WXRequest request, OnHttpListener listener) {
listener.onHttpFinish(successResponse());
}
};
WXStreamModule streamModule = createModule(adapter);
Callback cb = new Callback();
streamModule.fetch("{'url':'http://www.taobao.com'}",cb,null);
assert (boolean)cb.mData.get("ok");
}
@Test
public void testFetchHeaderReceived() throws Exception{
IWXHttpAdapter adapter = new IWXHttpAdapter() {
@Override
public void sendRequest(WXRequest request, OnHttpListener listener) {
Map<String,List<String>> headers = new HashMap<>();
headers.put("key", Arrays.asList("someval"));
listener.onHeadersReceived(200,headers);
}
};
WXStreamModule streamModule = createModule(adapter);
Callback cb = new Callback();
streamModule.fetch("{'url':'http://www.taobao.com'}",null,cb);
assert ((Map<String,String>)cb.mData.get("headers")).get("key").equals("someval");
}
@Test
public void testFetchRequestHttpbinCallback() throws Exception{
WXStreamModule streamModule = createModule(new DefaultWXHttpAdapter());
JSCallback progress = mock(JSCallback.class);
JSCallback finish = mock(JSCallback.class);
System.out.print("request start "+System.currentTimeMillis());
streamModule.fetch("{method: 'POST',url: 'http://httpbin.org/post',type:'json'}",finish,progress);
verify(progress,timeout(10*1000).atLeastOnce()).invokeAndKeepAlive(anyMapOf(String.class, Object.class));
verify(finish,timeout(10*1000).times(1)).invoke(anyMapOf(String.class, Object.class));
System.out.print("\nrequest finish"+System.currentTimeMillis());
}
@Test
public void testFetchStatus() throws Exception{
WXStreamModule streamModule = createModule(new IWXHttpAdapter() {
@Override
public void sendRequest(WXRequest request, OnHttpListener listener) {
WXResponse response = new WXResponse();
response.statusCode = "-1";
listener.onHttpFinish(response);
}
});
Callback finish = new Callback();
streamModule.fetch("",finish,null);
assertEquals(finish.mData.get(WXStreamModule.STATUS_TEXT),Status.ERR_INVALID_REQUEST);
streamModule.fetch("{method: 'POST',url: 'http://httpbin.org/post',type:'json'}",finish,null);
assertEquals(finish.mData.get(WXStreamModule.STATUS_TEXT),Status.ERR_CONNECT_FAILED);
streamModule = createModule(new IWXHttpAdapter() {
@Override
public void sendRequest(WXRequest request, OnHttpListener listener) {
WXResponse response = new WXResponse();
response.statusCode = "302";
listener.onHttpFinish(response);
}
});
streamModule.fetch("{method: 'POST',url: 'http://httpbin.org/post',type:'json'}",finish,null);
assertEquals(finish.mData.get(WXStreamModule.STATUS_TEXT),Status.getStatusText("302"));
}
}
| |
/* Copyright (c) 2013 OpenPlans. All rights reserved.
* This code is licensed under the BSD New License, available at the root
* application directory.
*/
package org.geogit.remote;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import javax.annotation.Nullable;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.geogit.api.ObjectId;
import org.geogit.api.Ref;
import org.geogit.api.RevObject;
import org.geogit.api.SymRef;
import org.geogit.repository.Repository;
import org.geogit.storage.datastream.ObjectReader;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.io.Closeables;
/**
* Utility functions for performing common communications and operations with http remotes.
*/
class HttpUtils {
/**
* Parse the provided ref string to a {@link Ref}. The input string should be in the following
* format:
* <p>
* 'NAME HASH' for a normal ref. e.g. 'refs/heads/master abcd1234ef567890dcba'
* <p>
* 'NAME TARGET HASH' for a symbolic ref. e.g. 'HEAD refs/heads/master abcd1234ef567890dcba'
*
* @param refString the string to parse
* @return the parsed ref
*/
public static Ref parseRef(String refString) {
Ref ref = null;
String[] tokens = refString.split(" ");
if (tokens.length == 2) {
// normal ref
// NAME HASH
String name = tokens[0];
ObjectId objectId = ObjectId.valueOf(tokens[1]);
ref = new Ref(name, objectId);
} else {
// symbolic ref
// NAME TARGET HASH
String name = tokens[0];
String targetRef = tokens[1];
ObjectId targetObjectId = ObjectId.valueOf(tokens[2]);
Ref target = new Ref(targetRef, targetObjectId);
ref = new SymRef(name, target);
}
return ref;
}
/**
* Consumes the error stream of the provided connection and then closes it.
*
* @param connection the connection to close
*/
public static void consumeErrStreamAndCloseConnection(@Nullable HttpURLConnection connection) {
if (connection == null) {
return;
}
try {
InputStream es = ((HttpURLConnection) connection).getErrorStream();
consumeAndCloseStream(es);
} catch (IOException ex) {
throw Throwables.propagate(ex);
} finally {
connection.disconnect();
}
}
/**
* Consumes the provided input stream and then closes it.
*
* @param stream the stream to consume and close
* @throws IOException
*/
public static void consumeAndCloseStream(InputStream stream) throws IOException {
if (stream != null) {
try {
// read the response body
while (stream.read() > -1) {
; // $codepro.audit.disable extraSemicolon
}
} finally {
// close the errorstream
Closeables.closeQuietly(stream);
}
}
}
/**
* Reads from the provided XML stream until an element with a name that matches the provided
* name is found.
*
* @param reader the XML stream
* @param name the element name to search for
* @throws XMLStreamException
*/
public static void readToElementStart(XMLStreamReader reader, String name)
throws XMLStreamException {
while (reader.hasNext()) {
if (reader.isStartElement() && reader.getLocalName().equals(name)) {
break;
}
reader.next();
}
}
/**
* Retrieves a {@link RevObject} from the remote repository.
*
* @param repositoryURL the URL of the repository
* @param localRepository the repository to save the object to, if {@code null}, the object will
* not be saved
* @param objectId the id of the object to retrieve
* @return the retrieved object, or {@link Optional#absent()} if the object was not found
*/
public static Optional<RevObject> getNetworkObject(URL repositoryURL,
@Nullable Repository localRepository, ObjectId objectId) {
HttpURLConnection connection = null;
Optional<RevObject> object = Optional.absent();
try {
String expanded = repositoryURL.toString() + "/repo/objects/" + objectId.toString();
connection = (HttpURLConnection) new URL(expanded).openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.connect();
// Get Response
InputStream is = connection.getInputStream();
try {
ObjectReader reader = new ObjectReader();
RevObject revObject = reader.read(objectId, is);
if (localRepository != null) {
localRepository.objectDatabase().put(revObject);
}
object = Optional.of(revObject);
} finally {
consumeAndCloseStream(is);
}
} catch (Exception e) {
Throwables.propagate(e);
} finally {
consumeErrStreamAndCloseConnection(connection);
}
return object;
}
/**
* Determines whether or not an object with the given {@link ObjectId} exists in the remote
* repository.
*
* @param repositoryURL the URL of the repository
* @param objectId the id to check for
* @return true if the object existed, false otherwise
*/
public static boolean networkObjectExists(URL repositoryURL, ObjectId objectId) {
HttpURLConnection connection = null;
boolean exists = false;
try {
String internalIp = InetAddress.getLocalHost().getHostName();
String expanded = repositoryURL.toString() + "/repo/exists?oid=" + objectId.toString()
+ "&internalIp=" + internalIp;
connection = (HttpURLConnection) new URL(expanded).openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.connect();
// Get Response
InputStream is = connection.getInputStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line = rd.readLine();
Preconditions.checkNotNull(line, "networkObjectExists returned no dat for %s",
expanded);
exists = line.length() > 0 && line.charAt(0) == '1';
} finally {
consumeAndCloseStream(is);
}
} catch (Exception e) {
Throwables.propagate(e);
} finally {
consumeErrStreamAndCloseConnection(connection);
}
return exists;
}
/**
* Updates the ref on the remote repository that matches the provided refspec to the new value.
*
* @param repositoryURL the URL of the repository
* @param refspec the refspec of the ref to update
* @param newValue the new value for the ref
* @param delete if true, the ref will be deleted
* @return the updated ref
*/
public static Ref updateRemoteRef(URL repositoryURL, String refspec, ObjectId newValue,
boolean delete) {
HttpURLConnection connection = null;
Ref updatedRef = null;
try {
String expanded;
if (!delete) {
expanded = repositoryURL.toString() + "/updateref?name=" + refspec + "&newValue="
+ newValue.toString();
} else {
expanded = repositoryURL.toString() + "/updateref?name=" + refspec + "&delete=true";
}
connection = (HttpURLConnection) new URL(expanded).openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.connect();
InputStream inputStream = connection.getInputStream();
XMLStreamReader reader = XMLInputFactory.newFactory()
.createXMLStreamReader(inputStream);
try {
readToElementStart(reader, "ChangedRef");
readToElementStart(reader, "name");
final String refName = reader.getElementText();
readToElementStart(reader, "objectId");
final String objectId = reader.getElementText();
readToElementStart(reader, "target");
String target = null;
if (reader.hasNext()) {
target = reader.getElementText();
}
reader.close();
if (target != null) {
updatedRef = new SymRef(refName, new Ref(target, ObjectId.valueOf(objectId)));
} else {
updatedRef = new Ref(refName, ObjectId.valueOf(objectId));
}
} finally {
reader.close();
inputStream.close();
}
} catch (Exception e) {
Throwables.propagate(e);
} finally {
consumeErrStreamAndCloseConnection(connection);
}
return updatedRef;
}
/**
* Gets the depth of the repository or commit if provided.
*
* @param repositoryURL the URL of the repository
* @param commit the commit whose depth should be determined, if null, the repository depth will
* be returned
* @return the depth of the repository or commit, or {@link Optional#absent()} if the repository
* is not shallow or the commit was not found
*/
public static Optional<Integer> getDepth(URL repositoryURL, @Nullable String commit) {
HttpURLConnection connection = null;
Optional<String> commitId = Optional.fromNullable(commit);
Optional<Integer> depth = Optional.absent();
try {
String expanded;
if (commitId.isPresent()) {
expanded = repositoryURL.toString() + "/repo/getdepth?commitId=" + commitId.get();
} else {
expanded = repositoryURL.toString() + "/repo/getdepth";
}
connection = (HttpURLConnection) new URL(expanded).openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.connect();
// Get Response
InputStream is = connection.getInputStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line = rd.readLine();
if (line != null) {
depth = Optional.of(Integer.parseInt(line));
}
} finally {
consumeAndCloseStream(is);
}
} catch (Exception e) {
Throwables.propagate(e);
} finally {
consumeErrStreamAndCloseConnection(connection);
}
return depth;
}
/**
* Gets the parents of the specified commit from the remote repository.
*
* @param repositoryURL the URL of the repository
* @param commit the id of the commit whose parents to retrieve
* @return a list of parent ids for the commit
*/
public static ImmutableList<ObjectId> getParents(URL repositoryURL, ObjectId commit) {
HttpURLConnection connection = null;
Builder<ObjectId> listBuilder = new ImmutableList.Builder<ObjectId>();
try {
String expanded = repositoryURL.toString() + "/repo/getparents?commitId="
+ commit.toString();
connection = (HttpURLConnection) new URL(expanded).openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.connect();
// Get Response
InputStream is = connection.getInputStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line = rd.readLine();
while (line != null) {
listBuilder.add(ObjectId.valueOf(line));
line = rd.readLine();
}
} finally {
consumeAndCloseStream(is);
}
} catch (Exception e) {
Throwables.propagate(e);
} finally {
consumeErrStreamAndCloseConnection(connection);
}
return listBuilder.build();
}
/**
* Retrieves the remote ref that matches the provided refspec.
*
* @param repositoryURL the URL of the repository
* @param refspec the refspec to search for
* @return the remote ref, or {@link Optional#absent()} if it wasn't found
*/
public static Optional<Ref> getRemoteRef(URL repositoryURL, String refspec) {
HttpURLConnection connection = null;
Optional<Ref> remoteRef = Optional.absent();
try {
String expanded = repositoryURL.toString() + "/refparse?name=" + refspec;
connection = (HttpURLConnection) new URL(expanded).openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.connect();
InputStream inputStream = connection.getInputStream();
XMLStreamReader reader = XMLInputFactory.newFactory()
.createXMLStreamReader(inputStream);
try {
HttpUtils.readToElementStart(reader, "Ref");
if (reader.hasNext()) {
HttpUtils.readToElementStart(reader, "name");
final String refName = reader.getElementText();
HttpUtils.readToElementStart(reader, "objectId");
final String objectId = reader.getElementText();
HttpUtils.readToElementStart(reader, "target");
String target = null;
if (reader.hasNext()) {
target = reader.getElementText();
}
reader.close();
if (target != null) {
remoteRef = Optional.of((Ref) new SymRef(refName, new Ref(target, ObjectId
.valueOf(objectId))));
} else {
remoteRef = Optional.of(new Ref(refName, ObjectId.valueOf(objectId)));
}
}
} finally {
reader.close();
inputStream.close();
}
} catch (Exception e) {
Throwables.propagate(e);
} finally {
HttpUtils.consumeErrStreamAndCloseConnection(connection);
}
return remoteRef;
}
/**
* Retrieves a list of features that were modified or deleted by a particular commit.
*
* @param repositoryURL the URL of the repository
* @param commit the id of the commit to check
* @return a list of features affected by the commit
*/
public static ImmutableList<ObjectId> getAffectedFeatures(URL repositoryURL, ObjectId commit) {
HttpURLConnection connection = null;
Builder<ObjectId> listBuilder = new ImmutableList.Builder<ObjectId>();
try {
String expanded = repositoryURL.toString() + "/repo/affectedfeatures?commitId="
+ commit.toString();
connection = (HttpURLConnection) new URL(expanded).openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.connect();
// Get Response
InputStream is = connection.getInputStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line = rd.readLine();
while (line != null) {
listBuilder.add(ObjectId.valueOf(line));
line = rd.readLine();
}
} finally {
consumeAndCloseStream(is);
}
} catch (Exception e) {
Throwables.propagate(e);
} finally {
consumeErrStreamAndCloseConnection(connection);
}
return listBuilder.build();
}
/**
* Begins a push operation to the target repository.
*
* @param repositoryURL the URL of the repository
*/
public static void beginPush(URL repositoryURL) {
HttpURLConnection connection = null;
try {
String internalIp = InetAddress.getLocalHost().getHostName();
String expanded = repositoryURL.toString() + "/repo/beginpush?internalIp=" + internalIp;
connection = (HttpURLConnection) new URL(expanded).openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.connect();
InputStream stream = connection.getInputStream();
HttpUtils.consumeAndCloseStream(stream);
} catch (Exception e) {
Throwables.propagate(e);
} finally {
HttpUtils.consumeErrStreamAndCloseConnection(connection);
}
}
/**
* Finalizes a push operation to the target repository. If the ref that we are pushing to was
* changed during push, the remote ref will not be updated.
*
* @param repositoryURL the URL of the repository
* @param refspec the refspec we are pushing to
* @param newCommitId the new value of the ref
* @param originalRefValue the value of the ref when we started pushing
*/
public static void endPush(URL repositoryURL, String refspec, ObjectId newCommitId,
String originalRefValue) {
HttpURLConnection connection = null;
try {
String internalIp = InetAddress.getLocalHost().getHostName();
String expanded = repositoryURL.toString() + "/repo/endpush?refspec=" + refspec
+ "&objectId=" + newCommitId.toString() + "&internalIp=" + internalIp
+ "&originalRefValue=" + originalRefValue;
connection = (HttpURLConnection) new URL(expanded).openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.connect();
connection.getInputStream();
// TODO: throw an exception if the remote ref was not updated.
} catch (Exception e) {
Throwables.propagate(e);
} finally {
HttpUtils.consumeErrStreamAndCloseConnection(connection);
}
}
}
| |
/*
* 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.
*/
/*
* Created by IntelliJ IDEA.
* User: spleaner
* Date: Aug 8, 2007
* Time: 2:20:33 PM
*/
package com.intellij.xml.refactoring;
import com.intellij.codeInsight.daemon.impl.quickfix.EmptyExpression;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.codeInsight.template.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.xml.XmlChildRole;
import com.intellij.psi.xml.XmlTag;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.util.PairProcessor;
import com.intellij.util.containers.Stack;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class XmlTagInplaceRenamer {
@NonNls private static final String PRIMARY_VARIABLE_NAME = "PrimaryVariable";
@NonNls private static final String OTHER_VARIABLE_NAME = "OtherVariable";
private final Editor myEditor;
private final static Stack<XmlTagInplaceRenamer> ourRenamersStack = new Stack<XmlTagInplaceRenamer>();
private ArrayList<RangeHighlighter> myHighlighters;
private XmlTagInplaceRenamer(@NotNull final Editor editor) {
myEditor = editor;
}
public static void rename(final Editor editor, @NotNull final XmlTag tag) {
if (!ourRenamersStack.isEmpty()) {
ourRenamersStack.peek().finish();
}
final XmlTagInplaceRenamer renamer = new XmlTagInplaceRenamer(editor);
ourRenamersStack.push(renamer);
renamer.rename(tag);
}
private void rename(@NotNull final XmlTag tag) {
final Pair<ASTNode, ASTNode> pair = getNamePair(tag);
if (pair == null) return;
final Project project = myEditor.getProject();
if (project != null) {
final List<TextRange> highlightRanges = new ArrayList<TextRange>();
highlightRanges.add(pair.first.getTextRange());
if (pair.second != null) {
highlightRanges.add(pair.second.getTextRange());
}
if (!CommonRefactoringUtil.checkReadOnlyStatus(project, tag)) {
return;
}
myHighlighters = new ArrayList<RangeHighlighter>();
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
final int offset = myEditor.getCaretModel().getOffset();
myEditor.getCaretModel().moveToOffset(tag.getTextOffset());
final Template t = buildTemplate(tag, pair);
TemplateManager.getInstance(project).startTemplate(myEditor, t, new TemplateEditingAdapter() {
@Override
public void templateFinished(final Template template, boolean brokenOff) {
finish();
}
@Override
public void templateCancelled(final Template template) {
finish();
}
}, new PairProcessor<String, String>() {
@Override
public boolean process(final String variableName, final String value) {
return value.length() == 0 || value.charAt(value.length() - 1) != ' ';
}
});
// restore old offset
myEditor.getCaretModel().moveToOffset(offset);
addHighlights(highlightRanges, myEditor, myHighlighters);
}
});
}
}, RefactoringBundle.message("rename.title"), null);
}
}
private void finish() {
ourRenamersStack.pop();
if (myHighlighters != null) {
Project project = myEditor.getProject();
if (project != null && !project.isDisposed()) {
final HighlightManager highlightManager = HighlightManager.getInstance(project);
for (final RangeHighlighter highlighter : myHighlighters) {
highlightManager.removeSegmentHighlighter(myEditor, highlighter);
}
}
}
}
private Pair<ASTNode, ASTNode> getNamePair(@NotNull final XmlTag tag) {
final int offset = myEditor.getCaretModel().getOffset();
final ASTNode node = tag.getNode();
assert node != null;
final ASTNode startTagName = XmlChildRole.START_TAG_NAME_FINDER.findChild(node);
if (startTagName == null) return null;
final ASTNode endTagName = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(node);
final ASTNode selected = (endTagName == null ||
startTagName.getTextRange().contains(offset) ||
startTagName.getTextRange().contains(offset - 1))
? startTagName
: endTagName;
final ASTNode other = (selected == startTagName) ? endTagName : startTagName;
return Pair.create(selected, other);
}
private static Template buildTemplate(@NotNull final XmlTag tag, @NotNull final Pair<ASTNode, ASTNode> pair) {
final TemplateBuilderImpl builder = new TemplateBuilderImpl(tag);
final ASTNode selected = pair.first;
final ASTNode other = pair.second;
builder.replaceElement(selected.getPsi(), PRIMARY_VARIABLE_NAME, new EmptyExpression() {
@Override
public Result calculateQuickResult(final ExpressionContext context) {
return new TextResult(selected.getText());
}
@Override
public Result calculateResult(final ExpressionContext context) {
return new TextResult(selected.getText());
}
}, true);
if (other != null) {
builder.replaceElement(other.getPsi(), OTHER_VARIABLE_NAME, PRIMARY_VARIABLE_NAME, false);
}
return builder.buildInlineTemplate();
}
private static void addHighlights(List<TextRange> ranges, Editor editor, ArrayList<RangeHighlighter> highlighters) {
EditorColorsManager colorsManager = EditorColorsManager.getInstance();
final TextAttributes attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES);
final HighlightManager highlightManager = HighlightManager.getInstance(editor.getProject());
for (final TextRange range : ranges) {
highlightManager.addOccurrenceHighlight(editor, range.getStartOffset(), range.getEndOffset(), attributes, 0, highlighters, null);
}
for (RangeHighlighter highlighter : highlighters) {
highlighter.setGreedyToLeft(true);
highlighter.setGreedyToRight(true);
}
}
}
| |
package net.scapeemulator.game.model.player;
import static net.scapeemulator.game.model.player.skills.prayer.Prayer.HEAL;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import java.util.ArrayList;
import java.util.List;
import net.scapeemulator.game.GameServer;
import net.scapeemulator.game.model.Position;
import net.scapeemulator.game.model.World;
import net.scapeemulator.game.model.definition.NPCDefinitions;
import net.scapeemulator.game.model.grounditem.GroundItemList;
import net.scapeemulator.game.model.grounditem.GroundItemList.Type;
import net.scapeemulator.game.model.grounditem.GroundItemSynchronizer;
import net.scapeemulator.game.model.mob.Animation;
import net.scapeemulator.game.model.mob.Mob;
import net.scapeemulator.game.model.mob.combat.AttackType;
import net.scapeemulator.game.model.npc.NPC;
import net.scapeemulator.game.model.object.GroundObjectSynchronizer;
import net.scapeemulator.game.model.player.PlayerVariables.Variable;
import net.scapeemulator.game.model.player.action.PlayerDeathAction;
import net.scapeemulator.game.model.player.appearance.Appearance;
import net.scapeemulator.game.model.player.bank.BankSession;
import net.scapeemulator.game.model.player.bank.BankSettings;
import net.scapeemulator.game.model.player.interfaces.AccessSet;
import net.scapeemulator.game.model.player.interfaces.InterfaceSet;
import net.scapeemulator.game.model.player.inventory.Inventory;
import net.scapeemulator.game.model.player.skills.Skill;
import net.scapeemulator.game.model.player.skills.SkillAppearanceListener;
import net.scapeemulator.game.model.player.skills.SkillMessageListener;
import net.scapeemulator.game.model.player.skills.SkillSet;
import net.scapeemulator.game.model.player.skills.construction.House;
import net.scapeemulator.game.model.player.skills.firemaking.Firemaking;
import net.scapeemulator.game.model.player.skills.fishing.FishingTool;
import net.scapeemulator.game.model.player.skills.magic.Rune;
import net.scapeemulator.game.model.player.skills.magic.Spellbook;
import net.scapeemulator.game.model.player.skills.mining.Pickaxe;
import net.scapeemulator.game.model.player.skills.prayer.Prayers;
import net.scapeemulator.game.model.player.skills.ranged.Arrow;
import net.scapeemulator.game.model.player.skills.ranged.Bow;
import net.scapeemulator.game.model.player.skills.woodcutting.Hatchet;
import net.scapeemulator.game.model.player.trade.TradeSession;
import net.scapeemulator.game.msg.Message;
import net.scapeemulator.game.msg.impl.ChatMessage;
import net.scapeemulator.game.msg.impl.EnergyMessage;
import net.scapeemulator.game.msg.impl.LogoutMessage;
import net.scapeemulator.game.msg.impl.PlayerMenuOptionMessage;
import net.scapeemulator.game.msg.impl.ServerMessage;
import net.scapeemulator.game.msg.impl.inter.InterfaceTextMessage;
import net.scapeemulator.game.net.game.GameSession;
import net.scapeemulator.game.util.StringUtils;
import net.scapeemulator.util.Base37Utils;
public final class Player extends Mob {
private static final Position[] HOME_LOCATIONS = { new Position(3222, 3222) };
private static int appearanceTicketCounter = 0;
private static Animation DEATH_ANIMATION = new Animation(7185, 50);
private static int nextAppearanceTicket() {
if (++appearanceTicketCounter == 0) {
appearanceTicketCounter = 1;
}
return appearanceTicketCounter;
}
private int databaseId;
private String username;
private String displayName;
private long longUsername;
private String password;
private int rights = 0;
private GameSession session;
private boolean regionChanging;
private boolean updateModelLists;
private boolean blockActions;
private Position lastKnownRegion;
private final List<Player> localPlayers = new ArrayList<>();
private final List<NPC> localNpcs = new ArrayList<>();
private Appearance appearance = new Appearance(this);
private int energy = 100;
private Player wantToTrade;
private TradeSession tradeSession;
private final House house = new House(this);
private House inHouse;
private final SkillSet skillSet = new SkillSet();
private BankSession bankSession;
private final BankSettings bankSettings = new BankSettings();
private final InventorySet inventorySet = new InventorySet(this);
private ChatMessage chatMessage;
private RegionPalette constructedRegion;
private SceneRebuiltListener sceneRebuiltListener;
private final PlayerTimers timers = new PlayerTimers();
private final Friends friends = new Friends(this);
private final Prayers prayers = new Prayers(this);
private final ScriptInput scriptInput = new ScriptInput(this);
private final PlayerSettings settings = new PlayerSettings(this);
private final PlayerVariables variables = new PlayerVariables();
private final InterfaceSet interfaceSet = new InterfaceSet(this);
private final GrandExchangeHandler grandExchangeHandler = new GrandExchangeHandler(this);
private final ShopHandler shopHandler = new ShopHandler(this);
private final StateSet stateSet = new StateSet(this);
private Spellbook spellbook = Spellbook.NORMAL_SPELLBOOK;
private final AccessSet accessSet = new AccessSet(this);
private final EquipmentBonuses equipmentBonuses = new EquipmentBonuses();
private final GroundItemList groundItems = new GroundItemList(Type.LOCAL);
private final GroundItemSynchronizer groundItemSync = new GroundItemSynchronizer(this);
private final GroundObjectSynchronizer groundObjSync = new GroundObjectSynchronizer(this);
private int[] appearanceTickets = new int[World.MAX_PLAYERS];
private int appearanceTicket = nextAppearanceTicket();
private final PlayerOption[] options = new PlayerOption[10];
private int pnpc = -1;
// TODO remove
private Position min;
private Position max;
public Player() {
init();
}
public boolean actionsBlocked() {
return blockActions || !alive();
}
private String addPlus(int bonus) {
return bonus > 0 ? "+" + bonus : "" + bonus;
}
public void appearanceUpdated() {
appearanceTicket = nextAppearanceTicket();
}
public void calculateEquipmentBonuses() {
for (AttackType type : AttackType.values()) {
if (type == AttackType.AIR || type == AttackType.WATER || type == AttackType.EARTH || type == AttackType.FIRE || type == AttackType.DRAGONFIRE) {
continue;
}
int typeAttackBonus = 0;
int typeDefenceBonus = 0;
for (Item equipped : getEquipment().toArray()) {
if (equipped == null) {
continue;
}
typeAttackBonus += equipped.getEquipmentDefinition().getBonuses().getAttackBonus(type);
typeDefenceBonus += equipped.getEquipmentDefinition().getBonuses().getDefenceBonus(type);
}
equipmentBonuses.setAttackBonus(type, typeAttackBonus);
equipmentBonuses.setDefenceBonus(type, typeDefenceBonus);
}
int prayerBonus = 0;
int strengthBonus = 0;
for (Item equipped : getEquipment().toArray()) {
if (equipped == null) {
continue;
}
prayerBonus += equipped.getEquipmentDefinition().getBonuses().getPrayerBonus();
strengthBonus += equipped.getEquipmentDefinition().getBonuses().getStrengthBonus();
}
equipmentBonuses.setPrayerBonus(prayerBonus);
equipmentBonuses.setStrengthBonus(strengthBonus);
Item weapon = getEquipment().get(Equipment.WEAPON);
Item ammo = getEquipment().get(Equipment.AMMO);
int rangeBonus = weapon == null ? 0 : weapon.getEquipmentDefinition().getBonuses().getRangeStrengthBonus();
if (rangeBonus == 0 && ammo != null) {
rangeBonus = ammo.getEquipmentDefinition().getBonuses().getRangeStrengthBonus();
}
equipmentBonuses.setRangeStrengthBonus(rangeBonus);
if (getInterfaceSet().getWindow().getCurrentId() == 667) {
sendEquipmentBonuses();
}
}
public void endBankSession() {
bankSession = null;
}
public AccessSet getAccessSet() {
return accessSet;
}
public Appearance getAppearance() {
return appearance;
}
public int getAppearanceTicket() {
return appearanceTicket;
}
public int[] getAppearanceTickets() {
return appearanceTickets;
}
public Inventory getBank() {
return inventorySet.getBank();
}
public BankSession getBankSession() {
return bankSession;
}
public BankSettings getBankSettings() {
return bankSettings;
}
public ChatMessage getChatMessage() {
return chatMessage;
}
@Override
public int getCurrentHitpoints() {
return skillSet.getCurrentLevel(Skill.HITPOINTS);
}
public int getDatabaseId() {
return databaseId;
}
public Animation getDeathAnimation() {
return DEATH_ANIMATION;
}
public String getDisplayName() {
return displayName;
}
public int getEnergy() {
return energy;
}
public Inventory getEquipment() {
return inventorySet.getEquipment();
}
public EquipmentBonuses getEquipmentBonuses() {
return equipmentBonuses;
}
public Friends getFriends() {
return friends;
}
public PlayerTimers getTimers() {
return timers;
}
public GrandExchangeHandler getGrandExchangeHandler() {
return grandExchangeHandler;
}
public GroundItemList getGroundItems() {
return groundItems;
}
@Override
public int getHealthRegen() {
int regen = prayers.prayerActive(HEAL) ? 2 : 1;
// Regen brace
if (getEquipment().get(Equipment.HANDS) != null) {
regen += getEquipment().get(Equipment.HANDS).getId() == 11133 ? 1 : 0;
}
return regen;
}
public Position getHomeLocation() {
return HOME_LOCATIONS[variables.getVar(Variable.HOME_LOCATION)];
}
public InterfaceSet getInterfaceSet() {
return interfaceSet;
}
public Inventory getInventory() {
return inventorySet.getInventory();
}
public InventorySet getInventorySet() {
return inventorySet;
}
public Position getLastKnownRegion() {
return lastKnownRegion;
}
public List<NPC> getLocalNpcs() {
return localNpcs;
}
public List<Player> getLocalPlayers() {
return localPlayers;
}
public long getLongUsername() {
return longUsername;
}
@Override
public int getMaximumHitpoints() {
return skillSet.getLevel(Skill.HITPOINTS);
}
public PlayerOption getOption(int id) {
return options[id];
}
public String getPassword() {
return password;
}
public PlayerCombatHandler getPlayerCombatHandler() {
return (PlayerCombatHandler) combatHandler;
}
public int getPNPC() {
return pnpc;
}
public int getPrayerPoints() {
return skillSet.getCurrentLevel(Skill.PRAYER);
}
public Prayers getPrayers() {
return prayers;
}
public int getRights() {
return rights;
}
public ScriptInput getScriptInput() {
return scriptInput;
}
public GameSession getSession() {
return session;
}
public PlayerSettings getSettings() {
return settings;
}
public PlayerVariables getVariables() {
return variables;
}
public ShopHandler getShopHandler() {
return shopHandler;
}
public House getHouse() {
return house;
}
public House getInHouse() {
return inHouse;
}
public void setInHouse(House inHouse) {
this.inHouse = inHouse;
}
public SkillSet getSkillSet() {
return skillSet;
}
public Spellbook getSpellbook() {
return spellbook;
}
public int getStance() {
if (pnpc > -1) {
return NPCDefinitions.forId(pnpc).getStance();
}
Item weapon = inventorySet.getEquipment().get(Equipment.WEAPON);
if (weapon != null) {
return EquipmentDefinition.forId(weapon.getId()).getStance();
} else {
return 1426;
}
}
public StateSet getStateSet() {
return stateSet;
}
public int getTotalWeight() {
return getInventory().getWeight() + getEquipment().getWeight();
}
public TradeSession getTradeSession() {
return tradeSession;
}
public boolean getUpdateModelLists() {
return updateModelLists;
}
public String getUsername() {
return username;
}
@Override
public void heal(int amount) {
int temp = getCurrentHitpoints() + amount;
temp = temp > getMaximumHitpoints() ? getMaximumHitpoints() : temp;
skillSet.setCurrentLevel(Skill.HITPOINTS, temp);
}
private void init() {
combatHandler = new PlayerCombatHandler(this);
skillSet.addListener(new SkillMessageListener(this));
skillSet.addListener(new SkillAppearanceListener(this));
World.getWorld().getGroundObjects().addListener(groundObjSync);
World.getWorld().getGroundItems().addListener(groundItemSync);
groundItems.addListener(groundItemSync);
/* Initialize all the player options */
for (int i = 0; i < options.length; i++) {
options[i] = new PlayerOption();
}
}
public boolean isChatUpdated() {
return chatMessage != null;
}
public boolean isRegionChanging() {
return regionChanging;
}
@Override
public boolean isRunning() {
return settings.isRunning();
}
/**
* Forces the player to logout. Only call from logout button.
*/
public void logout() {
ChannelFuture future = send(new LogoutMessage());
if (future != null) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
protected void onDeath() {
reset();
startAction(new PlayerDeathAction(this));
}
@Override
public void reduceHp(int amount) {
skillSet.setCurrentLevel(Skill.HITPOINTS, getCurrentHitpoints() - amount);
}
public void reducePrayerPoints(int amount) {
skillSet.setCurrentLevel(Skill.PRAYER, getPrayerPoints() - amount);
}
public void refreshGroundItems() {
groundItemSync.purge();
World.getWorld().getGroundItems().fireEvents(groundItemSync);
groundItems.fireEvents(groundItemSync);
}
public void refreshGroundObjects() {
groundObjSync.purge();
World.getWorld().getGroundObjects().fireEvents(groundObjSync);
}
public GroundObjectSynchronizer getGroundObjectSynchronizer() {
return groundObjSync;
}
public void refreshOptions() {
for (int i = 0; i < options.length; i++) {
PlayerOption option = options[i];
send(new PlayerMenuOptionMessage(i + 1, option.atTop(), option.getText()));
}
}
@Override
public void reset() {
super.reset();
updateModelLists = false;
regionChanging = false;
chatMessage = null;
constructedRegion = null;
}
public SceneRebuiltListener getSceneRebuiltListener() {
return sceneRebuiltListener;
}
public void setSceneRebuiltListener(SceneRebuiltListener sceneRebuiltListener) {
this.sceneRebuiltListener = sceneRebuiltListener;
}
public ChannelFuture send(Message message) {
if (session != null) {
return session.send(message);
} else {
return null;
}
}
public void sendEquipmentBonuses() {
setInterfaceText(667, 32, "0 kg");
setInterfaceText(667, 36, "Stab: " + addPlus(equipmentBonuses.getAttackBonus(AttackType.STAB)));
setInterfaceText(667, 37, "Slash: " + addPlus(equipmentBonuses.getAttackBonus(AttackType.SLASH)));
setInterfaceText(667, 38, "Crush: " + addPlus(equipmentBonuses.getAttackBonus(AttackType.CRUSH)));
setInterfaceText(667, 39, "Magic: " + addPlus(equipmentBonuses.getAttackBonus(AttackType.ALL_MAGIC)));
setInterfaceText(667, 40, "Ranged: " + addPlus(equipmentBonuses.getAttackBonus(AttackType.RANGE)));
setInterfaceText(667, 41, "Stab: " + addPlus(equipmentBonuses.getDefenceBonus(AttackType.STAB)));
setInterfaceText(667, 42, "Slash: " + addPlus(equipmentBonuses.getDefenceBonus(AttackType.SLASH)));
setInterfaceText(667, 43, "Crush: " + addPlus(equipmentBonuses.getDefenceBonus(AttackType.CRUSH)));
setInterfaceText(667, 44, "Magic: " + addPlus(equipmentBonuses.getDefenceBonus(AttackType.ALL_MAGIC)));
setInterfaceText(667, 45, "Range: " + addPlus(equipmentBonuses.getDefenceBonus(AttackType.RANGE)));
setInterfaceText(667, 46, "Summoning: 0");
setInterfaceText(667, 48, "Strength: " + addPlus(equipmentBonuses.getStrengthBonus()));
setInterfaceText(667, 49, "Prayer: " + addPlus(equipmentBonuses.getPrayerBonus()));
}
public void sendMessage(String text) {
send(new ServerMessage(text));
}
public void setActionsBlocked(boolean blockActions) {
this.blockActions = blockActions;
}
public void setAppearance(Appearance appearance) {
this.appearance = appearance;
appearanceUpdated();
}
public void setChatMessage(ChatMessage message) {
this.chatMessage = message;
}
public void setDatabaseId(int databaseId) {
this.databaseId = databaseId;
}
public void setEnergy(int energy) {
this.energy = energy;
this.send(new EnergyMessage(energy));
}
@Override
public void setHidden(boolean hidden) {
super.setHidden(hidden);
appearanceUpdated();
}
public void setInterfaceText(int widgetId, int componentId, String text) {
send(new InterfaceTextMessage(widgetId, componentId, text));
}
public void setLastKnownRegion(Position lastKnownRegion) {
this.lastKnownRegion = lastKnownRegion;
World.getWorld().getGroundObjects().removeListener(groundObjSync);
GameServer.getInstance().getMapLoader().load(lastKnownRegion.getX() / 64, lastKnownRegion.getY() / 64);
World.getWorld().getGroundObjects().addListener(groundObjSync);
this.regionChanging = true;
}
public void setMax() {
max = position;
sendMessage("Top right bounds set to " + max);
}
public void setMin() {
min = position;
sendMessage("Bottom left bounds set to " + min);
}
public void setPassword(String password) {
this.password = password;
}
public void setPNPC(int pnpc) {
this.pnpc = pnpc;
if (pnpc == -1) {
size = 0;
} else {
size = NPCDefinitions.forId(pnpc).getSize();
}
appearanceUpdated();
}
public void setRights(int rights) {
this.rights = rights;
}
public void setSession(GameSession session) {
this.session = session;
}
public void setSpawnPos(int id) {
sendMessage("Spawn for " + NPCDefinitions.forId(id).getName() + " sent to console.");
System.out.println("INSERT INTO `npcspawns`(`type`, `x`, `y`, `height`, `roam`, `min_x`, `min_y`, `max_x`, `max_y`) " + "VALUES (" + id + "," + position.getX() + "," + position.getY() + ","
+ position.getHeight() + "," + 1 + "," + min.getX() + "," + min.getY() + "," + max.getX() + "," + max.getY() + ");");
}
public void setSpellbook(Spellbook spellbook) {
this.spellbook = spellbook;
}
public void setTradeRequest(Player other) {
wantToTrade = other;
}
public void setTradeSession(TradeSession tradeSession) {
this.tradeSession = tradeSession;
}
public void setUpdateModelLists(boolean updateModelLists) {
this.updateModelLists = updateModelLists;
}
public void setUsername(String username) {
this.username = username.replaceAll(" ", "_").toLowerCase();
displayName = StringUtils.capitalize(username);
longUsername = Base37Utils.encodeBase37(username);
}
public void startBankSession() {
bankSession = new BankSession(this);
bankSession.init();
}
@Override
public void teleport(Position position) {
interfaceSet.resetAll();
super.teleport(position);
}
public void setClipped(boolean clipped) {
this.clipped = clipped;
}
public void toggleClipping() {
clipped = !clipped;
}
public void unregister() {
World.getWorld().getGroundItems().removeListener(groundItemSync);
World.getWorld().getGroundObjects().removeListener(groundObjSync);
friends.logout();
stopAction();
}
public boolean wantsToTrade(Player other) {
return other == wantToTrade;
}
public void setConstructedRegion(RegionPalette region) {
constructedRegion = region;
}
public RegionPalette getConstructedRegion() {
return constructedRegion;
}
public void onLogin() {
grandExchangeHandler.init();
calculateEquipmentBonuses();
friends.init();
if (variables.getVar(Variable.FIRST_LOGIN) == 1) {
variables.setVar(Variable.FIRST_LOGIN, 0);
sendMessage("Welcome, thank you for joining MoparScape!");
World.getWorld().sendGlobalMessage(getDisplayName() + " has joined the server! Welcome!");
// Starter items
getInventory().add(new Item(995, 500)); // Coins
getInventory().add(new Item(1171)); // Wooden shield
getInventory().add(new Item(1277)); // Bronze sword
getInventory().add(new Item(2309)); // Bread
getInventory().add(new Item(FishingTool.SMALL_NET.getToolId()));
getInventory().add(new Item(Hatchet.BRONZE.getItemId()));
getInventory().add(new Item(Pickaxe.BRONZE.getItemId()));
getInventory().add(new Item(Firemaking.TINDERBOX));
getInventory().add(new Item(Bow.SHORTBOW.getBowId()));
getInventory().add(new Item(Arrow.BRONZE.getArrowId(), 100));
getInventory().add(new Item(Rune.MIND.getItemId(), 100));
getInventory().add(new Item(Rune.AIR.getItemId(), 100));
getInventory().add(new Item(Rune.WATER.getItemId(), 25));
getInventory().add(new Item(Rune.EARTH.getItemId(), 25));
getInventory().add(new Item(Rune.FIRE.getItemId(), 25));
} else {
sendMessage("Welcome to MoparScape.");
World.getWorld().sendGlobalMessage(getDisplayName() + " has logged in.");
}
System.out.println("Player logged in: " + getDisplayName());
}
}
| |
/**
* Copyright 2016 Netflix, 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.netflix.conductor.server.resources;
import com.netflix.conductor.common.metadata.tasks.PollData;
import com.netflix.conductor.common.metadata.tasks.Task;
import com.netflix.conductor.common.metadata.tasks.TaskExecLog;
import com.netflix.conductor.common.metadata.tasks.TaskResult;
import com.netflix.conductor.common.run.ExternalStorageLocation;
import com.netflix.conductor.common.run.SearchResult;
import com.netflix.conductor.common.run.TaskSummary;
import com.netflix.conductor.service.TaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.Map;
/**
*
* @author visingh
*
*/
@Api(value="/tasks", produces=MediaType.APPLICATION_JSON, consumes=MediaType.APPLICATION_JSON, tags="Task Management")
@Path("/tasks")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_JSON })
@Singleton
public class TaskResource {
private final TaskService taskService;
@Inject
public TaskResource(TaskService taskService) {
this.taskService = taskService;
}
@GET
@Path("/poll/{tasktype}")
@ApiOperation("Poll for a task of a certain type")
@Consumes({MediaType.WILDCARD})
public Task poll(@PathParam("tasktype") String taskType,
@QueryParam("workerid") String workerId,
@QueryParam("domain") String domain) {
return taskService.poll(taskType, workerId, domain);
}
@GET
@Path("/poll/batch/{tasktype}")
@ApiOperation("batch Poll for a task of a certain type")
@Consumes({MediaType.WILDCARD})
public List<Task> batchPoll(@PathParam("tasktype") String taskType,
@QueryParam("workerid") String workerId,
@QueryParam("domain") String domain,
@DefaultValue("1") @QueryParam("count") Integer count,
@DefaultValue("100") @QueryParam("timeout") Integer timeout) {
return taskService.batchPoll(taskType, workerId, domain, count, timeout);
}
@GET
@Path("/in_progress/{tasktype}")
@ApiOperation("Get in progress tasks. The results are paginated.")
@Consumes({MediaType.WILDCARD})
public List<Task> getTasks(@PathParam("tasktype") String taskType,
@QueryParam("startKey") String startKey,
@QueryParam("count") @DefaultValue("100") Integer count) {
return taskService.getTasks(taskType, startKey, count);
}
@GET
@Path("/in_progress/{workflowId}/{taskRefName}")
@ApiOperation("Get in progress task for a given workflow id.")
@Consumes({MediaType.WILDCARD})
public Task getPendingTaskForWorkflow(@PathParam("workflowId") String workflowId,
@PathParam("taskRefName") String taskReferenceName) {
return taskService.getPendingTaskForWorkflow(workflowId, taskReferenceName);
}
@POST
@ApiOperation("Update a task")
@Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON})
public String updateTask(TaskResult taskResult) {
return taskService.updateTask(taskResult);
}
@POST
@Path("/{taskId}/ack")
@ApiOperation("Ack Task is received")
@Consumes({MediaType.WILDCARD})
public String ack(@PathParam("taskId") String taskId,
@QueryParam("workerid") String workerId) {
return taskService.ackTaskReceived(taskId, workerId);
}
@POST
@Path("/{taskId}/log")
@ApiOperation("Log Task Execution Details")
public void log(@PathParam("taskId") String taskId, String log) {
taskService.log(taskId, log);
}
@GET
@Path("/{taskId}/log")
@ApiOperation("Get Task Execution Logs")
public List<TaskExecLog> getTaskLogs(@PathParam("taskId") String taskId) {
return taskService.getTaskLogs(taskId);
}
@GET
@Path("/{taskId}")
@ApiOperation("Get task by Id")
@Consumes(MediaType.WILDCARD)
public Task getTask(@PathParam("taskId") String taskId) {
return taskService.getTask(taskId);
}
@DELETE
@Path("/queue/{taskType}/{taskId}")
@ApiOperation("Remove Task from a Task type queue")
@Consumes({MediaType.WILDCARD})
public void removeTaskFromQueue(@PathParam("taskType") String taskType,
@PathParam("taskId") String taskId) {
taskService.removeTaskFromQueue(taskType, taskId);
}
@GET
@Path("/queue/sizes")
@ApiOperation("Get Task type queue sizes")
@Consumes({MediaType.WILDCARD})
public Map<String, Integer> size(@QueryParam("taskType") List<String> taskTypes) {
return taskService.getTaskQueueSizes(taskTypes);
}
@GET
@Path("/queue/all/verbose")
@ApiOperation("Get the details about each queue")
@Consumes({MediaType.WILDCARD})
public Map<String, Map<String, Map<String, Long>>> allVerbose() {
return taskService.allVerbose();
}
@GET
@Path("/queue/all")
@ApiOperation("Get the details about each queue")
@Consumes({MediaType.WILDCARD})
public Map<String, Long> all() {
return taskService.getAllQueueDetails();
}
@GET
@Path("/queue/polldata")
@ApiOperation("Get the last poll data for a given task type")
@Consumes({MediaType.WILDCARD})
public List<PollData> getPollData(@QueryParam("taskType") String taskType) {
return taskService.getPollData(taskType);
}
@GET
@Path("/queue/polldata/all")
@ApiOperation("Get the last poll data for all task types")
@Consumes(MediaType.WILDCARD)
public List<PollData> getAllPollData() {
return taskService.getAllPollData();
}
@POST
@Path("/queue/requeue")
@ApiOperation("Requeue pending tasks for all the running workflows")
public String requeue() {
return taskService.requeue();
}
@POST
@Path("/queue/requeue/{taskType}")
@ApiOperation("Requeue pending tasks")
@Consumes(MediaType.WILDCARD)
@Produces({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON })
public String requeuePendingTask(@PathParam("taskType") String taskType) {
return taskService.requeuePendingTask(taskType);
}
@ApiOperation(value="Search for tasks based in payload and other parameters",
notes="use sort options as sort=<field>:ASC|DESC e.g. sort=name&sort=workflowId:DESC." +
" If order is not specified, defaults to ASC")
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("/search")
public SearchResult<TaskSummary> search(@QueryParam("start") @DefaultValue("0") int start,
@QueryParam("size") @DefaultValue("100") int size,
@QueryParam("sort") String sort,
@QueryParam("freeText") @DefaultValue("*") String freeText,
@QueryParam("query") String query) {
return taskService.search(start, size, sort, freeText, query);
}
@GET
@ApiOperation("Get the external uri where the task output payload is to be stored")
@Consumes(MediaType.WILDCARD)
@Path("/externalstoragelocation")
public ExternalStorageLocation getExternalStorageLocation(@QueryParam("path") String path) {
return taskService.getExternalStorageLocation(path);
}
}
| |
/*
* Copyright (c) 2017, 2018, Oracle Corporation and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the Apache License Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* If a copy of the Apache License Version 2.0 was not distributed with this file,
* You can obtain one at https://www.apache.org/licenses/LICENSE-2.0.html
*/
package com.netflix.spinnaker.igor.wercker;
import static com.netflix.spinnaker.igor.wercker.model.Run.startedAtComparator;
import com.netflix.spinnaker.igor.IgorConfigurationProperties;
import com.netflix.spinnaker.igor.wercker.model.Run;
import com.netflix.spinnaker.kork.jedis.RedisClientDelegate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/** Shared cache of build details for jenkins */
@Service
public class WerckerCache {
private static final String POLL_STAMP = "lastPollCycleTimestamp";
private static final String PIPELINE_ID = "pipelineId";
private static final String PIPELINE_NAME = "pipelineName";
private final RedisClientDelegate redisClientDelegate;
private final IgorConfigurationProperties igorConfigurationProperties;
@Autowired
public WerckerCache(
RedisClientDelegate redisClientDelegate,
IgorConfigurationProperties igorConfigurationProperties) {
this.redisClientDelegate = redisClientDelegate;
this.igorConfigurationProperties = igorConfigurationProperties;
}
public void setLastPollCycleTimestamp(String master, String pipeline, Long timestamp) {
String key = makeKey(master, pipeline);
redisClientDelegate.withCommandsClient(
c -> {
c.hset(key, POLL_STAMP, Long.toString(timestamp));
});
}
public Long getLastPollCycleTimestamp(String master, String pipeline) {
return redisClientDelegate.withCommandsClient(
c -> {
String ts = c.hget(makeKey(master, pipeline), POLL_STAMP);
return ts == null ? null : Long.parseLong(ts);
});
}
public String getPipelineID(String master, String pipeline) {
return redisClientDelegate.withCommandsClient(
c -> {
return c.hget(makeKey(master, pipeline), PIPELINE_ID);
});
}
public String getPipelineName(String master, String id) {
return redisClientDelegate.withCommandsClient(
c -> {
return c.hget(nameKey(master, id), PIPELINE_NAME);
});
}
public void setPipelineID(String master, String pipeline, String id) {
String key = makeKey(master, pipeline);
redisClientDelegate.withCommandsClient(
c -> {
c.hset(key, PIPELINE_ID, id);
});
String nameKey = nameKey(master, id);
redisClientDelegate.withCommandsClient(
c -> {
c.hset(nameKey, PIPELINE_NAME, pipeline);
});
}
public String getRunID(String master, String pipeline, final int buildNumber) {
String key = makeKey(master, pipeline) + ":runs";
final Map<String, String> existing =
redisClientDelegate.withCommandsClient(
c -> {
if (!c.exists(key)) {
return null;
}
return c.hgetAll(key);
});
String build = Integer.toString(buildNumber);
for (Entry<String, String> entry : existing.entrySet()) {
if (entry.getValue().equals(build)) {
return entry.getKey();
}
}
return null;
}
/**
* Creates entries in Redis for each run in the runs list (except if the run id already exists)
* and generates build numbers for each run id (ordered by startedAt date)
*
* @param master
* @param appAndPipelineName
* @param runs
* @return a map containing the generated build numbers for each run created, keyed by run id
*/
public Map<String, Integer> updateBuildNumbers(
String master, String appAndPipelineName, List<Run> runs) {
String key = makeKey(master, appAndPipelineName) + ":runs";
final Map<String, String> existing =
redisClientDelegate.withCommandsClient(
c -> {
if (!c.exists(key)) {
return null;
}
return c.hgetAll(key);
});
List<Run> newRuns = runs;
if (existing != null && existing.size() > 0) {
newRuns =
runs.stream()
.filter(run -> !existing.containsKey(run.getId()))
.collect(Collectors.toList());
}
Map<String, Integer> runIdToBuildNumber = new HashMap<>();
int startNumber = (existing == null || existing.size() == 0) ? 0 : existing.size();
newRuns.sort(startedAtComparator);
for (int i = 0; i < newRuns.size(); i++) {
int buildNum = startNumber + i;
setBuildNumber(master, appAndPipelineName, newRuns.get(i).getId(), buildNum);
runIdToBuildNumber.put(newRuns.get(i).getId(), buildNum);
}
return runIdToBuildNumber;
}
public void setBuildNumber(String master, String pipeline, String runID, int number) {
String key = makeKey(master, pipeline) + ":runs";
redisClientDelegate.withCommandsClient(
c -> {
c.hset(key, runID, Integer.toString(number));
});
}
public Long getBuildNumber(String master, String pipeline, String runID) {
return redisClientDelegate.withCommandsClient(
c -> {
String ts = c.hget(makeKey(master, pipeline) + ":runs", runID);
return ts == null ? null : Long.parseLong(ts);
});
}
public Boolean getEventPosted(String master, String job, String runID) {
String key = makeEventsKey(master, job);
return redisClientDelegate.withCommandsClient(c -> c.hget(key, runID) != null);
}
public void setEventPosted(String master, String job, String runID) {
String key = makeEventsKey(master, job);
redisClientDelegate.withCommandsClient(
c -> {
c.hset(key, runID, "POSTED");
});
}
public void pruneOldMarkers(String master, String job, Long cursor) {
remove(master, job);
redisClientDelegate.withCommandsClient(
c -> {
c.del(makeEventsKey(master, job));
});
}
public void remove(String master, String job) {
redisClientDelegate.withCommandsClient(
c -> {
c.del(makeKey(master, job));
});
}
private String makeEventsKey(String master, String job) {
return makeKey(master, job) + ":" + POLL_STAMP + ":events";
}
private String makeKey(String master, String job) {
return prefix() + ":" + master + ":" + job.toUpperCase() + ":" + job;
}
private String nameKey(String master, String pipelineId) {
return prefix() + ":" + master + ":all_pipelines:" + pipelineId;
}
private String prefix() {
return igorConfigurationProperties.getSpinnaker().getJedis().getPrefix() + "_wercker";
}
}
| |
/*
* 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.sysml.test.integration.functions.updateinplace;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.apache.sysml.hops.OptimizerUtils;
import org.apache.sysml.test.integration.AutomatedTestBase;
import org.apache.sysml.test.integration.TestConfiguration;
import org.apache.sysml.test.utils.TestUtils;
public class UpdateInPlaceTest extends AutomatedTestBase
{
private final static String TEST_DIR = "functions/updateinplace/";
private final static String TEST_NAME = "updateinplace";
private final static String TEST_CLASS_DIR = TEST_DIR + UpdateInPlaceTest.class.getSimpleName() + "/";
/* Test cases to test following scenarios
*
* Test scenarios Test case
* ------------------------------------------------------------------------------------
*
* Positive case::
* ===============
*
* Candidate UIP applicable testUIP
*
* Interleave Operalap::
* =====================
*
* Various loop types::
* --------------------
*
* Overlap for Consumer within while loop testUIPNAConsUsed
* Overlap for Consumer outside loop testUIPNAConsUsedOutsideDAG
* Overlap for Consumer within loop(not used) testUIPNAConsUsed
* Overlap for Consumer within for loop testUIPNAConsUsedForLoop
* Overlap for Consumer within inner parfor loop testUIPNAParFor
* Overlap for Consumer inside loop testUIPNAConsUsedInsideDAG
*
* Complex Statement::
* -------------------
*
* Overlap for Consumer within complex statement testUIPNAComplexConsUsed
* (Consumer in complex statement)
* Overlap for Consumer within complex statement testUIPNAComplexCandUsed
* (Candidate in complex statement)
*
* Else and Predicate case::
* -------------------------
*
* Overlap for Consumer within else clause testUIPNAConsUsedElse
* Overlap with consumer in predicate testUIPNACandInPredicate
*
* Multiple LIX for same object with interleave::
* ----------------------------------------------
*
* Overlap for Consumer with multiple lix testUIPNAMultiLIX
*
*
* Function Calls::
* ================
*
* Overlap for candidate used in function call testUIPNACandInFuncCall
* Overlap for consumer used in function call testUIPNAConsInFuncCall
* Function call without consumer/candidate testUIPFuncCall
*
*/
//Note: In order to run these tests against ParFor loop, parfor's DEBUG flag needs to be set in the script.
@Override
public void setUp() {
TestUtils.clearAssertionInformation();
addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, null));
}
@Test
public void testUIP()
{
List<String> listUIPRes = Arrays.asList("A");
runUpdateInPlaceTest(TEST_NAME, 1, listUIPRes, 2, 4, 4);
}
@Test
public void testUIPNAConsUsed()
{
List<String> listUIPRes = Arrays.asList();
runUpdateInPlaceTest(TEST_NAME, 2, listUIPRes, 0, 0, 4);
}
@Test
public void testUIPNAConsUsedOutsideDAG()
{
List<String> listUIPRes = Arrays.asList();
runUpdateInPlaceTest(TEST_NAME, 3, listUIPRes, 0, 0, 4);
}
@Test
public void testUIPConsNotUsed()
{
List<String> listUIPRes = Arrays.asList("A");
runUpdateInPlaceTest(TEST_NAME, 4, listUIPRes, 2, 4, 4);
}
@Test
public void testUIPNAConsUsedForLoop()
{
List<String> listUIPRes = Arrays.asList();
runUpdateInPlaceTest(TEST_NAME, 5, listUIPRes, 0, 0, 4);
}
@Test
public void testUIPNAComplexConsUsed()
{
List<String> listUIPRes = Arrays.asList();
runUpdateInPlaceTest(TEST_NAME, 6, listUIPRes, 0, 0, 4);
}
@Test
public void testUIPNAComplexCandUsed()
{
List<String> listUIPRes = Arrays.asList();
runUpdateInPlaceTest(TEST_NAME, 7, listUIPRes, 0, 0, 4);
}
@Test
public void testUIPNAConsUsedElse()
{
List<String> listUIPRes = Arrays.asList();
runUpdateInPlaceTest(TEST_NAME, 8, listUIPRes, 0, 0, 4);
}
@Test
public void testUIPNACandInPredicate()
{
List<String> listUIPRes = Arrays.asList();
runUpdateInPlaceTest(TEST_NAME, 9, listUIPRes, 0, 0, 4);
}
@Test
public void testUIPNAMultiLIX()
{
List<String> listUIPRes = Arrays.asList();
runUpdateInPlaceTest(TEST_NAME, 10, listUIPRes, 0, 0, 12);
}
@Test
public void testUIPNAParFor()
{
List<String> listUIPRes = Arrays.asList();
runUpdateInPlaceTest(TEST_NAME, 11, listUIPRes, 0, 0, 8);
}
@Test
public void testUIPNACandInFuncCall()
{
List<String> listUIPRes = Arrays.asList();
runUpdateInPlaceTest(TEST_NAME, 12, listUIPRes, 0, 0, 4);
}
@Test
public void testUIPNAConsInFuncCall()
{
List<String> listUIPRes = Arrays.asList();
runUpdateInPlaceTest(TEST_NAME, 13, listUIPRes, 0, 0, 4);
}
@Test
public void testUIPFuncCall()
{
List<String> listUIPRes = Arrays.asList("A");
runUpdateInPlaceTest(TEST_NAME, 14, listUIPRes, 2, 4, 8);
}
@Test
public void testUIPNAConsUsedInsideDAG()
{
List<String> listUIPRes = Arrays.asList();
runUpdateInPlaceTest(TEST_NAME, 15, listUIPRes, 0, 0, 4);
}
/**
*
* @param TEST_NAME
* @param iTestNumber
* @param listUIPRes
*/
private void runUpdateInPlaceTest( String TEST_NAME, int iTestNumber, List<String> listUIPExp, long lTotalUIPVar, long lTotalLixUIP, long lTotalLix)
{
boolean oldinplace = OptimizerUtils.ALLOW_LOOP_UPDATE_IN_PLACE;
if(shouldSkipTest())
return;
try
{
TestConfiguration config = getTestConfiguration(TEST_NAME);
loadTestConfiguration(config);
OptimizerUtils.ALLOW_LOOP_UPDATE_IN_PLACE = false;
// This is for running the junit test the new way, i.e., construct the arguments directly
String HOME = SCRIPT_DIR + TEST_DIR;
fullDMLScriptName = HOME + TEST_NAME + iTestNumber + ".dml";
programArgs = new String[]{"-stats"}; //new String[]{"-args", input("A"), output("B") };
runTest(true, false, null, -1);
}
finally {
OptimizerUtils.ALLOW_LOOP_UPDATE_IN_PLACE = oldinplace;
}
}
}
| |
package com.tscfdi.comprobante;
import com.tscfdi.common.DateInvoiceAdapter;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by lugty on 19/08/16.
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
name = "Comprobante",
propOrder = { "cfdiRelacionados", "emisor", "receptor", "conceptos", "impuestos", "complemento", "addenda" }
)
@XmlRootElement(name = "Comprobante")
public class DataComprobante {
@XmlAttribute(
name = "Version",
required = true
)
private String version;
@XmlAttribute(
name = "Serie"
)
private String serie;
@XmlAttribute(
name = "Folio"
)
private String folio;
@XmlAttribute(
name = "Fecha",
required = true
)
@XmlJavaTypeAdapter(DateInvoiceAdapter.class)
private Date fecha;
@XmlAttribute(
name = "Sello",
required = true
)
private String sello; // private readonly
@XmlAttribute(
name = "FormaPago",
required = true
)
private String formaPago;
@XmlAttribute(
name = "NoCertificado",
required = true
)
private String noCertificado; // private readonly
@XmlAttribute(
name = "Certificado",
required = true
)
private String certificado; //private readonly
@XmlAttribute(
name = "CondicionesDePago"
)
private String condicionesDePago;
@XmlAttribute(
name = "SubTotal",
required = true
)
private BigDecimal subTotal;
@XmlAttribute(
name = "Descuento"
)
private BigDecimal descuento;
@XmlAttribute(
name = "Moneda",
required = true
)
private String moneda;
@XmlAttribute(
name = "TipoCambio"
)
private String tipoCambio;
@XmlAttribute(
name = "Total",
required = true
)
private BigDecimal total;
@XmlAttribute(
name = "TipoDeComprobante",
required = true
)
private String tipoDeComprobante;
@XmlAttribute(
name = "MetodoPago"
)
private String metodoPago;
@XmlAttribute(
name = "LugarExpedicion",
required = true
)
private String lugarExpedicion;
@XmlAttribute(
name = "Confirmacion"
)
private String confirmacion;
@XmlElement(
name = "CfdiRelacionados"
)
private DataCfdiRelacionados cfdiRelacionados;
@XmlElement(
name = "Emisor",
required = true
)
private DataEmisor emisor;
@XmlElement(
name = "Receptor",
required = true
)
private DataReceptor receptor;
@XmlElementWrapper(name = "Conceptos", required = true)
@XmlElement(
name = "Concepto",
required = true
)
private List<DataConcepto> conceptos = new ArrayList<DataConcepto>();
@XmlElement(
name = "Impuestos"
)
private DataImpuesto impuestos;
@XmlElement(
name = "Complemento"
)
private DataComplemento complemento;
@XmlElement(
name = "Addenda"
)
private DataAddenda addenda;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getSerie() {
return serie;
}
public void setSerie(String serie) {
this.serie = serie;
}
public String getFolio() {
return folio;
}
public void setFolio(String folio) {
this.folio = folio;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public String getSello() {
return sello;
}
public void setSello(String sello) {
this.sello = sello;
}
public String getFormaPago() {
return formaPago;
}
public void setFormaPago(String formaPago) {
this.formaPago = formaPago;
}
public String getNoCertificado() {
return noCertificado;
}
public void setNoCertificado(String noCertificado) {
this.noCertificado = noCertificado;
}
public String getCertificado() {
return certificado;
}
public void setCertificado(String certificado) {
this.certificado = certificado;
}
public String getCondicionesDePago() {
return condicionesDePago;
}
public void setCondicionesDePago(String condicionesDePago) {
this.condicionesDePago = condicionesDePago;
}
public BigDecimal getSubTotal() {
return subTotal;
}
public void setSubTotal(BigDecimal subTotal) {
this.subTotal = subTotal;
}
public BigDecimal getDescuento() {
return descuento;
}
public void setDescuento(BigDecimal descuento) {
this.descuento = descuento;
}
public String getMoneda() {
return moneda;
}
public void setMoneda(String moneda) {
this.moneda = moneda;
}
public String getTipoCambio() {
return tipoCambio;
}
public void setTipoCambio(String tipoCambio) {
this.tipoCambio = tipoCambio;
}
public BigDecimal getTotal() {
return total;
}
public void setTotal(BigDecimal total) {
this.total = total;
}
public String getTipoDeComprobante() {
return tipoDeComprobante;
}
public void setTipoDeComprobante(String tipoDeComprobante) {
this.tipoDeComprobante = tipoDeComprobante;
}
public String getMetodoPago() {
return metodoPago;
}
public void setMetodoPago(String metodoPago) {
this.metodoPago = metodoPago;
}
public String getLugarExpedicion() {
return lugarExpedicion;
}
public void setLugarExpedicion(String lugarExpedicion) {
this.lugarExpedicion = lugarExpedicion;
}
public String getConfirmacion() {
return confirmacion;
}
public void setConfirmacion(String confirmacion) {
this.confirmacion = confirmacion;
}
public DataCfdiRelacionados getCfdiRelacionados() {
return cfdiRelacionados;
}
public void setCfdiRelacionados(DataCfdiRelacionados cfdiRelacionados) {
this.cfdiRelacionados = cfdiRelacionados;
}
public DataEmisor getEmisor() {
return emisor;
}
public void setEmisor(DataEmisor emisor) {
this.emisor = emisor;
}
public DataReceptor getReceptor() {
return receptor;
}
public void setReceptor(DataReceptor receptor) {
this.receptor = receptor;
}
public List<DataConcepto> getConceptos() {
return conceptos;
}
public void setConceptos(List<DataConcepto> conceptos) {
this.conceptos = conceptos;
}
public DataImpuesto getImpuestos() {
return impuestos;
}
public void setImpuestos(DataImpuesto impuestos) {
this.impuestos = impuestos;
}
public DataComplemento getComplemento() {
return complemento;
}
public void setComplemento(DataComplemento complemento) {
this.complemento = complemento;
}
public DataAddenda getAddenda() {
return addenda;
}
public void setAddenda(DataAddenda addenda) {
this.addenda = addenda;
}
}
| |
/*
* Copyright (c) 2016 riebie, Kippers <https://bitbucket.org/Kippers/mcclans-core-sponge>
*
* 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 nl.riebie.mcclans.commands.implementations;
import nl.riebie.mcclans.ClansImpl;
import nl.riebie.mcclans.api.events.*;
import nl.riebie.mcclans.clan.ClanImpl;
import nl.riebie.mcclans.clan.RankFactory;
import nl.riebie.mcclans.clan.RankImpl;
import nl.riebie.mcclans.commands.Toggle;
import nl.riebie.mcclans.commands.annotations.*;
import nl.riebie.mcclans.commands.constraints.ClanNameConstraint;
import nl.riebie.mcclans.commands.constraints.ClanTagConstraint;
import nl.riebie.mcclans.comparators.MemberComparator;
import nl.riebie.mcclans.events.EventDispatcher;
import nl.riebie.mcclans.messages.Messages;
import nl.riebie.mcclans.persistence.DatabaseHandler;
import nl.riebie.mcclans.player.ClanPlayerImpl;
import nl.riebie.mcclans.table.HorizontalTable;
import nl.riebie.mcclans.table.TableAdapter;
import nl.riebie.mcclans.utils.UUIDUtils;
import nl.riebie.mcclans.utils.Utils;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
/**
* Created by riebie on 28/02/2016.
*/
public class ClanAdminCommands {
@ChildGroup(ClanAdminClanPlayerCommands.class)
@Command(name = "clanplayer", description = "Top command for all admin clanplayer commands", spongePermission = "mcclans.admin.clanplayer.helppage")
public void adminClanPlayerRootCommand(CommandSource commandSource) {
commandSource.sendMessage(Text.of("TODO"));
}
@ChildGroup(ClanAdminTagCommands.class)
@Command(name = "tag", description = "Top command for all admin tag commands", spongePermission = "mcclans.admin.tag.helppage")
public void adminTagRootCommand(CommandSource commandSource) {
commandSource.sendMessage(Text.of("TODO"));
}
@Command(name = "coords", description = "See the coordinates of a clan's members", spongePermission = "mcclans.admin.coords")
public void adminCoordsCommand(CommandSource commandSource, @Parameter(name = "clanTag") ClanImpl clan, @PageParameter int page) {
List<Player> onlineMembers = new ArrayList<Player>();
List<ClanPlayerImpl> members = clan.getMembersImpl();
for (ClanPlayerImpl member : members) {
Optional<Player> playerOpt = Sponge.getServer().getPlayer(member.getUUID());
if (playerOpt.isPresent() && playerOpt.get().isOnline()) {
onlineMembers.add(playerOpt.get());
}
}
java.util.Collections.sort(members, new MemberComparator());
HorizontalTable<Player> table = new HorizontalTable<>("Clan coordinates " + clan.getName(), 10, (TableAdapter<Player>) (row, player, index) -> {
if (player.isOnline()) {
Location<World> location = player.getLocation();
row.setValue("Player", Text.of(player.getName()));
row.setValue("Location", Utils.formatLocation(location));
}
});
table.defineColumn("Player", 30);
table.defineColumn("Location", 30);
table.draw(onlineMembers, page, commandSource);
}
@Command(name = "backup", description = "Backup the database", spongePermission = "mcclans.admin.backup")
public void adminBackupCommand(CommandSource commandSource) {
Messages.sendBasicMessage(commandSource, Messages.SYSTEM_BACKUP_INITIATED);
DatabaseHandler.getInstance().backup();
}
@Command(name = "create", description = "Create a clan", spongePermission = "mcclans.admin.create")
public void adminCreateCommand(
CommandSource commandSource,
@Parameter(name = "owner") String owner,
@Parameter(name = "clanTag", constraint = ClanTagConstraint.class) String clanTag,
@Multiline @Parameter(name = "clanName", constraint = ClanNameConstraint.class) String clanName
) {
ClansImpl clansImpl = ClansImpl.getInstance();
ClanPlayerImpl targetClanPlayer = clansImpl.getClanPlayer(owner);
if (targetClanPlayer == null) {
UUID uuid = UUIDUtils.getUUID(owner);
Optional<Player> playerOpt;
if (uuid == null) {
playerOpt = Optional.empty();
} else {
playerOpt = Sponge.getServer().getPlayer(uuid);
}
if (playerOpt.isPresent() && playerOpt.get().isOnline()) {
targetClanPlayer = clansImpl.createClanPlayer(playerOpt.get().getUniqueId(), owner);
}
}
if (targetClanPlayer == null) {
Messages.sendPlayerNotOnline(commandSource, owner);
} else {
if (targetClanPlayer.getClan() == null) {
if (clansImpl.isTagAvailable(clanTag)) {
ClanCreateEvent.Admin clanCreateEvent = EventDispatcher.getInstance().dispatchAdminClanCreateEvent(clanTag, clanName, targetClanPlayer);
if (clanCreateEvent.isCancelled()) {
Messages.sendWarningMessage(commandSource, clanCreateEvent.getCancelMessage());
return;
}
ClanImpl clanImpl = clansImpl.createClanInternal(clanTag, clanName, targetClanPlayer);
Messages.sendBroadcastMessageClanCreatedBy(clanImpl.getName(), clanImpl.getTagColored(), commandSource.getName());
} else {
Messages.sendWarningMessage(commandSource, Messages.CLAN_TAG_EXISTS_ALREADY);
}
} else {
Messages.sendPlayerAlreadyInClan(commandSource, targetClanPlayer.getName());
}
}
}
@Command(name = "disband", description = "Disband a clan", spongePermission = "mcclans.admin.disband")
public void adminDisbandCommand(CommandSource commandSource, @Parameter(name = "clanTag") ClanImpl clan) {
ClanDisbandEvent.Admin event = EventDispatcher.getInstance().dispatchAdminClanDisbandEvent(clan);
if (event.isCancelled()) {
Messages.sendWarningMessage(commandSource, event.getCancelMessage());
} else {
ClansImpl clansImpl = ClansImpl.getInstance();
Messages.sendBroadcastMessageClanDisbandedBy(clan.getName(), clan.getTagColored(), commandSource.getName());
clansImpl.disbandClanInternal(clan);
}
}
@Command(name = "home", description = "Teleport to a clan home", isPlayerOnly = true, spongePermission = "mcclans.admin.home")
public void adminHomeCommand(CommandSource commandSource, ClanPlayerImpl clanPlayer, @Parameter(name = "clanTag") ClanImpl clan) {
Player player = (Player) commandSource;
Location<World> teleportLocation = clan.getHome();
if (teleportLocation == null) {
Messages.sendWarningMessage(commandSource, Messages.CLAN_HOME_LOCATION_IS_NOT_SET);
return;
}
ClanHomeTeleportEvent.Admin event = EventDispatcher.getInstance().dispatchAdminClanHomeTeleportEvent(clanPlayer, clan);
if (event.isCancelled()) {
Messages.sendWarningMessage(player, event.getCancelMessage());
} else {
player.setLocation(teleportLocation);
}
}
@Command(name = "invite", description = "Invite a player to a clan", spongePermission = "mcclans.admin.invite")
public void adminInviteCommand(CommandSource commandSource, @Parameter(name = "clanTag") ClanImpl clan, @Parameter(name = "playerName") ClanPlayerImpl invitedClanPlayer) {
Optional<Player> playerOpt = Sponge.getServer().getPlayer(invitedClanPlayer.getUUID());
if (!playerOpt.isPresent()) {
Messages.sendPlayerNotOnline(commandSource, invitedClanPlayer.getName());
return;
}
Player player = playerOpt.get();
if (invitedClanPlayer.getClan() != null) {
Messages.sendPlayerAlreadyInClan(commandSource, player.getName());
} else if (invitedClanPlayer.getClanInvite() != null) {
Messages.sendPlayerAlreadyInvitedByAnotherClan(commandSource, player.getName());
} else {
invitedClanPlayer.inviteToClan(clan);
clan.addInvitedPlayer(invitedClanPlayer);
Messages.sendInvitedToClan(player, clan.getName(), clan.getTagColored());
Messages.sendClanBroadcastMessagePlayerInvitedToTheClan(clan, player.getName(), commandSource.getName(), "invite");
}
}
@Command(name = "remove", description = "Remove a player from a clan", spongePermission = "mcclans.admin.remove")
public void adminRemoveCommand(CommandSource commandSource, @Parameter(name = "clanTag") ClanImpl clan, @Parameter(name = "playerName") String removeName) {
ClanPlayerImpl toBeRemovedClanPlayer = ClansImpl.getInstance().getClanPlayer(removeName);
if (toBeRemovedClanPlayer == null || !clan.equals(toBeRemovedClanPlayer.getClan())) {
toBeRemovedClanPlayer = clan.getMember(removeName);
}
if (toBeRemovedClanPlayer == null) {
Messages.sendPlayerNotAMemberOfThisClan(commandSource, removeName);
return;
}
if (toBeRemovedClanPlayer.equals(clan.getOwner())) {
Messages.sendWarningMessage(commandSource, Messages.YOU_CANNOT_REMOVE_THE_OWNER_FROM_THE_CLAN);
} else {
ClanMemberLeaveEvent.Admin clanMemberLeaveEvent = EventDispatcher.getInstance().dispatchAdminClanMemberLeaveEvent(clan, toBeRemovedClanPlayer);
if (clanMemberLeaveEvent.isCancelled()) {
Messages.sendWarningMessage(commandSource, clanMemberLeaveEvent.getCancelMessage());
} else {
clan.removeMember(toBeRemovedClanPlayer);
Messages.sendClanBroadcastMessagePlayerRemovedFromTheClanBy(clan, toBeRemovedClanPlayer.getName(), commandSource.getName());
Messages.sendYouHaveBeenRemovedFromClan(toBeRemovedClanPlayer, clan.getName());
}
}
}
@Command(name = "sethome", description = "Set the location of a clan home", isPlayerOnly = true, spongePermission = "mcclans.admin.sethome")
public void adminSetHomeCommand(CommandSource commandSource, @Parameter(name = "clanTag") ClanImpl clan) {
Player player = (Player) commandSource;
Location<World> location = player.getLocation();
ClanSetHomeEvent.Admin clanSetHomeEvent = EventDispatcher.getInstance().dispatchClanSetHomeAdmin(clan, location, commandSource);
if (clanSetHomeEvent.isCancelled()) {
Messages.sendWarningMessage(commandSource, clanSetHomeEvent.getCancelMessage());
} else {
clan.setHomeInternal(location);
Messages.sendBasicMessage(commandSource, Messages.CLAN_HOME_LOCATION_SET);
}
}
@Command(name = "setrank", description = "Set the rank of a member of a clan", spongePermission = "mcclans.admin.setrank")
public void adminSetRankCommand(CommandSource sender, @Parameter(name = "clanTag") ClanImpl clan, @Parameter(name = "playerName") ClanPlayerImpl targetClanPlayer,
@Parameter(name = "rankName") String rankName) {
if (!clan.equals(targetClanPlayer.getClan())) {
Messages.sendPlayerNotAMemberOfThisClan(sender, targetClanPlayer.getName());
return;
}
RankImpl rank = clan.getRank(rankName);
if (rank == null) {
Messages.sendWarningMessage(sender, Messages.RANK_DOES_NOT_EXIST);
} else if (targetClanPlayer.getRank().getName().toLowerCase().equals(RankFactory.getOwnerIdentifier().toLowerCase())) {
Messages.sendWarningMessage(sender, Messages.YOU_CANNOT_OVERWRITE_THE_OWNER_RANK);
} else {
if (RankFactory.getOwnerIdentifier().toLowerCase().equals(rank.getName().toLowerCase())) {
ClanOwnerChangeEvent.Admin clanOwnerChangeEvent = EventDispatcher.getInstance().dispatchAdminClanOwnerChangeEvent(clan, clan.getOwner(), targetClanPlayer);
if (clanOwnerChangeEvent.isCancelled()) {
Messages.sendWarningMessage(sender, clanOwnerChangeEvent.getCancelMessage());
return;
} else {
clan.setOwnerInternal(targetClanPlayer);
}
} else {
targetClanPlayer.setRank(rank);
}
Messages.sendRankOfPlayerSuccessfullyChangedToRank(sender, targetClanPlayer.getName(), rank.getName());
targetClanPlayer.sendMessage(Messages.getYourRankHasBeenChangedToRank(rank.getName()));
}
}
@Command(name = "spy", description = "Spy on all the clan chats", isPlayerOnly = true, spongePermission = "mcclans.admin.spy")
public void adminSpyCommand(CommandSource commandSource, ClanPlayerImpl clanPlayer, @Parameter(name = "toggle") Toggle toggle) {
if (toggle.getBoolean(clanPlayer.isSpy())) {
Messages.sendBasicMessage(commandSource, Messages.YOU_ARE_NOW_SPYING_ON_ALL_CLAN_CHATS);
clanPlayer.setSpy(true);
} else {
Messages.sendBasicMessage(commandSource, Messages.YOU_HAVE_STOPPED_SPYING_ON_ALL_CLAN_CHATS);
clanPlayer.setSpy(false);
}
}
}
| |
/*
* Copyright 2014 Feedzai
*
* 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.feedzai.commons.sql.abstraction.ddl;
import com.feedzai.commons.sql.abstraction.dml.K;
import com.google.common.collect.ImmutableList;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* Represents a database entity.
*
* @author Rui Vilao (rui.vilao@feedzai.com)
* @since 2.0.0
*/
public class DbEntity implements Serializable {
/**
* The entity name.
*/
private final String name;
/**
* The columns that compose the entity.
*/
private final List<DbColumn> columns;
/**
* The list of foreign keys.
*/
private final List<DbFk> fks;
/**
* The list of fields that compose the primary key.
*/
private final List<String> pkFields;
/**
* The list of indexes in the entity.
*/
private final List<DbIndex> indexes;
/**
* Creates a new instance of {@link DbEntity}.
*
* @param name The name of the entity.
* @param columns The column that compose the entity.
* @param fks The list of foreign keys.
* @param pkFields The list of fields that compose the primary key.
* @param indexes The list of indexes in the entity.
*/
protected DbEntity(String name, List<DbColumn> columns, List<DbFk> fks, List<String> pkFields, List<DbIndex> indexes) {
this.name = name;
this.columns = columns;
this.fks = fks;
this.pkFields = pkFields;
this.indexes = indexes;
}
/**
* Gets the name of the entity.
*
* @return The name of the entity.
*/
public String getName() {
return name;
}
/**
* Gets the list of columns of the entity.
*
* @return The list of columns of the entity.
*/
public List<DbColumn> getColumns() {
return columns;
}
/**
* Gets the immutable list of foreign keys.
*
* @return The immutable list of foreign keys.
*/
public List<DbFk> getFks() {
return fks;
}
/**
* Gets the immutable list of fields that compose the primary key.
*
* @return The immutable list of keys that compose the primary key.
*/
public List<String> getPkFields() {
return pkFields;
}
/**
* Gets the immutable list of indexes.
*
* @return The immutable list of indexes.
*/
public List<DbIndex> getIndexes() {
return indexes;
}
/**
* Checks if the given column is present in the list of columns.
*
* @param columnName The column name to check.
* @return {@code true} if the column is present in the list of columns, {@code false} otherwise.
*/
public boolean containsColumn(String columnName) {
return columns.stream()
.map(DbColumn::getName)
.anyMatch(listColName -> listColName.equals(columnName));
}
/**
* Returns a new builder out of the configuration.
*
* @return A new builder out of the configuration.
*/
public Builder newBuilder() {
return new Builder()
.name(name)
.addColumn(columns)
.addFk(fks)
.pkFields(pkFields)
.addIndexes(indexes);
}
/**
* Builder to create immutable {@link DbEntity} objects.
*/
public static class Builder implements com.feedzai.commons.sql.abstraction.util.Builder<DbEntity>, Serializable {
protected String name;
protected final List<DbColumn> columns = new ArrayList<>();
protected final List<DbFk> fks = new ArrayList<>();
protected final List<String> pkFields = new ArrayList<>();
protected final List<DbIndex> indexes = new ArrayList<>();
/**
* Sets the entity name.
*
* @param name The entity name.
* @return This builder.
*/
public Builder name(final String name) {
this.name = name;
return this;
}
/**
* Adds a column to the entity.
*
* @param dbColumn The column to add.
* @return This builder.
*/
public Builder addColumn(final DbColumn dbColumn) {
this.columns.add(dbColumn);
return this;
}
/**
* Removes the column with the given name.
*
* @param name The column name to remove.
* @return This builder.
*/
public Builder removeColumn(final String name) {
final Iterator<DbColumn> iterator = columns.iterator();
while (iterator.hasNext()) {
final DbColumn next = iterator.next();
if (next.getName().equals(name)) {
iterator.remove();
return this;
}
}
return this;
}
/**
* Adds the columns to the entity.
*
* @param dbColumn The columns to add.
* @return This builder.
*/
public Builder addColumn(final Collection<DbColumn> dbColumn) {
this.columns.addAll(dbColumn);
return this;
}
/**
* Adds a column to the entity.
*
* @param name The entity name.
* @param type The entity type.
* @param constraints The list of constraints.
* @return This builder.
*/
public Builder addColumn(final String name, final DbColumnType type, final DbColumnConstraint... constraints) {
addColumn(new DbColumn.Builder()
.name(name)
.addConstraints(constraints)
.type(type)
.build());
return this;
}
/**
* Adds a column to the entity.
*
* @param name The entity name.
* @param type The entity type.
* @param size The type size.
* @param constraints The list of constraints.
* @return This builder.
*/
public Builder addColumn(final String name, final DbColumnType type, final Integer size, final DbColumnConstraint... constraints) {
addColumn(new DbColumn.Builder()
.name(name)
.addConstraints(constraints)
.type(type)
.size(size)
.build());
return this;
}
/**
* Adds a column to the entity.
*
* @param name The entity name.
* @param type The entity type.
* @param autoInc {@code true} if the column is to autoincrement, {@code false} otherwise.
* @param constraints The list of constraints.
* @return This builder.
*/
public Builder addColumn(final String name, final DbColumnType type, final boolean autoInc, final DbColumnConstraint... constraints) {
addColumn(new DbColumn.Builder()
.name(name)
.addConstraints(constraints)
.type(type)
.autoInc(autoInc)
.build());
return this;
}
/**
* Adds a column to the entity.
*
* @param name The entity name.
* @param type The entity type.
* @param defaultValue The defaultValue for the column.
* @param constraints The list of constraints.
* @return This builder.
*/
public Builder addColumn(final String name, final DbColumnType type, final K defaultValue, final DbColumnConstraint... constraints) {
addColumn(new DbColumn.Builder()
.name(name)
.addConstraints(constraints)
.type(type)
.defaultValue(defaultValue)
.build());
return this;
}
/**
* Adds a column to the entity.
*
* @param name The entity name.
* @param type The entity type.
* @param size The type size.
* @param autoInc True if the column is to autoincrement, false otherwise.
* @param constraints The list of constraints.
* @return This builder.
*/
public Builder addColumn(final String name, final DbColumnType type, final Integer size, final boolean autoInc, final DbColumnConstraint... constraints) {
addColumn(new DbColumn.Builder()
.name(name)
.addConstraints(constraints)
.type(type).autoInc(autoInc)
.size(size)
.build());
return this;
}
/**
* Sets the PK fields.
*
* @param pkFields The PK fields.
* @return This builder.
*/
public Builder pkFields(final String... pkFields) {
return pkFields(Arrays.asList(pkFields));
}
/**
* Sets the PK fields.
*
* @param pkFields The PK fields.
* @return This builder.
*/
public Builder pkFields(final Collection<String> pkFields) {
this.pkFields.addAll(pkFields);
return this;
}
/**
* Adds an index.
*
* @param index The index.
* @return This builder.
*/
public Builder addIndex(final DbIndex index) {
this.indexes.add(index);
return this;
}
/**
* Adds an index.
*
* @param indexes The index.
* @return This builder.
*/
public Builder addIndexes(final Collection<DbIndex> indexes) {
this.indexes.addAll(indexes);
return this;
}
/**
* Adds an index.
*
* @param unique {@code true} if the index is unique, {@code false} otherwise.
* @param columns The columns that are part of the index.
* @return This builder.
*/
public Builder addIndex(final boolean unique, final String... columns) {
return addIndex(new DbIndex.Builder().columns(columns).unique(unique).build());
}
/**
* Adds an index.
*
* @param columns The columns that are part of the index.
* @return This builder.
*/
public Builder addIndex(final String... columns) {
return addIndex(false, columns);
}
/**
* Adds an index.
*
* @param columns The columns that are part of the index.
* @return This builder.
*/
public Builder addIndex(final Collection<String> columns) {
addIndex(new DbIndex.Builder().columns(columns).build());
return this;
}
/**
* Adds the FKs.
*
* @param fks The list of FKs.
* @return This builder.
*/
public Builder addFk(final DbFk... fks) {
return addFk(Arrays.asList(fks));
}
/**
* Adds the FKs.
*
* @param fks The list FKs builders..
* @return This builder.
*/
public Builder addFk(final DbFk.Builder... fks) {
for (DbFk.Builder fk : fks) {
addFk(fk.build());
}
return this;
}
/**
* Adds the FKs.
*
* @param fks The list of FKs.
* @return This builder.
*/
public Builder addFk(final Collection<DbFk> fks) {
this.fks.addAll(fks);
return this;
}
/**
* Clears all the FKs in this builder.
*
* @return This builder.
*/
public Builder clearFks() {
this.fks.clear();
return this;
}
/**
* Adds the FKs.
*
* @param fks The list of FKs.
* @return This object.
*/
public Builder addFks(final Collection<DbFk> fks) {
this.fks.addAll(fks);
return this;
}
@Override
public DbEntity build() {
return new DbEntity(
name,
ImmutableList.copyOf(columns),
ImmutableList.copyOf(fks),
ImmutableList.copyOf(pkFields),
ImmutableList.copyOf(indexes));
}
}
}
| |
package ruleml.translator.drl2ruleml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonToken;
import org.antlr.runtime.CommonTokenStream;
import org.drools.rule.builder.dialect.java.parser.JavaLexer;
import org.drools.core.util.StringUtils;
import reactionruleml.AtomType;
import reactionruleml.IndType;
import reactionruleml.OidType;
import reactionruleml.RelType;
import reactionruleml.SlotType;
import ruleml.translator.drl2ruleml.VariableBindingsManager.PropertyInfo;
import ruleml.translator.drl2ruleml.VariableBindingsManager.PropertyInfo.ValueType;
/**
* Analyzer for the THEN-Part of a drools rule.
*
* @author jabarski
*/
public class ThenPartAnalyzer {
// reference to the whenPartAnalyszer for the current rule
private WhenPartAnalyzer whenPartAnalyzer;
/**
* Constructor
*/
public ThenPartAnalyzer(WhenPartAnalyzer whenPartAnalyzer) {
this.whenPartAnalyzer = whenPartAnalyzer;
}
JAXBElement<?>[] processThenPart(String consequence) {
try {
// split on the EOL to check the number of lines
String[] parts = consequence.split("\n");
JAXBElement<?>[] thenParts = new JAXBElement<?>[parts.length];
// if (consequence.contains("insert")) {
// for (int i = 0; i < thenParts.length; i++) {
// JAXBElement<?> insert = createInsert(parts[i]);
// thenParts[i] = Drools2RuleMLTranslator.builder
// .createAssert(new JAXBElement<?>[] { insert });
// }
//
// } else if (consequence.contains("retract")) {
// for (int i = 0; i < thenParts.length; i++) {
// JAXBElement<?> retract = createRetract(parts[i]);
// thenParts[i] = Drools2RuleMLTranslator.builder
// .createRetract(new JAXBElement<?>[] { retract });
// }
// } else {
// throw new IllegalStateException(
// "Can not process the then part because it is not an insert or retract");
// }
return thenParts;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* Creates retract from the consequence part
*
* @param retract
* The line from the then part of a rule that contains retract.
* @return RetractType element
*/
private JAXBElement<?> createRetract(String retract) {
List<CommonToken> tokens = getTokensFromThenPart(retract);
if (tokens.size() != 1) {
throw new RuntimeException(
"The retract statement in the Then-part does not match the pattern: retract ($Var)");
}
JAXBElement<OidType> oid = Drools2RuleMLTranslator.builder
.createOid(tokens.get(0).getText());
return Drools2RuleMLTranslator.builder
.createAtom(new JAXBElement<?>[] { oid });
}
/**
* Creates insert from the consequence part
*
* @param insert
* The line from the then part of a rule that contains insert
* @return AssertType element
*/
private JAXBElement<?> createInsert(String insert)
throws ClassNotFoundException {
// get the data from consequence insert
List<CommonToken> dataFromInsert = getTokensFromThenPart(insert);
// get the name of the relation
String relName = "";
if (dataFromInsert.size() == 0) {
throw new IllegalStateException(
"The insert does not contain data: " + insert);
} else {
relName = dataFromInsert.get(0).getText();
dataFromInsert.remove(0);
}
// get the properties of the relation from the java class
if (StringUtils.isEmpty(relName)) {
throw new IllegalStateException("The relation name is empty: "
+ relName);
} else {
Class<?> clazz = Class.forName("ruleml.translator.TestDataModel$"
+ relName);
List<String> classProperties = Drools2RuleMLTranslator
.getPropertiesFromClass(clazz);
if (dataFromInsert.size() != classProperties.size()) {
System.out
.printf("Warning : the relation properties count %s does not coincide with arguments found in the counstructor:"
+ classProperties, insert);
}
// create the list with elements, the content of the atom relation
List<JAXBElement<?>> jaxbElements = new ArrayList<JAXBElement<?>>();
RelType relType = Drools2RuleMLTranslator.builder
.createRel(relName);
jaxbElements.add(Drools2RuleMLTranslator.builder.createOp(relType));
// iterate over the class properties
for (int i = 0; i < classProperties.size(); i++) {
// get the slot name
JAXBElement<IndType> slotName = Drools2RuleMLTranslator.builder
.createInd(classProperties.get(i));
// get the slot value
JAXBElement<?> slotValue = getSlotValue(dataFromInsert.get(i)
.getText());
// create slot
JAXBElement<SlotType> slot = Drools2RuleMLTranslator.builder
.createSlot(slotName, slotValue);
jaxbElements.add(slot);
}
// create atom
JAXBElement<AtomType> atom = Drools2RuleMLTranslator.builder
.createAtom(jaxbElements
.toArray(new JAXBElement<?>[jaxbElements.size()]));
return atom;
}
}
/**
* Creates slot from the given value.
*
* @param value
* The value of the field in slot.
* @return SlotType element.
*/
private JAXBElement<?> getSlotValue(String value) {
// set the slot value
JAXBElement<?> slotValue = null;
PropertyInfo propertyInfo = whenPartAnalyzer.getBindingsManager().get(
value);
if (propertyInfo == null) {
// value is a constant
value = value.replace("\"", "");
slotValue = Drools2RuleMLTranslator.builder.createInd(value);
} else {
if (propertyInfo.getType().equals(ValueType.IND)) {
slotValue = Drools2RuleMLTranslator.builder
.createInd(propertyInfo.getValue());
} else {
slotValue = Drools2RuleMLTranslator.builder
.createVar(propertyInfo.getVar());
}
}
return slotValue;
}
/**
* Parses the insert part and returns the java parts.
*
* @param insert
* The line from the then part of a rule that contains insert
* @return List with tha java tokens.
*/
private List<CommonToken> getTokensFromThenPart(String insert) {
List<CommonToken> result = new ArrayList<CommonToken>();
return result;
// try {
// CharStream cs = new ANTLRStringStream(insert);
// JavaLexer lexer = new JavaLexer(cs);
//
// CommonTokenStream tokens = new CommonTokenStream();
// tokens.setTokenSource(lexer);
//
// for (Object o : tokens.getTokens()) {
// CommonToken token = (CommonToken) o;
//
// if (token.getType() == 4 || token.getType() == 8) {
// result.add(token);
// }
// }
//
// // remove the insert or retract
// result.remove(0);
//
// return result;
// } catch (Exception e) {
// throw new IllegalStateException(
// "Error: Could not parse the then part of the drolls source", e);
// }
}
}
| |
/**
* 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.hadoop.hdfs.server.namenode.bookkeeper;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.server.common.HdfsConstants;
import org.apache.hadoop.hdfs.server.common.HdfsConstants.Transition;
import org.apache.hadoop.hdfs.server.namenode.EditLogFileInputStream;
import org.apache.hadoop.hdfs.server.namenode.EditLogFileOutputStream;
import org.apache.hadoop.hdfs.server.namenode.EditLogInputStream;
import org.apache.hadoop.hdfs.server.namenode.EditLogOutputStream;
import org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader;
import org.apache.hadoop.hdfs.server.namenode.FSEditLogTestUtil;
import org.apache.hadoop.hdfs.server.namenode.JournalManager;
import org.apache.hadoop.hdfs.server.namenode.JournalSet;
import org.apache.hadoop.hdfs.server.namenode.bookkeeper.metadata.EditLogLedgerMetadata;
import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;
import org.apache.hadoop.hdfs.util.InjectionEvent;
import org.apache.hadoop.util.InjectionEventI;
import org.apache.hadoop.util.InjectionHandler;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
public class TestBookKeeperJournalManager extends BookKeeperSetupUtil {
private static final Log LOG =
LogFactory.getLog(TestBookKeeperJournalManager.class);
private Configuration conf;
private BookKeeperJournalManager bkjm;
/**
* Initialize a BookKeeperJournalManager instance and format the namespace
* @param testName Name of the test
*/
private void setupTest(String testName) throws IOException {
conf = new Configuration();
NamespaceInfo nsi = new NamespaceInfo();
bkjm = new BookKeeperJournalManager(conf, createJournalURI(testName),
new NamespaceInfo(), null);
bkjm.transitionJournal(nsi, Transition.FORMAT, null);
}
@Test
public void testHasSomeData() throws Exception {
setupTest("test-has-some-data");
assertTrue("hasSomeData() returns true after initialization",
bkjm.hasSomeJournalData());
zkDeleteRecursively(bkjm.zkParentPath);
assertFalse("hasSomeData() returns false when zooKeeper data is empty",
bkjm.hasSomeJournalData());
}
@Test
public void testGetNumberOfTransactions() throws Exception {
setupTest("test-get-number-of-transactions");
EditLogOutputStream eos = bkjm.startLogSegment(1);
FSEditLogTestUtil.populateStreams(1, 100, eos);
bkjm.finalizeLogSegment(1, 100);
assertEquals(
"getNumberOfTransactions() is correct with a finalized log segment",
100, FSEditLogTestUtil.getNumberOfTransactions(bkjm, 1, false, true));
eos = bkjm.startLogSegment(101);
FSEditLogTestUtil.populateStreams(101, 150, eos);
assertEquals(
"getNumberOfTransactions() is correct with an in-progress log segment",
50, FSEditLogTestUtil.getNumberOfTransactions(bkjm, 101, true, true));
}
@Test
public void testGetInputStreamWithValidation() throws Exception {
setupTest("test-get-input-stream-with-validation");
File tempEditsFile = FSEditLogTestUtil.createTempEditsFile(
"test-get-input-stream-with-validation");
try {
TestBKJMInjectionHandler h = new TestBKJMInjectionHandler();
InjectionHandler.set(h);
EditLogOutputStream bkeos = bkjm.startLogSegment(1);
EditLogOutputStream elfos =
new EditLogFileOutputStream(tempEditsFile, null);
elfos.create();
FSEditLogTestUtil.populateStreams(1, 100, bkeos, elfos);
EditLogInputStream bkeis =
FSEditLogTestUtil.getJournalInputStream(bkjm, 1, true);
EditLogInputStream elfis = new EditLogFileInputStream(tempEditsFile);
Map<String, EditLogInputStream> streamByName =
ImmutableMap.of("BookKeeper", bkeis, "File", elfis);
FSEditLogTestUtil.assertStreamsAreEquivalent(100, streamByName);
assertNotNull("Log was validated", h.logValidation);
assertEquals("numTrasactions validated correctly",
100, h.logValidation.getNumTransactions());
assertEquals("endTxId validated correctly",
100, h.logValidation.getEndTxId());
} finally {
if (!tempEditsFile.delete()) {
LOG.warn("Unable to delete edits file: " +
tempEditsFile.getAbsolutePath());
}
}
}
@Test
public void testGetInputStreamNoValidationNoCheckLastTxId() throws Exception {
setupTest("test-get-input-stream-no-validation-no-check-last-txid");
File tempEditsFile = FSEditLogTestUtil.createTempEditsFile(
"test-get-input-stream-with-validation");
try {
EditLogOutputStream bkeos = bkjm.startLogSegment(1);
EditLogOutputStream elfos =
new EditLogFileOutputStream(tempEditsFile, null);
elfos.create();
FSEditLogTestUtil.populateStreams(1, 100, bkeos, elfos);
EditLogInputStream bkeis =
getJournalInputStreamDontCheckLastTxId(bkjm, 1);
EditLogInputStream elfis = new EditLogFileInputStream(tempEditsFile);
Map<String, EditLogInputStream> streamByName =
ImmutableMap.of("BookKeeper", bkeis, "File", elfis);
FSEditLogTestUtil.assertStreamsAreEquivalent(100, streamByName);
} finally {
if (!tempEditsFile.delete()) {
LOG.warn("Unable to delete edits file: " +
tempEditsFile.getAbsolutePath());
}
}
}
@Test
public void testRecoverUnfinalizedSegmentsEmptySegment() throws Exception {
setupTest("test-recover-unfinalized-segments-empty-segment");
TestBKJMInjectionHandler h = new TestBKJMInjectionHandler();
InjectionHandler.set(h);
bkjm.startLogSegment(1);
assertEquals("Ledger created for segment with firstTxId " + 1,
h.ledgerForStartedSegment.getFirstTxId(), 1);
bkjm.currentInProgressPath = null;
bkjm.recoverUnfinalizedSegments();
String ledgerPath = bkjm.metadataManager.fullyQualifiedPathForLedger(
h.ledgerForStartedSegment);
assertFalse("Zero length ledger was deleted from " + ledgerPath,
bkjm.metadataManager.ledgerExists(ledgerPath));
}
@Test
public void testRecoverUnfinalizedSegments() throws Exception {
setupTest("test-recover-unfinalized-segments");
TestBKJMInjectionHandler h = new TestBKJMInjectionHandler();
InjectionHandler.set(h);
EditLogOutputStream eos = bkjm.startLogSegment(1);
FSEditLogTestUtil.populateStreams(1, 100, eos);
bkjm.currentInProgressPath = null;
bkjm.recoverUnfinalizedSegments();
Collection<EditLogLedgerMetadata> ledgers =
bkjm.metadataManager.listLedgers(true);
assertEquals("Only one ledger must remain", 1, ledgers.size());
EditLogLedgerMetadata ledger = ledgers.iterator().next();
assertEquals("Ledger must be finalized with correct lastTxId",
ledger.getLastTxId(), 100);
assertEquals("Finalized ledger's ledgerId must match created ledger's id",
ledger.getLedgerId(), h.ledgerForStartedSegment.getLedgerId());
assertEquals("Finalized ledger's firstTxId", ledger.getFirstTxId(),
h.ledgerForStartedSegment.getFirstTxId());
}
static EditLogInputStream getJournalInputStreamDontCheckLastTxId(
JournalManager jm, long txId) throws IOException {
List<EditLogInputStream> streams = new ArrayList<EditLogInputStream>();
jm.selectInputStreams(streams, txId, true, false);
if (streams.size() < 1) {
throw new IOException("Cannot obtain stream for txid: " + txId);
}
Collections.sort(streams, JournalSet.EDIT_LOG_INPUT_STREAM_COMPARATOR);
if (txId == HdfsConstants.INVALID_TXID) {
return streams.get(0);
}
for (EditLogInputStream elis : streams) {
if (elis.getFirstTxId() == txId) {
return elis;
}
}
throw new IOException("Cannot obtain stream for txid: " + txId);
}
class TestBKJMInjectionHandler extends InjectionHandler {
EditLogLedgerMetadata ledgerForStartedSegment;
FSEditLogLoader.EditLogValidation logValidation;
@Override
protected void _processEvent(InjectionEventI event, Object... args) {
if (event == InjectionEvent.BKJM_STARTLOGSEGMENT) {
ledgerForStartedSegment = (EditLogLedgerMetadata) args[0];
} else if (event == InjectionEvent.BKJM_VALIDATELOGSEGMENT) {
logValidation = (FSEditLogLoader.EditLogValidation) args[0];
}
}
}
}
| |
package com.janith.weatherapp;
import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.janith.weatherapp.controller.FetchData;
import com.janith.weatherapp.controller.Utilities;
import com.janith.weatherapp.model.CityForecast;
import com.janith.weatherapp.model.Forecast;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements
CityListFragment.OnCitySelectedListener {
private Forecast forecast;
public String jsonStr;
private CityListFragment cityListFragment = null;
private DetailFragment detailFragment = null;
private URL weatherApiUrl;
private Intent intent;
public final static String FORECAST = "com.janith.weatherapp.FORECAST";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Utilities.isTab(this)){
tabletConfig();
} else {
handsetConfig();
}
getPermissions();
FetchData fetcher = new FetchData();
fetcher.setActivity(this);
try {
weatherApiUrl = new URL("http://api.openweathermap.org/data/2.5/group?id=1248991,1246294," +
"1241622,1235846,1231410,1241964,1244178,1251574,1237980,1226260,1242833&" +
"units=metric&appid=3b2fb05205935454966162c87c9e77e3");
fetcher.execute(weatherApiUrl);
} catch (MalformedURLException e) {
Log.d("URL Error", "Weather API URL is malformed");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.preferences, menu);
return true;
}
@Override
public void onCitySelected(int position) {
TextView detailTextView = null;
if (Utilities.isTab) {
detailTextView = (TextView) findViewById(R.id.detail_field);
}
String[] citiesList = getResources().getStringArray(R.array.cities_list);
String city = citiesList[position];
if(jsonStr == null || jsonStr.isEmpty()){
showToast("Weather Data Acquiring Failed!");
}
if (detailTextView != null){
detailTextView.setText(null);
if(forecast!=null){
CityForecast cityForecast = forecast.getCityForcast(city);
detailTextView.setText(cityForecast.getForcastString());
}
}
if(!Utilities.isTab){
if(forecast!=null & intent!=null) {
CityForecast cityForecast = forecast.getCityForcast(city);
// showDetailFragment(cityForecast.getForecastString());
intent.putExtra(FORECAST, cityForecast.getForcastString());
startActivity(intent);
}
}
}
private void tabletConfig(){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
FrameLayout detailFrame = (FrameLayout) findViewById(R.id.list_container);
detailFrame.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1));
if (detailFragment == null) {
detailFragment = new DetailFragment();
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, detailFragment);
transaction.setTransition(FragmentTransaction.TRANSIT_NONE);
transaction.commit();
if (cityListFragment == null) {
cityListFragment = new CityListFragment();
}
FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction();
transaction2.replace(R.id.list_container, cityListFragment);
transaction2.setTransition(FragmentTransaction.TRANSIT_NONE);
transaction2.commit();
}
private void handsetConfig() {
if (cityListFragment == null) {
cityListFragment = new CityListFragment();
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.list_container, cityListFragment);
transaction.setTransition(FragmentTransaction.TRANSIT_NONE);
transaction.commit();
intent = new Intent(this, DetailActivity.class);
}
//--------------------- Not used anymore. A new activity is used instead -----------------------
/*
private void showDetailFragment(String msg) {
FrameLayout detailFrame = (FrameLayout) findViewById(R.id.list_container);
detailFrame.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 0));
if (detailFragment == null) {
detailFragment = new DetailFragment();
}
detailFragment.msg = msg;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.list_container, detailFragment);
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_NONE);
transaction.commit();
}
*/
//----------------------------------------------------------------------------------------------
private void getPermissions() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.INTERNET)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.INTERNET},10);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.INTERNET},10);
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (forecast != null) {
outState.putSerializable("forecast", forecast);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
forecast = (Forecast) savedInstanceState.getSerializable("forecast");
}
public void showToast(String message) {
Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
toast.show();
}
public void dataAcquired(String jsonString) {
if (jsonString != null) {
jsonStr = jsonString;
showToast("Weather Data Acquired");
forecast = Utilities.parseJson(jsonString);
} else {
showToast("JSON Acquire Failed");
}
}
}
| |
/*
* 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.tinkerpop.gremlin.process.traversal.step.map;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
import org.apache.tinkerpop.gremlin.process.traversal.step.ByModulating;
import org.apache.tinkerpop.gremlin.process.traversal.step.Configuring;
import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Parameters;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.WithOptions;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalRing;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalUtil;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.PropertyType;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
* @author Daniel Kuppitz (http://gremlin.guru)
*/
public class PropertyMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>>
implements TraversalParent, ByModulating, Configuring {
protected final String[] propertyKeys;
protected final PropertyType returnType;
protected int tokens;
protected Traversal.Admin<Element, ? extends Property> propertyTraversal;
private Parameters parameters = new Parameters();
private TraversalRing<K, E> traversalRing;
public PropertyMapStep(final Traversal.Admin traversal, final PropertyType propertyType, final String... propertyKeys) {
super(traversal);
this.propertyKeys = propertyKeys;
this.returnType = propertyType;
this.propertyTraversal = null;
this.traversalRing = new TraversalRing<>();
}
public PropertyMapStep(final Traversal.Admin traversal, final int options, final PropertyType propertyType, final String... propertyKeys) {
this(traversal, propertyType, propertyKeys);
this.configure(WithOptions.tokens, options);
}
@Override
protected Map<K, E> map(final Traverser.Admin<Element> traverser) {
final Map<Object, Object> map = new LinkedHashMap<>();
final Element element = traverser.get();
final boolean isVertex = element instanceof Vertex;
if (this.returnType == PropertyType.VALUE) {
if (includeToken(WithOptions.ids)) map.put(T.id, element.id());
if (element instanceof VertexProperty) {
if (includeToken(WithOptions.keys)) map.put(T.key, ((VertexProperty<?>) element).key());
if (includeToken(WithOptions.values)) map.put(T.value, ((VertexProperty<?>) element).value());
} else {
if (includeToken(WithOptions.labels)) map.put(T.label, element.label());
}
}
final Iterator<? extends Property> properties = null == this.propertyTraversal ?
element.properties(this.propertyKeys) :
TraversalUtil.applyAll(traverser, this.propertyTraversal);
//final Iterator<? extends Property> properties = element.properties(this.propertyKeys);
while (properties.hasNext()) {
final Property<?> property = properties.next();
final Object value = this.returnType == PropertyType.VALUE ? property.value() : property;
if (isVertex) {
map.compute(property.key(), (k, v) -> {
final List<Object> values = v != null ? (List<Object>) v : new ArrayList<>();
values.add(value);
return values;
});
} else {
map.put(property.key(), value);
}
}
if (!traversalRing.isEmpty()) {
for (final Object key : map.keySet()) {
map.compute(key, (k, v) -> TraversalUtil.applyNullable(v, (Traversal.Admin) this.traversalRing.next()));
}
this.traversalRing.reset();
}
return (Map) map;
}
@Override
public void configure(final Object... keyValues) {
if (keyValues[0].equals(WithOptions.tokens)) {
if (keyValues.length == 2 && keyValues[1] instanceof Boolean) {
this.tokens = ((boolean) keyValues[1]) ? WithOptions.all : WithOptions.none;
} else {
for (int i = 1; i < keyValues.length; i++) {
if (!(keyValues[i] instanceof Integer))
throw new IllegalArgumentException("WithOptions.tokens requires Integer arguments (possible " + "" +
"values are: WithOptions.[none|ids|labels|keys|values|all])");
this.tokens |= (int) keyValues[i];
}
}
} else {
this.parameters.set(this, keyValues);
}
}
@Override
public Parameters getParameters() {
return parameters;
}
@Override
public List<Traversal.Admin<K, E>> getLocalChildren() {
final List<Traversal.Admin<K, E>> result = new ArrayList<>();
if (null != this.propertyTraversal)
result.add((Traversal.Admin) propertyTraversal);
result.addAll(this.traversalRing.getTraversals());
return Collections.unmodifiableList(result);
}
@Override
public void modulateBy(final Traversal.Admin<?, ?> selectTraversal) {
this.traversalRing.addTraversal(this.integrateChild(selectTraversal));
}
public void setPropertyTraversal(final Traversal.Admin<Element, ? extends Property> propertyTraversal) {
this.propertyTraversal = this.integrateChild(propertyTraversal);
}
public PropertyType getReturnType() {
return this.returnType;
}
public String[] getPropertyKeys() {
return propertyKeys;
}
public String toString() {
return StringFactory.stepString(this, Arrays.asList(this.propertyKeys),
this.traversalRing, this.returnType.name().toLowerCase());
}
@Override
public PropertyMapStep<K,E> clone() {
final PropertyMapStep<K,E> clone = (PropertyMapStep<K,E>) super.clone();
if (null != this.propertyTraversal)
clone.propertyTraversal = this.propertyTraversal.clone();
clone.traversalRing = this.traversalRing.clone();
return clone;
}
@Override
public int hashCode() {
int result = super.hashCode() ^ this.returnType.hashCode() ^ Integer.hashCode(this.tokens);
if (null != this.propertyTraversal)
result ^= this.propertyTraversal.hashCode();
for (final String propertyKey : this.propertyKeys) {
result ^= propertyKey.hashCode();
}
return result ^ this.traversalRing.hashCode();
}
@Override
public void setTraversal(final Traversal.Admin<?, ?> parentTraversal) {
super.setTraversal(parentTraversal);
if (null != this.propertyTraversal)
this.integrateChild(this.propertyTraversal);
this.traversalRing.getTraversals().forEach(this::integrateChild);
}
@Override
public Set<TraverserRequirement> getRequirements() {
return this.getSelfAndChildRequirements(TraverserRequirement.OBJECT);
}
public int getIncludedTokens() {
return this.tokens;
}
private boolean includeToken(final int token) {
return 0 != (this.tokens & token);
}
}
| |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content.browser.input;
import android.view.View;
import com.google.common.annotations.VisibleForTesting;
/**
* CursorController for selecting a range of text.
*/
public abstract class SelectionHandleController implements CursorController {
// The following constants match the ones in
// third_party/WebKit/public/web/WebTextDirection.h
private static final int TEXT_DIRECTION_DEFAULT = 0;
private static final int TEXT_DIRECTION_LTR = 1;
private static final int TEXT_DIRECTION_RTL = 2;
/** The cursor controller images, lazily created when shown. */
private HandleView mStartHandle, mEndHandle;
/** Whether handles should show automatically when text is selected. */
private boolean mAllowAutomaticShowing = true;
/** Whether selection anchors are active. */
private boolean mIsShowing;
private View mParent;
private int mFixedHandleX;
private int mFixedHandleY;
public SelectionHandleController(View parent) {
mParent = parent;
}
/** Automatically show selection anchors when text is selected. */
public void allowAutomaticShowing() {
mAllowAutomaticShowing = true;
}
/** Hide selection anchors, and don't automatically show them. */
public void hideAndDisallowAutomaticShowing() {
hide();
mAllowAutomaticShowing = false;
}
@Override
public boolean isShowing() {
return mIsShowing;
}
@Override
public void hide() {
if (mIsShowing) {
if (mStartHandle != null) mStartHandle.hide();
if (mEndHandle != null) mEndHandle.hide();
mIsShowing = false;
}
}
void cancelFadeOutAnimation() {
hide();
}
/**
* Updates the selection for a movement of the given handle (which
* should be the start handle or end handle) to coordinates x,y.
* Note that this will not actually result in the handle moving to (x,y):
* selectBetweenCoordinates(x1,y1,x2,y2) will trigger the selection and set the
* actual coordinates later via set[Start|End]HandlePosition.
*/
@Override
public void updatePosition(HandleView handle, int x, int y) {
selectBetweenCoordinates(mFixedHandleX, mFixedHandleY, x, y);
}
@Override
public void beforeStartUpdatingPosition(HandleView handle) {
HandleView fixedHandle = (handle == mStartHandle) ? mEndHandle : mStartHandle;
mFixedHandleX = fixedHandle.getAdjustedPositionX();
mFixedHandleY = fixedHandle.getLineAdjustedPositionY();
}
/**
* The concrete implementation must trigger a selection between the given
* coordinates and (possibly asynchronously) set the actual handle positions
* after the selection is made via set[Start|End]HandlePosition.
*/
protected abstract void selectBetweenCoordinates(int x1, int y1, int x2, int y2);
/**
* @return true iff this controller is being used to move the selection start.
*/
boolean isSelectionStartDragged() {
return mStartHandle != null && mStartHandle.isDragging();
}
/**
* @return true iff this controller is being used to drag either the selection start or end.
*/
public boolean isDragging() {
return (mStartHandle != null && mStartHandle.isDragging()) ||
(mEndHandle != null && mEndHandle.isDragging());
}
@Override
public void onTouchModeChanged(boolean isInTouchMode) {
if (!isInTouchMode) {
hide();
}
}
@Override
public void onDetached() {}
/**
* Moves the start handle so that it points at the given coordinates.
* @param x The start handle position X in physical pixels.
* @param y The start handle position Y in physical pixels.
*/
public void setStartHandlePosition(float x, float y) {
mStartHandle.positionAt((int) x, (int) y);
}
/**
* Moves the end handle so that it points at the given coordinates.
* @param x The end handle position X in physical pixels.
* @param y The end handle position Y in physical pixels.
*/
public void setEndHandlePosition(float x, float y) {
mEndHandle.positionAt((int) x, (int) y);
}
/**
* If the handles are not visible, sets their visibility to View.VISIBLE and begins fading them
* in.
*/
public void beginHandleFadeIn() {
mStartHandle.beginFadeIn();
mEndHandle.beginFadeIn();
}
/**
* Sets the start and end handles to the given visibility.
*/
public void setHandleVisibility(int visibility) {
mStartHandle.setVisibility(visibility);
mEndHandle.setVisibility(visibility);
}
/**
* Shows the handles if allowed.
*
* @param startDir Direction (left/right) of start handle.
* @param endDir Direction (left/right) of end handle.
*/
public void onSelectionChanged(int startDir, int endDir) {
if (mAllowAutomaticShowing) {
showHandles(startDir, endDir);
}
}
/**
* Sets both start and end position and show the handles.
* Note: this method does not trigger a selection, see
* selectBetweenCoordinates()
*
* @param startDir Direction (left/right) of start handle.
* @param endDir Direction (left/right) of end handle.
*/
public void showHandles(int startDir, int endDir) {
createHandlesIfNeeded(startDir, endDir);
showHandlesIfNeeded();
}
@VisibleForTesting
public HandleView getStartHandleViewForTest() {
return mStartHandle;
}
@VisibleForTesting
public HandleView getEndHandleViewForTest() {
return mEndHandle;
}
private void createHandlesIfNeeded(int startDir, int endDir) {
if (mStartHandle == null) {
mStartHandle = new HandleView(this,
startDir == TEXT_DIRECTION_RTL ? HandleView.RIGHT : HandleView.LEFT, mParent);
}
if (mEndHandle == null) {
mEndHandle = new HandleView(this,
endDir == TEXT_DIRECTION_RTL ? HandleView.LEFT : HandleView.RIGHT, mParent);
}
}
private void showHandlesIfNeeded() {
if (!mIsShowing) {
mIsShowing = true;
mStartHandle.show();
mEndHandle.show();
setHandleVisibility(HandleView.VISIBLE);
}
}
}
| |
package com.dihanov.musiq.ui.main.mainfragments.favorites.album;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.dihanov.musiq.R;
import com.dihanov.musiq.data.repository.user.UserSettingsRepository;
import com.dihanov.musiq.models.Album;
import com.dihanov.musiq.ui.adapters.AbstractAdapter;
import com.dihanov.musiq.ui.adapters.AlbumDetailsAdapter;
import com.dihanov.musiq.ui.main.AlbumDetailsPopupWindowManager;
import com.dihanov.musiq.ui.main.MainActivity;
import com.dihanov.musiq.ui.main.mainfragments.ViewPagerCustomizedFragment;
import com.dihanov.musiq.util.FavoritesManager;
import com.dihanov.musiq.util.HelperMethods;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by dimitar.dihanov on 11/2/2017.
*/
public class FavoriteAlbums extends ViewPagerCustomizedFragment implements FavoriteAlbumsContract.View, AbstractAdapter.OnItemClickedListener<Album> {
public static final String TITLE = "favorite albums";
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
@Inject
FavoriteAlbumsContract.Presenter favoriteFragmentsPresenter;
@Inject
AlbumDetailsPopupWindowManager albumDetailsPopupWindowManager;
@Inject
UserSettingsRepository userSettingsRepository;
@Inject
FavoritesManager favoritesManager;
private MainActivity mainActivity;
public static FavoriteAlbums newInstance() {
Bundle args = new Bundle();
FavoriteAlbums albumResultFragment = new FavoriteAlbums();
albumResultFragment.setArguments(args);
return albumResultFragment;
}
public MainActivity getMainActivity() {
return mainActivity;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mainActivity = (MainActivity)getActivity();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.artist_search_fragment, container, false);
ButterKnife.bind(this, view);
//very important to call this - this enables us to use the below method(onCreateOptionsMenu), and allows us
//to receive calls from MainActivity's onCreateOptionsMenu
setHasOptionsMenu(true);
initRecyclerView();
this.favoriteFragmentsPresenter.takeView(this);
this.favoriteFragmentsPresenter.loadFavoriteAlbums(
userSettingsRepository.getSerializedFavoriteAlbums());
return view;
}
private void initRecyclerView() {
RecyclerView.LayoutManager layoutManager = null;
//check if tablet --> 3 columns instead of 2;
if (HelperMethods.isTablet(mainActivity)){
layoutManager = new GridLayoutManager(mainActivity, 3);
recyclerView.addItemDecoration(new FavoriteAlbums.GridSpacingItemDecoration(3, HelperMethods.dpToPx(10, mainActivity), true));
} else {
layoutManager = new GridLayoutManager(mainActivity, 2);
recyclerView.addItemDecoration(new FavoriteAlbums.GridSpacingItemDecoration(2, HelperMethods.dpToPx(10, mainActivity), true));
}
if(layoutManager == null){
return;
}
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(new AlbumDetailsAdapter(mainActivity,
new ArrayList<>(),
true, this,
userSettingsRepository.getFavoriteAlbums(), favoritesManager));
}
@Override
public Context getContext() {
return this.mainActivity;
}
@Override
public void onDestroy() {
super.onDestroy();
this.favoriteFragmentsPresenter.leaveView();
}
@Override
public void onResume() {
super.onResume();
//we need to refresh the artists just in case the user has modified the favorites
loadFavoriteAlbums(
userSettingsRepository.getSerializedFavoriteAlbums());
}
@Override
public void onItemClicked(Album item) {
favoriteFragmentsPresenter.fetchEntireAlbumInfo(item.getArtist().toString(), item.getName());
}
@Override
public void showProgressBar() {
mainActivity.showProgressBar();
}
@Override
public void showAlbumDetails(Album fullAlbum) {
albumDetailsPopupWindowManager.showAlbumDetails(mainActivity, fullAlbum);
}
@Override
public void hideProgressBar() {
mainActivity.hideProgressBar();
}
@Override
public void setArtistAlbumsList(List<Album> albums) {
((AlbumDetailsAdapter) recyclerView.getAdapter()).setArtistAlbumsList(albums);
}
private class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
private void loadFavoriteAlbums(Set<String> favorites) {
//resetting the adapter
recyclerView.setAdapter(new AlbumDetailsAdapter(this.mainActivity, new ArrayList<>(), true, this, userSettingsRepository.getFavoriteAlbums(), favoritesManager));
favoriteFragmentsPresenter.loadFavoriteAlbums(favorites);
}
}
| |
/*
* Entagged Audio Tag library
* Copyright (c) 2003-2005 Raphael Slinckx <raphael@slinckx.net>
* Copyright (c) 2004-2005 Christian Laireiter <liree@web.de>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jaudiotagger.audio.ogg;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.audio.ogg.util.OggCRCFactory;
import org.jaudiotagger.audio.ogg.util.OggPageHeader;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.vorbiscomment.VorbisCommentTag;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* Write Vorbis Tag within an ogg
* <p/>
* VorbisComment holds the tag information within an ogg file
*/
public class OggVorbisTagWriter {
// Logger Object
public static Logger logger = Logger.getLogger("org.jaudiotagger.audio.ogg");
private OggVorbisCommentTagCreator tc = new OggVorbisCommentTagCreator();
private OggVorbisTagReader reader = new OggVorbisTagReader();
public void delete(RandomAccessFile raf, RandomAccessFile tempRaf) throws IOException, CannotReadException, CannotWriteException {
try {
reader.read(raf);
} catch (CannotReadException e) {
write(VorbisCommentTag.createNewTag(), raf, tempRaf);
return;
}
VorbisCommentTag emptyTag = VorbisCommentTag.createNewTag();
//Go back to start of file
raf.seek(0);
write(emptyTag, raf, tempRaf);
}
public void write(Tag tag, RandomAccessFile raf, RandomAccessFile rafTemp) throws CannotReadException, CannotWriteException, IOException {
//logger.info("Starting to write file:");
//1st Page:Identification Header
//logger.fine("Read 1st Page:identificationHeader:");
OggPageHeader pageHeader = OggPageHeader.read(raf);
raf.seek(0);
//Write 1st page (unchanged) and place writer pointer at end of data
rafTemp.getChannel().transferFrom(raf.getChannel(), 0, pageHeader.getPageLength() + OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + pageHeader.getSegmentTable().length);
rafTemp.skipBytes(pageHeader.getPageLength() + OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + pageHeader.getSegmentTable().length);
//logger.fine("Written identificationHeader:");
//2nd page:Comment and Setup if there is enough room, may also (although not normally) contain audio frames
OggPageHeader secondPageHeader = OggPageHeader.read(raf);
//2nd Page:Store the end of Header
long secondPageHeaderEndPos = raf.getFilePointer();
//logger.fine("Read 2nd Page:comment and setup and possibly audio:Header finishes at file position:" + secondPageHeaderEndPos);
//Get header sizes
raf.seek(0);
OggVorbisTagReader.OggVorbisHeaderSizes vorbisHeaderSizes = reader.readOggVorbisHeaderSizes(raf);
//Convert the OggVorbisComment header to raw packet data
ByteBuffer newComment = tc.convert(tag);
//Compute new comment length(this may need to be spread over multiple pages)
int newCommentLength = newComment.capacity();
//Calculate new size of new 2nd page
int newSecondPageDataLength = vorbisHeaderSizes.getSetupHeaderSize() + newCommentLength + vorbisHeaderSizes.getExtraPacketDataSize();
//logger.fine("Old 2nd Page no of packets: " + secondPageHeader.getPacketList().size());
//logger.fine("Old 2nd Page size: " + secondPageHeader.getPageLength());
// logger.fine("Old last packet incomplete: " + secondPageHeader.isLastPacketIncomplete());
//logger.fine("Setup Header Size: " + vorbisHeaderSizes.getSetupHeaderSize());
// logger.fine("Extra Packets: " + vorbisHeaderSizes.getExtraPacketList().size());
//logger.fine("Extra Packet Size: " + vorbisHeaderSizes.getExtraPacketDataSize());
//logger.fine("Old comment: " + vorbisHeaderSizes.getCommentHeaderSize());
//logger.fine("New comment: " + newCommentLength);
//logger.fine("New Page Data Size: " + newSecondPageDataLength);
//Second Page containing new vorbis, setup and possibly some extra packets can fit on one page
if (isCommentAndSetupHeaderFitsOnASinglePage(newCommentLength, vorbisHeaderSizes.getSetupHeaderSize(), vorbisHeaderSizes.getExtraPacketList())) {
//And if comment and setup header originally fitted on both, the length of the 2nd
//page must be less than maximum size allowed
//AND
//there must be two packets with last being complete because they may have
//elected to split the setup over multiple pages instead of using up whole page - (as long
//as the last lacing value is 255 they can do this)
// OR
//There are more than the packets in which case have complete setup header and some audio packets
//we dont care if the last audio packet is split on next page as long as we preserve it
if ((secondPageHeader.getPageLength() < OggPageHeader.MAXIMUM_PAGE_DATA_SIZE) && (((secondPageHeader.getPacketList().size() == 2) && (!secondPageHeader.isLastPacketIncomplete())) || (secondPageHeader.getPacketList().size() > 2))) {
//logger.info("Header and Setup remain on single page:");
replaceSecondPageOnly(vorbisHeaderSizes, newCommentLength, newSecondPageDataLength, secondPageHeader, newComment, secondPageHeaderEndPos, raf, rafTemp);
}
//Original 2nd page spanned multiple pages so more work to do
else {
//logger.info("Header and Setup now on single page:");
replaceSecondPageAndRenumberPageSeqs(vorbisHeaderSizes, newCommentLength, newSecondPageDataLength, secondPageHeader, newComment, raf, rafTemp);
}
}
//Bit more complicated, have to create a load of new pages and renumber audio
else {
//logger.info("Header and Setup with shift audio:");
replacePagesAndRenumberPageSeqs(vorbisHeaderSizes, newCommentLength, secondPageHeader, newComment, raf, rafTemp);
}
}
/**
* Calculate checkSum over the Page
*
* @param page
*/
private void calculateChecksumOverPage(ByteBuffer page) {
//CRC should be zero before calculating it
page.putInt(OggPageHeader.FIELD_PAGE_CHECKSUM_POS, 0);
//Compute CRC over the page //TODO shouldnt really use array();
byte[] crc = OggCRCFactory.computeCRC(page.array());
for (int i = 0; i < crc.length; i++) {
page.put(OggPageHeader.FIELD_PAGE_CHECKSUM_POS + i, crc[i]);
}
//Rewind to start of Page
page.rewind();
}
/**
* Create a second Page, and add comment header to it, but page is incomplete may want to add addition header and need to calculate CRC
*
* @param vorbisHeaderSizes
* @param newCommentLength
* @param newSecondPageLength
* @param secondPageHeader
* @param newComment
* @return
* @throws IOException
*/
private ByteBuffer startCreateBasicSecondPage(
OggVorbisTagReader.OggVorbisHeaderSizes vorbisHeaderSizes,
int newCommentLength,
int newSecondPageLength,
OggPageHeader secondPageHeader,
ByteBuffer newComment) throws IOException {
// logger.fine("WriteOgg Type 1");
byte[] segmentTable = createSegmentTable(newCommentLength, vorbisHeaderSizes.getSetupHeaderSize(), vorbisHeaderSizes.getExtraPacketList());
int newSecondPageHeaderLength = OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + segmentTable.length;
// logger.fine("New second page header length:" + newSecondPageHeaderLength);
// logger.fine("No of segments:" + segmentTable.length);
ByteBuffer secondPageBuffer = ByteBuffer.allocate(newSecondPageLength + newSecondPageHeaderLength);
secondPageBuffer.order(ByteOrder.LITTLE_ENDIAN);
//Build the new 2nd page header, can mostly be taken from the original upto the segment length OggS capture
secondPageBuffer.put(secondPageHeader.getRawHeaderData(), 0, OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH - 1);
//Number of Page Segments
secondPageBuffer.put((byte) segmentTable.length);
//Page segment table
for (byte aSegmentTable : segmentTable) {
secondPageBuffer.put(aSegmentTable);
}
//Add New VorbisComment
secondPageBuffer.put(newComment);
return secondPageBuffer;
}
/**
* Usually can use this method, previously comment and setup header all fit on page 2
* and they still do, so just replace this page. And copy further pages as is.
*
* @param vorbisHeaderSizes
* @param newCommentLength
* @param newSecondPageLength
* @param secondPageHeader
* @param newComment
* @param secondPageHeaderEndPos
* @param raf
* @param rafTemp
* @throws IOException
*/
private void replaceSecondPageOnly(
OggVorbisTagReader.OggVorbisHeaderSizes vorbisHeaderSizes,
int newCommentLength,
int newSecondPageLength,
OggPageHeader secondPageHeader,
ByteBuffer newComment,
long secondPageHeaderEndPos,
RandomAccessFile raf,
RandomAccessFile rafTemp) throws IOException {
// logger.fine("WriteOgg Type 1");
ByteBuffer secondPageBuffer = startCreateBasicSecondPage(vorbisHeaderSizes, newCommentLength, newSecondPageLength, secondPageHeader, newComment);
raf.seek(secondPageHeaderEndPos);
//Skip comment header
raf.skipBytes(vorbisHeaderSizes.getCommentHeaderSize());
//Read in setup header and extra packets
raf.getChannel().read(secondPageBuffer);
calculateChecksumOverPage(secondPageBuffer);
rafTemp.getChannel().write(secondPageBuffer);
rafTemp.getChannel().transferFrom(raf.getChannel(), rafTemp.getFilePointer(), raf.length() - raf.getFilePointer());
}
/**
* Previously comment and/or setup header was on a number of pages now can just replace this page fitting all
* on 2nd page, and renumber subsequent sequence pages
*
* @param originalHeaderSizes
* @param newCommentLength
* @param newSecondPageLength
* @param secondPageHeader
* @param newComment
* @param raf
* @param rafTemp
* @throws IOException
* @throws org.jaudiotagger.audio.exceptions.CannotReadException
*
* @throws org.jaudiotagger.audio.exceptions.CannotWriteException
*
*/
private void replaceSecondPageAndRenumberPageSeqs(OggVorbisTagReader.OggVorbisHeaderSizes originalHeaderSizes, int newCommentLength, int newSecondPageLength, OggPageHeader secondPageHeader, ByteBuffer newComment, RandomAccessFile raf, RandomAccessFile rafTemp) throws IOException, CannotReadException, CannotWriteException {
// logger.fine("WriteOgg Type 2");
ByteBuffer secondPageBuffer = startCreateBasicSecondPage(originalHeaderSizes, newCommentLength, newSecondPageLength, secondPageHeader, newComment);
//Add setup header and packets
int pageSequence = secondPageHeader.getPageSequence();
byte[] setupHeaderData = reader.convertToVorbisSetupHeaderPacketAndAdditionalPackets(originalHeaderSizes.getSetupHeaderStartPosition(), raf);
// logger.finest(setupHeaderData.length + ":" + secondPageBuffer.position() + ":" + secondPageBuffer.capacity());
secondPageBuffer.put(setupHeaderData);
calculateChecksumOverPage(secondPageBuffer);
rafTemp.getChannel().write(secondPageBuffer);
writeRemainingPages(pageSequence, raf, rafTemp);
}
/**
* CommentHeader extends over multiple pages OR Comment Header doesnt but it's got larger causing some extra
* packets to be shifted onto another page.
*
* @param originalHeaderSizes
* @param newCommentLength
* @param secondPageHeader
* @param newComment
* @param raf
* @param rafTemp
* @throws IOException
* @throws CannotReadException
* @throws CannotWriteException
*/
private void replacePagesAndRenumberPageSeqs(OggVorbisTagReader.OggVorbisHeaderSizes originalHeaderSizes, int newCommentLength, OggPageHeader secondPageHeader, ByteBuffer newComment, RandomAccessFile raf, RandomAccessFile rafTemp) throws IOException, CannotReadException, CannotWriteException {
int pageSequence = secondPageHeader.getPageSequence();
//We need to work out how to split the newcommentlength over the pages
int noOfCompletePagesNeededForComment = newCommentLength / OggPageHeader.MAXIMUM_PAGE_DATA_SIZE;
// logger.info("Comment requires:" + noOfCompletePagesNeededForComment + " complete pages");
//Create the Pages
int newCommentOffset = 0;
if (noOfCompletePagesNeededForComment > 0) {
for (int i = 0; i < noOfCompletePagesNeededForComment; i++) {
//Create ByteBuffer for the New page
byte[] segmentTable = this.createSegments(OggPageHeader.MAXIMUM_PAGE_DATA_SIZE, false);
int pageHeaderLength = OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + segmentTable.length;
ByteBuffer pageBuffer = ByteBuffer.allocate(pageHeaderLength + OggPageHeader.MAXIMUM_PAGE_DATA_SIZE);
pageBuffer.order(ByteOrder.LITTLE_ENDIAN);
//Now create the page basing it on the existing 2ndpageheader
pageBuffer.put(secondPageHeader.getRawHeaderData(), 0, OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH - 1);
//Number of Page Segments
pageBuffer.put((byte) segmentTable.length);
//Page segment table
for (byte aSegmentTable : segmentTable) {
pageBuffer.put(aSegmentTable);
}
//Get next bit of Comment
ByteBuffer nextPartOfComment = newComment.slice();
nextPartOfComment.limit(OggPageHeader.MAXIMUM_PAGE_DATA_SIZE);
pageBuffer.put(nextPartOfComment);
//Recalculate Page Sequence Number
pageBuffer.putInt(OggPageHeader.FIELD_PAGE_SEQUENCE_NO_POS, pageSequence);
pageSequence++;
//Set Header Flag to indicate continuous (except for first flag)
if (i != 0) {
pageBuffer.put(OggPageHeader.FIELD_HEADER_TYPE_FLAG_POS, OggPageHeader.HeaderTypeFlag.CONTINUED_PACKET.getFileValue());
}
calculateChecksumOverPage(pageBuffer);
rafTemp.getChannel().write(pageBuffer);
newCommentOffset += OggPageHeader.MAXIMUM_PAGE_DATA_SIZE;
newComment.position(newCommentOffset);
}
}
int lastPageCommentPacketSize = newCommentLength % OggPageHeader.MAXIMUM_PAGE_DATA_SIZE;
// logger.fine("Last comment packet size:" + lastPageCommentPacketSize);
//End of comment and setup header cannot fit on the last page
if (!isCommentAndSetupHeaderFitsOnASinglePage(lastPageCommentPacketSize, originalHeaderSizes.getSetupHeaderSize(), originalHeaderSizes.getExtraPacketList())) {
// logger.fine("WriteOgg Type 3");
//Write the last part of comment only (its possible it might be the only comment)
{
byte[] segmentTable = createSegments(lastPageCommentPacketSize, true);
int pageHeaderLength = OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + segmentTable.length;
ByteBuffer pageBuffer = ByteBuffer.allocate(lastPageCommentPacketSize + pageHeaderLength);
pageBuffer.order(ByteOrder.LITTLE_ENDIAN);
pageBuffer.put(secondPageHeader.getRawHeaderData(), 0, OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH - 1);
pageBuffer.put((byte) segmentTable.length);
for (byte aSegmentTable : segmentTable) {
pageBuffer.put(aSegmentTable);
}
newComment.position(newCommentOffset);
pageBuffer.put(newComment.slice());
pageBuffer.putInt(OggPageHeader.FIELD_PAGE_SEQUENCE_NO_POS, pageSequence);
if (noOfCompletePagesNeededForComment > 0) {
pageBuffer.put(OggPageHeader.FIELD_HEADER_TYPE_FLAG_POS, OggPageHeader.HeaderTypeFlag.CONTINUED_PACKET.getFileValue());
}
// logger.fine("Writing Last Comment Page " + pageSequence + " to file");
pageSequence++;
calculateChecksumOverPage(pageBuffer);
rafTemp.getChannel().write(pageBuffer);
}
//Now write header and extra packets onto next page
{
byte[] segmentTable = this.createSegmentTable(originalHeaderSizes.getSetupHeaderSize(), originalHeaderSizes.getExtraPacketList());
int pageHeaderLength = OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + segmentTable.length;
byte[] setupHeaderData = reader.convertToVorbisSetupHeaderPacketAndAdditionalPackets(originalHeaderSizes.getSetupHeaderStartPosition(), raf);
ByteBuffer pageBuffer = ByteBuffer.allocate(setupHeaderData.length + pageHeaderLength);
pageBuffer.order(ByteOrder.LITTLE_ENDIAN);
pageBuffer.put(secondPageHeader.getRawHeaderData(), 0, OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH - 1);
pageBuffer.put((byte) segmentTable.length);
for (byte aSegmentTable : segmentTable) {
pageBuffer.put(aSegmentTable);
}
pageBuffer.put(setupHeaderData);
pageBuffer.putInt(OggPageHeader.FIELD_PAGE_SEQUENCE_NO_POS, pageSequence);
//pageBuffer.put(OggPageHeader.FIELD_HEADER_TYPE_FLAG_POS, OggPageHeader.HeaderTypeFlag.CONTINUED_PACKET.getFileValue());
// logger.fine("Writing Setup Header and packets Page " + pageSequence + " to file");
calculateChecksumOverPage(pageBuffer);
rafTemp.getChannel().write(pageBuffer);
}
} else {
//End of Comment and SetupHeader and extra packets can fit on one page
// logger.fine("WriteOgg Type 4");
//Create last header page
int newSecondPageDataLength = originalHeaderSizes.getSetupHeaderSize() + lastPageCommentPacketSize + originalHeaderSizes.getExtraPacketDataSize();
newComment.position(newCommentOffset);
ByteBuffer lastComment = newComment.slice();
ByteBuffer lastHeaderBuffer = startCreateBasicSecondPage(
originalHeaderSizes,
lastPageCommentPacketSize,
newSecondPageDataLength,
secondPageHeader,
lastComment);
//Now find the setupheader which is on a different page
raf.seek(originalHeaderSizes.getSetupHeaderStartPosition());
//Add setup Header and Extra Packets (although it will fit in this page, it may be over multiple pages in its original form
//so need to use this function to convert to raw data
byte[] setupHeaderData = reader.convertToVorbisSetupHeaderPacketAndAdditionalPackets(originalHeaderSizes.getSetupHeaderStartPosition(), raf);
lastHeaderBuffer.put(setupHeaderData);
//Page Sequence No
lastHeaderBuffer.putInt(OggPageHeader.FIELD_PAGE_SEQUENCE_NO_POS, pageSequence);
//Set Header Flag to indicate continuous (contains end of comment)
lastHeaderBuffer.put(OggPageHeader.FIELD_HEADER_TYPE_FLAG_POS, OggPageHeader.HeaderTypeFlag.CONTINUED_PACKET.getFileValue());
calculateChecksumOverPage(lastHeaderBuffer);
rafTemp.getChannel().write(lastHeaderBuffer);
}
//Write the rest of the original file
writeRemainingPages(pageSequence, raf, rafTemp);
}
/**
* Write all the remaining pages as they are except that the page sequence needs to be modified.
*
* @param pageSequence
* @param raf
* @param rafTemp
* @throws IOException
* @throws CannotReadException
* @throws CannotWriteException
*/
public void writeRemainingPages(int pageSequence, RandomAccessFile raf, RandomAccessFile rafTemp) throws IOException, CannotReadException, CannotWriteException {
long startAudio = raf.getFilePointer();
long startAudioWritten = rafTemp.getFilePointer();
//TODO there is a risk we wont have enough memory to create these buffers
ByteBuffer bb = ByteBuffer.allocate((int) (raf.length() - raf.getFilePointer()));
ByteBuffer bbTemp = ByteBuffer.allocate((int) (raf.length() - raf.getFilePointer()));
//Read in the rest of the data into bytebuffer and rewind it to start
raf.getChannel().read(bb);
bb.rewind();
while (bb.hasRemaining()) {
OggPageHeader nextPage = OggPageHeader.read(bb);
//Create buffer large enough for next page (header and data) and set byte order to LE so we can use
//putInt method
ByteBuffer nextPageHeaderBuffer = ByteBuffer.allocate(nextPage.getRawHeaderData().length + nextPage.getPageLength());
nextPageHeaderBuffer.order(ByteOrder.LITTLE_ENDIAN);
nextPageHeaderBuffer.put(nextPage.getRawHeaderData());
ByteBuffer data = bb.slice();
data.limit(nextPage.getPageLength());
nextPageHeaderBuffer.put(data);
nextPageHeaderBuffer.putInt(OggPageHeader.FIELD_PAGE_SEQUENCE_NO_POS, ++pageSequence);
calculateChecksumOverPage(nextPageHeaderBuffer);
bb.position(bb.position() + nextPage.getPageLength());
nextPageHeaderBuffer.rewind();
bbTemp.put(nextPageHeaderBuffer);
}
//Now just write as a single IO operation
bbTemp.rewind();
rafTemp.getChannel().write(bbTemp);
//Check we have written all the data
//TODO could we do any other checks to check data written correctly ?
if ((raf.length() - startAudio) != (rafTemp.length() - startAudioWritten)) {
throw new CannotWriteException("File written counts don't match, file not written");
}
}
public void writeRemainingPagesOld(int pageSequence, RandomAccessFile raf, RandomAccessFile rafTemp) throws IOException, CannotReadException, CannotWriteException {
//Now the Page Sequence Number for all the subsequent pages (containing audio frames) are out because there are
//less pages before then there used to be, so need to adjust
long startAudio = raf.getFilePointer();
long startAudioWritten = rafTemp.getFilePointer();
// logger.fine("Writing audio, audio starts in original file at :" + startAudio + ":Written to:" + startAudioWritten);
while (raf.getFilePointer() < raf.length()) {
// logger.fine("Reading Ogg Page");
OggPageHeader nextPage = OggPageHeader.read(raf);
//Create buffer large enough for next page (header and data) and set byte order to LE so we can use
//putInt method
ByteBuffer nextPageHeaderBuffer = ByteBuffer.allocate(nextPage.getRawHeaderData().length + nextPage.getPageLength());
nextPageHeaderBuffer.order(ByteOrder.LITTLE_ENDIAN);
nextPageHeaderBuffer.put(nextPage.getRawHeaderData());
raf.getChannel().read(nextPageHeaderBuffer);
//Recalculate Page Sequence Number
nextPageHeaderBuffer.putInt(OggPageHeader.FIELD_PAGE_SEQUENCE_NO_POS, ++pageSequence);
//Calculate Checksum
calculateChecksumOverPage(nextPageHeaderBuffer);
rafTemp.getChannel().write(nextPageHeaderBuffer);
}
if ((raf.length() - startAudio) != (rafTemp.length() - startAudioWritten)) {
throw new CannotWriteException("File written counts don't match, file not written");
}
}
/**
* This method creates a new segment table for the second page (header).
*
* @param newCommentLength The length of the Vorbis Comment
* @param setupHeaderLength The length of Setup Header, zero if comment String extends
* over multiple pages and this is not the last page.
* @param extraPackets If there are packets immediately after setup header in same page, they
* need including in the segment table
* @return new segment table.
*/
private byte[] createSegmentTable(int newCommentLength, int setupHeaderLength, List<OggPageHeader.PacketStartAndLength> extraPackets) {
// logger.finest("Create SegmentTable CommentLength:" + newCommentLength + ":SetupHeaderLength:" + setupHeaderLength);
ByteArrayOutputStream resultBaos = new ByteArrayOutputStream();
byte[] newStart;
byte[] restShouldBe;
byte[] nextPacket;
//Vorbis Comment
if (setupHeaderLength == 0) {
//Comment Stream continues onto next page so last lacing value can be 255
newStart = createSegments(newCommentLength, false);
return newStart;
} else {
//Comment Stream finishes on this page so if is a multiple of 255
//have to add an extra entry.
newStart = createSegments(newCommentLength, true);
}
//Setup Header, should be closed
if (extraPackets.size() > 0) {
restShouldBe = createSegments(setupHeaderLength, true);
}
//.. continue sonto next page
else {
restShouldBe = createSegments(setupHeaderLength, false);
}
// logger.finest("Created " + newStart.length + " segments for header");
// logger.finest("Created " + restShouldBe.length + " segments for setup");
try {
resultBaos.write(newStart);
resultBaos.write(restShouldBe);
if (extraPackets.size() > 0) {
//Packets are being copied literally not converted from a length, so always pass
//false parameter, TODO is this statement correct
// logger.finer("Creating segments for " + extraPackets.size() + " packets");
for (OggPageHeader.PacketStartAndLength packet : extraPackets) {
nextPacket = createSegments(packet.getLength(), false);
resultBaos.write(nextPacket);
}
}
} catch (IOException ioe) {
throw new RuntimeException("Unable to create segment table:" + ioe.getMessage());
}
return resultBaos.toByteArray();
}
/**
* This method creates a new segment table for the second half of setup header
*
* @param setupHeaderLength The length of Setup Header, zero if comment String extends
* over multiple pages and this is not the last page.
* @param extraPackets If there are packets immediately after setup header in same page, they
* need including in the segment table
* @return new segment table.
*/
private byte[] createSegmentTable(int setupHeaderLength, List<OggPageHeader.PacketStartAndLength> extraPackets) {
ByteArrayOutputStream resultBaos = new ByteArrayOutputStream();
byte[] restShouldBe;
byte[] nextPacket;
//Setup Header
restShouldBe = createSegments(setupHeaderLength, true);
try {
resultBaos.write(restShouldBe);
if (extraPackets.size() > 0) {
//Packets are being copied literally not converted from a length, so always pass
//false parameter, TODO is this statement correct
for (OggPageHeader.PacketStartAndLength packet : extraPackets) {
nextPacket = createSegments(packet.getLength(), false);
resultBaos.write(nextPacket);
}
}
} catch (IOException ioe) {
throw new RuntimeException("Unable to create segment table:" + ioe.getMessage());
}
return resultBaos.toByteArray();
}
/**
* This method creates a byte array of values whose sum should
* be the value of <code>length</code>.<br>
*
* @param length Size of the page which should be
* represented as 255 byte packets.
* @param quitStream If true and a length is a multiple of 255 we need another
* segment table entry with the value of 0. Else it's the last stream of the
* table which is already ended.
* @return Array of packet sizes. However only the last packet will
* differ from 255.
* <p/>
*/
//TODO if pass is data of max length (65025 bytes) and have quitStream==true
//this will return 256 segments which is illegal, should be checked somewhere
private byte[] createSegments(int length, boolean quitStream) {
// logger.finest("Create Segments for length:" + length + ":QuitStream:" + quitStream);
//It is valid to have nil length packets
if (length == 0) {
byte[] result = new byte[1];
result[0] = (byte) 0x00;
return result;
}
byte[] result = new byte[length / OggPageHeader.MAXIMUM_SEGMENT_SIZE + ((length % OggPageHeader.MAXIMUM_SEGMENT_SIZE == 0 && !quitStream) ? 0 : 1)];
int i = 0;
for (; i < result.length - 1; i++) {
result[i] = (byte) 0xFF;
}
result[result.length - 1] = (byte) (length - (i * OggPageHeader.MAXIMUM_SEGMENT_SIZE));
return result;
}
/**
* @param commentLength
* @param setupHeaderLength
* @param extraPacketList
* @return true if there is enough room to fit the comment and the setup headers on one page taking into
* account the maximum no of segments allowed per page and zero lacing values.
*/
private boolean isCommentAndSetupHeaderFitsOnASinglePage(int commentLength, int setupHeaderLength, List<OggPageHeader.PacketStartAndLength> extraPacketList) {
int totalDataSize = 0;
if (commentLength == 0) {
totalDataSize++;
} else {
totalDataSize = (commentLength / OggPageHeader.MAXIMUM_SEGMENT_SIZE) + 1;
if (commentLength % OggPageHeader.MAXIMUM_SEGMENT_SIZE == 0) {
totalDataSize++;
}
}
// logger.finest("Require:" + totalDataSize + " segments for comment");
if (setupHeaderLength == 0) {
totalDataSize++;
} else {
totalDataSize += (setupHeaderLength / OggPageHeader.MAXIMUM_SEGMENT_SIZE) + 1;
if (setupHeaderLength % OggPageHeader.MAXIMUM_SEGMENT_SIZE == 0) {
totalDataSize++;
}
}
// logger.finest("Require:" + totalDataSize + " segments for comment plus setup");
for (OggPageHeader.PacketStartAndLength extraPacket : extraPacketList) {
if (extraPacket.getLength() == 0) {
totalDataSize++;
} else {
totalDataSize += (extraPacket.getLength() / OggPageHeader.MAXIMUM_SEGMENT_SIZE) + 1;
if (extraPacket.getLength() % OggPageHeader.MAXIMUM_SEGMENT_SIZE == 0) {
totalDataSize++;
}
}
}
// logger.finest("Total No Of Segment If New Comment And Header Put On One Page:" + totalDataSize);
return totalDataSize <= OggPageHeader.MAXIMUM_NO_OF_SEGMENT_SIZE;
}
}
| |
/*
* Copyright 2008 ZXing 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.phonedeck.lqrt;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author satorux@google.com (Satoru Takabayashi) - creator
* @author dswitkin@google.com (Daniel Switkin) - ported from C++
*/
public final class Encoder {
// The original table is defined in the table 5 of JISX0510:2004 (p.19).
private static final int[] ALPHANUMERIC_TABLE = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f
36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f
};
static final String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1";
private Encoder() {
}
// The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details.
// Basically it applies four rules and summate all penalties.
private static int calculateMaskPenalty(ByteMatrix matrix) {
return MaskUtil.applyMaskPenaltyRule1(matrix)
+ MaskUtil.applyMaskPenaltyRule2(matrix)
+ MaskUtil.applyMaskPenaltyRule3(matrix)
+ MaskUtil.applyMaskPenaltyRule4(matrix);
}
/**
* Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen
* internally by chooseMode(). On success, store the result in "qrCode".
*
* We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
* "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very
* strong error correction for this purpose.
*
* Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
* with which clients can specify the encoding mode. For now, we don't need the functionality.
*/
public static QRCode encode(String content, ErrorCorrectionLevel ecLevel) throws WriterException {
return encode(content, ecLevel, null);
}
public static QRCode encode(String content,
ErrorCorrectionLevel ecLevel,
String encoding) throws WriterException {
// Determine what character encoding has been specified by the caller, if any
if (encoding == null) {
encoding = DEFAULT_BYTE_MODE_ENCODING;
}
// Pick an encoding mode appropriate for the content. Note that this will not attempt to use
// multiple modes / segments even if that were more efficient. Twould be nice.
Mode mode = chooseMode(content, encoding);
// This will store the header information, like mode and
// length, as well as "header" segments like an ECI segment.
BitArray headerBits = new BitArray();
// Append ECI segment if applicable
if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.equals(encoding)) {
CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
if (eci != null) {
appendECI(eci, headerBits);
}
}
// (With ECI in place,) Write the mode marker
appendModeInfo(mode, headerBits);
// Collect data within the main segment, separately, to count its size if needed. Don't add it to
// main payload yet.
BitArray dataBits = new BitArray();
appendBytes(content, mode, dataBits, encoding);
// Hard part: need to know version to know how many bits length takes. But need to know how many
// bits it takes to know version. First we take a guess at version by assuming version will be
// the minimum, 1:
int provisionalBitsNeeded = headerBits.getSize()
+ mode.getCharacterCountBits(Version.getVersionForNumber(1))
+ dataBits.getSize();
Version provisionalVersion = chooseVersion(provisionalBitsNeeded, ecLevel);
// Use that guess to calculate the right version. I am still not sure this works in 100% of cases.
int bitsNeeded = headerBits.getSize()
+ mode.getCharacterCountBits(provisionalVersion)
+ dataBits.getSize();
Version version = chooseVersion(bitsNeeded, ecLevel);
BitArray headerAndDataBits = new BitArray();
headerAndDataBits.appendBitArray(headerBits);
// Find "length" of main segment and write it
int numLetters = mode == Mode.BYTE ? dataBits.getSizeInBytes() : content.length();
appendLengthInfo(numLetters, version, mode, headerAndDataBits);
// Put data together into the overall payload
headerAndDataBits.appendBitArray(dataBits);
Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
int numDataBytes = version.getTotalCodewords() - ecBlocks.getTotalECCodewords();
// Terminate the bits properly.
terminateBits(numDataBytes, headerAndDataBits);
// Interleave data bits with error correction code.
BitArray finalBits = interleaveWithECBytes(headerAndDataBits,
version.getTotalCodewords(),
numDataBytes,
ecBlocks.getNumBlocks());
QRCode qrCode = new QRCode();
qrCode.setECLevel(ecLevel);
qrCode.setMode(mode);
qrCode.setVersion(version);
// Choose the mask pattern and set to "qrCode".
int dimension = version.getDimensionForVersion();
ByteMatrix matrix = new ByteMatrix(dimension, dimension);
int maskPattern = chooseMaskPattern(finalBits, ecLevel, version, matrix);
qrCode.setMaskPattern(maskPattern);
// Build the matrix and set it to "qrCode".
MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix);
qrCode.setMatrix(matrix);
return qrCode;
}
/**
* @return the code point of the table used in alphanumeric mode or
* -1 if there is no corresponding code in the table.
*/
static int getAlphanumericCode(int code) {
if (code < ALPHANUMERIC_TABLE.length) {
return ALPHANUMERIC_TABLE[code];
}
return -1;
}
public static Mode chooseMode(String content) {
return chooseMode(content, null);
}
/**
* Choose the best mode by examining the content. Note that 'encoding' is used as a hint;
* if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}.
*/
private static Mode chooseMode(String content, String encoding) {
if ("Shift_JIS".equals(encoding)) {
// Choose Kanji mode if all input are double-byte characters
return isOnlyDoubleByteKanji(content) ? Mode.KANJI : Mode.BYTE;
}
boolean hasNumeric = false;
boolean hasAlphanumeric = false;
for (int i = 0; i < content.length(); ++i) {
char c = content.charAt(i);
if (c >= '0' && c <= '9') {
hasNumeric = true;
} else if (getAlphanumericCode(c) != -1) {
hasAlphanumeric = true;
} else {
return Mode.BYTE;
}
}
if (hasAlphanumeric) {
return Mode.ALPHANUMERIC;
}
if (hasNumeric) {
return Mode.NUMERIC;
}
return Mode.BYTE;
}
private static boolean isOnlyDoubleByteKanji(String content) {
byte[] bytes;
try {
bytes = content.getBytes("Shift_JIS");
} catch (UnsupportedEncodingException ignored) {
return false;
}
int length = bytes.length;
if (length % 2 != 0) {
return false;
}
for (int i = 0; i < length; i += 2) {
int byte1 = bytes[i] & 0xFF;
if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) {
return false;
}
}
return true;
}
private static int chooseMaskPattern(BitArray bits,
ErrorCorrectionLevel ecLevel,
Version version,
ByteMatrix matrix) throws WriterException {
int minPenalty = Integer.MAX_VALUE; // Lower penalty is better.
int bestMaskPattern = -1;
// We try all mask patterns to choose the best one.
for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
int penalty = calculateMaskPenalty(matrix);
if (penalty < minPenalty) {
minPenalty = penalty;
bestMaskPattern = maskPattern;
}
}
return bestMaskPattern;
}
private static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel) throws WriterException {
// In the following comments, we use numbers of Version 7-H.
for (int versionNum = 1; versionNum <= 40; versionNum++) {
Version version = Version.getVersionForNumber(versionNum);
// numBytes = 196
int numBytes = version.getTotalCodewords();
// getNumECBytes = 130
Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
int numEcBytes = ecBlocks.getTotalECCodewords();
// getNumDataBytes = 196 - 130 = 66
int numDataBytes = numBytes - numEcBytes;
int totalInputBytes = (numInputBits + 7) / 8;
if (numDataBytes >= totalInputBytes) {
return version;
}
}
throw new WriterException("Data too big");
}
/**
* Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
*/
static void terminateBits(int numDataBytes, BitArray bits) throws WriterException {
int capacity = numDataBytes << 3;
if (bits.getSize() > capacity) {
throw new WriterException("data bits cannot fit in the QR Code" + bits.getSize() + " > " +
capacity);
}
for (int i = 0; i < 4 && bits.getSize() < capacity; ++i) {
bits.appendBit(false);
}
// Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
// If the last byte isn't 8-bit aligned, we'll add padding bits.
int numBitsInLastByte = bits.getSize() & 0x07;
if (numBitsInLastByte > 0) {
for (int i = numBitsInLastByte; i < 8; i++) {
bits.appendBit(false);
}
}
// If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
int numPaddingBytes = numDataBytes - bits.getSizeInBytes();
for (int i = 0; i < numPaddingBytes; ++i) {
bits.appendBits((i & 0x01) == 0 ? 0xEC : 0x11, 8);
}
if (bits.getSize() != capacity) {
throw new WriterException("Bits size does not equal capacity");
}
}
/**
* Get number of data bytes and number of error correction bytes for block id "blockID". Store
* the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
* JISX0510:2004 (p.30)
*/
static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes,
int numDataBytes,
int numRSBlocks,
int blockID,
int[] numDataBytesInBlock,
int[] numECBytesInBlock) throws WriterException {
if (blockID >= numRSBlocks) {
throw new WriterException("Block ID too large");
}
// numRsBlocksInGroup2 = 196 % 5 = 1
int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
// numRsBlocksInGroup1 = 5 - 1 = 4
int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
// numTotalBytesInGroup1 = 196 / 5 = 39
int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
// numTotalBytesInGroup2 = 39 + 1 = 40
int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
// numDataBytesInGroup1 = 66 / 5 = 13
int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
// numDataBytesInGroup2 = 13 + 1 = 14
int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
// numEcBytesInGroup1 = 39 - 13 = 26
int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
// numEcBytesInGroup2 = 40 - 14 = 26
int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
// Sanity checks.
// 26 = 26
if (numEcBytesInGroup1 != numEcBytesInGroup2) {
throw new WriterException("EC bytes mismatch");
}
// 5 = 4 + 1.
if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) {
throw new WriterException("RS blocks mismatch");
}
// 196 = (13 + 26) * 4 + (14 + 26) * 1
if (numTotalBytes !=
((numDataBytesInGroup1 + numEcBytesInGroup1) *
numRsBlocksInGroup1) +
((numDataBytesInGroup2 + numEcBytesInGroup2) *
numRsBlocksInGroup2)) {
throw new WriterException("Total bytes mismatch");
}
if (blockID < numRsBlocksInGroup1) {
numDataBytesInBlock[0] = numDataBytesInGroup1;
numECBytesInBlock[0] = numEcBytesInGroup1;
} else {
numDataBytesInBlock[0] = numDataBytesInGroup2;
numECBytesInBlock[0] = numEcBytesInGroup2;
}
}
/**
* Interleave "bits" with corresponding error correction bytes. On success, store the result in
* "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
*/
static BitArray interleaveWithECBytes(BitArray bits,
int numTotalBytes,
int numDataBytes,
int numRSBlocks) throws WriterException {
// "bits" must have "getNumDataBytes" bytes of data.
if (bits.getSizeInBytes() != numDataBytes) {
throw new WriterException("Number of bits and data bytes does not match");
}
// Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
// store the divided data bytes blocks and error correction bytes blocks into "blocks".
int dataBytesOffset = 0;
int maxNumDataBytes = 0;
int maxNumEcBytes = 0;
// Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
Collection<BlockPair> blocks = new ArrayList<BlockPair>(numRSBlocks);
for (int i = 0; i < numRSBlocks; ++i) {
int[] numDataBytesInBlock = new int[1];
int[] numEcBytesInBlock = new int[1];
getNumDataBytesAndNumECBytesForBlockID(
numTotalBytes, numDataBytes, numRSBlocks, i,
numDataBytesInBlock, numEcBytesInBlock);
int size = numDataBytesInBlock[0];
byte[] dataBytes = new byte[size];
bits.toBytes(8*dataBytesOffset, dataBytes, 0, size);
byte[] ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
blocks.add(new BlockPair(dataBytes, ecBytes));
maxNumDataBytes = Math.max(maxNumDataBytes, size);
maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.length);
dataBytesOffset += numDataBytesInBlock[0];
}
if (numDataBytes != dataBytesOffset) {
throw new WriterException("Data bytes does not match offset");
}
BitArray result = new BitArray();
// First, place data blocks.
for (int i = 0; i < maxNumDataBytes; ++i) {
for (BlockPair block : blocks) {
byte[] dataBytes = block.getDataBytes();
if (i < dataBytes.length) {
result.appendBits(dataBytes[i], 8);
}
}
}
// Then, place error correction blocks.
for (int i = 0; i < maxNumEcBytes; ++i) {
for (BlockPair block : blocks) {
byte[] ecBytes = block.getErrorCorrectionBytes();
if (i < ecBytes.length) {
result.appendBits(ecBytes[i], 8);
}
}
}
if (numTotalBytes != result.getSizeInBytes()) { // Should be same.
throw new WriterException("Interleaving error: " + numTotalBytes + " and " +
result.getSizeInBytes() + " differ.");
}
return result;
}
static byte[] generateECBytes(byte[] dataBytes, int numEcBytesInBlock) {
int numDataBytes = dataBytes.length;
int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
for (int i = 0; i < numDataBytes; i++) {
toEncode[i] = dataBytes[i] & 0xFF;
}
new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256).encode(toEncode, numEcBytesInBlock);
byte[] ecBytes = new byte[numEcBytesInBlock];
for (int i = 0; i < numEcBytesInBlock; i++) {
ecBytes[i] = (byte) toEncode[numDataBytes + i];
}
return ecBytes;
}
/**
* Append mode info. On success, store the result in "bits".
*/
static void appendModeInfo(Mode mode, BitArray bits) {
bits.appendBits(mode.getBits(), 4);
}
/**
* Append length info. On success, store the result in "bits".
*/
static void appendLengthInfo(int numLetters, Version version, Mode mode, BitArray bits) throws WriterException {
int numBits = mode.getCharacterCountBits(version);
if (numLetters >= (1 << numBits)) {
throw new WriterException(numLetters + " is bigger than " + ((1 << numBits) - 1));
}
bits.appendBits(numLetters, numBits);
}
/**
* Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
*/
static void appendBytes(String content,
Mode mode,
BitArray bits,
String encoding) throws WriterException {
switch (mode) {
case NUMERIC:
appendNumericBytes(content, bits);
break;
case ALPHANUMERIC:
appendAlphanumericBytes(content, bits);
break;
case BYTE:
append8BitBytes(content, bits, encoding);
break;
case KANJI:
appendKanjiBytes(content, bits);
break;
default:
throw new WriterException("Invalid mode: " + mode);
}
}
static void appendNumericBytes(CharSequence content, BitArray bits) {
int length = content.length();
int i = 0;
while (i < length) {
int num1 = content.charAt(i) - '0';
if (i + 2 < length) {
// Encode three numeric letters in ten bits.
int num2 = content.charAt(i + 1) - '0';
int num3 = content.charAt(i + 2) - '0';
bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
i += 3;
} else if (i + 1 < length) {
// Encode two numeric letters in seven bits.
int num2 = content.charAt(i + 1) - '0';
bits.appendBits(num1 * 10 + num2, 7);
i += 2;
} else {
// Encode one numeric letter in four bits.
bits.appendBits(num1, 4);
i++;
}
}
}
static void appendAlphanumericBytes(CharSequence content, BitArray bits) throws WriterException {
int length = content.length();
int i = 0;
while (i < length) {
int code1 = getAlphanumericCode(content.charAt(i));
if (code1 == -1) {
throw new WriterException();
}
if (i + 1 < length) {
int code2 = getAlphanumericCode(content.charAt(i + 1));
if (code2 == -1) {
throw new WriterException();
}
// Encode two alphanumeric letters in 11 bits.
bits.appendBits(code1 * 45 + code2, 11);
i += 2;
} else {
// Encode one alphanumeric letter in six bits.
bits.appendBits(code1, 6);
i++;
}
}
}
static void append8BitBytes(String content, BitArray bits, String encoding)
throws WriterException {
byte[] bytes;
try {
bytes = content.getBytes(encoding);
} catch (UnsupportedEncodingException uee) {
throw new WriterException(uee);
}
for (byte b : bytes) {
bits.appendBits(b, 8);
}
}
static void appendKanjiBytes(String content, BitArray bits) throws WriterException {
byte[] bytes;
try {
bytes = content.getBytes("Shift_JIS");
} catch (UnsupportedEncodingException uee) {
throw new WriterException(uee);
}
int length = bytes.length;
for (int i = 0; i < length; i += 2) {
int byte1 = bytes[i] & 0xFF;
int byte2 = bytes[i + 1] & 0xFF;
int code = (byte1 << 8) | byte2;
int subtracted = -1;
if (code >= 0x8140 && code <= 0x9ffc) {
subtracted = code - 0x8140;
} else if (code >= 0xe040 && code <= 0xebbf) {
subtracted = code - 0xc140;
}
if (subtracted == -1) {
throw new WriterException("Invalid byte sequence");
}
int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
bits.appendBits(encoded, 13);
}
}
private static void appendECI(CharacterSetECI eci, BitArray bits) {
bits.appendBits(Mode.ECI.getBits(), 4);
// This is correct for values up to 127, which is all we need now.
bits.appendBits(eci.getValue(), 8);
}
}
| |
package org.sep4j;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
*
* @author chenjianjx
*
*/
public class SsioTest {
@Rule
public ExpectedException expectedEx = ExpectedException.none();
@Test
public void shouldSaveTest() {
Assert.assertTrue(Ssio.shouldSave(null, true));
Assert.assertTrue(Ssio.shouldSave(Arrays.asList(new DatumError()), true));
Assert.assertTrue(Ssio.shouldSave(null, false));
Assert.assertTrue(Ssio.shouldSave(new ArrayList<DatumError>(), false));
Assert.assertFalse(Ssio.shouldSave(Arrays.asList(new DatumError()), false));
}
@Test
public void validateRecordClass_NullClass() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("null");
Ssio.validateRecordClass(null);
}
@Test
public void createRecordIndexTest() {
Ssio.createRecordInstance(DefaultConstructorBean.class);
Ssio.createRecordInstance(PrivateClassBean.class);
}
@Test
public void createRecordIndexTest_NoDefaultConstructor() {
expectedEx.expect(RuntimeException.class);
expectedEx.expectMessage("<init>()");
Ssio.createRecordInstance(NoDefaultConstructorBean.class);
}
@Test
public void validateReverseHeaderMapTest_Null() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("null");
Ssio.validateReverseHeaderMap(null);
}
@Test
public void validateReverseHeaderMapTest_Empty() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("empty");
Map<String, String> map = new HashMap<String, String>();
Ssio.validateReverseHeaderMap(map);
}
@Test
public void validateReverseHeaderMapTest_Positive() {
Map<String, String> map = new HashMap<String, String>();
map.put("someText", "someProp");
Ssio.validateReverseHeaderMap(map);
}
@Test
public void validateReverseHeaderMapTest_TextBlank() {
Map<String, String> map = new HashMap<String, String>();
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("blank headerText");
expectedEx.expectMessage("1");
map.put("text1", "prop1");
map.put(" ", "prop2");
Ssio.validateReverseHeaderMap(map);
}
@Test
public void validateReverseHeaderMapTest_PropBlank() {
Map<String, String> map = new HashMap<String, String>();
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("blank propName");
expectedEx.expectMessage("1");
map.put("text1", "prop1");
map.put("text2", " ");
Ssio.validateReverseHeaderMap(map);
}
@Test
public void validateHeaderMapTest_Null() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("null");
Ssio.validateHeaderMap(null);
}
@Test
public void validateHeaderMapTest_Empty() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("empty");
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
Ssio.validateHeaderMap(map);
}
@Test
public void validateHeaderMapTest_Positive() {
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put("someProp", "someText");
Ssio.validateHeaderMap(map);
}
@Test
public void validateHeaderMapTest_PropBlank() {
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("blank propName");
expectedEx.expectMessage("1");
map.put("prop1", "text1");
map.put(" ", "text2");
Ssio.validateHeaderMap(map);
}
@Test
public void setPropertyWithCellTextTest_StrProp() {
SsioUnitTestRecord record = new SsioUnitTestRecord();
Ssio.setPropertyWithCellValue(SsioUnitTestRecord.class, record, "strProp", "abc");
Assert.assertEquals("abc", record.getStrProp());
Ssio.setPropertyWithCellValue(SsioUnitTestRecord.class, record, "strProp", null);
Assert.assertNull(record.getStrProp());
}
@Test
public void setPropertyWithCellTextTest_IntObjProp() {
SsioUnitTestRecord record = new SsioUnitTestRecord();
Ssio.setPropertyWithCellValue(SsioUnitTestRecord.class, record, "intObjProp", "123");
Assert.assertEquals(new Integer(123), record.getIntObjProp());
Ssio.setPropertyWithCellValue(SsioUnitTestRecord.class, record, "intObjProp", null);
Assert.assertNull(record.getIntObjProp());
}
@Test
public void setPropertyWithCellTextTest_IntObjProp_NotNumer() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("No suitable setter");
SsioUnitTestRecord record = new SsioUnitTestRecord();
Ssio.setPropertyWithCellValue(SsioUnitTestRecord.class, record, "intObjProp", "abc");
}
@Test
public void setPropertyWithCellTextTest_PrimIntProp() {
SsioUnitTestRecord record = new SsioUnitTestRecord();
Ssio.setPropertyWithCellValue(SsioUnitTestRecord.class, record, "primIntProp", "123");
Assert.assertEquals(123, record.getPrimIntProp());
}
@Test
public void setPropertyWithCellTextTest_PrimIntProp_NullText() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("No suitable setter");
SsioUnitTestRecord record = new SsioUnitTestRecord();
Ssio.setPropertyWithCellValue(SsioUnitTestRecord.class, record, "primIntProp", null);
}
@Test
public void setPropertyWithCellTextTest_PrimIntProp_NotNumber() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("No suitable setter");
SsioUnitTestRecord record = new SsioUnitTestRecord();
Ssio.setPropertyWithCellValue(SsioUnitTestRecord.class, record, "primIntProp", "abc");
}
@Test
public void readCellAsStringOrDateTest() {
Row row = createRowForTest();
Cell blankCell = row.createCell(0, Cell.CELL_TYPE_BLANK);
Cell boolCell = row.createCell(1, Cell.CELL_TYPE_BOOLEAN);
boolCell.setCellValue(true);
Cell errCell = row.createCell(2, Cell.CELL_TYPE_ERROR);
Cell formulaCell = row.createCell(3, Cell.CELL_TYPE_FORMULA);
formulaCell.setCellValue("a1 + a2");
Cell numericCell = row.createCell(4, Cell.CELL_TYPE_NUMERIC);
numericCell.setCellValue("100.00");
Cell strCell = row.createCell(5, Cell.CELL_TYPE_STRING);
strCell.setCellValue(" abc ");
Date now = new Date();
Cell dateCell = row.createCell(6, Cell.CELL_TYPE_NUMERIC);
dateCell.setCellValue(now);
CellStyle dateStyle = row.getSheet().getWorkbook().createCellStyle();
dateStyle.setDataFormat(row.getSheet().getWorkbook().createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss.SSS"));
dateCell.setCellStyle(dateStyle);
Assert.assertNull(Ssio.readCellAsStringOrDate(null));
Assert.assertNull(Ssio.readCellAsStringOrDate(blankCell));
Assert.assertEquals("true", Ssio.readCellAsStringOrDate(boolCell));
Assert.assertNull(Ssio.readCellAsStringOrDate(errCell));
Assert.assertNull(Ssio.readCellAsStringOrDate(formulaCell));
Assert.assertEquals("100.00", Ssio.readCellAsStringOrDate(numericCell));
Assert.assertEquals("abc", Ssio.readCellAsStringOrDate(strCell));
Assert.assertEquals(now, Ssio.readCellAsStringOrDate(dateCell));
}
@SuppressWarnings("unused")
private static class SsioUnitTestRecord {
private int primIntProp;
private Integer intObjProp;
private String strProp;
public int getPrimIntProp() {
return primIntProp;
}
public void setPrimIntProp(int primIntProp) {
this.primIntProp = primIntProp;
}
public Integer getIntObjProp() {
return intObjProp;
}
public void setIntObjProp(Integer intObjProp) {
this.intObjProp = intObjProp;
}
public String getStrProp() {
return strProp;
}
public void setStrProp(String strProp) {
this.strProp = strProp;
}
}
private static class PrivateClassBean {
}
public static class DefaultConstructorBean {
}
public static class NoDefaultConstructorBean {
public NoDefaultConstructorBean(Object param) {
}
}
private Row createRowForTest() {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
return row;
}
}
| |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.services.resources;
import org.jboss.logging.Logger;
import org.jboss.resteasy.spi.BadRequestException;
import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.AbstractOAuthClient;
import org.keycloak.OAuth2Constants;
import org.keycloak.common.ClientConnection;
import org.keycloak.common.util.KeycloakUriBuilder;
import org.keycloak.common.util.UriUtils;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.services.ForbiddenException;
import org.keycloak.services.managers.AppAuthManager;
import org.keycloak.services.managers.Auth;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.util.CookieHelper;
import org.keycloak.util.TokenUtil;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.Set;
/**
* Helper class for securing local services. Provides login basics as well as CSRF check basics
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public abstract class AbstractSecuredLocalService {
private static final Logger logger = Logger.getLogger(AbstractSecuredLocalService.class);
private static final String KEYCLOAK_STATE_CHECKER = "KEYCLOAK_STATE_CHECKER";
protected final ClientModel client;
protected RealmModel realm;
@Context
protected UriInfo uriInfo;
@Context
protected HttpHeaders headers;
@Context
protected ClientConnection clientConnection;
protected String stateChecker;
@Context
protected KeycloakSession session;
@Context
protected HttpRequest request;
protected Auth auth;
public AbstractSecuredLocalService(RealmModel realm, ClientModel client) {
this.realm = realm;
this.client = client;
}
@Path("login-redirect")
@GET
public Response loginRedirect(@QueryParam("code") String code,
@QueryParam("state") String state,
@QueryParam("error") String error,
@QueryParam("path") String path,
@QueryParam("referrer") String referrer,
@Context HttpHeaders headers) {
try {
if (error != null) {
logger.debug("error from oauth");
throw new ForbiddenException("error");
}
if (path != null && !getValidPaths().contains(path)) {
throw new BadRequestException("Invalid path");
}
if (!realm.isEnabled()) {
logger.debug("realm not enabled");
throw new ForbiddenException();
}
if (!client.isEnabled()) {
logger.debug("account management app not enabled");
throw new ForbiddenException();
}
if (code == null) {
logger.debug("code not specified");
throw new BadRequestException("code not specified");
}
if (state == null) {
logger.debug("state not specified");
throw new BadRequestException("state not specified");
}
KeycloakUriBuilder redirect = KeycloakUriBuilder.fromUri(getBaseRedirectUri());
if (path != null) {
redirect.path(path);
}
if (referrer != null) {
redirect.queryParam("referrer", referrer);
}
return Response.status(302).location(redirect.build()).build();
} finally {
}
}
protected void updateCsrfChecks() {
Cookie cookie = headers.getCookies().get(KEYCLOAK_STATE_CHECKER);
if (cookie != null) {
stateChecker = cookie.getValue();
} else {
stateChecker = KeycloakModelUtils.generateSecret();
String cookiePath = AuthenticationManager.getRealmCookiePath(realm, uriInfo);
boolean secureOnly = realm.getSslRequired().isRequired(clientConnection);
CookieHelper.addCookie(KEYCLOAK_STATE_CHECKER, stateChecker, cookiePath, null, null, -1, secureOnly, true);
}
}
protected abstract Set<String> getValidPaths();
/**
* Check to see if form post has sessionId hidden field and match it against the session id.
*
* @param formData
*/
protected void csrfCheck(final MultivaluedMap<String, String> formData) {
if (!auth.isCookieAuthenticated()) return;
String stateChecker = formData.getFirst("stateChecker");
if (!this.stateChecker.equals(stateChecker)) {
throw new ForbiddenException();
}
}
/**
* Check to see if form post has sessionId hidden field and match it against the session id.
*
*/
protected void csrfCheck(String stateChecker) {
if (!auth.isCookieAuthenticated()) return;
if (auth.getSession() == null) return;
if (!this.stateChecker.equals(stateChecker)) {
throw new ForbiddenException();
}
}
protected abstract URI getBaseRedirectUri();
protected Response login(String path) {
OAuthRedirect oauth = new OAuthRedirect();
String authUrl = OIDCLoginProtocolService.authUrl(uriInfo).build(realm.getName()).toString();
oauth.setAuthUrl(authUrl);
oauth.setClientId(client.getClientId());
oauth.setSecure(realm.getSslRequired().isRequired(clientConnection));
UriBuilder uriBuilder = UriBuilder.fromUri(getBaseRedirectUri()).path("login-redirect");
if (path != null) {
uriBuilder.queryParam("path", path);
}
String referrer = uriInfo.getQueryParameters().getFirst("referrer");
if (referrer != null) {
uriBuilder.queryParam("referrer", referrer);
}
String referrerUri = uriInfo.getQueryParameters().getFirst("referrer_uri");
if (referrerUri != null) {
uriBuilder.queryParam("referrer_uri", referrerUri);
}
URI accountUri = uriBuilder.build(realm.getName());
oauth.setStateCookiePath(accountUri.getRawPath());
return oauth.redirect(uriInfo, accountUri.toString());
}
protected Response authenticateBrowser() {
AppAuthManager authManager = new AppAuthManager();
AuthenticationManager.AuthResult authResult = authManager.authenticateIdentityCookie(session, realm);
if (authResult != null) {
auth = new Auth(realm, authResult.getToken(), authResult.getUser(), client, authResult.getSession(), true);
} else {
return login(null);
}
// don't allow cors requests
// This is to prevent CSRF attacks.
String requestOrigin = UriUtils.getOrigin(uriInfo.getBaseUri());
String origin = headers.getRequestHeaders().getFirst("Origin");
if (origin != null && !requestOrigin.equals(origin)) {
throw new ForbiddenException();
}
if (!request.getHttpMethod().equals("GET")) {
String referrer = headers.getRequestHeaders().getFirst("Referer");
if (referrer != null && !requestOrigin.equals(UriUtils.getOrigin(referrer))) {
throw new ForbiddenException();
}
}
updateCsrfChecks();
return null;
}
static class OAuthRedirect extends AbstractOAuthClient {
/**
* closes client
*/
public void stop() {
}
public Response redirect(UriInfo uriInfo, String redirectUri) {
String state = getStateCode();
String scopeParam = TokenUtil.attachOIDCScope(scope);
UriBuilder uriBuilder = UriBuilder.fromUri(authUrl)
.queryParam(OAuth2Constants.CLIENT_ID, clientId)
.queryParam(OAuth2Constants.REDIRECT_URI, redirectUri)
.queryParam(OAuth2Constants.STATE, state)
.queryParam(OAuth2Constants.RESPONSE_TYPE, OAuth2Constants.CODE)
.queryParam(OAuth2Constants.SCOPE, scopeParam);
URI url = uriBuilder.build();
NewCookie cookie = new NewCookie(getStateCookieName(), state, getStateCookiePath(uriInfo), null, null, -1, isSecure, true);
logger.debug("NewCookie: " + cookie.toString());
logger.debug("Oauth Redirect to: " + url);
return Response.status(302)
.location(url)
.cookie(cookie).build();
}
private String getStateCookiePath(UriInfo uriInfo) {
if (stateCookiePath != null) return stateCookiePath;
return uriInfo.getBaseUri().getRawPath();
}
}
}
| |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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.amazonaws.services.batch.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* A data volume used in a job's container properties.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/Volume" target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Volume implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The contents of the <code>host</code> parameter determine whether your data volume persists on the host container
* instance and where it is stored. If the host parameter is empty, then the Docker daemon assigns a host path for
* your data volume. However, the data is not guaranteed to persist after the containers associated with it stop
* running.
* </p>
*/
private Host host;
/**
* <p>
* The name of the volume. Up to 255 letters (uppercase and lowercase), numbers, hyphens, and underscores are
* allowed. This name is referenced in the <code>sourceVolume</code> parameter of container definition
* <code>mountPoints</code>.
* </p>
*/
private String name;
/**
* <p>
* The contents of the <code>host</code> parameter determine whether your data volume persists on the host container
* instance and where it is stored. If the host parameter is empty, then the Docker daemon assigns a host path for
* your data volume. However, the data is not guaranteed to persist after the containers associated with it stop
* running.
* </p>
*
* @param host
* The contents of the <code>host</code> parameter determine whether your data volume persists on the host
* container instance and where it is stored. If the host parameter is empty, then the Docker daemon assigns
* a host path for your data volume. However, the data is not guaranteed to persist after the containers
* associated with it stop running.
*/
public void setHost(Host host) {
this.host = host;
}
/**
* <p>
* The contents of the <code>host</code> parameter determine whether your data volume persists on the host container
* instance and where it is stored. If the host parameter is empty, then the Docker daemon assigns a host path for
* your data volume. However, the data is not guaranteed to persist after the containers associated with it stop
* running.
* </p>
*
* @return The contents of the <code>host</code> parameter determine whether your data volume persists on the host
* container instance and where it is stored. If the host parameter is empty, then the Docker daemon assigns
* a host path for your data volume. However, the data is not guaranteed to persist after the containers
* associated with it stop running.
*/
public Host getHost() {
return this.host;
}
/**
* <p>
* The contents of the <code>host</code> parameter determine whether your data volume persists on the host container
* instance and where it is stored. If the host parameter is empty, then the Docker daemon assigns a host path for
* your data volume. However, the data is not guaranteed to persist after the containers associated with it stop
* running.
* </p>
*
* @param host
* The contents of the <code>host</code> parameter determine whether your data volume persists on the host
* container instance and where it is stored. If the host parameter is empty, then the Docker daemon assigns
* a host path for your data volume. However, the data is not guaranteed to persist after the containers
* associated with it stop running.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Volume withHost(Host host) {
setHost(host);
return this;
}
/**
* <p>
* The name of the volume. Up to 255 letters (uppercase and lowercase), numbers, hyphens, and underscores are
* allowed. This name is referenced in the <code>sourceVolume</code> parameter of container definition
* <code>mountPoints</code>.
* </p>
*
* @param name
* The name of the volume. Up to 255 letters (uppercase and lowercase), numbers, hyphens, and underscores are
* allowed. This name is referenced in the <code>sourceVolume</code> parameter of container definition
* <code>mountPoints</code>.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the volume. Up to 255 letters (uppercase and lowercase), numbers, hyphens, and underscores are
* allowed. This name is referenced in the <code>sourceVolume</code> parameter of container definition
* <code>mountPoints</code>.
* </p>
*
* @return The name of the volume. Up to 255 letters (uppercase and lowercase), numbers, hyphens, and underscores
* are allowed. This name is referenced in the <code>sourceVolume</code> parameter of container definition
* <code>mountPoints</code>.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the volume. Up to 255 letters (uppercase and lowercase), numbers, hyphens, and underscores are
* allowed. This name is referenced in the <code>sourceVolume</code> parameter of container definition
* <code>mountPoints</code>.
* </p>
*
* @param name
* The name of the volume. Up to 255 letters (uppercase and lowercase), numbers, hyphens, and underscores are
* allowed. This name is referenced in the <code>sourceVolume</code> parameter of container definition
* <code>mountPoints</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Volume withName(String name) {
setName(name);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getHost() != null)
sb.append("Host: ").append(getHost()).append(",");
if (getName() != null)
sb.append("Name: ").append(getName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Volume == false)
return false;
Volume other = (Volume) obj;
if (other.getHost() == null ^ this.getHost() == null)
return false;
if (other.getHost() != null && other.getHost().equals(this.getHost()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getHost() == null) ? 0 : getHost().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
return hashCode;
}
@Override
public Volume clone() {
try {
return (Volume) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.batch.model.transform.VolumeMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/services/campaign_budget_service.proto
package com.google.ads.googleads.v10.services;
/**
* <pre>
* A single operation (create, update, remove) on a campaign budget.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.services.CampaignBudgetOperation}
*/
public final class CampaignBudgetOperation extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v10.services.CampaignBudgetOperation)
CampaignBudgetOperationOrBuilder {
private static final long serialVersionUID = 0L;
// Use CampaignBudgetOperation.newBuilder() to construct.
private CampaignBudgetOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CampaignBudgetOperation() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new CampaignBudgetOperation();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CampaignBudgetOperation(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
com.google.ads.googleads.v10.resources.CampaignBudget.Builder subBuilder = null;
if (operationCase_ == 1) {
subBuilder = ((com.google.ads.googleads.v10.resources.CampaignBudget) operation_).toBuilder();
}
operation_ =
input.readMessage(com.google.ads.googleads.v10.resources.CampaignBudget.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom((com.google.ads.googleads.v10.resources.CampaignBudget) operation_);
operation_ = subBuilder.buildPartial();
}
operationCase_ = 1;
break;
}
case 18: {
com.google.ads.googleads.v10.resources.CampaignBudget.Builder subBuilder = null;
if (operationCase_ == 2) {
subBuilder = ((com.google.ads.googleads.v10.resources.CampaignBudget) operation_).toBuilder();
}
operation_ =
input.readMessage(com.google.ads.googleads.v10.resources.CampaignBudget.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom((com.google.ads.googleads.v10.resources.CampaignBudget) operation_);
operation_ = subBuilder.buildPartial();
}
operationCase_ = 2;
break;
}
case 26: {
java.lang.String s = input.readStringRequireUtf8();
operationCase_ = 3;
operation_ = s;
break;
}
case 34: {
com.google.protobuf.FieldMask.Builder subBuilder = null;
if (updateMask_ != null) {
subBuilder = updateMask_.toBuilder();
}
updateMask_ = input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(updateMask_);
updateMask_ = subBuilder.buildPartial();
}
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.services.CampaignBudgetServiceProto.internal_static_google_ads_googleads_v10_services_CampaignBudgetOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.services.CampaignBudgetServiceProto.internal_static_google_ads_googleads_v10_services_CampaignBudgetOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.services.CampaignBudgetOperation.class, com.google.ads.googleads.v10.services.CampaignBudgetOperation.Builder.class);
}
private int operationCase_ = 0;
private java.lang.Object operation_;
public enum OperationCase
implements com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
CREATE(1),
UPDATE(2),
REMOVE(3),
OPERATION_NOT_SET(0);
private final int value;
private OperationCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static OperationCase valueOf(int value) {
return forNumber(value);
}
public static OperationCase forNumber(int value) {
switch (value) {
case 1: return CREATE;
case 2: return UPDATE;
case 3: return REMOVE;
case 0: return OPERATION_NOT_SET;
default: return null;
}
}
public int getNumber() {
return this.value;
}
};
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public static final int UPDATE_MASK_FIELD_NUMBER = 4;
private com.google.protobuf.FieldMask updateMask_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return updateMask_ != null;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return getUpdateMask();
}
public static final int CREATE_FIELD_NUMBER = 1;
/**
* <pre>
* Create operation: No resource name is expected for the new budget.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget create = 1;</code>
* @return Whether the create field is set.
*/
@java.lang.Override
public boolean hasCreate() {
return operationCase_ == 1;
}
/**
* <pre>
* Create operation: No resource name is expected for the new budget.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget create = 1;</code>
* @return The create.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CampaignBudget getCreate() {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CampaignBudget) operation_;
}
return com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance();
}
/**
* <pre>
* Create operation: No resource name is expected for the new budget.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget create = 1;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CampaignBudgetOrBuilder getCreateOrBuilder() {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CampaignBudget) operation_;
}
return com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance();
}
public static final int UPDATE_FIELD_NUMBER = 2;
/**
* <pre>
* Update operation: The campaign budget is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget update = 2;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 2;
}
/**
* <pre>
* Update operation: The campaign budget is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget update = 2;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CampaignBudget getUpdate() {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v10.resources.CampaignBudget) operation_;
}
return com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance();
}
/**
* <pre>
* Update operation: The campaign budget is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget update = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CampaignBudgetOrBuilder getUpdateOrBuilder() {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v10.resources.CampaignBudget) operation_;
}
return com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance();
}
public static final int REMOVE_FIELD_NUMBER = 3;
/**
* <pre>
* Remove operation: A resource name for the removed budget is expected, in
* this format:
* `customers/{customer_id}/campaignBudgets/{budget_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return Whether the remove field is set.
*/
public boolean hasRemove() {
return operationCase_ == 3;
}
/**
* <pre>
* Remove operation: A resource name for the removed budget is expected, in
* this format:
* `customers/{customer_id}/campaignBudgets/{budget_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return The remove.
*/
public java.lang.String getRemove() {
java.lang.Object ref = "";
if (operationCase_ == 3) {
ref = operation_;
}
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (operationCase_ == 3) {
operation_ = s;
}
return s;
}
}
/**
* <pre>
* Remove operation: A resource name for the removed budget is expected, in
* this format:
* `customers/{customer_id}/campaignBudgets/{budget_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return The bytes for remove.
*/
public com.google.protobuf.ByteString
getRemoveBytes() {
java.lang.Object ref = "";
if (operationCase_ == 3) {
ref = operation_;
}
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
if (operationCase_ == 3) {
operation_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (operationCase_ == 1) {
output.writeMessage(1, (com.google.ads.googleads.v10.resources.CampaignBudget) operation_);
}
if (operationCase_ == 2) {
output.writeMessage(2, (com.google.ads.googleads.v10.resources.CampaignBudget) operation_);
}
if (operationCase_ == 3) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, operation_);
}
if (updateMask_ != null) {
output.writeMessage(4, getUpdateMask());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (operationCase_ == 1) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, (com.google.ads.googleads.v10.resources.CampaignBudget) operation_);
}
if (operationCase_ == 2) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, (com.google.ads.googleads.v10.resources.CampaignBudget) operation_);
}
if (operationCase_ == 3) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, operation_);
}
if (updateMask_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, getUpdateMask());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v10.services.CampaignBudgetOperation)) {
return super.equals(obj);
}
com.google.ads.googleads.v10.services.CampaignBudgetOperation other = (com.google.ads.googleads.v10.services.CampaignBudgetOperation) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask()
.equals(other.getUpdateMask())) return false;
}
if (!getOperationCase().equals(other.getOperationCase())) return false;
switch (operationCase_) {
case 1:
if (!getCreate()
.equals(other.getCreate())) return false;
break;
case 2:
if (!getUpdate()
.equals(other.getUpdate())) return false;
break;
case 3:
if (!getRemove()
.equals(other.getRemove())) return false;
break;
case 0:
default:
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
switch (operationCase_) {
case 1:
hash = (37 * hash) + CREATE_FIELD_NUMBER;
hash = (53 * hash) + getCreate().hashCode();
break;
case 2:
hash = (37 * hash) + UPDATE_FIELD_NUMBER;
hash = (53 * hash) + getUpdate().hashCode();
break;
case 3:
hash = (37 * hash) + REMOVE_FIELD_NUMBER;
hash = (53 * hash) + getRemove().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v10.services.CampaignBudgetOperation prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* A single operation (create, update, remove) on a campaign budget.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.services.CampaignBudgetOperation}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.services.CampaignBudgetOperation)
com.google.ads.googleads.v10.services.CampaignBudgetOperationOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.services.CampaignBudgetServiceProto.internal_static_google_ads_googleads_v10_services_CampaignBudgetOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.services.CampaignBudgetServiceProto.internal_static_google_ads_googleads_v10_services_CampaignBudgetOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.services.CampaignBudgetOperation.class, com.google.ads.googleads.v10.services.CampaignBudgetOperation.Builder.class);
}
// Construct using com.google.ads.googleads.v10.services.CampaignBudgetOperation.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (updateMaskBuilder_ == null) {
updateMask_ = null;
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
operationCase_ = 0;
operation_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v10.services.CampaignBudgetServiceProto.internal_static_google_ads_googleads_v10_services_CampaignBudgetOperation_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CampaignBudgetOperation getDefaultInstanceForType() {
return com.google.ads.googleads.v10.services.CampaignBudgetOperation.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CampaignBudgetOperation build() {
com.google.ads.googleads.v10.services.CampaignBudgetOperation result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CampaignBudgetOperation buildPartial() {
com.google.ads.googleads.v10.services.CampaignBudgetOperation result = new com.google.ads.googleads.v10.services.CampaignBudgetOperation(this);
if (updateMaskBuilder_ == null) {
result.updateMask_ = updateMask_;
} else {
result.updateMask_ = updateMaskBuilder_.build();
}
if (operationCase_ == 1) {
if (createBuilder_ == null) {
result.operation_ = operation_;
} else {
result.operation_ = createBuilder_.build();
}
}
if (operationCase_ == 2) {
if (updateBuilder_ == null) {
result.operation_ = operation_;
} else {
result.operation_ = updateBuilder_.build();
}
}
if (operationCase_ == 3) {
result.operation_ = operation_;
}
result.operationCase_ = operationCase_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v10.services.CampaignBudgetOperation) {
return mergeFrom((com.google.ads.googleads.v10.services.CampaignBudgetOperation)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v10.services.CampaignBudgetOperation other) {
if (other == com.google.ads.googleads.v10.services.CampaignBudgetOperation.getDefaultInstance()) return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
switch (other.getOperationCase()) {
case CREATE: {
mergeCreate(other.getCreate());
break;
}
case UPDATE: {
mergeUpdate(other.getUpdate());
break;
}
case REMOVE: {
operationCase_ = 3;
operation_ = other.operation_;
onChanged();
break;
}
case OPERATION_NOT_SET: {
break;
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v10.services.CampaignBudgetOperation parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v10.services.CampaignBudgetOperation) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int operationCase_ = 0;
private java.lang.Object operation_;
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public Builder clearOperation() {
operationCase_ = 0;
operation_ = null;
onChanged();
return this;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return updateMaskBuilder_ != null || updateMask_ != null;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
onChanged();
} else {
updateMaskBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder setUpdateMask(
com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
onChanged();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (updateMask_ != null) {
updateMask_ =
com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial();
} else {
updateMask_ = value;
}
onChanged();
} else {
updateMaskBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder clearUpdateMask() {
if (updateMaskBuilder_ == null) {
updateMask_ = null;
onChanged();
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null ?
com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(),
getParentForChildren(),
isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CampaignBudget, com.google.ads.googleads.v10.resources.CampaignBudget.Builder, com.google.ads.googleads.v10.resources.CampaignBudgetOrBuilder> createBuilder_;
/**
* <pre>
* Create operation: No resource name is expected for the new budget.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget create = 1;</code>
* @return Whether the create field is set.
*/
@java.lang.Override
public boolean hasCreate() {
return operationCase_ == 1;
}
/**
* <pre>
* Create operation: No resource name is expected for the new budget.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget create = 1;</code>
* @return The create.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CampaignBudget getCreate() {
if (createBuilder_ == null) {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CampaignBudget) operation_;
}
return com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance();
} else {
if (operationCase_ == 1) {
return createBuilder_.getMessage();
}
return com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance();
}
}
/**
* <pre>
* Create operation: No resource name is expected for the new budget.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget create = 1;</code>
*/
public Builder setCreate(com.google.ads.googleads.v10.resources.CampaignBudget value) {
if (createBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
onChanged();
} else {
createBuilder_.setMessage(value);
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Create operation: No resource name is expected for the new budget.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget create = 1;</code>
*/
public Builder setCreate(
com.google.ads.googleads.v10.resources.CampaignBudget.Builder builderForValue) {
if (createBuilder_ == null) {
operation_ = builderForValue.build();
onChanged();
} else {
createBuilder_.setMessage(builderForValue.build());
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Create operation: No resource name is expected for the new budget.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget create = 1;</code>
*/
public Builder mergeCreate(com.google.ads.googleads.v10.resources.CampaignBudget value) {
if (createBuilder_ == null) {
if (operationCase_ == 1 &&
operation_ != com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance()) {
operation_ = com.google.ads.googleads.v10.resources.CampaignBudget.newBuilder((com.google.ads.googleads.v10.resources.CampaignBudget) operation_)
.mergeFrom(value).buildPartial();
} else {
operation_ = value;
}
onChanged();
} else {
if (operationCase_ == 1) {
createBuilder_.mergeFrom(value);
}
createBuilder_.setMessage(value);
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Create operation: No resource name is expected for the new budget.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget create = 1;</code>
*/
public Builder clearCreate() {
if (createBuilder_ == null) {
if (operationCase_ == 1) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
} else {
if (operationCase_ == 1) {
operationCase_ = 0;
operation_ = null;
}
createBuilder_.clear();
}
return this;
}
/**
* <pre>
* Create operation: No resource name is expected for the new budget.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget create = 1;</code>
*/
public com.google.ads.googleads.v10.resources.CampaignBudget.Builder getCreateBuilder() {
return getCreateFieldBuilder().getBuilder();
}
/**
* <pre>
* Create operation: No resource name is expected for the new budget.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget create = 1;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CampaignBudgetOrBuilder getCreateOrBuilder() {
if ((operationCase_ == 1) && (createBuilder_ != null)) {
return createBuilder_.getMessageOrBuilder();
} else {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CampaignBudget) operation_;
}
return com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance();
}
}
/**
* <pre>
* Create operation: No resource name is expected for the new budget.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget create = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CampaignBudget, com.google.ads.googleads.v10.resources.CampaignBudget.Builder, com.google.ads.googleads.v10.resources.CampaignBudgetOrBuilder>
getCreateFieldBuilder() {
if (createBuilder_ == null) {
if (!(operationCase_ == 1)) {
operation_ = com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance();
}
createBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CampaignBudget, com.google.ads.googleads.v10.resources.CampaignBudget.Builder, com.google.ads.googleads.v10.resources.CampaignBudgetOrBuilder>(
(com.google.ads.googleads.v10.resources.CampaignBudget) operation_,
getParentForChildren(),
isClean());
operation_ = null;
}
operationCase_ = 1;
onChanged();;
return createBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CampaignBudget, com.google.ads.googleads.v10.resources.CampaignBudget.Builder, com.google.ads.googleads.v10.resources.CampaignBudgetOrBuilder> updateBuilder_;
/**
* <pre>
* Update operation: The campaign budget is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget update = 2;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 2;
}
/**
* <pre>
* Update operation: The campaign budget is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget update = 2;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CampaignBudget getUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v10.resources.CampaignBudget) operation_;
}
return com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance();
} else {
if (operationCase_ == 2) {
return updateBuilder_.getMessage();
}
return com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The campaign budget is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget update = 2;</code>
*/
public Builder setUpdate(com.google.ads.googleads.v10.resources.CampaignBudget value) {
if (updateBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
onChanged();
} else {
updateBuilder_.setMessage(value);
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The campaign budget is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget update = 2;</code>
*/
public Builder setUpdate(
com.google.ads.googleads.v10.resources.CampaignBudget.Builder builderForValue) {
if (updateBuilder_ == null) {
operation_ = builderForValue.build();
onChanged();
} else {
updateBuilder_.setMessage(builderForValue.build());
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The campaign budget is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget update = 2;</code>
*/
public Builder mergeUpdate(com.google.ads.googleads.v10.resources.CampaignBudget value) {
if (updateBuilder_ == null) {
if (operationCase_ == 2 &&
operation_ != com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance()) {
operation_ = com.google.ads.googleads.v10.resources.CampaignBudget.newBuilder((com.google.ads.googleads.v10.resources.CampaignBudget) operation_)
.mergeFrom(value).buildPartial();
} else {
operation_ = value;
}
onChanged();
} else {
if (operationCase_ == 2) {
updateBuilder_.mergeFrom(value);
}
updateBuilder_.setMessage(value);
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The campaign budget is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget update = 2;</code>
*/
public Builder clearUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 2) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
} else {
if (operationCase_ == 2) {
operationCase_ = 0;
operation_ = null;
}
updateBuilder_.clear();
}
return this;
}
/**
* <pre>
* Update operation: The campaign budget is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget update = 2;</code>
*/
public com.google.ads.googleads.v10.resources.CampaignBudget.Builder getUpdateBuilder() {
return getUpdateFieldBuilder().getBuilder();
}
/**
* <pre>
* Update operation: The campaign budget is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget update = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CampaignBudgetOrBuilder getUpdateOrBuilder() {
if ((operationCase_ == 2) && (updateBuilder_ != null)) {
return updateBuilder_.getMessageOrBuilder();
} else {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v10.resources.CampaignBudget) operation_;
}
return com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The campaign budget is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CampaignBudget update = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CampaignBudget, com.google.ads.googleads.v10.resources.CampaignBudget.Builder, com.google.ads.googleads.v10.resources.CampaignBudgetOrBuilder>
getUpdateFieldBuilder() {
if (updateBuilder_ == null) {
if (!(operationCase_ == 2)) {
operation_ = com.google.ads.googleads.v10.resources.CampaignBudget.getDefaultInstance();
}
updateBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CampaignBudget, com.google.ads.googleads.v10.resources.CampaignBudget.Builder, com.google.ads.googleads.v10.resources.CampaignBudgetOrBuilder>(
(com.google.ads.googleads.v10.resources.CampaignBudget) operation_,
getParentForChildren(),
isClean());
operation_ = null;
}
operationCase_ = 2;
onChanged();;
return updateBuilder_;
}
/**
* <pre>
* Remove operation: A resource name for the removed budget is expected, in
* this format:
* `customers/{customer_id}/campaignBudgets/{budget_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return Whether the remove field is set.
*/
@java.lang.Override
public boolean hasRemove() {
return operationCase_ == 3;
}
/**
* <pre>
* Remove operation: A resource name for the removed budget is expected, in
* this format:
* `customers/{customer_id}/campaignBudgets/{budget_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return The remove.
*/
@java.lang.Override
public java.lang.String getRemove() {
java.lang.Object ref = "";
if (operationCase_ == 3) {
ref = operation_;
}
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (operationCase_ == 3) {
operation_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Remove operation: A resource name for the removed budget is expected, in
* this format:
* `customers/{customer_id}/campaignBudgets/{budget_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return The bytes for remove.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getRemoveBytes() {
java.lang.Object ref = "";
if (operationCase_ == 3) {
ref = operation_;
}
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
if (operationCase_ == 3) {
operation_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Remove operation: A resource name for the removed budget is expected, in
* this format:
* `customers/{customer_id}/campaignBudgets/{budget_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @param value The remove to set.
* @return This builder for chaining.
*/
public Builder setRemove(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
operationCase_ = 3;
operation_ = value;
onChanged();
return this;
}
/**
* <pre>
* Remove operation: A resource name for the removed budget is expected, in
* this format:
* `customers/{customer_id}/campaignBudgets/{budget_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearRemove() {
if (operationCase_ == 3) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
return this;
}
/**
* <pre>
* Remove operation: A resource name for the removed budget is expected, in
* this format:
* `customers/{customer_id}/campaignBudgets/{budget_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @param value The bytes for remove to set.
* @return This builder for chaining.
*/
public Builder setRemoveBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
operationCase_ = 3;
operation_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v10.services.CampaignBudgetOperation)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v10.services.CampaignBudgetOperation)
private static final com.google.ads.googleads.v10.services.CampaignBudgetOperation DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v10.services.CampaignBudgetOperation();
}
public static com.google.ads.googleads.v10.services.CampaignBudgetOperation getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CampaignBudgetOperation>
PARSER = new com.google.protobuf.AbstractParser<CampaignBudgetOperation>() {
@java.lang.Override
public CampaignBudgetOperation parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CampaignBudgetOperation(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<CampaignBudgetOperation> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CampaignBudgetOperation> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CampaignBudgetOperation getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver14;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFBsnTlvHashGtpHeaderMatchVer14 implements OFBsnTlvHashGtpHeaderMatch {
private static final Logger logger = LoggerFactory.getLogger(OFBsnTlvHashGtpHeaderMatchVer14.class);
// version: 1.4
final static byte WIRE_VERSION = 5;
final static int LENGTH = 6;
private final static short DEFAULT_FIRST_HEADER_BYTE = (short) 0x0;
private final static short DEFAULT_FIRST_HEADER_MASK = (short) 0x0;
// OF message fields
private final short firstHeaderByte;
private final short firstHeaderMask;
//
// Immutable default instance
final static OFBsnTlvHashGtpHeaderMatchVer14 DEFAULT = new OFBsnTlvHashGtpHeaderMatchVer14(
DEFAULT_FIRST_HEADER_BYTE, DEFAULT_FIRST_HEADER_MASK
);
// package private constructor - used by readers, builders, and factory
OFBsnTlvHashGtpHeaderMatchVer14(short firstHeaderByte, short firstHeaderMask) {
this.firstHeaderByte = U8.normalize(firstHeaderByte);
this.firstHeaderMask = U8.normalize(firstHeaderMask);
}
// Accessors for OF message fields
@Override
public int getType() {
return 0x68;
}
@Override
public short getFirstHeaderByte() {
return firstHeaderByte;
}
@Override
public short getFirstHeaderMask() {
return firstHeaderMask;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
public OFBsnTlvHashGtpHeaderMatch.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFBsnTlvHashGtpHeaderMatch.Builder {
final OFBsnTlvHashGtpHeaderMatchVer14 parentMessage;
// OF message fields
private boolean firstHeaderByteSet;
private short firstHeaderByte;
private boolean firstHeaderMaskSet;
private short firstHeaderMask;
BuilderWithParent(OFBsnTlvHashGtpHeaderMatchVer14 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public int getType() {
return 0x68;
}
@Override
public short getFirstHeaderByte() {
return firstHeaderByte;
}
@Override
public OFBsnTlvHashGtpHeaderMatch.Builder setFirstHeaderByte(short firstHeaderByte) {
this.firstHeaderByte = firstHeaderByte;
this.firstHeaderByteSet = true;
return this;
}
@Override
public short getFirstHeaderMask() {
return firstHeaderMask;
}
@Override
public OFBsnTlvHashGtpHeaderMatch.Builder setFirstHeaderMask(short firstHeaderMask) {
this.firstHeaderMask = firstHeaderMask;
this.firstHeaderMaskSet = true;
return this;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
@Override
public OFBsnTlvHashGtpHeaderMatch build() {
short firstHeaderByte = this.firstHeaderByteSet ? this.firstHeaderByte : parentMessage.firstHeaderByte;
short firstHeaderMask = this.firstHeaderMaskSet ? this.firstHeaderMask : parentMessage.firstHeaderMask;
//
return new OFBsnTlvHashGtpHeaderMatchVer14(
firstHeaderByte,
firstHeaderMask
);
}
}
static class Builder implements OFBsnTlvHashGtpHeaderMatch.Builder {
// OF message fields
private boolean firstHeaderByteSet;
private short firstHeaderByte;
private boolean firstHeaderMaskSet;
private short firstHeaderMask;
@Override
public int getType() {
return 0x68;
}
@Override
public short getFirstHeaderByte() {
return firstHeaderByte;
}
@Override
public OFBsnTlvHashGtpHeaderMatch.Builder setFirstHeaderByte(short firstHeaderByte) {
this.firstHeaderByte = firstHeaderByte;
this.firstHeaderByteSet = true;
return this;
}
@Override
public short getFirstHeaderMask() {
return firstHeaderMask;
}
@Override
public OFBsnTlvHashGtpHeaderMatch.Builder setFirstHeaderMask(short firstHeaderMask) {
this.firstHeaderMask = firstHeaderMask;
this.firstHeaderMaskSet = true;
return this;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
//
@Override
public OFBsnTlvHashGtpHeaderMatch build() {
short firstHeaderByte = this.firstHeaderByteSet ? this.firstHeaderByte : DEFAULT_FIRST_HEADER_BYTE;
short firstHeaderMask = this.firstHeaderMaskSet ? this.firstHeaderMask : DEFAULT_FIRST_HEADER_MASK;
return new OFBsnTlvHashGtpHeaderMatchVer14(
firstHeaderByte,
firstHeaderMask
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFBsnTlvHashGtpHeaderMatch> {
@Override
public OFBsnTlvHashGtpHeaderMatch readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property type == 0x68
short type = bb.readShort();
if(type != (short) 0x68)
throw new OFParseError("Wrong type: Expected=0x68(0x68), got="+type);
int length = U16.f(bb.readShort());
if(length != 6)
throw new OFParseError("Wrong length: Expected=6(6), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
short firstHeaderByte = U8.f(bb.readByte());
short firstHeaderMask = U8.f(bb.readByte());
OFBsnTlvHashGtpHeaderMatchVer14 bsnTlvHashGtpHeaderMatchVer14 = new OFBsnTlvHashGtpHeaderMatchVer14(
firstHeaderByte,
firstHeaderMask
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", bsnTlvHashGtpHeaderMatchVer14);
return bsnTlvHashGtpHeaderMatchVer14;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFBsnTlvHashGtpHeaderMatchVer14Funnel FUNNEL = new OFBsnTlvHashGtpHeaderMatchVer14Funnel();
static class OFBsnTlvHashGtpHeaderMatchVer14Funnel implements Funnel<OFBsnTlvHashGtpHeaderMatchVer14> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFBsnTlvHashGtpHeaderMatchVer14 message, PrimitiveSink sink) {
// fixed value property type = 0x68
sink.putShort((short) 0x68);
// fixed value property length = 6
sink.putShort((short) 0x6);
sink.putShort(message.firstHeaderByte);
sink.putShort(message.firstHeaderMask);
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFBsnTlvHashGtpHeaderMatchVer14> {
@Override
public void write(ByteBuf bb, OFBsnTlvHashGtpHeaderMatchVer14 message) {
// fixed value property type = 0x68
bb.writeShort((short) 0x68);
// fixed value property length = 6
bb.writeShort((short) 0x6);
bb.writeByte(U8.t(message.firstHeaderByte));
bb.writeByte(U8.t(message.firstHeaderMask));
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFBsnTlvHashGtpHeaderMatchVer14(");
b.append("firstHeaderByte=").append(firstHeaderByte);
b.append(", ");
b.append("firstHeaderMask=").append(firstHeaderMask);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFBsnTlvHashGtpHeaderMatchVer14 other = (OFBsnTlvHashGtpHeaderMatchVer14) obj;
if( firstHeaderByte != other.firstHeaderByte)
return false;
if( firstHeaderMask != other.firstHeaderMask)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + firstHeaderByte;
result = prime * result + firstHeaderMask;
return result;
}
}
| |
/*
* $Header:
* /cvsroot/remotetea/remotetea/src/org/acplt/oncrpc/server/OncRpcUdpServerTransport
* .java,v 1.4 2008/01/02 15:13:35 haraldalbrecht Exp $
*
* Copyright (c) 1999, 2000 Lehrstuhl fuer Prozessleittechnik (PLT), RWTH Aachen
* D-52064 Aachen, Germany. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Library General Public License as published by the Free
* Software Foundation; either version 2 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 Library General Public License for more
* details.
*
* You should have received a copy of the GNU Library General Public License
* along with this program (see the file COPYING.LIB for more details); if not,
* write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
* 02139, USA.
*/
package org.acplt.oncrpc.server;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import org.acplt.oncrpc.OncRpcAuthenticationException;
import org.acplt.oncrpc.OncRpcException;
import org.acplt.oncrpc.OncRpcPortmapClient;
import org.acplt.oncrpc.OncRpcProtocols;
import org.acplt.oncrpc.OncRpcUdpSocketHelper;
import org.acplt.oncrpc.XdrAble;
import org.acplt.oncrpc.XdrDecodingStream;
import org.acplt.oncrpc.XdrEncodingStream;
import org.acplt.oncrpc.XdrUdpDecodingStream;
import org.acplt.oncrpc.XdrUdpEncodingStream;
/**
* Instances of class <code>OncRpcUdpServerTransport</code> encapsulate
* UDP/IP-based XDR streams of ONC/RPC servers. This server transport class is
* responsible for receiving ONC/RPC calls over UDP/IP.
*
* @see OncRpcServerTransport
* @see OncRpcTcpServerTransport
*
* @version $Revision: 1.4 $ $Date: 2008/01/02 15:13:35 $ $State: Exp $ $Locker:
* $
* @author Harald Albrecht
*/
public class OncRpcUdpServerTransport extends OncRpcServerTransport {
/**
* Indicates that <code>BeginDecoding</code> has been called for the
* receiving XDR stream, so that it should be closed later using
* <code>EndDecoding</code>.
*/
private boolean pendingDecoding = false;
/**
* XDR decoding stream used when receiving requests via UDP/IP from ONC/RPC
* clients.
*/
private XdrUdpDecodingStream receivingXdr;
/**
* XDR encoding stream used for sending replies via UDP/IP back to an
* ONC/RPC client.
*/
private XdrUdpEncodingStream sendingXdr;
/**
* UDP socket used for datagram-based communication with ONC/RPC clients.
*/
private DatagramSocket socket;
/**
* Socket helper object supplying missing methods for JDK 1.1 backwards
* compatibility. So much for compile once, does not run everywhere.
*/
private OncRpcUdpSocketHelper socketHelper;
/**
* Create a new instance of a <code>OncRpcUdpServerTransport</code> which
* encapsulates UDP/IP-based XDR streams of an ONC/RPC server. Using a
* server transport, ONC/RPC calls are received and the corresponding
* replies are sent back. This constructor is a convenience constructor for
* those transports handling only a single ONC/RPC program and version
* number.
*
* @param dispatcher
* Reference to interface of an object capable of dispatching
* (handling) ONC/RPC calls.
* @param bindAddr
* The local Internet Address the server will bind to.
* @param port
* Number of port where the server will wait for incoming calls.
* @param info
* Array of program and version number tuples of the ONC/RPC
* programs and versions handled by this transport.
* @param bufferSize
* Size of buffer for receiving and sending UDP/IP datagrams
* containing ONC/RPC call and reply messages.
*/
public OncRpcUdpServerTransport(
OncRpcDispatchable dispatcher,
InetAddress bindAddr,
int port,
OncRpcServerTransportRegistrationInfo[] info,
int bufferSize) throws OncRpcException,
IOException {
super(dispatcher, port, info);
//
// Make sure the buffer is large enough and resize system buffers
// accordingly, if possible.
//
if (bufferSize < 1024) {
bufferSize = 1024;
}
socket = new DatagramSocket(port);
socketHelper = new OncRpcUdpSocketHelper(socket);
if (port == 0) {
this.port = socket.getLocalPort();
}
if (socketHelper.getSendBufferSize() < bufferSize) {
socketHelper.setSendBufferSize(bufferSize);
}
if (socketHelper.getReceiveBufferSize() < bufferSize) {
socketHelper.setReceiveBufferSize(bufferSize);
}
//
// Create the necessary encoding and decoding streams, so we can
// communicate at all.
//
sendingXdr = new XdrUdpEncodingStream(socket, bufferSize);
receivingXdr = new XdrUdpDecodingStream(socket, bufferSize);
}
/**
* Create a new instance of a <code>OncRpcUdpServerTransport</code> which
* encapsulates UDP/IP-based XDR streams of an ONC/RPC server. Using a
* server transport, ONC/RPC calls are received and the corresponding
* replies are sent back. This constructor is a convenience constructor for
* those transports handling only a single ONC/RPC program and version
* number.
*
* @param dispatcher
* Reference to interface of an object capable of dispatching
* (handling) ONC/RPC calls.
* @param port
* Number of port where the server will wait for incoming calls.
* @param program
* Number of ONC/RPC program handled by this server transport.
* @param version
* Version number of ONC/RPC program handled.
* @param bufferSize
* Size of buffer for receiving and sending UDP/IP datagrams
* containing ONC/RPC call and reply messages.
*/
public OncRpcUdpServerTransport(OncRpcDispatchable dispatcher, int port,
int program, int version, int bufferSize)
throws OncRpcException,
IOException {
this(
dispatcher,
port,
new OncRpcServerTransportRegistrationInfo[] { new OncRpcServerTransportRegistrationInfo(
program,
version) },
bufferSize);
}
/**
* Create a new instance of a <code>OncRpcUdpServerTransport</code> which
* encapsulates UDP/IP-based XDR streams of an ONC/RPC server. Using a
* server transport, ONC/RPC calls are received and the corresponding
* replies are sent back. This constructor is a convenience constructor for
* those transports handling only a single ONC/RPC program and version
* number.
*
* @param dispatcher
* Reference to interface of an object capable of dispatching
* (handling) ONC/RPC calls.
* @param port
* Number of port where the server will wait for incoming calls.
* @param info
* Array of program and version number tuples of the ONC/RPC
* programs and versions handled by this transport.
* @param bufferSize
* Size of buffer for receiving and sending UDP/IP datagrams
* containing ONC/RPC call and reply messages.
*/
public OncRpcUdpServerTransport(
OncRpcDispatchable dispatcher,
int port,
OncRpcServerTransportRegistrationInfo[] info,
int bufferSize) throws OncRpcException,
IOException {
this(dispatcher, null, port, info, bufferSize);
}
/**
* The real workhorse handling incoming requests, dispatching them and
* sending back replies.
*/
public void _listen() {
OncRpcCallInformation callInfo = new OncRpcCallInformation(this);
for (;;) {
//
// Start decoding the incomming call. This involves remembering
// from whom we received the call so we can later send back the
// appropriate reply message.
// Note that for UDP-based communication we don't need to deal
// with timeouts.
//
try {
pendingDecoding = true;
receivingXdr.beginDecoding();
callInfo.peerAddress = receivingXdr.getSenderAddress();
callInfo.peerPort = receivingXdr.getSenderPort();
} catch (IOException e) {
//
// In case of I/O Exceptions (especially socket exceptions)
// close the file and leave the stage. There's nothing we can
// do anymore.
//
close();
return;
} catch (OncRpcException e) {
//
// In case of ONC/RPC exceptions at this stage we're silently
// ignoring that there was some data coming in...
//
continue;
}
try {
//
// Pull off the ONC/RPC call header of the XDR stream.
//
callInfo.callMessage.xdrDecode(receivingXdr);
} catch (IOException e) {
//
// In case of I/O Exceptions (especially socket exceptions)
// close the file and leave the stage. There's nothing we can
// do anymore.
//
close();
return;
} catch (OncRpcException e) {
//
// In case of ONC/RPC exceptions at this stage we're silently
// ignoring that there was some data coming in, as we're not
// sure we got enough information to send a matching reply
// message back to the caller.
//
if (pendingDecoding) {
pendingDecoding = false;
try {
receivingXdr.endDecoding();
} catch (IOException e2) {
close();
return;
} catch (OncRpcException e2) {
}
}
continue;
}
try {
//
// Let the dispatcher retrieve the call parameters, work on
// it and send back the reply.
// To make it once again clear: the dispatch called has to
// pull off the parameters of the stream!
//
dispatcher.dispatchOncRpcCall(callInfo,
callInfo.callMessage.program,
callInfo.callMessage.version,
callInfo.callMessage.procedure);
} catch (Exception e) {
//
// In case of some other runtime exception, we report back to
// the caller a system error.
//
// In case of UDP-bases transports we can do so, because we
// know that we can reset the buffer and serialize another
// reply message even in case we caught some OncRpcException.
//
// Note that we "kill" the transport by closing it when we
// got stuck with an I/O exception when trying to send back
// an error reply.
//
if (pendingDecoding) {
pendingDecoding = false;
try {
receivingXdr.endDecoding();
} catch (IOException e2) {
close();
return;
} catch (OncRpcException e2) {
}
}
//
// Check for authentication exceptions, which are reported back
// as is. Otherwise, just report a system error
// -- very generic, indeed.
//
try {
if (e instanceof OncRpcAuthenticationException) {
callInfo.failAuthenticationFailed(((OncRpcAuthenticationException) e).getAuthStatus());
} else {
callInfo.failSystemError();
}
} catch (IOException e2) {
close();
return;
} catch (OncRpcException e2) {
}
//
// Phew. Done with the error reply. So let's wait for new
// incoming ONC/RPC calls...
//
}
}
}
/**
* Close the server transport and free any resources associated with it.
*
* <p>
* Note that the server transport is <b>not deregistered</b>. You'll have to
* do it manually if you need to do so. The reason for this behaviour is,
* that the portmapper removes all entries regardless of the protocol
* (TCP/IP or UDP/IP) for a given ONC/RPC program number and version.
*
* <p>
* Calling this method on a <code>OncRpcUdpServerTransport</code> results in
* the UDP network socket immediately being closed. The handler thread will
* therefore either terminate directly or when it tries to sent back a reply
* which it was about to handle at the time the close method was called.
*/
@Override
public void close() {
if (socket != null) {
//
// Since there is a non-zero chance of getting race conditions,
// we now first set the socket instance member to null, before
// we close the corresponding socket. This avoids null-pointer
// exceptions in the method which waits for new requests: it is
// possible that this method is awakened because the socket has
// been closed before we could set the socket instance member to
// null. Many thanks to Michael Smith for tracking down this one.
//
DatagramSocket deadSocket = socket;
socket = null;
deadSocket.close();
}
if (sendingXdr != null) {
XdrEncodingStream deadXdrStream = sendingXdr;
sendingXdr = null;
try {
deadXdrStream.close();
} catch (IOException e) {
} catch (OncRpcException e) {
}
}
if (receivingXdr != null) {
XdrDecodingStream deadXdrStream = receivingXdr;
receivingXdr = null;
try {
deadXdrStream.close();
} catch (IOException e) {
} catch (OncRpcException e) {
}
}
}
/**
* Get the character encoding for (de-)serializing strings.
*
* @return the encoding currently used for (de-)serializing strings. If
* <code>null</code>, then the system's default encoding is used.
*/
@Override
public String getCharacterEncoding() {
return sendingXdr.getCharacterEncoding();
}
/**
* Creates a new thread and uses this thread to listen to incoming ONC/RPC
* requests, then dispatches them and finally sends back the appropriate
* reply messages. Control in the calling thread immediately returns after
* the handler thread has been created.
*
* <p>
* Currently only one call after the other is dispatched, so no
* multithreading is done when receiving multiple calls. Instead, later
* calls have to wait for the current call to finish before they are
* handled.
*/
@Override
public void listen() {
Thread listener = new Thread("UDP server transport listener thread") {
@Override
public void run() {
_listen();
}
};
listener.setDaemon(true);
listener.start();
}
/**
* Register the UDP/IP port where this server transport waits for incoming
* requests with the ONC/RPC portmapper.
*
* @throws OncRpcException
* if the portmapper could not be contacted successfully.
*/
@Override
public void register() throws OncRpcException {
try {
OncRpcPortmapClient portmapper = new OncRpcPortmapClient(
InetAddress.getLocalHost());
int size = info.length;
for (int idx = 0; idx < size; ++idx) {
//
// Try to register the port for our transport with the local
// ONC/RPC
// portmapper. If this fails, bail out with an exception.
//
if (!portmapper.setPort(info[idx].program, info[idx].version,
OncRpcProtocols.ONCRPC_UDP, port)) {
throw (new OncRpcException(
OncRpcException.RPC_CANNOTREGISTER));
}
}
} catch (IOException e) {
throw (new OncRpcException(OncRpcException.RPC_FAILED));
}
}
/**
* Set the character encoding for (de-)serializing strings.
*
* @param characterEncoding
* the encoding to use for (de-)serializing strings. If
* <code>null</code>, the system's default encoding is to be
* used.
*/
@Override
public void setCharacterEncoding(String characterEncoding) {
sendingXdr.setCharacterEncoding(characterEncoding);
receivingXdr.setCharacterEncoding(characterEncoding);
}
/**
* Begins the sending phase for ONC/RPC replies. This method belongs to the
* lower-level access pattern when handling ONC/RPC calls.
*
* @param callInfo
* Information about ONC/RPC call for which we are about to send
* back the reply.
* @param state
* ONC/RPC reply header indicating success or failure.
*
* @throws OncRpcException
* if an ONC/RPC exception occurs, like the data could not be
* successfully serialized.
* @throws IOException
* if an I/O exception occurs, like transmission
*/
@Override
protected void beginEncoding(OncRpcCallInformation callInfo,
OncRpcServerReplyMessage state)
throws OncRpcException,
IOException {
//
// In case decoding has not been properly finished, do it now to
// free up pending resources, etc.
//
if (pendingDecoding) {
pendingDecoding = false;
receivingXdr.endDecoding();
}
//
// Now start encoding using the reply message header first...
//
sendingXdr.beginEncoding(callInfo.peerAddress, callInfo.peerPort);
state.xdrEncode(sendingXdr);
}
/**
* Finishes call parameter deserialization. Afterwards the XDR stream
* returned by {@link #getXdrDecodingStream} must not be used any more. This
* method belongs to the lower-level access pattern when handling ONC/RPC
* calls.
*
* @throws OncRpcException
* if an ONC/RPC exception occurs, like the data could not be
* successfully deserialized.
* @throws IOException
* if an I/O exception occurs, like transmission failures over
* the network, etc.
*/
@Override
protected void endDecoding() throws OncRpcException, IOException {
if (pendingDecoding) {
pendingDecoding = false;
receivingXdr.endDecoding();
}
}
/**
* Finishes encoding the reply to this ONC/RPC call. Afterwards you must not
* use the XDR stream returned by {@link #getXdrEncodingStream} any longer.
*
* @throws OncRpcException
* if an ONC/RPC exception occurs, like the data could not be
* successfully serialized.
* @throws IOException
* if an I/O exception occurs, like transmission failures over
* the network, etc.
*/
@Override
protected void endEncoding() throws OncRpcException, IOException {
//
// Close the case. Finito.
//
sendingXdr.endEncoding();
}
/**
* Returns XDR stream which can be used for deserializing the parameters of
* this ONC/RPC call. This method belongs to the lower-level access pattern
* when handling ONC/RPC calls.
*
* @return Reference to decoding XDR stream.
*/
@Override
protected XdrDecodingStream getXdrDecodingStream() {
return receivingXdr;
}
/**
* Returns XDR stream which can be used for eserializing the reply to this
* ONC/RPC call. This method belongs to the lower-level access pattern when
* handling ONC/RPC calls.
*
* @return Reference to enecoding XDR stream.
*/
@Override
protected XdrEncodingStream getXdrEncodingStream() {
return sendingXdr;
}
/**
* Send back an ONC/RPC reply to the original caller. This is rather a
* low-level method, typically not used by applications. Dispatcher handling
* ONC/RPC calls have to use the
* {@link OncRpcCallInformation#reply(XdrAble)} method instead on the call
* object supplied to the handler.
*
* @param callInfo
* information about the original call, which are necessary to
* send back the reply to the appropriate caller.
* @param state
* ONC/RPC reply message header indicating success or failure and
* containing associated state information.
* @param reply
* If not <code>null</code>, then this parameter references the
* reply to be serialized after the reply message header.
*
* @throws OncRpcException
* if an ONC/RPC exception occurs, like the data could not be
* successfully serialized.
* @throws IOException
* if an I/O exception occurs, like transmission failures over
* the network, etc.
*
* @see OncRpcCallInformation
* @see OncRpcDispatchable
*/
@Override
protected void reply(OncRpcCallInformation callInfo,
OncRpcServerReplyMessage state, XdrAble reply)
throws OncRpcException,
IOException {
beginEncoding(callInfo, state);
if (reply != null) {
reply.xdrEncode(sendingXdr);
}
endEncoding();
}
/**
* Retrieves the parameters sent within an ONC/RPC call message. It also
* makes sure that the deserialization process is properly finished after
* the call parameters have been retrieved. Under the hood this method
* therefore calls {@link XdrDecodingStream#endDecoding} to free any pending
* resources from the decoding stage.
*
* @throws OncRpcException
* if an ONC/RPC exception occurs, like the data could not be
* successfully deserialized.
* @throws IOException
* if an I/O exception occurs, like transmission failures over
* the network, etc.
*/
@Override
protected void retrieveCall(XdrAble call) throws OncRpcException,
IOException {
call.xdrDecode(receivingXdr);
if (pendingDecoding) {
pendingDecoding = false;
receivingXdr.endDecoding();
}
}
}
// End of OncRpcUdpServerTransport.java
| |
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.testsuite.webauthn;
import org.jboss.arquillian.graphene.page.Page;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.WebAuthnConstants;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.authentication.authenticators.browser.PasswordFormFactory;
import org.keycloak.authentication.authenticators.browser.UsernameFormFactory;
import org.keycloak.authentication.authenticators.browser.WebAuthnAuthenticatorFactory;
import org.keycloak.authentication.authenticators.browser.WebAuthnPasswordlessAuthenticatorFactory;
import org.keycloak.authentication.requiredactions.WebAuthnPasswordlessRegisterFactory;
import org.keycloak.authentication.requiredactions.WebAuthnRegisterFactory;
import org.keycloak.common.util.SecretGenerator;
import org.keycloak.events.Details;
import org.keycloak.events.EventType;
import org.keycloak.models.credential.WebAuthnCredentialModel;
import org.keycloak.models.credential.dto.WebAuthnCredentialData;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.EventRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.testsuite.AssertEvents;
import org.keycloak.testsuite.admin.AbstractAdminTest;
import org.keycloak.testsuite.admin.ApiUtil;
import org.keycloak.testsuite.pages.AppPage;
import org.keycloak.testsuite.pages.AppPage.RequestType;
import org.keycloak.testsuite.pages.ErrorPage;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.pages.LoginUsernameOnlyPage;
import org.keycloak.testsuite.pages.PasswordPage;
import org.keycloak.testsuite.pages.RegisterPage;
import org.keycloak.testsuite.pages.SelectAuthenticatorPage;
import org.keycloak.testsuite.updaters.RealmAttributeUpdater;
import org.keycloak.testsuite.util.FlowUtil;
import org.keycloak.testsuite.webauthn.pages.WebAuthnLoginPage;
import org.keycloak.testsuite.webauthn.pages.WebAuthnRegisterPage;
import org.keycloak.testsuite.webauthn.updaters.WebAuthnRealmAttributeUpdater;
import org.keycloak.util.JsonSerialization;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.keycloak.models.AuthenticationExecutionModel.Requirement.ALTERNATIVE;
import static org.keycloak.models.AuthenticationExecutionModel.Requirement.REQUIRED;
public class WebAuthnRegisterAndLoginTest extends AbstractWebAuthnVirtualTest {
@Rule
public AssertEvents events = new AssertEvents(this);
@Page
protected AppPage appPage;
@Page
protected LoginPage loginPage;
@Page
protected WebAuthnLoginPage webAuthnLoginPage;
@Page
protected RegisterPage registerPage;
@Page
protected ErrorPage errorPage;
@Page
protected WebAuthnRegisterPage webAuthnRegisterPage;
@Page
protected LoginUsernameOnlyPage loginUsernamePage;
@Page
protected PasswordPage passwordPage;
@Page
protected SelectAuthenticatorPage selectAuthenticatorPage;
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
}
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
RealmRepresentation realmRepresentation = AbstractAdminTest.loadJson(getClass().getResourceAsStream("/webauthn/testrealm-webauthn.json"), RealmRepresentation.class);
List<String> acceptableAaguids = new ArrayList<>();
acceptableAaguids.add("00000000-0000-0000-0000-000000000000");
acceptableAaguids.add("6d44ba9b-f6ec-2e49-b930-0c8fe920cb73");
realmRepresentation.setWebAuthnPolicyAcceptableAaguids(acceptableAaguids);
testRealms.add(realmRepresentation);
}
@Test
public void registerUserSuccess() throws IOException {
String username = "registerUserSuccess";
String password = "password";
String email = "registerUserSuccess@email";
String userId = null;
try (RealmAttributeUpdater rau = updateRealmWithDefaultWebAuthnSettings(testRealm()).update()) {
loginPage.open();
loginPage.clickRegister();
registerPage.assertCurrent();
String authenticatorLabel = SecretGenerator.getInstance().randomString(24);
registerPage.register("firstName", "lastName", email, username, password, password);
// User was registered. Now he needs to register WebAuthn credential
webAuthnRegisterPage.assertCurrent();
webAuthnRegisterPage.clickRegister();
webAuthnRegisterPage.registerWebAuthnCredential(authenticatorLabel);
appPage.assertCurrent();
assertThat(appPage.getRequestType(), is(RequestType.AUTH_RESPONSE));
appPage.openAccount();
// confirm that registration is successfully completed
userId = events.expectRegister(username, email).assertEvent().getUserId();
// confirm registration event
EventRepresentation eventRep = events.expectRequiredAction(EventType.CUSTOM_REQUIRED_ACTION)
.user(userId)
.detail(Details.CUSTOM_REQUIRED_ACTION, WebAuthnRegisterFactory.PROVIDER_ID)
.detail(WebAuthnConstants.PUBKEY_CRED_LABEL_ATTR, authenticatorLabel)
.detail(WebAuthnConstants.PUBKEY_CRED_AAGUID_ATTR, ALL_ZERO_AAGUID)
.assertEvent();
String regPubKeyCredentialId = eventRep.getDetails().get(WebAuthnConstants.PUBKEY_CRED_ID_ATTR);
// confirm login event
String sessionId = events.expectLogin()
.user(userId)
.detail(Details.CUSTOM_REQUIRED_ACTION, WebAuthnRegisterFactory.PROVIDER_ID)
.detail(WebAuthnConstants.PUBKEY_CRED_LABEL_ATTR, authenticatorLabel)
.assertEvent().getSessionId();
// confirm user registered
assertUserRegistered(userId, username.toLowerCase(), email.toLowerCase());
assertRegisteredCredentials(userId, ALL_ZERO_AAGUID, "none");
events.clear();
// logout by user
appPage.logout();
// confirm logout event
events.expectLogout(sessionId)
.user(userId)
.assertEvent();
// login by user
loginPage.open();
loginPage.login(username, password);
webAuthnLoginPage.assertCurrent();
webAuthnLoginPage.clickAuthenticate();
appPage.assertCurrent();
assertThat(appPage.getRequestType(), is(RequestType.AUTH_RESPONSE));
appPage.openAccount();
// confirm login event
sessionId = events.expectLogin()
.user(userId)
.detail(WebAuthnConstants.PUBKEY_CRED_ID_ATTR, regPubKeyCredentialId)
.detail("web_authn_authenticator_user_verification_checked", Boolean.FALSE.toString())
.assertEvent().getSessionId();
events.clear();
// logout by user
appPage.logout();
// confirm logout event
events.expectLogout(sessionId)
.user(userId)
.assertEvent();
} finally {
removeFirstCredentialForUser(userId, WebAuthnCredentialModel.TYPE_TWOFACTOR);
}
}
@Test
public void testWebAuthnPasswordlessAlternativeWithWebAuthnAndPassword() throws IOException {
String userId = null;
final String WEBAUTHN_LABEL = "webauthn";
final String PASSWORDLESS_LABEL = "passwordless";
try (RealmAttributeUpdater rau = new RealmAttributeUpdater(testRealm())
.setBrowserFlow(webAuthnTogetherPasswordlessFlow())
.update()) {
UserRepresentation user = ApiUtil.findUserByUsername(testRealm(), "test-user@localhost");
assertThat(user, notNullValue());
user.getRequiredActions().add(WebAuthnPasswordlessRegisterFactory.PROVIDER_ID);
UserResource userResource = testRealm().users().get(user.getId());
assertThat(userResource, notNullValue());
userResource.update(user);
user = userResource.toRepresentation();
assertThat(user, notNullValue());
assertThat(user.getRequiredActions(), hasItem(WebAuthnPasswordlessRegisterFactory.PROVIDER_ID));
userId = user.getId();
loginUsernamePage.open();
loginUsernamePage.login("test-user@localhost");
passwordPage.assertCurrent();
passwordPage.login("password");
events.clear();
webAuthnRegisterPage.assertCurrent();
webAuthnRegisterPage.clickRegister();
webAuthnRegisterPage.registerWebAuthnCredential(PASSWORDLESS_LABEL);
webAuthnRegisterPage.assertCurrent();
webAuthnRegisterPage.clickRegister();
webAuthnRegisterPage.registerWebAuthnCredential(WEBAUTHN_LABEL);
appPage.assertCurrent();
events.expectRequiredAction(EventType.CUSTOM_REQUIRED_ACTION)
.user(userId)
.detail(Details.CUSTOM_REQUIRED_ACTION, WebAuthnPasswordlessRegisterFactory.PROVIDER_ID)
.detail(WebAuthnConstants.PUBKEY_CRED_LABEL_ATTR, PASSWORDLESS_LABEL)
.assertEvent();
events.expectRequiredAction(EventType.CUSTOM_REQUIRED_ACTION)
.user(userId)
.detail(Details.CUSTOM_REQUIRED_ACTION, WebAuthnRegisterFactory.PROVIDER_ID)
.detail(WebAuthnConstants.PUBKEY_CRED_LABEL_ATTR, WEBAUTHN_LABEL)
.assertEvent();
final String sessionID = events.expectLogin()
.user(userId)
.assertEvent()
.getSessionId();
events.clear();
appPage.logout();
events.expectLogout(sessionID)
.user(userId)
.assertEvent();
// Password + WebAuthn security key
loginUsernamePage.open();
loginUsernamePage.assertCurrent();
loginUsernamePage.login("test-user@localhost");
passwordPage.assertCurrent();
passwordPage.login("password");
webAuthnLoginPage.assertCurrent();
webAuthnLoginPage.clickAuthenticate();
appPage.assertCurrent();
appPage.logout();
// Only passwordless login
loginUsernamePage.open();
loginUsernamePage.login("test-user@localhost");
passwordPage.assertCurrent();
passwordPage.assertTryAnotherWayLinkAvailability(true);
passwordPage.clickTryAnotherWayLink();
selectAuthenticatorPage.assertCurrent();
assertThat(selectAuthenticatorPage.getLoginMethodHelpText(SelectAuthenticatorPage.SECURITY_KEY),
is("Use your security key for passwordless sign in."));
selectAuthenticatorPage.selectLoginMethod(SelectAuthenticatorPage.SECURITY_KEY);
webAuthnLoginPage.assertCurrent();
webAuthnLoginPage.clickAuthenticate();
appPage.assertCurrent();
appPage.logout();
} finally {
removeFirstCredentialForUser(userId, WebAuthnCredentialModel.TYPE_TWOFACTOR, WEBAUTHN_LABEL);
removeFirstCredentialForUser(userId, WebAuthnCredentialModel.TYPE_PASSWORDLESS, PASSWORDLESS_LABEL);
}
}
@Test
public void testWebAuthnTwoFactorAndWebAuthnPasswordlessTogether() throws IOException {
// Change binding to browser-webauthn-passwordless. This is flow, which contains both "webauthn" and "webauthn-passwordless" authenticator
try (RealmAttributeUpdater rau = new RealmAttributeUpdater(testRealm()).setBrowserFlow("browser-webauthn-passwordless").update()) {
// Login as test-user@localhost with password
loginPage.open();
loginPage.login("test-user@localhost", "password");
errorPage.assertCurrent();
// User is not allowed to register passwordless authenticator in this flow
assertThat(events.poll().getError(), is("invalid_user_credentials"));
assertThat(errorPage.getError(), is("Cannot login, credential setup required."));
}
}
private void assertUserRegistered(String userId, String username, String email) {
UserRepresentation user = getUser(userId);
assertThat(user, notNullValue());
assertThat(user.getCreatedTimestamp(), notNullValue());
// test that timestamp is current with 60s tollerance
assertThat((System.currentTimeMillis() - user.getCreatedTimestamp()) < 60000, is(true));
// test user info is set from form
assertThat(user.getUsername(), is(username.toLowerCase()));
assertThat(user.getEmail(), is(email.toLowerCase()));
assertThat(user.getFirstName(), is("firstName"));
assertThat(user.getLastName(), is("lastName"));
}
private void assertRegisteredCredentials(String userId, String aaguid, String attestationStatementFormat) {
List<CredentialRepresentation> credentials = getCredentials(userId);
credentials.forEach(i -> {
if (WebAuthnCredentialModel.TYPE_TWOFACTOR.equals(i.getType())) {
try {
WebAuthnCredentialData data = JsonSerialization.readValue(i.getCredentialData(), WebAuthnCredentialData.class);
assertThat(data.getAaguid(), is(aaguid));
assertThat(data.getAttestationStatementFormat(), is(attestationStatementFormat));
} catch (IOException e) {
Assert.fail();
}
}
});
}
protected UserRepresentation getUser(String userId) {
return testRealm().users().get(userId).toRepresentation();
}
protected List<CredentialRepresentation> getCredentials(String userId) {
return testRealm().users().get(userId).credentials();
}
private static WebAuthnRealmAttributeUpdater updateRealmWithDefaultWebAuthnSettings(RealmResource resource) {
return new WebAuthnRealmAttributeUpdater(resource)
.setWebAuthnPolicySignatureAlgorithms(Collections.singletonList("ES256"))
.setWebAuthnPolicyAttestationConveyancePreference("none")
.setWebAuthnPolicyAuthenticatorAttachment("cross-platform")
.setWebAuthnPolicyRequireResidentKey("No")
.setWebAuthnPolicyRpId(null)
.setWebAuthnPolicyUserVerificationRequirement("preferred")
.setWebAuthnPolicyAcceptableAaguids(Collections.singletonList(ALL_ZERO_AAGUID));
}
/**
* This flow contains:
* <p>
* UsernameForm REQUIRED
* Subflow REQUIRED
* ** WebAuthnPasswordlessAuthenticator ALTERNATIVE
* ** sub-subflow ALTERNATIVE
* **** PasswordForm ALTERNATIVE
* **** WebAuthnAuthenticator ALTERNATIVE
*
* @return flow alias
*/
private String webAuthnTogetherPasswordlessFlow() {
final String newFlowAlias = "browser-together-webauthn-flow";
testingClient.server(TEST_REALM_NAME).run(session -> FlowUtil.inCurrentRealm(session).copyBrowserFlow(newFlowAlias));
testingClient.server(TEST_REALM_NAME).run(session -> {
FlowUtil.inCurrentRealm(session)
.selectFlow(newFlowAlias)
.inForms(forms -> forms
.clear()
.addAuthenticatorExecution(REQUIRED, UsernameFormFactory.PROVIDER_ID)
.addSubFlowExecution(REQUIRED, subFlow -> subFlow
.addAuthenticatorExecution(ALTERNATIVE, WebAuthnPasswordlessAuthenticatorFactory.PROVIDER_ID)
.addSubFlowExecution(ALTERNATIVE, passwordFlow -> passwordFlow
.addAuthenticatorExecution(REQUIRED, PasswordFormFactory.PROVIDER_ID)
.addAuthenticatorExecution(REQUIRED, WebAuthnAuthenticatorFactory.PROVIDER_ID))
))
.defineAsBrowserFlow();
});
return newFlowAlias;
}
private void removeFirstCredentialForUser(String userId, String credentialType) {
removeFirstCredentialForUser(userId, credentialType, null);
}
/**
* Remove first occurring credential from user with specific credentialType
*
* @param userId userId
* @param credentialType type of credential
* @param assertUserLabel user label of credential
*/
private void removeFirstCredentialForUser(String userId, String credentialType, String assertUserLabel) {
if (userId == null || credentialType == null) return;
final UserResource userResource = testRealm().users().get(userId);
final CredentialRepresentation credentialRep = userResource.credentials()
.stream()
.filter(credential -> credentialType.equals(credential.getType()))
.findFirst().orElse(null);
assertThat(credentialRep, notNullValue());
if (assertUserLabel != null) {
assertThat(credentialRep.getUserLabel(), is(assertUserLabel));
}
userResource.removeCredential(credentialRep.getId());
}
}
| |
/*
* 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.cocoon.components.language.programming.java;
import org.apache.avalon.excalibur.pool.Recyclable;
import org.apache.cocoon.components.language.programming.CompilerError;
import org.apache.cocoon.components.language.programming.LanguageCompiler;
import org.apache.cocoon.util.ClassUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
import org.eclipse.jdt.internal.compiler.IProblemFactory;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Eclipse Java Compiler
*
* @version $Id$
*/
public class EclipseJavaCompiler implements LanguageCompiler, Recyclable {
boolean debug;
String sourceDir;
String sourceFile;
String destDir;
String sourceEncoding;
int compilerComplianceLevel;
List errors = new LinkedList();
public EclipseJavaCompiler() {
this.debug = true;
}
public void recycle() {
sourceFile = null;
sourceDir = null;
destDir = null;
sourceEncoding = null;
errors.clear();
}
public void setFile(String file) {
// This is the absolute path to the file to be compiled
this.sourceFile = file;
}
public void setSource(String srcDir) {
// This is the "sourcepath" of the file to be compiled
this.sourceDir = srcDir;
}
public void setDestination(String destDir) {
// This is the output directory)
this.destDir = destDir;
}
public void setEncoding(String encoding) {
this.sourceEncoding = encoding;
}
/**
* Set the version of the java source code to be compiled
*
* @param compilerComplianceLevel The version of the JVM for which the code was written.
* i.e: 130 = Java 1.3, 140 = Java 1.4 and 150 = Java 1.5
*
* @since 2.1.7
*/
public void setCompilerComplianceLevel(int compilerComplianceLevel) {
this.compilerComplianceLevel = compilerComplianceLevel;
}
/**
* Eclipse Java compiler ignores class path setting and uses current
* Java class loader
* @param cp classpath to be ignored
*/
public void setClasspath(String cp) {
// Not used
}
private String makeClassName(String fileName) throws IOException {
File origFile = new File(fileName);
String canonical = null;
if (origFile.exists()) {
canonical = origFile.getCanonicalPath().replace('\\', '/');
}
String str = fileName;
str = str.replace('\\', '/');
if (sourceDir != null) {
String prefix =
new File(sourceDir).getCanonicalPath().replace('\\', '/');
if (canonical != null) {
if (canonical.startsWith(prefix)) {
String result = canonical.substring(prefix.length() + 1,
canonical.length() -5);
result = result.replace('/', '.');
return result;
}
} else {
File t = new File(sourceDir, fileName);
if (t.exists()) {
str = t.getCanonicalPath().replace('\\', '/');
String result = str.substring(prefix.length()+1,
str.length() - 5).replace('/', '.');
return result;
}
}
}
if (fileName.endsWith(".java")) {
fileName = fileName.substring(0, fileName.length() - 5);
}
return StringUtils.replaceChars(fileName, "\\/", "..");
}
public boolean compile() throws IOException {
final String targetClassName = makeClassName(sourceFile);
final ClassLoader classLoader = ClassUtils.getClassLoader();
String[] fileNames = new String[] {sourceFile};
String[] classNames = new String[] {targetClassName};
class CompilationUnit implements ICompilationUnit {
String className;
String sourceFile;
CompilationUnit(String sourceFile, String className) {
this.className = className;
this.sourceFile = sourceFile;
}
public char[] getFileName() {
return className.toCharArray();
}
public char[] getContents() {
char[] result = null;
FileReader fr = null;
try {
fr = new FileReader(sourceFile);
final Reader reader = new BufferedReader(fr);
try {
if (reader != null) {
char[] chars = new char[8192];
StringBuffer buf = new StringBuffer();
int count;
while ((count = reader.read(chars, 0, chars.length)) > 0) {
buf.append(chars, 0, count);
}
result = new char[buf.length()];
buf.getChars(0, result.length, result, 0);
}
} finally {
reader.close();
}
} catch (IOException e) {
handleError(className, -1, -1, e.getMessage());
}
return result;
}
public char[] getMainTypeName() {
int dot = className.lastIndexOf('.');
if (dot > 0) {
return className.substring(dot + 1).toCharArray();
}
return className.toCharArray();
}
public char[][] getPackageName() {
StringTokenizer izer = new StringTokenizer(className, ".");
char[][] result = new char[izer.countTokens()-1][];
for (int i = 0; i < result.length; i++) {
String tok = izer.nextToken();
result[i] = tok.toCharArray();
}
return result;
}
}
final INameEnvironment env = new INameEnvironment() {
public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < compoundTypeName.length; i++) {
if (i > 0) {
result.append(".");
}
result.append(compoundTypeName[i]);
}
return findType(result.toString());
}
public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < packageName.length; i++) {
if (i > 0) {
result.append(".");
}
result.append(packageName[i]);
}
result.append(".");
result.append(typeName);
return findType(result.toString());
}
private NameEnvironmentAnswer findType(String className) {
try {
if (className.equals(targetClassName)) {
ICompilationUnit compilationUnit =
new CompilationUnit(sourceFile, className);
return
new NameEnvironmentAnswer(compilationUnit, null);
}
String resourceName =
className.replace('.', '/') + ".class";
InputStream is =
classLoader.getResourceAsStream(resourceName);
if (is != null) {
byte[] classBytes;
byte[] buf = new byte[8192];
ByteArrayOutputStream baos =
new ByteArrayOutputStream(buf.length);
int count;
while ((count = is.read(buf, 0, buf.length)) > 0) {
baos.write(buf, 0, count);
}
baos.flush();
classBytes = baos.toByteArray();
char[] fileName = className.toCharArray();
ClassFileReader classFileReader =
new ClassFileReader(classBytes, fileName,
true);
return
new NameEnvironmentAnswer(classFileReader, null);
}
} catch (IOException exc) {
handleError(className, -1, -1,
exc.getMessage());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
handleError(className, -1, -1,
exc.getMessage());
}
return null;
}
private boolean isPackage(String result) {
if (result.equals(targetClassName)) {
return false;
}
String resourceName = result.replace('.', '/') + ".class";
InputStream is =
classLoader.getResourceAsStream(resourceName);
return is == null;
}
public boolean isPackage(char[][] parentPackageName, char[] packageName) {
StringBuffer result = new StringBuffer();
if (parentPackageName != null) {
for (int i = 0; i < parentPackageName.length; i++) {
if (i > 0) {
result.append(".");
}
result.append(parentPackageName[i]);
}
}
String str = new String(packageName);
if (Character.isUpperCase(str.charAt(0)) && !isPackage(result.toString())) {
return false;
}
result.append(".");
result.append(str);
return isPackage(result.toString());
}
public void cleanup() {
// EMPTY
}
};
final IErrorHandlingPolicy policy =
DefaultErrorHandlingPolicies.proceedWithAllProblems();
final Map settings = new HashMap(9);
settings.put(CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
settings.put(CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
settings.put(CompilerOptions.OPTION_ReportDeprecation,
CompilerOptions.IGNORE);
settings.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE);
if (sourceEncoding != null) {
settings.put(CompilerOptions.OPTION_Encoding, sourceEncoding);
}
if (debug) {
settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
}
// Set the sourceCodeVersion
switch (this.compilerComplianceLevel) {
case 150:
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
break;
case 140:
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
break;
default:
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
}
// Set the target platform
switch (SystemUtils.JAVA_VERSION_INT) {
case 150:
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
break;
case 140:
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
break;
default:
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
}
final IProblemFactory problemFactory =
new DefaultProblemFactory(Locale.getDefault());
final ICompilerRequestor requestor = new ICompilerRequestor() {
public void acceptResult(CompilationResult result) {
try {
if (result.hasErrors()) {
IProblem[] errors = result.getErrors();
for (int i = 0; i < errors.length; i++) {
IProblem error = errors[i];
String name = new String(errors[i].getOriginatingFileName());
handleError(name, error.getSourceLineNumber(), -1, error.getMessage());
}
} else {
ClassFile[] classFiles = result.getClassFiles();
for (int i = 0; i < classFiles.length; i++) {
ClassFile classFile = classFiles[i];
char[][] compoundName = classFile.getCompoundName();
StringBuffer className = new StringBuffer();
for (int j = 0; j < compoundName.length; j++) {
if (j > 0) {
className.append(".");
}
className.append(compoundName[j]);
}
byte[] bytes = classFile.getBytes();
String outFile = destDir + "/" +
className.toString().replace('.', '/') + ".class";
FileOutputStream fout = new FileOutputStream(outFile);
BufferedOutputStream bos = new BufferedOutputStream(fout);
bos.write(bytes);
bos.close();
}
}
} catch (IOException exc) {
exc.printStackTrace();
}
}
};
ICompilationUnit[] compilationUnits =
new ICompilationUnit[classNames.length];
for (int i = 0; i < compilationUnits.length; i++) {
String className = classNames[i];
compilationUnits[i] = new CompilationUnit(fileNames[i], className);
}
Compiler compiler = new Compiler(env,
policy,
settings,
requestor,
problemFactory);
compiler.compile(compilationUnits);
return errors.size() == 0;
}
void handleError(String className, int line, int column, Object errorMessage) {
String fileName =
className.replace('.', File.separatorChar) + ".java";
if (column < 0) column = 0;
errors.add(new CompilerError(fileName,
true,
line,
column,
line,
column,
errorMessage.toString()));
}
public List getErrors() throws IOException {
return errors;
}
}
| |
/*
* Copyright 2017 StreamSets 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.streamsets.pipeline.stage.destination.solr;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.streamsets.pipeline.api.Field;
import com.streamsets.pipeline.api.OnRecordError;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.Stage;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.Target;
import com.streamsets.pipeline.sdk.RecordCreator;
import com.streamsets.pipeline.sdk.TargetRunner;
import com.streamsets.pipeline.solr.api.Errors;
import com.streamsets.pipeline.solr.api.SdcSolrTestUtil;
import com.streamsets.pipeline.solr.api.SdcSolrTestUtilFactory;
import com.streamsets.pipeline.stage.processor.scripting.ProcessingMode;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.apache.solr.SolrJettyTestBase;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
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 TestSolrTarget extends SolrJettyTestBase {
private static final Logger LOG = LoggerFactory.getLogger(TestSolrTarget.class);
private static JettySolrRunner jetty;
private static MissingFieldAction emptyFieldRecordError = MissingFieldAction.TO_ERROR;
private static SdcSolrTestUtil sdcSolrTestUtil;
@BeforeClass
public static void beforeTest() throws Exception {
File solrHomeDir = new File("target", UUID.randomUUID().toString());
Assert.assertTrue(solrHomeDir.mkdirs());
URL url = Thread.currentThread().getContextClassLoader().getResource("solr/");
Assert.assertNotNull(url);
FileUtils.copyDirectoryToDirectory(new File(url.toURI()), solrHomeDir);
jetty = createJetty(solrHomeDir.getAbsolutePath() + "/solr", (String)null, null);
String jettyUrl = jetty.getBaseUrl().toString() + "/" + "collection1";
sdcSolrTestUtil = SdcSolrTestUtilFactory.getInstance().create(jettyUrl);
}
@AfterClass
public static void destory() {
sdcSolrTestUtil.destroy();
}
@SuppressWarnings("unchecked")
@Test
public void testValidations() throws Exception {
String solrURI = jetty.getBaseUrl().toString() + "/" + "collection1";
Target target = new SolrTarget(InstanceTypeOptions.SINGLE_NODE, null, null, ProcessingMode.BATCH, null, null, false,
emptyFieldRecordError, false);
TargetRunner runner = new TargetRunner.Builder(SolrDTarget.class, target).build();
List<Stage.ConfigIssue> issues = runner.runValidateConfigs();
Assert.assertEquals(2, issues.size());
Assert.assertTrue(issues.get(0).toString().contains(Errors.SOLR_00.name()));
Assert.assertTrue(issues.get(1).toString().contains(Errors.SOLR_02.name()));
target = new SolrTarget(InstanceTypeOptions.SOLR_CLOUD, null, null, ProcessingMode.BATCH, null, null, false,
emptyFieldRecordError, false);
runner = new TargetRunner.Builder(SolrDTarget.class, target).build();
issues = runner.runValidateConfigs();
Assert.assertEquals(2, issues.size());
Assert.assertTrue(issues.get(0).toString().contains(Errors.SOLR_01.name()));
Assert.assertTrue(issues.get(1).toString().contains(Errors.SOLR_02.name()));
//Valid Solr URI
target = new SolrTarget(InstanceTypeOptions.SINGLE_NODE, solrURI, null, ProcessingMode.BATCH, null, null, false,
emptyFieldRecordError, false);
runner = new TargetRunner.Builder(SolrDTarget.class, target).build();
issues = runner.runValidateConfigs();
Assert.assertEquals(1, issues.size());
Assert.assertTrue(issues.get(0).toString().contains(Errors.SOLR_02.name()));
List<SolrFieldMappingConfig> fieldNamesMap = new ArrayList<>();
fieldNamesMap.add(new SolrFieldMappingConfig("/field", "solrFieldMapping"));
target = new SolrTarget(InstanceTypeOptions.SINGLE_NODE, "invalidSolrURI", null, ProcessingMode.BATCH,
fieldNamesMap, null, false, emptyFieldRecordError, false);
runner = new TargetRunner.Builder(SolrDTarget.class, target).build();
issues = runner.runValidateConfigs();
Assert.assertEquals(1, issues.size());
Assert.assertTrue(issues.get(0).toString().contains(Errors.SOLR_03.name()));
}
private Target createTarget() {
String solrURI = jetty.getBaseUrl().toString() + "/" + "collection1";
List<SolrFieldMappingConfig> fieldNamesMap = new ArrayList<>();
fieldNamesMap.add(new SolrFieldMappingConfig("/a", "id"));
fieldNamesMap.add(new SolrFieldMappingConfig("/a", "name"));
fieldNamesMap.add(new SolrFieldMappingConfig("/b", "sku"));
fieldNamesMap.add(new SolrFieldMappingConfig("/c", "manu"));
fieldNamesMap.add(new SolrFieldMappingConfig("/titleMultiValued", "title"));
return new SolrTarget(InstanceTypeOptions.SINGLE_NODE, solrURI, null, ProcessingMode.BATCH, fieldNamesMap, null,
false, emptyFieldRecordError, false);
}
@SuppressWarnings("unchecked")
@Test
public void testWriteRecords() throws Exception {
Target target = createTarget();
TargetRunner runner = new TargetRunner.Builder(SolrDTarget.class, target).build();
try {
//delete all index
sdcSolrTestUtil.deleteByQuery("*:*");
runner.runInit();
List<Record> records = new ArrayList<>();
Record record1 = RecordCreator.create();
record1.set(Field.create(ImmutableMap.of(
"a", Field.create("Hello"),
"b", Field.create("i"),
"c", Field.create("t"),
"titleMultiValued", Field.create(ImmutableList.of(Field.create("title1"), Field.create("title2")))
)));
Record record2 = RecordCreator.create();
record2.set(Field.create(ImmutableMap.of(
"a", Field.create("Bye"),
"b", Field.create("i"),
"c", Field.create("t"),
"titleMultiValued", Field.create(ImmutableList.of(Field.create("title1"), Field.create("title2")))
)));
records.add(record1);
records.add(record2);
runner.runWrite(records);
Assert.assertTrue(runner.getErrorRecords().isEmpty());
Assert.assertTrue(runner.getErrors().isEmpty());
Map<String, String> parameters = new HashMap();
parameters.put("q", "name:Hello");
List<Map<String, Object>> solrDocuments = sdcSolrTestUtil.query(parameters);
Assert.assertEquals(1, solrDocuments.size());
Map<String, Object> solrDocument = solrDocuments.get(0);
String fieldAVal = (String) solrDocument.get("name");
Assert.assertNotNull(fieldAVal);
Assert.assertEquals("Hello", fieldAVal);
String fieldBVal = (String) solrDocument.get("sku");
Assert.assertNotNull(fieldBVal);
Assert.assertEquals("i", fieldBVal);
String fieldCVal = (String) solrDocument.get("manu");
Assert.assertNotNull(fieldCVal);
Assert.assertEquals("t", fieldCVal);
List<String> titleCVal = (List<String>) solrDocument.get("title");
Assert.assertNotNull(titleCVal);
Assert.assertEquals(2, titleCVal.size());
Assert.assertEquals("title1", titleCVal.get(0));
Assert.assertEquals("title2", titleCVal.get(1));
} catch (Exception e) {
LOG.error("Exception while writing records", e);
throw e;
}
finally {
runner.runDestroy();
}
}
@SuppressWarnings("unchecked")
@Test
public void testWriteRecordsOnErrorDiscard() throws Exception {
Target target = createTarget();
TargetRunner runner = new TargetRunner.Builder(SolrDTarget.class, target).setOnRecordError(OnRecordError.DISCARD)
.build();
try {
//delete all index
sdcSolrTestUtil.deleteByQuery("*:*");
runner.runInit();
List<Record> records = new ArrayList<>();
Record record1 = RecordCreator.create();
record1.set(Field.create(ImmutableMap.of("nota", Field.create("Hello"),
"b", Field.create("i1"), "c", Field.create("t1"))));
Record record2 = RecordCreator.create();
record2.set(Field.create(ImmutableMap.of("a", Field.create("Bye"),
"b", Field.create("i2"), "c2", Field.create("t2"))));
records.add(record1);
records.add(record2);
runner.runWrite(records);
Assert.assertTrue(runner.getErrorRecords().isEmpty());
Assert.assertTrue(runner.getErrors().isEmpty());
Map<String, String> parameters = new HashMap();
parameters.put("q", "sku:i1");
List<Map<String, Object>> solrDocuments = sdcSolrTestUtil.query(parameters);
Assert.assertEquals(0, solrDocuments.size());
} finally {
runner.runDestroy();
}
}
@SuppressWarnings("unchecked")
@Test
public void testWriteRecordsOnErrorToError() throws Exception {
Target target = createTarget();
TargetRunner runner = new TargetRunner.Builder(SolrDTarget.class, target).setOnRecordError(OnRecordError.TO_ERROR)
.build();
try {
//delete all index
sdcSolrTestUtil.deleteByQuery("*:*");
runner.runInit();
List<Record> records = new ArrayList<>();
Record record1 = RecordCreator.create();
// intentionally create Record with mismatching field name ("nota" instead of "a") to trigger an error
record1.set(Field.create(ImmutableMap.of("nota", Field.create("Hello"),
"b", Field.create("i1"), "c", Field.create("t1"))));
Record record2 = RecordCreator.create();
record2.set(Field.create(ImmutableMap.of("a", Field.create("Bye"),
"b", Field.create("i2"), "c", Field.create("t2"))));
records.add(record1);
records.add(record2);
runner.runWrite(records);
Assert.assertEquals(2, runner.getErrorRecords().size());
Assert.assertEquals("Hello", runner.getErrorRecords().get(0).get("/nota").getValueAsString());
Assert.assertTrue(runner.getErrors().isEmpty());
Map<String, String> parameters = new HashMap();
parameters.put("q", "sku:i1");
List<Map<String, Object>> solrDocuments = sdcSolrTestUtil.query(parameters);
Assert.assertEquals(0, solrDocuments.size());
} finally {
runner.runDestroy();
}
}
@SuppressWarnings("unchecked")
@Test
public void testWriteRecordsOnErrorToErrorDuringIndexing() throws Exception {
//Create target without solr field id
String solrURI = jetty.getBaseUrl().toString() + "/" + "collection1";
List<SolrFieldMappingConfig> fieldNamesMap = new ArrayList<>();
fieldNamesMap.add(new SolrFieldMappingConfig("/a", "name"));
Target target = new SolrTarget(InstanceTypeOptions.SINGLE_NODE, solrURI, null, ProcessingMode.BATCH, fieldNamesMap,
null, false, emptyFieldRecordError, false);
TargetRunner runner = new TargetRunner.Builder(SolrDTarget.class, target).setOnRecordError(OnRecordError.TO_ERROR)
.build();
try {
//delete all index
sdcSolrTestUtil.deleteByQuery("*:*");
runner.runInit();
List<Record> records = new ArrayList<>();
Record record1 = RecordCreator.create();
record1.set(Field.create(ImmutableMap.of("nota", Field.create("Hello"),
"b", Field.create("i1"), "c", Field.create("t1"))));
Record record2 = RecordCreator.create();
record2.set(Field.create(ImmutableMap.of("a", Field.create("Bye"),
"b", Field.create("i2"), "c", Field.create("t2"))));
records.add(record1);
records.add(record2);
runner.runWrite(records);
Assert.assertEquals(2, runner.getErrorRecords().size());
Assert.assertEquals("Hello", runner.getErrorRecords().get(0).get("/nota").getValueAsString());
Assert.assertTrue(runner.getErrors().isEmpty());
Map<String, String> parameters = new HashedMap();
parameters.put("q", "sku:i1");
List<Map<String, Object>> solrDocuments = sdcSolrTestUtil.query(parameters);
Assert.assertEquals(0, solrDocuments.size());
} finally {
runner.runDestroy();
}
}
@Test(expected = StageException.class)
public void testWriteRecordsOnErrorStopPipeline() throws Exception {
Target target = createTarget();
TargetRunner runner = new TargetRunner.Builder(SolrDTarget.class, target)
.setOnRecordError(OnRecordError.STOP_PIPELINE)
.build();
try {
runner.runInit();
List<Record> records = new ArrayList<>();
Record record1 = RecordCreator.create();
record1.set(Field.create(ImmutableMap.of("nota", Field.create("Hello"),
"b", Field.create("i1"), "c", Field.create("t1"))));
Record record2 = RecordCreator.create();
record2.set(Field.create(ImmutableMap.of("a", Field.create("Bye"),
"b", Field.create("i2"), "c", Field.create("t2"))));
records.add(record1);
records.add(record2);
runner.runWrite(records);
} finally {
runner.runDestroy();
}
}
@Test(expected = StageException.class)
public void testWriteEmptyFieldRecordOnErrorStopPipeline() throws Exception {
String solrURI = jetty.getBaseUrl().toString() + "/" + "collection1";
List<SolrFieldMappingConfig> fieldNamesMap = new ArrayList<>();
fieldNamesMap.add(new SolrFieldMappingConfig("/a", "id"));
final MissingFieldAction emptyFieldRecordError = MissingFieldAction.STOP_PIPELINE;
Target target = new SolrTarget(
InstanceTypeOptions.SINGLE_NODE,
solrURI,
null,
ProcessingMode.BATCH,
fieldNamesMap,
null,
false,
emptyFieldRecordError,
false
);
TargetRunner runner = new TargetRunner.Builder(SolrDTarget.class, target)
.setOnRecordError(OnRecordError.DISCARD)
.build();
try {
runner.runInit();
// create empty record
List<Record> records = new ArrayList<>();
Record record = RecordCreator.create();
records.add(record);
runner.runWrite(records);
} finally {
runner.runDestroy();
}
}
public void testWriteEmptyFieldRecordOnErrorSendToError() throws Exception {
String solrURI = jetty.getBaseUrl().toString() + "/" + "collection1";
List<SolrFieldMappingConfig> fieldNamesMap = new ArrayList<>();
fieldNamesMap.add(new SolrFieldMappingConfig("/a", "id"));
final MissingFieldAction emptyFieldRecordError = MissingFieldAction.TO_ERROR;
Target target = new SolrTarget(
InstanceTypeOptions.SINGLE_NODE,
solrURI,
null,
ProcessingMode.BATCH,
fieldNamesMap,
null,
false,
emptyFieldRecordError,
false
);
TargetRunner runner = new TargetRunner.Builder(SolrDTarget.class, target)
.setOnRecordError(OnRecordError.TO_ERROR)
.build();
try {
runner.runInit();
// create empty record
List<Record> records = new ArrayList<>();
Record record = RecordCreator.create();
records.add(record);
runner.runWrite(records);
Assert.assertEquals(1, runner.getErrorRecords().size());
} finally {
runner.runDestroy();
}
}
public void testWriteEmptyFieldRecordOnErrorDiscard() throws Exception {
String solrURI = jetty.getBaseUrl().toString() + "/" + "collection1";
List<SolrFieldMappingConfig> fieldNamesMap = new ArrayList<>();
fieldNamesMap.add(new SolrFieldMappingConfig("/a", "id"));
MissingFieldAction emptyFieldRecordError = MissingFieldAction.DISCARD;
Target target = new SolrTarget(
InstanceTypeOptions.SINGLE_NODE,
solrURI,
null,
ProcessingMode.BATCH,
fieldNamesMap,
null,
false,
emptyFieldRecordError,
false
);
TargetRunner runner = new TargetRunner.Builder(SolrDTarget.class, target)
.setOnRecordError(OnRecordError.DISCARD)
.build();
try {
runner.runInit();
// create empty record
List<Record> records = new ArrayList<>();
Record record = RecordCreator.create();
records.add(record);
runner.runWrite(records);
Assert.assertEquals(0, runner.getErrorRecords().size());
} finally {
runner.runDestroy();
}
}
}
| |
package com.vaadin.tests.tickets;
import java.util.Iterator;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.MethodProperty;
import com.vaadin.server.SystemError;
import com.vaadin.server.ThemeResource;
import com.vaadin.shared.ui.AlignmentInfo.Bits;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Form;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
import com.vaadin.ui.Layout.AlignmentHandler;
import com.vaadin.ui.LegacyWindow;
import com.vaadin.ui.NativeSelect;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
public class Ticket1710 extends com.vaadin.server.LegacyApplication {
@Override
public void init() {
setTheme("tests-tickets");
VerticalLayout lo = new VerticalLayout();
setMainWindow(new LegacyWindow("#1710", lo));
lo.setMargin(true);
lo.setSpacing(true);
lo.setWidth("100%");
// Hiding controls
HorizontalLayout hidingControls = new HorizontalLayout();
lo.addComponent(hidingControls);
// OrderedLayout
final VerticalLayout orderedLayout = new VerticalLayout();
LayoutTestingPanel oltp = new LayoutTestingPanel("OrderedLayout",
orderedLayout);
CheckBox cb = new CheckBox("OrderedLayout",
new MethodProperty<Boolean>(oltp, "visible"));
cb.setImmediate(true);
hidingControls.addComponent(cb);
lo.addComponent(oltp);
orderedLayout.setSpacing(false);
addFields(orderedLayout);
// GridLayout
GridLayout grid = new GridLayout(1, 1);
Panel g1tp = new LayoutTestingPanel("Gridlayout with 1 column", grid);
cb = new CheckBox("GridLayout (1col)", new MethodProperty<Boolean>(
g1tp, "visible"));
cb.setImmediate(true);
hidingControls.addComponent(cb);
g1tp.setVisible(false);
lo.addComponent(g1tp);
grid.setSpacing(true);
addFields(grid);
GridLayout grid2 = new GridLayout(2, 1);
Panel g2tp = new LayoutTestingPanel("Gridlayout with 2 columns", grid2);
cb = new CheckBox("GridLayout (2cols)", new MethodProperty<Boolean>(
g2tp, "visible"));
cb.setImmediate(true);
hidingControls.addComponent(cb);
g2tp.setVisible(false);
lo.addComponent(g2tp);
grid2.setSpacing(true);
addFields(grid2);
// ExpandLayout
VerticalLayout el = new VerticalLayout();
Panel elp = new LayoutTestingPanel(
"ExpandLayout width first component expanded", el);
cb = new CheckBox("ExpandLayout (vertical)",
new MethodProperty<Boolean>(elp, "visible"));
cb.setImmediate(true);
hidingControls.addComponent(cb);
elp.setVisible(false);
el.setHeight("700px");
addFields(el);
Component firstComponent = el.getComponentIterator().next();
firstComponent.setSizeFull();
el.setExpandRatio(firstComponent, 1);
lo.addComponent(elp);
HorizontalLayout elh = new HorizontalLayout();
Panel elhp = new LayoutTestingPanel(
"ExpandLayout width first component expanded; horizontal", elh);
cb = new CheckBox("ExpandLayout (horizontal)",
new MethodProperty<Boolean>(elhp, "visible"));
cb.setImmediate(true);
hidingControls.addComponent(cb);
elhp.setVisible(false);
elh.setWidth("2000px");
elh.setHeight("100px");
addFields(elh);
Component firstComponentElh = elh.getComponentIterator().next();
firstComponentElh.setSizeFull();
elh.setExpandRatio(firstComponentElh, 1);
lo.addComponent(elhp);
// CustomLayout
VerticalLayout cl = new VerticalLayout();
Panel clp = new LayoutTestingPanel("CustomLayout", cl);
cb = new CheckBox("CustomLayout", new MethodProperty<Boolean>(clp,
"visible"));
cb.setImmediate(true);
hidingControls.addComponent(cb);
clp.setVisible(false);
lo.addComponent(clp);
cl.addComponent(new Label("<<< Add customlayout testcase here >>>"));
// Form
VerticalLayout formPanelLayout = new VerticalLayout();
formPanelLayout.setMargin(true);
Panel formPanel = new Panel("Form", formPanelLayout);
cb = new CheckBox("Form", new MethodProperty<Boolean>(formPanel,
"visible"));
cb.setImmediate(true);
hidingControls.addComponent(cb);
formPanel.setVisible(false);
formPanelLayout.addComponent(getFormPanelExample());
lo.addComponent(formPanel);
for (Iterator<Component> i = hidingControls.getComponentIterator(); i
.hasNext();) {
((AbstractComponent) i.next()).setImmediate(true);
}
}
private Form getFormPanelExample() {
Form f = new Form();
f.setCaption("Test form");
CheckBox fb2 = new CheckBox("Test button", true);
fb2.setComponentError(new SystemError("Test error"));
f.addField("fb2", fb2);
TextField ft1 = new TextField("With caption");
ft1.setComponentError(new SystemError("Error"));
f.addField("ft1", ft1);
TextField ft2 = new TextField();
ft2.setComponentError(new SystemError("Error"));
ft2.setValue("Without caption");
f.addField("ft2", ft2);
TextField ft3 = new TextField("With caption and required");
ft3.setComponentError(new SystemError("Error"));
ft3.setRequired(true);
f.addField("ft3", ft3);
return f;
}
private void addFields(ComponentContainer lo) {
Button button = new Button("Test button");
button.setComponentError(new SystemError("Test error"));
lo.addComponent(button);
CheckBox b2 = new CheckBox("Test button");
b2.setComponentError(new SystemError("Test error"));
lo.addComponent(b2);
TextField t1 = new TextField("With caption");
t1.setComponentError(new SystemError("Error"));
lo.addComponent(t1);
TextField t2 = new TextField("With caption and required");
t2.setComponentError(new SystemError("Error"));
t2.setRequired(true);
lo.addComponent(t2);
TextField t3 = new TextField();
t3.setValue("Without caption");
t3.setComponentError(new SystemError("Error"));
lo.addComponent(t3);
lo.addComponent(new TextField("Textfield with no error in it"));
TextField tt1 = new TextField("100% wide Textfield with no error in it");
tt1.setWidth("100%");
lo.addComponent(tt1);
TextField tt2 = new TextField();
tt2.setWidth("100%");
tt2.setValue("100% wide Textfield with no error in it and no caption");
lo.addComponent(tt2);
TextField t4 = new TextField();
t4.setValue("Without caption, With required");
t4.setComponentError(new SystemError("Error"));
t4.setRequired(true);
lo.addComponent(t4);
TextField t5 = new TextField();
t5.setValue("Without caption, WIDE");
t5.setComponentError(new SystemError("Error"));
t5.setWidth("100%");
lo.addComponent(t5);
TextField t6 = new TextField();
t6.setValue("Without caption, With required, WIDE");
t6.setComponentError(new SystemError("Error"));
t6.setRequired(true);
t6.setWidth("100%");
lo.addComponent(t6);
TextField t7 = new TextField();
t7.setValue("With icon and required and icon");
t7.setComponentError(new SystemError("Error"));
t7.setRequired(true);
t7.setIcon(new ThemeResource("../runo/icons/16/ok.png"));
lo.addComponent(t7);
DateField d1 = new DateField(
"Datefield with caption and icon, next one without caption");
d1.setComponentError(new SystemError("Error"));
d1.setRequired(true);
d1.setIcon(new ThemeResource("../runo/icons/16/ok.png"));
lo.addComponent(d1);
DateField d2 = new DateField();
d2.setComponentError(new SystemError("Error"));
d2.setRequired(true);
lo.addComponent(d2);
}
public class LayoutTestingPanel extends Panel {
Layout testedLayout;
HorizontalLayout controls = new HorizontalLayout();
CheckBox marginLeft = new CheckBox("m-left", false);
CheckBox marginRight = new CheckBox("m-right", false);
CheckBox marginTop = new CheckBox("m-top", false);
CheckBox marginBottom = new CheckBox("m-bottom", false);
CheckBox spacing = new CheckBox("spacing", false);
VerticalLayout testPanelLayout = new VerticalLayout();
LayoutTestingPanel(String caption, Layout layout) {
super(caption);
VerticalLayout internalLayout = new VerticalLayout();
internalLayout.setWidth("100%");
setContent(internalLayout);
testedLayout = layout;
testPanelLayout.setWidth("100%");
VerticalLayout controlWrapperLayout = new VerticalLayout();
controlWrapperLayout.setMargin(true);
Panel controlWrapper = new Panel(controlWrapperLayout);
controlWrapperLayout.addComponent(controls);
controlWrapper.setWidth("100%");
controlWrapper.setStyleName("controls");
internalLayout.addComponent(controlWrapper);
Panel testPanel = new Panel(testPanelLayout);
testPanel.setStyleName("testarea");
testPanelLayout.addComponent(testedLayout);
internalLayout.addComponent(testPanel);
internalLayout.setMargin(true);
internalLayout.setSpacing(true);
controls.setSpacing(true);
controls.setMargin(false);
controls.addComponent(new Label("width"));
controls.addComponent(new TextField(new MethodProperty<Float>(
testedLayout, "width")));
CheckBox widthPercentsCheckBox = new CheckBox("%",
new MethodProperty<Boolean>(this, "widthPercents"));
widthPercentsCheckBox.setImmediate(true);
controls.addComponent(widthPercentsCheckBox);
controls.addComponent(new Label("height"));
controls.addComponent(new TextField(new MethodProperty<Float>(
testedLayout, "height")));
CheckBox heightPercentsCheckBox = new CheckBox("%",
new MethodProperty<Boolean>(this, "heightPercents"));
heightPercentsCheckBox.setImmediate(true);
controls.addComponent(heightPercentsCheckBox);
controls.addComponent(marginLeft);
controls.addComponent(marginRight);
controls.addComponent(marginTop);
controls.addComponent(marginBottom);
if (testedLayout instanceof Layout.SpacingHandler) {
controls.addComponent(spacing);
}
Property.ValueChangeListener marginSpacingListener = new Property.ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
updateMarginsAndSpacing();
}
};
marginBottom.addListener(marginSpacingListener);
marginTop.addListener(marginSpacingListener);
marginLeft.addListener(marginSpacingListener);
marginRight.addListener(marginSpacingListener);
spacing.addListener(marginSpacingListener);
updateMarginsAndSpacing();
addAlignmentControls();
testedLayout.setStyleName("tested-layout");
setStyleName("layout-testing-panel");
for (Iterator<Component> i = controls.getComponentIterator(); i
.hasNext();) {
((AbstractComponent) i.next()).setImmediate(true);
}
}
@SuppressWarnings("deprecation")
private void addAlignmentControls() {
if (!(testedLayout instanceof Layout.AlignmentHandler)) {
return;
}
@SuppressWarnings("unused")
final Layout.AlignmentHandler ah = (AlignmentHandler) testedLayout;
final NativeSelect vAlign = new NativeSelect();
final NativeSelect hAlign = new NativeSelect();
controls.addComponent(new Label("component alignment"));
controls.addComponent(hAlign);
controls.addComponent(vAlign);
hAlign.setNullSelectionAllowed(false);
vAlign.setNullSelectionAllowed(false);
vAlign.addItem(new Integer(Bits.ALIGNMENT_TOP));
vAlign.setItemCaption(new Integer(Bits.ALIGNMENT_TOP), "top");
vAlign.addItem(new Integer(Bits.ALIGNMENT_VERTICAL_CENTER));
vAlign.setItemCaption(new Integer(Bits.ALIGNMENT_VERTICAL_CENTER),
"center");
vAlign.addItem(new Integer(Bits.ALIGNMENT_BOTTOM));
vAlign.setItemCaption(new Integer(Bits.ALIGNMENT_BOTTOM), "bottom");
hAlign.addItem(new Integer(Bits.ALIGNMENT_LEFT));
hAlign.setItemCaption(new Integer(Bits.ALIGNMENT_LEFT), "left");
hAlign.addItem(new Integer(Bits.ALIGNMENT_HORIZONTAL_CENTER));
hAlign.setItemCaption(
new Integer(Bits.ALIGNMENT_HORIZONTAL_CENTER), "center");
hAlign.addItem(new Integer(Bits.ALIGNMENT_RIGHT));
hAlign.setItemCaption(new Integer(Bits.ALIGNMENT_RIGHT), "right");
Property.ValueChangeListener alignmentChangeListener = new Property.ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
Integer h = ((Integer) hAlign.getValue()).intValue();
int v = ((Integer) vAlign.getValue()).intValue();
updateAlignments(new Alignment(h + v));
}
};
hAlign.setValue(new Integer(Bits.ALIGNMENT_LEFT));
vAlign.addListener(alignmentChangeListener);
hAlign.addListener(alignmentChangeListener);
vAlign.setValue(new Integer(Bits.ALIGNMENT_TOP));
controls.addComponent(new Label("layout alignment"));
final NativeSelect lAlign = new NativeSelect();
controls.addComponent(lAlign);
lAlign.setNullSelectionAllowed(false);
lAlign.addItem(new Integer(Bits.ALIGNMENT_LEFT));
lAlign.setItemCaption(new Integer(Bits.ALIGNMENT_LEFT), "left");
lAlign.addItem(new Integer(Bits.ALIGNMENT_HORIZONTAL_CENTER));
lAlign.setItemCaption(
new Integer(Bits.ALIGNMENT_HORIZONTAL_CENTER), "center");
lAlign.addItem(new Integer(Bits.ALIGNMENT_RIGHT));
lAlign.setItemCaption(new Integer(Bits.ALIGNMENT_RIGHT), "right");
lAlign.addListener(new Property.ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
testPanelLayout.setComponentAlignment(
testedLayout,
new Alignment(((Integer) lAlign.getValue())
.intValue() + Bits.ALIGNMENT_TOP));
}
});
}
private void updateAlignments(Alignment a) {
for (Iterator<Component> i = testedLayout.getComponentIterator(); i
.hasNext();) {
((Layout.AlignmentHandler) testedLayout).setComponentAlignment(
i.next(), a);
}
}
private void updateMarginsAndSpacing() {
if (testedLayout instanceof Layout.MarginHandler) {
((Layout.MarginHandler) testedLayout).setMargin(new MarginInfo(
marginTop.getValue().booleanValue(), marginRight
.getValue().booleanValue(), marginBottom
.getValue().booleanValue(), marginLeft
.getValue().booleanValue()));
}
if (testedLayout instanceof Layout.SpacingHandler) {
((Layout.SpacingHandler) testedLayout).setSpacing(spacing
.getValue().booleanValue());
}
}
}
}
| |
package pk.com.habsoft.robosim.filters.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* State objects are a collection of Object Instances.
*
* @author James MacGlashan
*
*/
public class MutableState implements State {
/**
* List of object instances that define the state
*/
protected List<ObjectInstance> objectInstances;
/**
* Map from object names to their instances
*/
protected Map<String, ObjectInstance> objectMap;
/**
* Map of object instances organized by class name
*/
protected Map<String, List<ObjectInstance>> objectIndexByClass;
public MutableState() {
super();
this.initDataStructures();
}
/**
* Initializes this state as a deep copy of the object instances in the
* provided source state s
*
* @param s
* the source state from which this state will be initialized.
*/
public MutableState(MutableState s) {
super();
this.initDataStructures();
for (ObjectInstance o : s.objectInstances) {
this.addObject(o.copy());
}
}
/**
* Returns a deep copy of this state.
*
* @return a deep copy of this state.
*/
@Override
public MutableState copy() {
return new MutableState(this);
}
/**
* Performs a semi-deep copy of the state in which only the objects with the
* names in deepCopyObjectNames are deep copied and the rest of the objects
* are shallowed copied.
*
* @param deepCopyObjectNames
* the names of the objects to be deep copied.
* @return a new state that is a mix of a shallow and deep copy of this
* state.
*/
public MutableState semiDeepCopy(String... deepCopyObjectNames) {
Set<ObjectInstance> deepCopyObjectSet = new HashSet<ObjectInstance>(deepCopyObjectNames.length);
for (String n : deepCopyObjectNames) {
deepCopyObjectSet.add(this.getObject(n));
}
return this.semiDeepCopy(deepCopyObjectSet);
}
/**
* Performs a semi-deep copy of the state in which only the objects in
* deepCopyObjects are deep copied and the rest of the objects are shallowed
* copied.
*
* @param deepCopyObjects
* the objects to be deep copied
* @return a new state that is a mix of a shallow and deep copy of this
* state.
*/
public MutableState semiDeepCopy(ObjectInstance... deepCopyObjects) {
Set<ObjectInstance> deepCopyObjectSet = new HashSet<ObjectInstance>(deepCopyObjects.length);
for (ObjectInstance d : deepCopyObjects) {
deepCopyObjectSet.add(d);
}
return this.semiDeepCopy(deepCopyObjectSet);
}
/**
* Performs a semi-deep copy of the state in which only the objects in
* deepCopyObjects are deep copied and the rest of the objects are shallowed
* copied.
*
* @param deepCopyObjects
* the objects to be deep copied
* @return a new state that is a mix of a shallow and deep copy of this
* state.
*/
public MutableState semiDeepCopy(Set<ObjectInstance> deepCopyObjects) {
MutableState s = new MutableState();
for (ObjectInstance o : this.objectInstances) {
if (deepCopyObjects.contains(o)) {
s.addObject(o.copy());
} else {
s.addObject(o);
}
}
return s;
}
protected void initDataStructures() {
objectInstances = new ArrayList<ObjectInstance>();
objectMap = new HashMap<String, ObjectInstance>();
objectIndexByClass = new HashMap<String, List<ObjectInstance>>();
}
/**
* Adds object instance o to this state.
*
* @param o
* the object instance to be added to this state.
*/
public State addObject(ObjectInstance o) {
String oname = o.getName();
if (objectMap.containsKey(oname)) {
return this; // don't add an object that conflicts with another
// object of the same name
}
objectMap.put(oname, o);
objectInstances.add(o);
this.addObjectClassIndexing(o);
return this;
}
public State addAllObjects(Collection<ObjectInstance> objects) {
for (ObjectInstance object : objects) {
this.addObject(object);
}
return this;
}
private void addObjectClassIndexing(ObjectInstance o) {
String otclass = o.getClassName();
// manage true indexing
if (objectIndexByClass.containsKey(otclass)) {
objectIndexByClass.get(otclass).add(o);
} else {
ArrayList<ObjectInstance> classList = new ArrayList<ObjectInstance>();
classList.add(o);
objectIndexByClass.put(otclass, classList);
}
}
/**
* Removes the object instance with the name oname from this state.
*
* @param oname
* the name of the object instance to remove.
*/
public State removeObject(String oname) {
this.removeObject(objectMap.get(oname));
return this;
}
/**
* Removes the object instance o from this state.
*
* @param o
* the object instance to remove from this state.
*/
public State removeObject(ObjectInstance o) {
if (o == null) {
return this;
}
String oname = o.getName();
if (!objectMap.containsKey(oname)) {
return this; // make sure we're removing something that actually
// exists in this state!
}
objectInstances.remove(o);
objectMap.remove(oname);
this.removeObjectClassIndexing(o);
return this;
}
public State removeAllObjects(Collection<ObjectInstance> objects) {
for (ObjectInstance object : objects) {
this.removeObject(object);
}
return this;
}
private void removeObjectClassIndexing(ObjectInstance o) {
String otclass = o.getClassName();
List<ObjectInstance> classTList = objectIndexByClass.get(otclass);
// if this index has more than one entry, then we can just remove from
// it and be done
if (classTList.size() > 1) {
classTList.remove(o);
} else {
// otherwise we have to remove class entries for it
objectIndexByClass.remove(otclass);
}
}
/**
* Renames the identifier for object instance o in this state to newName.
*
* @param o
* the object instance to rename in this state
* @param newName
* the new name of the object instance
*/
public State renameObject(ObjectInstance o, String newName) {
String originalName = o.getName();
o.setName(newName);
objectMap.remove(originalName);
objectMap.put(newName, o);
return this;
}
/**
* Returns the number of object instances in this state.
*
* @return the number of object instances in this state.
*/
public int numTotalObjects() {
return objectInstances.size();
}
/**
* Returns the object in this state with the name oname
*
* @param oname
* the name of the object instance to return
* @return the object instance with the name oname or null if there is no
* object in this state named oname
*/
public ObjectInstance getObject(String oname) {
return objectMap.get(oname);
}
/**
* Returns the list of observable and hidden object instances in this state.
*
* @return the list of observable and hidden object instances in this state.
*/
public List<ObjectInstance> getAllObjects() {
List<ObjectInstance> objects = new ArrayList<ObjectInstance>(objectInstances);
return objects;
}
/**
* Returns all objects that belong to the object class named oclass
*
* @param oclass
* the name of the object class for which objects should be
* returned
* @return all objects that belong to the object class named oclass
*/
public List<ObjectInstance> getObjectsOfClass(String oclass) {
List<ObjectInstance> tmp = objectIndexByClass.get(oclass);
if (tmp == null) {
return new ArrayList<ObjectInstance>();
}
return new ArrayList<ObjectInstance>(tmp);
}
/**
* Returns the first indexed object of the object class named oclass
*
* @param oclass
* the name of the object class for which the first indexed
* object should be returned.
* @return the first indexed object of the object class named oclass
*/
public ObjectInstance getFirstObjectOfClass(String oclass) {
List<ObjectInstance> obs = this.objectIndexByClass.get(oclass);
if (obs != null && !obs.isEmpty()) {
return obs.get(0);
}
return null;
}
/**
* Returns a set of of the object class names for all object classes that
* have instantiated objects in this state.
*
* @return a set of of the object class names for all object classes that
* have instantiated objects in this state.
*/
public Set<String> getObjectClassesPresent() {
return new HashSet<String>(objectIndexByClass.keySet());
}
/**
* Returns a list of list of object instances, grouped by object class
*
* @return a list of list of object instances, grouped by object class
*/
public List<List<ObjectInstance>> getAllObjectsByClass() {
return new ArrayList<List<ObjectInstance>>(objectIndexByClass.values());
}
/**
* Returns a string representation of this state using observable and hidden
* object instances.
*
* @return a string representation of this state using observable and hidden
* object instances.
*/
public String getCompleteStateDescription() {
String desc = "";
for (ObjectInstance o : objectInstances) {
desc = desc + o.getObjectDescription() + "\n";
}
return desc;
}
@Override
public String toString() {
return this.getCompleteStateDescription();
}
@Override
public State setObjectsValue(String objectName, String attrib, int val) {
ObjectInstance obj = this.objectMap.get(objectName);
if (obj == null) {
throw new RuntimeException("Object " + objectName + " does not exist in this state");
}
obj.setValue(attrib, val);
return this;
}
}
| |
/*-
* Copyright (c) 2013-2017 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 org.fedoraproject.xmvn.model;
import org.apache.maven.model.Activation;
import org.apache.maven.model.ActivationFile;
import org.apache.maven.model.ActivationOS;
import org.apache.maven.model.ActivationProperty;
import org.apache.maven.model.Build;
import org.apache.maven.model.BuildBase;
import org.apache.maven.model.CiManagement;
import org.apache.maven.model.Contributor;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.DependencyManagement;
import org.apache.maven.model.DeploymentRepository;
import org.apache.maven.model.Developer;
import org.apache.maven.model.DistributionManagement;
import org.apache.maven.model.Exclusion;
import org.apache.maven.model.Extension;
import org.apache.maven.model.IssueManagement;
import org.apache.maven.model.License;
import org.apache.maven.model.MailingList;
import org.apache.maven.model.Model;
import org.apache.maven.model.Notifier;
import org.apache.maven.model.Organization;
import org.apache.maven.model.Parent;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginExecution;
import org.apache.maven.model.PluginManagement;
import org.apache.maven.model.Prerequisites;
import org.apache.maven.model.Profile;
import org.apache.maven.model.Relocation;
import org.apache.maven.model.ReportPlugin;
import org.apache.maven.model.ReportSet;
import org.apache.maven.model.Reporting;
import org.apache.maven.model.Repository;
import org.apache.maven.model.RepositoryPolicy;
import org.apache.maven.model.Resource;
import org.apache.maven.model.Scm;
import org.apache.maven.model.Site;
/**
* @author Mikolaj Izdebski
*/
public class AbstractModelVisitor
implements ModelVisitor
{
@Override
public Build replaceBuild( Build build )
{
return build;
}
@Override
public Extension replaceBuildExtension( Extension extension )
{
return extension;
}
@Override
public String replaceBuildFilter( String filter )
{
return filter;
}
@Override
public Plugin replaceBuildPlugin( Plugin plugin )
{
return plugin;
}
@Override
public Dependency replaceBuildPluginDependency( Dependency dependency )
{
return dependency;
}
@Override
public Exclusion replaceBuildPluginDependencyExclusion( Exclusion exclusion )
{
return exclusion;
}
@Override
public PluginExecution replaceBuildPluginExecution( PluginExecution execution )
{
return execution;
}
@Override
public String replaceBuildPluginExecutionGoal( String goal )
{
return goal;
}
@Override
public PluginManagement replaceBuildPluginManagement( PluginManagement pluginManagement )
{
return pluginManagement;
}
@Override
public Plugin replaceBuildPluginManagementPlugin( Plugin plugin )
{
return plugin;
}
@Override
public Dependency replaceBuildPluginManagementPluginDependency( Dependency dependency )
{
return dependency;
}
@Override
public Exclusion replaceBuildPluginManagementPluginDependencyExclusion( Exclusion exclusion )
{
return exclusion;
}
@Override
public PluginExecution replaceBuildPluginManagementPluginExecution( PluginExecution execution )
{
return execution;
}
@Override
public String replaceBuildPluginManagementPluginExecutionGoal( String goal )
{
return goal;
}
@Override
public Resource replaceBuildResource( Resource resource )
{
return resource;
}
@Override
public String replaceBuildResourceExclude( String exclude )
{
return exclude;
}
@Override
public String replaceBuildResourceInclude( String include )
{
return include;
}
@Override
public Resource replaceBuildTestResource( Resource testResource )
{
return testResource;
}
@Override
public String replaceBuildTestResourceExclude( String exclude )
{
return exclude;
}
@Override
public String replaceBuildTestResourceInclude( String include )
{
return include;
}
@Override
public CiManagement replaceCiManagement( CiManagement ciManagement )
{
return ciManagement;
}
@Override
public Notifier replaceCiManagementNotifier( Notifier notifier )
{
return notifier;
}
@Override
public String replaceCiManagementNotifierConfiguration( String configurationElementKey,
String configurationElementValue )
{
return configurationElementValue;
}
@Override
public Contributor replaceContributor( Contributor contributor )
{
return contributor;
}
@Override
public String replaceContributorProperty( String propertyKey, String propertyValue )
{
return propertyValue;
}
@Override
public String replaceContributorRole( String role )
{
return role;
}
@Override
public Dependency replaceDependency( Dependency dependency )
{
return dependency;
}
@Override
public Exclusion replaceDependencyExclusion( Exclusion exclusion )
{
return exclusion;
}
@Override
public DependencyManagement replaceDependencyManagement( DependencyManagement dependencyManagement )
{
return dependencyManagement;
}
@Override
public Dependency replaceDependencyManagementDependency( Dependency dependency )
{
return dependency;
}
@Override
public Exclusion replaceDependencyManagementDependencyExclusion( Exclusion exclusion )
{
return exclusion;
}
@Override
public Developer replaceDeveloper( Developer developer )
{
return developer;
}
@Override
public String replaceDeveloperProperty( String propertyKey, String propertyValue )
{
return propertyValue;
}
@Override
public String replaceDeveloperRole( String role )
{
return role;
}
@Override
public DistributionManagement replaceDistributionManagement( DistributionManagement distributionManagement )
{
return distributionManagement;
}
@Override
public Relocation replaceDistributionManagementRelocation( Relocation relocation )
{
return relocation;
}
@Override
public DeploymentRepository replaceDistributionManagementRepository( DeploymentRepository repository )
{
return repository;
}
@Override
public RepositoryPolicy replaceDistributionManagementRepositoryRelease( RepositoryPolicy releases )
{
return releases;
}
@Override
public RepositoryPolicy replaceDistributionManagementRepositorySnapshot( RepositoryPolicy snapshots )
{
return snapshots;
}
@Override
public Site replaceDistributionManagementSite( Site site )
{
return site;
}
@Override
public DeploymentRepository replaceDistributionManagementSnapshotRepository( DeploymentRepository snapshotRepository )
{
return snapshotRepository;
}
@Override
public RepositoryPolicy replaceDistributionManagementSnapshotRepositoryRelease( RepositoryPolicy releases )
{
return releases;
}
@Override
public RepositoryPolicy replaceDistributionManagementSnapshotRepositorySnapshot( RepositoryPolicy snapshots )
{
return snapshots;
}
@Override
public IssueManagement replaceIssueManagement( IssueManagement issueManagement )
{
return issueManagement;
}
@Override
public License replaceLicense( License license )
{
return license;
}
@Override
public MailingList replaceMailingList( MailingList mailingList )
{
return mailingList;
}
@Override
public String replaceMailingListOtherArchive( String otherArchive )
{
return otherArchive;
}
@Override
public String replaceModule( String module )
{
return module;
}
@Override
public Organization replaceOrganization( Organization organization )
{
return organization;
}
@Override
public Parent replaceParent( Parent parent )
{
return parent;
}
@Override
public Repository replacePluginRepository( Repository pluginRepository )
{
return pluginRepository;
}
@Override
public RepositoryPolicy replacePluginRepositoryRelease( RepositoryPolicy releases )
{
return releases;
}
@Override
public RepositoryPolicy replacePluginRepositorySnapshot( RepositoryPolicy snapshots )
{
return snapshots;
}
@Override
public Prerequisites replacePrerequisite( Prerequisites prerequisites )
{
return prerequisites;
}
@Override
public Profile replaceProfile( Profile profile )
{
return profile;
}
@Override
public Activation replaceProfileActivation( Activation activation )
{
return activation;
}
@Override
public ActivationFile replaceProfileActivationFile( ActivationFile file )
{
return file;
}
@Override
public ActivationOS replaceProfileActivationO( ActivationOS os )
{
return os;
}
@Override
public ActivationProperty replaceProfileActivationProperty( ActivationProperty property )
{
return property;
}
@Override
public BuildBase replaceProfileBuild( BuildBase build )
{
return build;
}
@Override
public String replaceProfileBuildFilter( String filter )
{
return filter;
}
@Override
public Plugin replaceProfileBuildPlugin( Plugin plugin )
{
return plugin;
}
@Override
public Dependency replaceProfileBuildPluginDependency( Dependency dependency )
{
return dependency;
}
@Override
public Exclusion replaceProfileBuildPluginDependencyExclusion( Exclusion exclusion )
{
return exclusion;
}
@Override
public PluginExecution replaceProfileBuildPluginExecution( PluginExecution execution )
{
return execution;
}
@Override
public String replaceProfileBuildPluginExecutionGoal( String goal )
{
return goal;
}
@Override
public PluginManagement replaceProfileBuildPluginManagement( PluginManagement pluginManagement )
{
return pluginManagement;
}
@Override
public Plugin replaceProfileBuildPluginManagementPlugin( Plugin plugin )
{
return plugin;
}
@Override
public Dependency replaceProfileBuildPluginManagementPluginDependency( Dependency dependency )
{
return dependency;
}
@Override
public Exclusion replaceProfileBuildPluginManagementPluginDependencyExclusion( Exclusion exclusion )
{
return exclusion;
}
@Override
public PluginExecution replaceProfileBuildPluginManagementPluginExecution( PluginExecution execution )
{
return execution;
}
@Override
public String replaceProfileBuildPluginManagementPluginExecutionGoal( String goal )
{
return goal;
}
@Override
public Resource replaceProfileBuildResource( Resource resource )
{
return resource;
}
@Override
public String replaceProfileBuildResourceExclude( String exclude )
{
return exclude;
}
@Override
public String replaceProfileBuildResourceInclude( String include )
{
return include;
}
@Override
public Resource replaceProfileBuildTestResource( Resource testResource )
{
return testResource;
}
@Override
public String replaceProfileBuildTestResourceExclude( String exclude )
{
return exclude;
}
@Override
public String replaceProfileBuildTestResourceInclude( String include )
{
return include;
}
@Override
public Dependency replaceProfileDependency( Dependency dependency )
{
return dependency;
}
@Override
public Exclusion replaceProfileDependencyExclusion( Exclusion exclusion )
{
return exclusion;
}
@Override
public DependencyManagement replaceProfileDependencyManagement( DependencyManagement dependencyManagement )
{
return dependencyManagement;
}
@Override
public Dependency replaceProfileDependencyManagementDependency( Dependency dependency )
{
return dependency;
}
@Override
public Exclusion replaceProfileDependencyManagementDependencyExclusion( Exclusion exclusion )
{
return exclusion;
}
@Override
public DistributionManagement replaceProfileDistributionManagement( DistributionManagement distributionManagement )
{
return distributionManagement;
}
@Override
public Relocation replaceProfileDistributionManagementRelocation( Relocation relocation )
{
return relocation;
}
@Override
public DeploymentRepository replaceProfileDistributionManagementRepository( DeploymentRepository repository )
{
return repository;
}
@Override
public RepositoryPolicy replaceProfileDistributionManagementRepositoryRelease( RepositoryPolicy releases )
{
return releases;
}
@Override
public RepositoryPolicy replaceProfileDistributionManagementRepositorySnapshot( RepositoryPolicy snapshots )
{
return snapshots;
}
@Override
public Site replaceProfileDistributionManagementSite( Site site )
{
return site;
}
@Override
public DeploymentRepository replaceProfileDistributionManagementSnapshotRepository( DeploymentRepository snapshotRepository )
{
return snapshotRepository;
}
@Override
public RepositoryPolicy replaceProfileDistributionManagementSnapshotRepositoryRelease( RepositoryPolicy releases )
{
return releases;
}
@Override
public RepositoryPolicy replaceProfileDistributionManagementSnapshotRepositorySnapshot( RepositoryPolicy snapshots )
{
return snapshots;
}
@Override
public String replaceProfileModule( String module )
{
return module;
}
@Override
public Repository replaceProfilePluginRepository( Repository pluginRepository )
{
return pluginRepository;
}
@Override
public RepositoryPolicy replaceProfilePluginRepositoryRelease( RepositoryPolicy releases )
{
return releases;
}
@Override
public RepositoryPolicy replaceProfilePluginRepositorySnapshot( RepositoryPolicy snapshots )
{
return snapshots;
}
@Override
public String replaceProfileProperty( String propertyKey, String propertyValue )
{
return propertyValue;
}
@Override
public Reporting replaceProfileReporting( Reporting reporting )
{
return reporting;
}
@Override
public ReportPlugin replaceProfileReportingPlugin( ReportPlugin plugin )
{
return plugin;
}
@Override
public ReportSet replaceProfileReportingPluginReportSet( ReportSet reportSet )
{
return reportSet;
}
@Override
public String replaceProfileReportingPluginReportSetReport( String report )
{
return report;
}
@Override
public Repository replaceProfileRepository( Repository repository )
{
return repository;
}
@Override
public RepositoryPolicy replaceProfileRepositoryRelease( RepositoryPolicy releases )
{
return releases;
}
@Override
public RepositoryPolicy replaceProfileRepositorySnapshot( RepositoryPolicy snapshots )
{
return snapshots;
}
@Override
public String replaceProperty( String propertyKey, String propertyValue )
{
return propertyValue;
}
@Override
public Reporting replaceReporting( Reporting reporting )
{
return reporting;
}
@Override
public ReportPlugin replaceReportingPlugin( ReportPlugin plugin )
{
return plugin;
}
@Override
public ReportSet replaceReportingPluginReportSet( ReportSet reportSet )
{
return reportSet;
}
@Override
public String replaceReportingPluginReportSetReport( String report )
{
return report;
}
@Override
public Repository replaceRepository( Repository repository )
{
return repository;
}
@Override
public RepositoryPolicy replaceRepositoryRelease( RepositoryPolicy releases )
{
return releases;
}
@Override
public RepositoryPolicy replaceRepositorySnapshot( RepositoryPolicy snapshots )
{
return snapshots;
}
@Override
public Scm replaceScm( Scm scm )
{
return scm;
}
@Override
public void visitBuild( Build build )
{
}
@Override
public void visitBuildExtension( Extension extension )
{
}
@Override
public void visitBuildFilter( String filter )
{
}
@Override
public void visitBuildPlugin( Plugin plugin )
{
}
@Override
public void visitBuildPluginDependency( Dependency dependency )
{
}
@Override
public void visitBuildPluginDependencyExclusion( Exclusion exclusion )
{
}
@Override
public void visitBuildPluginExecution( PluginExecution execution )
{
}
@Override
public void visitBuildPluginExecutionGoal( String goal )
{
}
@Override
public void visitBuildPluginManagement( PluginManagement pluginManagement )
{
}
@Override
public void visitBuildPluginManagementPlugin( Plugin plugin )
{
}
@Override
public void visitBuildPluginManagementPluginDependency( Dependency dependency )
{
}
@Override
public void visitBuildPluginManagementPluginDependencyExclusion( Exclusion exclusion )
{
}
@Override
public void visitBuildPluginManagementPluginExecution( PluginExecution execution )
{
}
@Override
public void visitBuildPluginManagementPluginExecutionGoal( String goal )
{
}
@Override
public void visitBuildResource( Resource resource )
{
}
@Override
public void visitBuildResourceExclude( String exclude )
{
}
@Override
public void visitBuildResourceInclude( String include )
{
}
@Override
public void visitBuildTestResource( Resource testResource )
{
}
@Override
public void visitBuildTestResourceExclude( String exclude )
{
}
@Override
public void visitBuildTestResourceInclude( String include )
{
}
@Override
public void visitCiManagement( CiManagement ciManagement )
{
}
@Override
public void visitCiManagementNotifier( Notifier notifier )
{
}
@Override
public void visitCiManagementNotifierConfiguration( String configurationElementKey,
String configurationElementValue )
{
}
@Override
public void visitContributor( Contributor contributor )
{
}
@Override
public void visitContributorProperty( String propertyKey, String propertyValue )
{
}
@Override
public void visitContributorRole( String role )
{
}
@Override
public void visitDependency( Dependency dependency )
{
}
@Override
public void visitDependencyExclusion( Exclusion exclusion )
{
}
@Override
public void visitDependencyManagement( DependencyManagement dependencyManagement )
{
}
@Override
public void visitDependencyManagementDependency( Dependency dependency )
{
}
@Override
public void visitDependencyManagementDependencyExclusion( Exclusion exclusion )
{
}
@Override
public void visitDeveloper( Developer developer )
{
}
@Override
public void visitDeveloperProperty( String propertyKey, String propertyValue )
{
}
@Override
public void visitDeveloperRole( String role )
{
}
@Override
public void visitDistributionManagement( DistributionManagement distributionManagement )
{
}
@Override
public void visitDistributionManagementRelocation( Relocation relocation )
{
}
@Override
public void visitDistributionManagementRepository( DeploymentRepository repository )
{
}
@Override
public void visitDistributionManagementRepositoryRelease( RepositoryPolicy releases )
{
}
@Override
public void visitDistributionManagementRepositorySnapshot( RepositoryPolicy snapshots )
{
}
@Override
public void visitDistributionManagementSite( Site site )
{
}
@Override
public void visitDistributionManagementSnapshotRepository( DeploymentRepository snapshotRepository )
{
}
@Override
public void visitDistributionManagementSnapshotRepositoryRelease( RepositoryPolicy releases )
{
}
@Override
public void visitDistributionManagementSnapshotRepositorySnapshot( RepositoryPolicy snapshots )
{
}
@Override
public void visitIssueManagement( IssueManagement issueManagement )
{
}
@Override
public void visitLicense( License license )
{
}
@Override
public void visitMailingList( MailingList mailingList )
{
}
@Override
public void visitMailingListOtherArchive( String otherArchive )
{
}
@Override
public void visitModule( String module )
{
}
@Override
public void visitOrganization( Organization organization )
{
}
@Override
public void visitParent( Parent parent )
{
}
@Override
public void visitPluginRepository( Repository pluginRepository )
{
}
@Override
public void visitPluginRepositoryRelease( RepositoryPolicy releases )
{
}
@Override
public void visitPluginRepositorySnapshot( RepositoryPolicy snapshots )
{
}
@Override
public void visitPrerequisite( Prerequisites prerequisites )
{
}
@Override
public void visitProfile( Profile profile )
{
}
@Override
public void visitProfileActivation( Activation activation )
{
}
@Override
public void visitProfileActivationFile( ActivationFile file )
{
}
@Override
public void visitProfileActivationO( ActivationOS os )
{
}
@Override
public void visitProfileActivationProperty( ActivationProperty property )
{
}
@Override
public void visitProfileBuild( BuildBase build )
{
}
@Override
public void visitProfileBuildFilter( String filter )
{
}
@Override
public void visitProfileBuildPlugin( Plugin plugin )
{
}
@Override
public void visitProfileBuildPluginDependency( Dependency dependency )
{
}
@Override
public void visitProfileBuildPluginDependencyExclusion( Exclusion exclusion )
{
}
@Override
public void visitProfileBuildPluginExecution( PluginExecution execution )
{
}
@Override
public void visitProfileBuildPluginExecutionGoal( String goal )
{
}
@Override
public void visitProfileBuildPluginManagement( PluginManagement pluginManagement )
{
}
@Override
public void visitProfileBuildPluginManagementPlugin( Plugin plugin )
{
}
@Override
public void visitProfileBuildPluginManagementPluginDependency( Dependency dependency )
{
}
@Override
public void visitProfileBuildPluginManagementPluginDependencyExclusion( Exclusion exclusion )
{
}
@Override
public void visitProfileBuildPluginManagementPluginExecution( PluginExecution execution )
{
}
@Override
public void visitProfileBuildPluginManagementPluginExecutionGoal( String goal )
{
}
@Override
public void visitProfileBuildResource( Resource resource )
{
}
@Override
public void visitProfileBuildResourceExclude( String exclude )
{
}
@Override
public void visitProfileBuildResourceInclude( String include )
{
}
@Override
public void visitProfileBuildTestResource( Resource testResource )
{
}
@Override
public void visitProfileBuildTestResourceExclude( String exclude )
{
}
@Override
public void visitProfileBuildTestResourceInclude( String include )
{
}
@Override
public void visitProfileDependency( Dependency dependency )
{
}
@Override
public void visitProfileDependencyExclusion( Exclusion exclusion )
{
}
@Override
public void visitProfileDependencyManagement( DependencyManagement dependencyManagement )
{
}
@Override
public void visitProfileDependencyManagementDependency( Dependency dependency )
{
}
@Override
public void visitProfileDependencyManagementDependencyExclusion( Exclusion exclusion )
{
}
@Override
public void visitProfileDistributionManagement( DistributionManagement distributionManagement )
{
}
@Override
public void visitProfileDistributionManagementRelocation( Relocation relocation )
{
}
@Override
public void visitProfileDistributionManagementRepository( DeploymentRepository repository )
{
}
@Override
public void visitProfileDistributionManagementRepositoryRelease( RepositoryPolicy releases )
{
}
@Override
public void visitProfileDistributionManagementRepositorySnapshot( RepositoryPolicy snapshots )
{
}
@Override
public void visitProfileDistributionManagementSite( Site site )
{
}
@Override
public void visitProfileDistributionManagementSnapshotRepository( DeploymentRepository snapshotRepository )
{
}
@Override
public void visitProfileDistributionManagementSnapshotRepositoryRelease( RepositoryPolicy releases )
{
}
@Override
public void visitProfileDistributionManagementSnapshotRepositorySnapshot( RepositoryPolicy snapshots )
{
}
@Override
public void visitProfileModule( String module )
{
}
@Override
public void visitProfilePluginRepository( Repository pluginRepository )
{
}
@Override
public void visitProfilePluginRepositoryRelease( RepositoryPolicy releases )
{
}
@Override
public void visitProfilePluginRepositorySnapshot( RepositoryPolicy snapshots )
{
}
@Override
public void visitProfileProperty( String propertyKey, String propertyValue )
{
}
@Override
public void visitProfileReporting( Reporting reporting )
{
}
@Override
public void visitProfileReportingPlugin( ReportPlugin plugin )
{
}
@Override
public void visitProfileReportingPluginReportSet( ReportSet reportSet )
{
}
@Override
public void visitProfileReportingPluginReportSetReport( String report )
{
}
@Override
public void visitProfileRepository( Repository repository )
{
}
@Override
public void visitProfileRepositoryRelease( RepositoryPolicy releases )
{
}
@Override
public void visitProfileRepositorySnapshot( RepositoryPolicy snapshots )
{
}
@Override
public void visitProject( Model model )
{
}
@Override
public void visitProperty( String propertyKey, String propertyValue )
{
}
@Override
public void visitReporting( Reporting reporting )
{
}
@Override
public void visitReportingPlugin( ReportPlugin plugin )
{
}
@Override
public void visitReportingPluginReportSet( ReportSet reportSet )
{
}
@Override
public void visitReportingPluginReportSetReport( String report )
{
}
@Override
public void visitRepository( Repository repository )
{
}
@Override
public void visitRepositoryRelease( RepositoryPolicy releases )
{
}
@Override
public void visitRepositorySnapshot( RepositoryPolicy snapshots )
{
}
@Override
public void visitScm( Scm scm )
{
}
}
| |
/*
* 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.proton.plug.context;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import io.netty.buffer.ByteBuf;
import org.apache.qpid.proton.engine.Connection;
import org.apache.qpid.proton.engine.Delivery;
import org.apache.qpid.proton.engine.Link;
import org.apache.qpid.proton.engine.Session;
import org.apache.qpid.proton.engine.Transport;
import org.proton.plug.AMQPConnectionCallback;
import org.proton.plug.AMQPConnectionContext;
import org.proton.plug.SASLResult;
import org.proton.plug.exceptions.ActiveMQAMQPException;
import org.proton.plug.handler.ProtonHandler;
import org.proton.plug.handler.impl.DefaultEventHandler;
import org.proton.plug.util.ByteUtil;
import org.proton.plug.util.DebugInfo;
import static org.proton.plug.context.AMQPConstants.Connection.DEFAULT_IDLE_TIMEOUT;
import static org.proton.plug.context.AMQPConstants.Connection.DEFAULT_CHANNEL_MAX;
import static org.proton.plug.context.AMQPConstants.Connection.DEFAULT_MAX_FRAME_SIZE;
public abstract class AbstractConnectionContext extends ProtonInitializable implements AMQPConnectionContext
{
protected ProtonHandler handler = ProtonHandler.Factory.create();
protected AMQPConnectionCallback connectionCallback;
private final Map<Session, AbstractProtonSessionContext> sessions = new ConcurrentHashMap<>();
protected LocalListener listener = new LocalListener();
public AbstractConnectionContext(AMQPConnectionCallback connectionCallback)
{
this(connectionCallback, DEFAULT_IDLE_TIMEOUT, DEFAULT_MAX_FRAME_SIZE, DEFAULT_CHANNEL_MAX);
}
public AbstractConnectionContext(AMQPConnectionCallback connectionCallback, int idleTimeout, int maxFrameSize, int channelMax)
{
this.connectionCallback = connectionCallback;
connectionCallback.setConnection(this);
Transport transport = handler.getTransport();
if (idleTimeout > 0)
{
transport.setIdleTimeout(idleTimeout);
transport.tick(idleTimeout / 2);
}
transport.setChannelMax(channelMax);
transport.setMaxFrameSize(maxFrameSize);
handler.addEventHandler(listener);
}
public SASLResult getSASLResult()
{
return handler.getSASLResult();
}
@Override
public void inputBuffer(ByteBuf buffer)
{
if (DebugInfo.debug)
{
ByteUtil.debugFrame("Buffer Received ", buffer);
}
handler.inputBuffer(buffer);
}
public void destroy()
{
connectionCallback.close();
}
/**
* See comment at {@link org.proton.plug.AMQPConnectionContext#isSyncOnFlush()}
*/
public boolean isSyncOnFlush()
{
return false;
}
public Object getLock()
{
return handler.getLock();
}
@Override
public int capacity()
{
return handler.capacity();
}
@Override
public void outputDone(int bytes)
{
handler.outputDone(bytes);
}
public void flush()
{
handler.flush();
}
public void close()
{
handler.close();
}
protected AbstractProtonSessionContext getSessionExtension(Session realSession) throws ActiveMQAMQPException
{
AbstractProtonSessionContext sessionExtension = sessions.get(realSession);
if (sessionExtension == null)
{
// how this is possible? Log a warn here
sessionExtension = newSessionExtension(realSession);
realSession.setContext(sessionExtension);
sessions.put(realSession, sessionExtension);
}
return sessionExtension;
}
protected abstract void remoteLinkOpened(Link link) throws Exception;
protected abstract AbstractProtonSessionContext newSessionExtension(Session realSession) throws ActiveMQAMQPException;
@Override
public boolean checkDataReceived()
{
return handler.checkDataReceived();
}
@Override
public long getCreationTime()
{
return handler.getCreationTime();
}
protected void flushBytes()
{
ByteBuf bytes;
// handler.outputBuffer has the lock
while ((bytes = handler.outputBuffer()) != null)
{
connectionCallback.onTransport(bytes, AbstractConnectionContext.this);
}
}
// This listener will perform a bunch of things here
class LocalListener extends DefaultEventHandler
{
@Override
public void onSASLInit(ProtonHandler handler, Connection connection)
{
handler.createServerSASL(connectionCallback.getSASLMechnisms());
}
@Override
public void onTransport(Transport transport)
{
flushBytes();
}
@Override
public void onRemoteOpen(Connection connection) throws Exception
{
synchronized (getLock())
{
connection.setContext(AbstractConnectionContext.this);
connection.open();
}
initialise();
}
@Override
public void onRemoteClose(Connection connection)
{
synchronized (getLock())
{
connection.close();
for (AbstractProtonSessionContext protonSession : sessions.values())
{
protonSession.close();
}
sessions.clear();
}
// We must force write the channel before we actually destroy the connection
onTransport(handler.getTransport());
destroy();
}
@Override
public void onLocalOpen(Session session) throws Exception
{
getSessionExtension(session);
}
@Override
public void onRemoteOpen(Session session) throws Exception
{
getSessionExtension(session).initialise();
synchronized (getLock())
{
session.open();
}
}
@Override
public void onLocalClose(Session session) throws Exception
{
}
@Override
public void onRemoteClose(Session session) throws Exception
{
synchronized (getLock())
{
session.close();
}
AbstractProtonSessionContext sessionContext = (AbstractProtonSessionContext) session.getContext();
if (sessionContext != null)
{
sessionContext.close();
sessions.remove(session);
session.setContext(null);
}
}
@Override
public void onRemoteOpen(Link link) throws Exception
{
remoteLinkOpened(link);
}
@Override
public void onFlow(Link link) throws Exception
{
((ProtonDeliveryHandler) link.getContext()).onFlow(link.getCredit());
}
@Override
public void onRemoteClose(Link link) throws Exception
{
link.close();
ProtonDeliveryHandler linkContext = (ProtonDeliveryHandler) link.getContext();
if (linkContext != null)
{
linkContext.close();
}
}
public void onRemoteDetach(Link link) throws Exception
{
link.detach();
}
public void onDelivery(Delivery delivery) throws Exception
{
ProtonDeliveryHandler handler = (ProtonDeliveryHandler) delivery.getLink().getContext();
if (handler != null)
{
handler.onMessage(delivery);
}
else
{
// TODO: logs
System.err.println("Handler is null, can't delivery " + delivery);
}
}
}
}
| |
/*
* Copyright 2011-2022 the original author or 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
*
* https://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.lettuce.core.internal;
/**
* An immutable representation of a host and port.
*
* @author Mark Paluch
* @author Larry Battle
* @since 4.2
*/
public class HostAndPort {
private static final int NO_PORT = -1;
public final String hostText;
public final int port;
/**
*
* @param hostText must not be empty or {@code null}.
* @param port
*/
private HostAndPort(String hostText, int port) {
LettuceAssert.notNull(hostText, "HostText must not be null");
this.hostText = hostText;
this.port = port;
}
/**
* Create a {@link HostAndPort} of {@code host} and {@code port}
*
* @param host the hostname
* @param port a valid port
* @return the {@link HostAndPort} of {@code host} and {@code port}
*/
public static HostAndPort of(String host, int port) {
LettuceAssert.isTrue(isValidPort(port), () -> String.format("Port out of range: %s", port));
HostAndPort parsedHost = parse(host);
LettuceAssert.isTrue(!parsedHost.hasPort(), () -> String.format("Host has a port: %s", host));
return new HostAndPort(host, port);
}
/**
* Parse a host and port string into a {@link HostAndPort}. The port is optional. Examples: {@code host:port} or
* {@code host}
*
* @param hostPortString
* @return
*/
public static HostAndPort parse(String hostPortString) {
LettuceAssert.notNull(hostPortString, "HostPortString must not be null");
String host;
String portString = null;
if (hostPortString.startsWith("[")) {
String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString);
host = hostAndPort[0];
portString = hostAndPort[1];
} else {
int colonPos = hostPortString.indexOf(':');
if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) {
// Exactly 1 colon. Split into host:port.
host = hostPortString.substring(0, colonPos);
portString = hostPortString.substring(colonPos + 1);
} else {
// 0 or 2+ colons. Bare hostname or IPv6 literal.
host = hostPortString;
}
}
int port = NO_PORT;
if (!LettuceStrings.isEmpty(portString)) {
// Try to parse the whole port string as a number.
// JDK7 accepts leading plus signs. We don't want to.
LettuceAssert.isTrue(!portString.startsWith("+"), () -> String.format("Cannot port number: %s", hostPortString));
try {
port = Integer.parseInt(portString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(String.format("Cannot parse port number: %s", hostPortString));
}
LettuceAssert.isTrue(isValidPort(port), () -> String.format("Port number out of range: %s", hostPortString));
}
return new HostAndPort(host, port);
}
/**
* Temporary workaround until Redis provides IPv6 addresses in bracket notation. Allows parsing of {@code 1.2.3.4:6479} and
* {@code dead:beef:dead:beef:affe::1:6379} into host and port. We assume the last item after the colon is a port.
*
* @param hostAndPortPart the string containing the host and port
* @return the parsed {@link HostAndPort}.
*/
public static HostAndPort parseCompat(String hostAndPortPart) {
int firstColonIndex = hostAndPortPart.indexOf(':');
int lastColonIndex = hostAndPortPart.lastIndexOf(':');
int bracketIndex = hostAndPortPart.lastIndexOf(']');
if (firstColonIndex != lastColonIndex && lastColonIndex != -1 && bracketIndex == -1) {
String hostPart = hostAndPortPart.substring(0, lastColonIndex);
String portPart = hostAndPortPart.substring(lastColonIndex + 1);
return HostAndPort.of(hostPart, Integer.parseInt(portPart));
}
return HostAndPort.parse(hostAndPortPart);
}
/**
*
* @return {@code true} if has a port.
*/
public boolean hasPort() {
return port != NO_PORT;
}
/**
*
* @return the host text.
*/
public String getHostText() {
return hostText;
}
/**
*
* @return the port.
*/
public int getPort() {
if (!hasPort()) {
throw new IllegalStateException("No port present.");
}
return port;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof HostAndPort))
return false;
HostAndPort that = (HostAndPort) o;
if (port != that.port)
return false;
return hostText != null ? hostText.equals(that.hostText) : that.hostText == null;
}
@Override
public int hashCode() {
int result = hostText != null ? hostText.hashCode() : 0;
result = 31 * result + port;
return result;
}
/**
* Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails.
*
* @param hostPortString the full bracketed host-port specification. Post might not be specified.
* @return an array with 2 strings: host and port, in that order.
* @throws IllegalArgumentException if parsing the bracketed host-port string fails.
*/
private static String[] getHostAndPortFromBracketedHost(String hostPortString) {
LettuceAssert.isTrue(hostPortString.charAt(0) == '[',
() -> String.format("Bracketed host-port string must start with a bracket: %s", hostPortString));
int colonIndex = hostPortString.indexOf(':');
int closeBracketIndex = hostPortString.lastIndexOf(']');
LettuceAssert.isTrue(colonIndex > -1 && closeBracketIndex > colonIndex,
() -> String.format("Invalid bracketed host/port: %s", hostPortString));
String host = hostPortString.substring(1, closeBracketIndex);
if (closeBracketIndex + 1 == hostPortString.length()) {
return new String[] { host, "" };
} else {
LettuceAssert.isTrue(hostPortString.charAt(closeBracketIndex + 1) == ':',
"Only a colon may follow a close bracket: " + hostPortString);
for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) {
LettuceAssert.isTrue(Character.isDigit(hostPortString.charAt(i)),
() -> String.format("Port must be numeric: %s", hostPortString));
}
return new String[] { host, hostPortString.substring(closeBracketIndex + 2) };
}
}
/**
*
* @param port the port number
* @return {@code true} for valid port numbers.
*/
private static boolean isValidPort(int port) {
return port >= 0 && port <= 65535;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(hostText);
if (hasPort()) {
sb.append(':').append(port);
}
return sb.toString();
}
}
| |
/*
* Copyright 2016 IBM Corp.
* 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.jsonstore;
import android.content.Context;
import android.test.InstrumentationTestCase;
import com.jsonstore.api.JSONStore;
import com.jsonstore.api.JSONStoreCollection;
import com.jsonstore.database.SearchFieldType;
import com.jsonstore.exceptions.JSONStoreDestroyFailureException;
import com.jsonstore.exceptions.JSONStoreException;
import com.jsonstore.exceptions.JSONStoreInvalidSchemaException;
import com.jsonstore.exceptions.JSONStoreSchemaMismatchException;
import com.jsonstore.exceptions.JSONStoreTransactionFailureException;
import java.util.LinkedList;
import java.util.List;
public class OpenCollectionTest extends InstrumentationTestCase {
public OpenCollectionTest() {
super();
}
/**
* @return The {@link Context} of the test project.
*/
private Context getTestContext()
{
try
{
return getInstrumentation().getContext();
}
catch (final Exception exception)
{
exception.printStackTrace();
return null;
}
}
public void testSimpleOpenCollection() throws JSONStoreException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
JSONStoreCollection simpleCol = new JSONStoreCollection("simple");
simpleCol.setSearchField("win", SearchFieldType.BOOLEAN);
//Open collection.
List<JSONStoreCollection> collections = new LinkedList<JSONStoreCollection>();
collections.add(simpleCol);
store.openCollections(collections);
assertFalse("Collection marked reopened when not reopened", simpleCol.wasReopened());
assertEquals("Collection could not be located in JSONStore instance", store.getCollectionByName("simple"), simpleCol);
store.destroy();
}
public void testMultipleOpenCollection() throws JSONStoreException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
JSONStoreCollection simpleCol = new JSONStoreCollection("simple");
simpleCol.setSearchField("win", SearchFieldType.BOOLEAN);
JSONStoreCollection anotherCol = new JSONStoreCollection("another");
simpleCol.setSearchField("winrar", SearchFieldType.BOOLEAN);
//Open collection.
List<JSONStoreCollection> collections = new LinkedList<JSONStoreCollection>();
collections.add(simpleCol);
collections.add(anotherCol);
store.openCollections(collections);
assertFalse("Collection marked reopened when not reopened", simpleCol.wasReopened());
assertEquals("Collection simple could not be located in JSONStore instance", store.getCollectionByName("simple"), simpleCol);
assertEquals("Collection another could not be located in JSONStore instance", store.getCollectionByName("another"), anotherCol);
store.destroy();
}
public void testMultipleOpenCollectionsWithNull() throws JSONStoreException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
JSONStoreCollection simpleCol = new JSONStoreCollection("simple");
simpleCol.setSearchField("win", SearchFieldType.BOOLEAN);
//Open collection.
List<JSONStoreCollection> collections = new LinkedList<JSONStoreCollection>();
collections.add(simpleCol);
collections.add(null);
store.openCollections(collections);
assertFalse("Collection marked reopened when not reopened", simpleCol.wasReopened());
assertEquals("Collection simple could not be located in JSONStore instance", store.getCollectionByName("simple"), simpleCol);
store.destroy();
}
public void testReopenCollection() throws JSONStoreException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
JSONStoreCollection simpleCol = new JSONStoreCollection("simple");
simpleCol.setSearchField("win", SearchFieldType.BOOLEAN);
//Open collection.
List<JSONStoreCollection> collections = new LinkedList<JSONStoreCollection>();
collections.add(simpleCol);
store.openCollections(collections);
assertFalse("Collection marked reopened when not reopened", simpleCol.wasReopened());
store.closeAll();
store.openCollections(collections);
assertTrue("Collection marked not reopened when reopened", simpleCol.wasReopened());
store.destroy();
}
public void testNullSearchField() throws JSONStoreException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
JSONStoreCollection simpleCol = new JSONStoreCollection("simple");
simpleCol.setSearchField(null, SearchFieldType.BOOLEAN);
//Open collection.
List<JSONStoreCollection> collections = new LinkedList<JSONStoreCollection>();
collections.add(simpleCol);
store.openCollections(collections);
assertEquals("Search field list should be empty", simpleCol.getSearchFields().size(), 0);
store.destroy();
}
public void testNullSearchFieldWithAdditionalNonNulls() throws JSONStoreException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
JSONStoreCollection simpleCol = new JSONStoreCollection("simple");
simpleCol.setSearchField("realfield", SearchFieldType.BOOLEAN);
simpleCol.setSearchField(null, SearchFieldType.BOOLEAN);
//Open collection.
List<JSONStoreCollection> collections = new LinkedList<JSONStoreCollection>();
collections.add(simpleCol);
store.openCollections(collections);
assertEquals("Search field list should only contain 1", simpleCol.getSearchFields().size(), 1);
store.destroy();
}
public void testReopenCollectionMoreSearchFields() throws JSONStoreException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
JSONStoreCollection simpleCol = new JSONStoreCollection("simple");
simpleCol.setSearchField("win", SearchFieldType.BOOLEAN);
//Open collection.
List<JSONStoreCollection> collections = new LinkedList<JSONStoreCollection>();
collections.add(simpleCol);
store.openCollections(collections);
assertFalse("Collection marked reopened when not reopened", simpleCol.wasReopened());
store.closeAll();
simpleCol.setSearchField("fail", SearchFieldType.BOOLEAN);
try {
store.openCollections(collections);
} catch (JSONStoreSchemaMismatchException e) {
store.destroy();
return;
}
store.destroy();
assertTrue("Collection with different search fields did not throw a schema mismatch exception", false);
}
public void testReopenCollectionLessSearchFields() throws JSONStoreException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
JSONStoreCollection simpleCol = new JSONStoreCollection("simple");
simpleCol.setSearchField("win", SearchFieldType.BOOLEAN);
simpleCol.setSearchField("win2", SearchFieldType.BOOLEAN);
//Open collection.
List<JSONStoreCollection> collections = new LinkedList<JSONStoreCollection>();
collections.add(simpleCol);
store.openCollections(collections);
assertFalse("Collection marked reopened when not reopened", simpleCol.wasReopened());
store.closeAll();
simpleCol = new JSONStoreCollection("simple");
simpleCol.setSearchField("win", SearchFieldType.BOOLEAN);
collections = new LinkedList<JSONStoreCollection>();
collections.add(simpleCol);
try {
store.openCollections(collections);
} catch (JSONStoreSchemaMismatchException e) {
store.destroy();
return;
}
store.destroy();
assertTrue("Collection with less search fields did not throw a schema mismatch exception", false);
}
public void testNullSearchFieldType() throws JSONStoreException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
JSONStoreCollection simpleCol = new JSONStoreCollection("simple");
simpleCol.setSearchField("test", null);
//Open collection.
List<JSONStoreCollection> collections = new LinkedList<JSONStoreCollection>();
collections.add(simpleCol);
store.openCollections(collections);
assertEquals("Search field list should be 1", simpleCol.getSearchFields().size(), 1);
SearchFieldType t = simpleCol.getSearchFields().get("test");
assertTrue("Default search field type should be string", t == SearchFieldType.STRING);
store.destroy();
}
public void testNoSearchFields() throws JSONStoreException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
JSONStoreCollection simpleCol = new JSONStoreCollection("simple");
//Open collection.
List<JSONStoreCollection> collections = new LinkedList<JSONStoreCollection>();
collections.add(simpleCol);
store.openCollections(collections);
assertEquals("Search field list should be 0", simpleCol.getSearchFields().size(), 0);
store.destroy();
}
public void testCollectionNullName() throws JSONStoreDestroyFailureException, JSONStoreTransactionFailureException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
try {
new JSONStoreCollection(null);
} catch (JSONStoreInvalidSchemaException e) {
store.destroy();
return;
}
assertTrue("Invalid schema should have been thrown!", false);
store.destroy();
}
public void testNullCollection() throws JSONStoreException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
//Open collection.
List<JSONStoreCollection> collections = null;
store.openCollections(collections);
store.destroy();
}
public void testOpenNoCollections() throws JSONStoreException {
JSONStore store = JSONStore.getInstance(getTestContext());
store.destroy();
//Open collection.
List<JSONStoreCollection> collections = new LinkedList<JSONStoreCollection>();
store.openCollections(collections);
store.destroy();
}
}
| |
/*
* 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.presto.mongodb;
import com.facebook.presto.spi.ConnectorPageSink;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.StandardErrorCode;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.type.BigintType;
import com.facebook.presto.spi.type.BooleanType;
import com.facebook.presto.spi.type.DateType;
import com.facebook.presto.spi.type.DecimalType;
import com.facebook.presto.spi.type.Decimals;
import com.facebook.presto.spi.type.DoubleType;
import com.facebook.presto.spi.type.IntegerType;
import com.facebook.presto.spi.type.NamedTypeSignature;
import com.facebook.presto.spi.type.SmallintType;
import com.facebook.presto.spi.type.TimeType;
import com.facebook.presto.spi.type.TimestampType;
import com.facebook.presto.spi.type.TimestampWithTimeZoneType;
import com.facebook.presto.spi.type.TinyintType;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeSignatureParameter;
import com.facebook.presto.spi.type.VarbinaryType;
import com.google.common.collect.ImmutableList;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.InsertManyOptions;
import io.airlift.slice.Slice;
import org.bson.Document;
import org.bson.types.Binary;
import org.bson.types.ObjectId;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import static com.facebook.presto.mongodb.ObjectIdType.OBJECT_ID;
import static com.facebook.presto.mongodb.TypeUtils.isArrayType;
import static com.facebook.presto.mongodb.TypeUtils.isMapType;
import static com.facebook.presto.mongodb.TypeUtils.isRowType;
import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED;
import static com.facebook.presto.spi.type.DateTimeEncoding.unpackMillisUtc;
import static com.facebook.presto.spi.type.Varchars.isVarcharType;
import static java.util.Collections.unmodifiableList;
import static java.util.Collections.unmodifiableMap;
import static java.util.concurrent.CompletableFuture.completedFuture;
public class MongoPageSink
implements ConnectorPageSink
{
private final MongoSession mongoSession;
private final ConnectorSession session;
private final SchemaTableName schemaTableName;
private final List<MongoColumnHandle> columns;
private final String implicitPrefix;
public MongoPageSink(MongoClientConfig config,
MongoSession mongoSession,
ConnectorSession session,
SchemaTableName schemaTableName,
List<MongoColumnHandle> columns)
{
this.mongoSession = mongoSession;
this.session = session;
this.schemaTableName = schemaTableName;
this.columns = columns;
this.implicitPrefix = config.getImplicitRowFieldPrefix();
}
@Override
public CompletableFuture<?> appendPage(Page page)
{
MongoCollection<Document> collection = mongoSession.getCollection(schemaTableName);
List<Document> batch = new ArrayList<>(page.getPositionCount());
for (int position = 0; position < page.getPositionCount(); position++) {
Document doc = new Document();
for (int channel = 0; channel < page.getChannelCount(); channel++) {
MongoColumnHandle column = columns.get(channel);
doc.append(column.getName(), getObjectValue(columns.get(channel).getType(), page.getBlock(channel), position));
}
batch.add(doc);
}
collection.insertMany(batch, new InsertManyOptions().ordered(true));
return NOT_BLOCKED;
}
private Object getObjectValue(Type type, Block block, int position)
{
if (block.isNull(position)) {
if (type.equals(OBJECT_ID)) {
return new ObjectId();
}
return null;
}
if (type.equals(OBJECT_ID)) {
return new ObjectId(block.getSlice(position, 0, block.getLength(position)).getBytes());
}
if (type.equals(BooleanType.BOOLEAN)) {
return type.getBoolean(block, position);
}
if (type.equals(BigintType.BIGINT)) {
return type.getLong(block, position);
}
if (type.equals(IntegerType.INTEGER)) {
return (int) type.getLong(block, position);
}
if (type.equals(SmallintType.SMALLINT)) {
return (short) type.getLong(block, position);
}
if (type.equals(TinyintType.TINYINT)) {
return (byte) type.getLong(block, position);
}
if (type.equals(DoubleType.DOUBLE)) {
return type.getDouble(block, position);
}
if (isVarcharType(type)) {
return type.getSlice(block, position).toStringUtf8();
}
if (type.equals(VarbinaryType.VARBINARY)) {
return new Binary(type.getSlice(block, position).getBytes());
}
if (type.equals(DateType.DATE)) {
long days = type.getLong(block, position);
return new Date(TimeUnit.DAYS.toMillis(days));
}
if (type.equals(TimeType.TIME)) {
long millisUtc = type.getLong(block, position);
return new Date(millisUtc);
}
if (type.equals(TimestampType.TIMESTAMP)) {
long millisUtc = type.getLong(block, position);
return new Date(millisUtc);
}
if (type.equals(TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE)) {
long millisUtc = unpackMillisUtc(type.getLong(block, position));
return new Date(millisUtc);
}
if (type instanceof DecimalType) {
// TODO: decimal type might not support yet
DecimalType decimalType = (DecimalType) type;
BigInteger unscaledValue;
if (decimalType.isShort()) {
unscaledValue = BigInteger.valueOf(decimalType.getLong(block, position));
}
else {
unscaledValue = Decimals.decodeUnscaledValue(decimalType.getSlice(block, position));
}
return new BigDecimal(unscaledValue);
}
if (isArrayType(type)) {
Type elementType = type.getTypeParameters().get(0);
Block arrayBlock = block.getObject(position, Block.class);
List<Object> list = new ArrayList<>(arrayBlock.getPositionCount());
for (int i = 0; i < arrayBlock.getPositionCount(); i++) {
Object element = getObjectValue(elementType, arrayBlock, i);
list.add(element);
}
return unmodifiableList(list);
}
if (isMapType(type)) {
Type keyType = type.getTypeParameters().get(0);
Type valueType = type.getTypeParameters().get(1);
Block mapBlock = block.getObject(position, Block.class);
// map type is converted into list of fixed keys document
List<Object> values = new ArrayList<>(mapBlock.getPositionCount() / 2);
for (int i = 0; i < mapBlock.getPositionCount(); i += 2) {
Map<String, Object> mapValue = new HashMap<>();
mapValue.put("key", getObjectValue(keyType, mapBlock, i));
mapValue.put("value", getObjectValue(valueType, mapBlock, i + 1));
values.add(mapValue);
}
return unmodifiableList(values);
}
if (isRowType(type)) {
Block rowBlock = block.getObject(position, Block.class);
List<Type> fieldTypes = type.getTypeParameters();
if (fieldTypes.size() != rowBlock.getPositionCount()) {
throw new PrestoException(StandardErrorCode.GENERIC_INTERNAL_ERROR, "Expected row value field count does not match type field count");
}
if (isImplicitRowType(type)) {
List<Object> rowValue = new ArrayList<>();
for (int i = 0; i < rowBlock.getPositionCount(); i++) {
Object element = getObjectValue(fieldTypes.get(i), rowBlock, i);
rowValue.add(element);
}
return unmodifiableList(rowValue);
}
Map<String, Object> rowValue = new HashMap<>();
for (int i = 0; i < rowBlock.getPositionCount(); i++) {
rowValue.put(
type.getTypeSignature().getParameters().get(i).getNamedTypeSignature().getName(),
getObjectValue(fieldTypes.get(i), rowBlock, i));
}
return unmodifiableMap(rowValue);
}
throw new PrestoException(NOT_SUPPORTED, "unsupported type: " + type);
}
private boolean isImplicitRowType(Type type)
{
return type.getTypeSignature().getParameters()
.stream()
.map(TypeSignatureParameter::getNamedTypeSignature)
.map(NamedTypeSignature::getName)
.allMatch(name -> name.startsWith(implicitPrefix));
}
@Override
public CompletableFuture<Collection<Slice>> finish()
{
return completedFuture(ImmutableList.of());
}
@Override
public void abort()
{
}
}
| |
/*
* Copyright 2015 Rhythm & Hues Studios.
*
* 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.rhythm.louie.util;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.slf4j.LoggerFactory;
/**
*
* @author cjohnson
* @param <E>
*/
public class FutureList<E> implements Collection<E>, List<E> {
private final List<ListenableFuture<E>> futures;
public FutureList() {
futures = new ArrayList<>();
}
public FutureList(List<? extends ListenableFuture<E>> futures) {
this();
this.futures.addAll(futures);
}
@Override
public int size() {
return futures.size();
}
@Override
public boolean isEmpty() {
return futures.isEmpty();
}
@Override
public E get(int index) {
try {
return futures.get(index).get();
} catch (InterruptedException | ExecutionException ex) {
LoggerFactory.getLogger(FutureList.class).error("Error getting item", ex);
}
return null;
}
@Override
public E remove(int index) {
Future<E> current = futures.remove(index);
if (current!=null&¤t.isDone()) {
try {
return current.get();
} catch (InterruptedException | ExecutionException e) {}
}
return null;
}
@Override
public Iterator<E> iterator() {
return new CompletedItr();
}
/**
* An iterator that returns the items in their original order, but blocks if necessary
*/
private class CompletedItr implements Iterator<E> {
Iterator<ListenableFuture<E>> futureIter;
public CompletedItr() {
futureIter = Futures.inCompletionOrder(futures).iterator();
}
@Override
public boolean hasNext() {
return futureIter.hasNext();
}
@Override
public E next() {
try {
return futureIter.next().get();
} catch (InterruptedException | ExecutionException ex) {
LoggerFactory.getLogger(FutureList.class).error("Error iterating", ex);
}
return null;
}
@Override
public void remove() {
futureIter.remove();
}
}
/**
* Returns items that are completed first
*/
private class ExpermimentalCompletedItr implements Iterator<E> {
LinkedList<Future<E>> processing;
public ExpermimentalCompletedItr() {
processing = new LinkedList<Future<E>>(futures);
}
@Override
public boolean hasNext() {
return !processing.isEmpty();
}
@Override
public E next() {
if (processing.isEmpty()) {
throw new NoSuchElementException();
}
try {
while (true) {
Iterator<Future<E>> pIter = processing.iterator();
while (pIter.hasNext()) {
Future<E> item = pIter.next();
if (item.isDone()) {
pIter.remove();
return item.get();
}
}
Thread.sleep(10);
}
} catch (InterruptedException | ExecutionException ex) {
LoggerFactory.getLogger(FutureList.class).error("Error iterating", ex);
}
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Remove items from a FutureList is not supported");
}
}
@Override
public boolean add(E e) {
return futures.add(Futures.immediateFuture(e));
}
public boolean addFuture(ListenableFuture<E> futureItem) {
return futures.add(futureItem);
}
@Override
public E set(int index, E element) {
futures.set(index, Futures.immediateFuture(element));
// not sure what to return here
return element;
}
@Override
public void add(int index, E element) {
futures.add(index, Futures.immediateFuture(element));
}
@Override
public boolean addAll(Collection<? extends E> c) {
if (c.isEmpty()) {
return false;
}
for (E item : c) {
add(item);
}
return true;
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
if (index < 0 || index > size())
throw new IndexOutOfBoundsException("Index "+index+" is out of bounds");
if (c.isEmpty()) {
return false;
}
for (E e : c) {
add(index++, e);
}
return true;
}
@Override
public void clear() {
futures.clear();
}
@Override
public boolean contains(Object o) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object[] toArray() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T> T[] toArray(T[] a) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean removeAll(Collection c) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean retainAll(Collection c) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean containsAll(Collection c) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean equals(Object o) {
return this==o;
}
@Override
public int hashCode() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int indexOf(Object o) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int lastIndexOf(Object o) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ListIterator<E> listIterator() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ListIterator<E> listIterator(int index) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.crash;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.IntDef;
import org.chromium.base.Log;
import org.chromium.base.StreamUtil;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.browser.preferences.privacy.CrashReportingPermissionManager;
import org.chromium.chrome.browser.preferences.privacy.PrivacyPreferencesManager;
import org.chromium.chrome.browser.util.HttpURLConnectionFactory;
import org.chromium.chrome.browser.util.HttpURLConnectionFactoryImpl;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.zip.GZIPOutputStream;
/**
* This class tries to upload a minidump to the crash server.
*
* It is implemented as a Callable<Boolean> and returns true on successful uploads,
* and false otherwise.
*/
public class MinidumpUploadCallable implements Callable<Integer> {
private static final String TAG = "MDUploadCallable";
// These preferences are obsolete and are kept only for removing from user preferences.
protected static final String PREF_DAY_UPLOAD_COUNT = "crash_day_dump_upload_count";
protected static final String PREF_LAST_UPLOAD_DAY = "crash_dump_last_upload_day";
protected static final String PREF_LAST_UPLOAD_WEEK = "crash_dump_last_upload_week";
protected static final String PREF_WEEK_UPLOAD_SIZE = "crash_dump_week_upload_size";
@VisibleForTesting
protected static final String CRASH_URL_STRING = "https://clients2.google.com/cr/report";
@VisibleForTesting
protected static final String CONTENT_TYPE_TMPL = "multipart/form-data; boundary=%s";
@IntDef({
UPLOAD_SUCCESS,
UPLOAD_FAILURE,
UPLOAD_USER_DISABLED,
UPLOAD_COMMANDLINE_DISABLED
})
public @interface MinidumpUploadStatus {}
public static final int UPLOAD_SUCCESS = 0;
public static final int UPLOAD_FAILURE = 1;
public static final int UPLOAD_USER_DISABLED = 2;
public static final int UPLOAD_COMMANDLINE_DISABLED = 3;
private final File mFileToUpload;
private final File mLogfile;
private final HttpURLConnectionFactory mHttpURLConnectionFactory;
private final CrashReportingPermissionManager mPermManager;
public MinidumpUploadCallable(File fileToUpload, File logfile, Context context) {
this(fileToUpload, logfile, new HttpURLConnectionFactoryImpl(),
PrivacyPreferencesManager.getInstance(context));
removeOutdatedPrefs(PreferenceManager.getDefaultSharedPreferences(context));
}
public MinidumpUploadCallable(File fileToUpload, File logfile,
HttpURLConnectionFactory httpURLConnectionFactory,
CrashReportingPermissionManager permManager) {
mFileToUpload = fileToUpload;
mLogfile = logfile;
mHttpURLConnectionFactory = httpURLConnectionFactory;
mPermManager = permManager;
}
@Override
public Integer call() {
// TODO(jchinlee): address proper cleanup procedures for command line flag-disabled uploads.
if (mPermManager.isUploadCommandLineDisabled()) {
Log.i(TAG, "Minidump upload is disabled by command line flag. Retaining file.");
return UPLOAD_COMMANDLINE_DISABLED;
}
if (mPermManager.isUploadEnabledForTests()) {
Log.i(TAG, "Minidump upload enabled for tests, skipping other checks.");
} else {
if (!mPermManager.isUploadUserPermitted()) {
Log.i(TAG, "Minidump upload is not permitted by user. Marking file as uploaded for "
+ "cleanup to prevent future uploads.");
cleanupMinidumpFile();
return UPLOAD_USER_DISABLED;
}
boolean isLimited = mPermManager.isUploadLimited();
if (isLimited || !mPermManager.isUploadPermitted()) {
Log.i(TAG, "Minidump cannot currently be uploaded due to constraints.");
return UPLOAD_FAILURE;
}
}
HttpURLConnection connection =
mHttpURLConnectionFactory.createHttpURLConnection(CRASH_URL_STRING);
if (connection == null) {
return UPLOAD_FAILURE;
}
FileInputStream minidumpInputStream = null;
try {
if (!configureConnectionForHttpPost(connection)) {
return UPLOAD_FAILURE;
}
minidumpInputStream = new FileInputStream(mFileToUpload);
streamCopy(minidumpInputStream, new GZIPOutputStream(connection.getOutputStream()));
boolean success = handleExecutionResponse(connection);
return success ? UPLOAD_SUCCESS : UPLOAD_FAILURE;
} catch (IOException e) {
// For now just log the stack trace.
Log.w(TAG, "Error while uploading " + mFileToUpload.getName(), e);
return UPLOAD_FAILURE;
} finally {
connection.disconnect();
if (minidumpInputStream != null) {
StreamUtil.closeQuietly(minidumpInputStream);
}
}
}
/**
* Configures a HttpURLConnection to send a HTTP POST request for uploading the minidump.
*
* This also reads the content-type from the minidump file.
*
* @param connection the HttpURLConnection to configure
* @return true if successful.
* @throws IOException
*/
private boolean configureConnectionForHttpPost(HttpURLConnection connection)
throws IOException {
// Read the boundary which we need for the content type.
String boundary = readBoundary();
if (boundary == null) {
return false;
}
connection.setDoOutput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Encoding", "gzip");
connection.setRequestProperty("Content-Type", String.format(CONTENT_TYPE_TMPL, boundary));
return true;
}
/**
* Reads the HTTP response and cleans up successful uploads.
*
* @param connection the connection to read the response from
* @return true if the upload was successful, false otherwise.
* @throws IOException
*/
private Boolean handleExecutionResponse(HttpURLConnection connection) throws IOException {
int responseCode = connection.getResponseCode();
if (isSuccessful(responseCode)) {
String responseContent = getResponseContentAsString(connection);
// The crash server returns the crash ID.
String id = responseContent != null ? responseContent : "unknown";
Log.i(TAG, "Minidump " + mFileToUpload.getName() + " uploaded successfully, id: " + id);
// TODO(acleung): MinidumpUploadService is in charge of renaming while this class is
// in charge of deleting. We should move all the file system operations into
// MinidumpUploadService instead.
cleanupMinidumpFile();
try {
appendUploadedEntryToLog(id);
} catch (IOException ioe) {
Log.e(TAG, "Fail to write uploaded entry to log file");
}
return true;
} else {
// Log the results of the upload. Note that periodic upload failures aren't bad
// because we will need to throttle uploads in the future anyway.
String msg = String.format(Locale.US,
"Failed to upload %s with code: %d (%s).",
mFileToUpload.getName(), responseCode, connection.getResponseMessage());
Log.i(TAG, msg);
// TODO(acleung): The return status informs us about why an upload might be
// rejected. The next logical step is to put the reasons in an UMA histogram.
return false;
}
}
/**
* Records the upload entry to a log file
* similar to what is done in chrome/app/breakpad_linux.cc
*
* @param id The crash ID return from the server.
*/
private void appendUploadedEntryToLog(String id) throws IOException {
FileWriter writer = new FileWriter(mLogfile, /* Appending */ true);
// The log entries are formated like so:
// seconds_since_epoch,crash_id
StringBuilder sb = new StringBuilder();
sb.append(System.currentTimeMillis() / 1000);
sb.append(",");
sb.append(id);
sb.append('\n');
try {
// Since we are writing one line at a time, lets forget about BufferWriters.
writer.write(sb.toString());
} finally {
writer.close();
}
}
/**
* Get the boundary from the file, we need it for the content-type.
*
* @return the boundary if found, else null.
* @throws IOException
*/
private String readBoundary() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(mFileToUpload));
String boundary = reader.readLine();
reader.close();
if (boundary == null || boundary.trim().isEmpty()) {
Log.e(TAG, "Ignoring invalid crash dump: '" + mFileToUpload + "'");
return null;
}
boundary = boundary.trim();
if (!boundary.startsWith("--") || boundary.length() < 10) {
Log.e(TAG, "Ignoring invalidly bound crash dump: '" + mFileToUpload + "'");
return null;
}
boundary = boundary.substring(2); // Remove the initial --
return boundary;
}
/**
* Mark file we just uploaded for cleanup later.
*
* We do not immediately delete the file for testing reasons,
* but if marking the file fails, we do delete it right away.
*/
private void cleanupMinidumpFile() {
if (!CrashFileManager.tryMarkAsUploaded(mFileToUpload)) {
Log.w(TAG, "Unable to mark " + mFileToUpload + " as uploaded.");
if (!mFileToUpload.delete()) {
Log.w(TAG, "Cannot delete " + mFileToUpload);
}
}
}
/**
* Returns whether the response code indicates a successful HTTP request.
*
* @param responseCode the response code
* @return true if response code indicates success, false otherwise.
*/
private static boolean isSuccessful(int responseCode) {
return responseCode == 200 || responseCode == 201 || responseCode == 202;
}
/**
* Reads the response from |connection| as a String.
*
* @param connection the connection to read the response from.
* @return the content of the response.
* @throws IOException
*/
private static String getResponseContentAsString(HttpURLConnection connection)
throws IOException {
String responseContent = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
streamCopy(connection.getInputStream(), baos);
if (baos.size() > 0) {
responseContent = baos.toString();
}
return responseContent;
}
/**
* Copies all available data from |inStream| to |outStream|. Closes both
* streams when done.
*
* @param inStream the stream to read
* @param outStream the stream to write to
* @throws IOException
*/
private static void streamCopy(InputStream inStream,
OutputStream outStream) throws IOException {
byte[] temp = new byte[4096];
int bytesRead = inStream.read(temp);
while (bytesRead >= 0) {
outStream.write(temp, 0, bytesRead);
bytesRead = inStream.read(temp);
}
inStream.close();
outStream.close();
}
// TODO(gayane): Remove this function and unused prefs in M51. crbug.com/555022
private void removeOutdatedPrefs(SharedPreferences sharedPreferences) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(PREF_DAY_UPLOAD_COUNT)
.remove(PREF_LAST_UPLOAD_DAY)
.remove(PREF_LAST_UPLOAD_WEEK)
.remove(PREF_WEEK_UPLOAD_SIZE)
.apply();
}
}
| |
/*
* Licensed to Crate.io GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.beans;
import io.crate.common.Suppliers;
import io.crate.execution.engine.collect.stats.JobsLogs;
import io.crate.metadata.sys.MetricsView;
import io.crate.planner.Plan.StatementType;
import io.crate.planner.operators.StatementClassifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
public class QueryStats implements QueryStatsMBean {
private static final Set<StatementType> CLASSIFIED_STATEMENT_TYPES =
Set.of(StatementType.SELECT, StatementType.INSERT, StatementType.UPDATE, StatementType.DELETE,
StatementType.MANAGEMENT, StatementType.COPY, StatementType.DDL);
static class Metric {
private long failedCount;
private long totalCount;
private long sumOfDurations;
Metric(long sumOfDurations, long totalCount, long failedCount) {
this.sumOfDurations = sumOfDurations;
this.totalCount = totalCount;
this.failedCount = failedCount;
}
void inc(long duration, long totalCount, long failedCount) {
this.sumOfDurations += duration;
this.totalCount += totalCount;
this.failedCount += failedCount;
}
long totalCount() {
return totalCount;
}
long sumOfDurations() {
return sumOfDurations;
}
long failedCount() {
return failedCount;
}
}
public static final String NAME = "io.crate.monitoring:type=QueryStats";
private static final Metric DEFAULT_METRIC = new Metric(0, 0, 0) {
@Override
void inc(long duration, long totalCount, long failedCount) {
throw new AssertionError("inc must not be called on default metric - it's immutable");
}
};
private final Supplier<Map<StatementType, Metric>> metricByStmtType;
public QueryStats(JobsLogs jobsLogs) {
metricByStmtType = Suppliers.memoizeWithExpiration(
() -> createMetricsMap(jobsLogs.metrics()),
1,
TimeUnit.SECONDS
);
}
static Map<StatementType, Metric> createMetricsMap(Iterable<MetricsView> metrics) {
Map<StatementType, Metric> metricsByStmtType = new HashMap<>();
for (MetricsView classifiedMetrics : metrics) {
long sumOfDurations = classifiedMetrics.sumOfDurations();
long failedCount = classifiedMetrics.failedCount();
metricsByStmtType.compute(classificationType(classifiedMetrics.classification()), (key, oldMetric) -> {
if (oldMetric == null) {
return new Metric(sumOfDurations, classifiedMetrics.totalCount(), failedCount);
}
oldMetric.inc(sumOfDurations, classifiedMetrics.totalCount(), failedCount);
return oldMetric;
});
}
return metricsByStmtType;
}
private static StatementType classificationType(StatementClassifier.Classification classification) {
if (classification == null || !CLASSIFIED_STATEMENT_TYPES.contains(classification.type())) {
return StatementType.UNDEFINED;
}
return classification.type();
}
@Override
public long getSelectQueryTotalCount() {
return metricByStmtType.get().getOrDefault(StatementType.SELECT, DEFAULT_METRIC).totalCount();
}
@Override
public long getInsertQueryTotalCount() {
return metricByStmtType.get().getOrDefault(StatementType.INSERT, DEFAULT_METRIC).totalCount();
}
@Override
public long getUpdateQueryTotalCount() {
return metricByStmtType.get().getOrDefault(StatementType.UPDATE, DEFAULT_METRIC).totalCount();
}
@Override
public long getDeleteQueryTotalCount() {
return metricByStmtType.get().getOrDefault(StatementType.DELETE, DEFAULT_METRIC).totalCount();
}
@Override
public long getManagementQueryTotalCount() {
return metricByStmtType.get().getOrDefault(StatementType.MANAGEMENT, DEFAULT_METRIC).totalCount();
}
@Override
public long getDDLQueryTotalCount() {
return metricByStmtType.get().getOrDefault(StatementType.DDL, DEFAULT_METRIC).totalCount();
}
@Override
public long getCopyQueryTotalCount() {
return metricByStmtType.get().getOrDefault(StatementType.COPY, DEFAULT_METRIC).totalCount();
}
@Override
public long getUndefinedQueryTotalCount() {
return metricByStmtType.get().getOrDefault(StatementType.UNDEFINED, DEFAULT_METRIC).totalCount();
}
@Override
public long getSelectQuerySumOfDurations() {
return metricByStmtType.get().getOrDefault(StatementType.SELECT, DEFAULT_METRIC).sumOfDurations();
}
@Override
public long getInsertQuerySumOfDurations() {
return metricByStmtType.get().getOrDefault(StatementType.INSERT, DEFAULT_METRIC).sumOfDurations();
}
@Override
public long getUpdateQuerySumOfDurations() {
return metricByStmtType.get().getOrDefault(StatementType.UPDATE, DEFAULT_METRIC).sumOfDurations();
}
@Override
public long getDeleteQuerySumOfDurations() {
return metricByStmtType.get().getOrDefault(StatementType.DELETE, DEFAULT_METRIC).sumOfDurations();
}
@Override
public long getManagementQuerySumOfDurations() {
return metricByStmtType.get().getOrDefault(StatementType.MANAGEMENT, DEFAULT_METRIC).sumOfDurations();
}
@Override
public long getDDLQuerySumOfDurations() {
return metricByStmtType.get().getOrDefault(StatementType.DDL, DEFAULT_METRIC).sumOfDurations();
}
@Override
public long getCopyQuerySumOfDurations() {
return metricByStmtType.get().getOrDefault(StatementType.COPY, DEFAULT_METRIC).sumOfDurations();
}
@Override
public long getUndefinedQuerySumOfDurations() {
return metricByStmtType.get().getOrDefault(StatementType.UNDEFINED, DEFAULT_METRIC).sumOfDurations();
}
@Override
public long getSelectQueryFailedCount() {
return metricByStmtType.get().getOrDefault(StatementType.SELECT, DEFAULT_METRIC).failedCount();
}
@Override
public long getInsertQueryFailedCount() {
return metricByStmtType.get().getOrDefault(StatementType.INSERT, DEFAULT_METRIC).failedCount();
}
@Override
public long getUpdateQueryFailedCount() {
return metricByStmtType.get().getOrDefault(StatementType.UPDATE, DEFAULT_METRIC).failedCount();
}
@Override
public long getDeleteQueryFailedCount() {
return metricByStmtType.get().getOrDefault(StatementType.DELETE, DEFAULT_METRIC).failedCount();
}
@Override
public long getManagementQueryFailedCount() {
return metricByStmtType.get().getOrDefault(StatementType.MANAGEMENT, DEFAULT_METRIC).failedCount();
}
@Override
public long getDDLQueryFailedCount() {
return metricByStmtType.get().getOrDefault(StatementType.DDL, DEFAULT_METRIC).failedCount();
}
@Override
public long getCopyQueryFailedCount() {
return metricByStmtType.get().getOrDefault(StatementType.COPY, DEFAULT_METRIC).failedCount();
}
@Override
public long getUndefinedQueryFailedCount() {
return metricByStmtType.get().getOrDefault(StatementType.UNDEFINED, DEFAULT_METRIC).failedCount();
}
}
| |
package org.zackratos.weather.weatherlist2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import org.litepal.crud.DataSupport;
import org.zackratos.weather.BaseFragment;
import org.zackratos.weather.weatherlist.BingApi;
import org.zackratos.weather.Constants;
import org.zackratos.weather.addPlace.County;
import org.zackratos.weather.HttpUtils;
import org.zackratos.weather.R;
import org.zackratos.weather.SPUtils;
import org.zackratos.weather.weather.Weather;
import org.zackratos.weather.addPlace.AddPlaceActivity;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
/**
* Created by Administrator on 2017/6/17.
*/
public class DrawerFragment extends BaseFragment {
public static DrawerFragment newInstance() {
return new DrawerFragment();
}
@BindView(R.id.drawer_county_list)
RecyclerView countyListView;
@BindView(R.id.drawer_header)
ImageView headerView;
@OnClick(R.id.drawer_fab)
void onFabClick() {
startActivityForResult(AddPlaceActivity.newIntent(getActivity()), Constants.Drawer.REQUEST_CODE);
}
Unbinder unbinder;
private WeatherAdapter adapter;
private Callback callback;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback = (Callback) activity;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_drawer, container, false);
unbinder = ButterKnife.bind(this, view);
initView();
return view;
}
private void initView() {
countyListView.setLayoutManager(new LinearLayoutManager(getActivity()));
Observable.create(new ObservableOnSubscribe<List<Weather>>() {
@Override
public void subscribe(@NonNull ObservableEmitter<List<Weather>> e) throws Exception {
List<Weather> weathers = DataSupport.select("weatherid", "countyname")
.find(Weather.class);
e.onNext(weathers);
e.onComplete();
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<Weather>>() {
@Override
public void accept(@NonNull List<Weather> weathers) throws Exception {
updateUI(weathers);
}
});
Glide.with(this).load(SPUtils.getBingAdd(getActivity())).into(headerView);
HttpUtils.getRetrofit(BingApi.BING_PIC)
.create(BingApi.class)
.rxAddress()
.subscribeOn(Schedulers.io())
.map(new Function<ResponseBody, String>() {
@Override
public String apply(@NonNull ResponseBody responseBody) throws Exception {
return responseBody.string();
}
})
.doOnNext(new Consumer<String>() {
@Override
public void accept(@NonNull String s) throws Exception {
SPUtils.putBingAdd(getActivity(), s);
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<String>() {
@Override
public void accept(@NonNull String s) throws Exception {
Glide.with(DrawerFragment.this)
.load(s)
.into(headerView);
}
}, new Consumer<Throwable>() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
}
});
}
private void updateUI(List<Weather> weathers) {
if (adapter == null) {
adapter = new WeatherAdapter(weathers);
countyListView.setAdapter(adapter);
adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
}
});
} else {
adapter.setNewData(weathers);
adapter.notifyDataSetChanged();
if (countyListView.getAdapter() == null) {
countyListView.setAdapter(adapter);
}
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@Override
public void onDetach() {
super.onDetach();
callback = null;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Constants.Drawer.REQUEST_CODE) {
switch (resultCode) {
case Activity.RESULT_OK:
addSelectWeather(data);
break;
case Constants.AddPlace.LOCATE_RESULT:
addLocateWeather(data);
break;
default:
break;
}
}
}
private void addSelectWeather(Intent intent) {
Observable.just(intent)
.subscribeOn(Schedulers.io())
.map(new Function<Intent, Integer>() {
@Override
public Integer apply(@NonNull Intent intent) throws Exception {
return AddPlaceActivity.getCountyId(intent);
}
})
.map(new Function<Integer, County>() {
@Override
public County apply(@NonNull Integer integer) throws Exception {
return DataSupport.find(County.class, integer);
}
})
.doOnNext(new Consumer<County>() {
@Override
public void accept(@NonNull County county) throws Exception {
List<Weather> weathers = adapter.getData();
for (int i = 0; i < weathers.size(); i++) {
Weather weather = weathers.get(i);
if (weather.getWeatherId().equals(county.getWeatherId())) {
return;
}
}
Weather weather = new Weather.Builder()
.countyName(county.getName())
.weatherId(county.getWeatherId())
.build();
adapter.getData().add(weather);
weather.save();
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<County>() {
@Override
public void accept(@NonNull County county) throws Exception {
adapter.notifyItemInserted(adapter.getData().size() - 1);
}
}, new Consumer<Throwable>() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
}
});
}
private void addLocateWeather(Intent intent) {
/* Observable.just(intent)
.subscribeOn(Schedulers.io())
.map(new Function<Intent, SearchBasic>() {
@Override
public SearchBasic apply(@NonNull Intent intent) throws Exception {
return AddPlaceActivity.getBasic(intent);
}
})
.filter(new Predicate<SearchBasic>() {
@Override
public boolean test(@NonNull SearchBasic searchBasic) throws Exception {
List<Weather> weathers = DataSupport.select("weatherid").find(Weather.class);
for (int i = 0; i < weathers.size(); i++) {
Weather weather = weathers.get(i);
if (weather.getWeatherId().equals(searchBasic.getId())) {
return false;
}
}
return true;
}
})
.doOnNext(new Consumer<SearchBasic>() {
@Override
public void accept(@NonNull SearchBasic searchBasic) throws Exception {
Weather weather = new Weather.Builder()
.weatherId(searchBasic.getId())
.countyName(searchBasic.getCity())
.build();
adapter.getData().add(weather);
weather.save();
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<SearchBasic>() {
@Override
public void accept(@NonNull SearchBasic searchBasic) throws Exception {
adapter.notifyItemInserted(adapter.getData().size() - 1);
}
}, new Consumer<Throwable>() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
}
});*/
}
private class WeatherAdapter extends BaseQuickAdapter<Weather, BaseViewHolder> {
public WeatherAdapter(@Nullable List<Weather> data) {
super(R.layout.item_drawer, data);
}
@Override
protected void convert(BaseViewHolder helper, Weather item) {
helper.setText(R.id.drawer_item_name, item.getCountyName());
}
}
public interface Callback {
void switchWeather(int id);
}
}
| |
package de.mpii.fsm.util;
//import gnu.trove.TIntArrayList;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.mahout.math.list.IntArrayList;
/**
* Writable wrapping an int[].
*
* @author Klaus Berberich (kberberi@mpi-inf.mpg.de)
*/
@SuppressWarnings("rawtypes")
public class IntArrayWritable implements WritableComparable {
private int b = 0;
private int e = 0;
private int[] contents;
public IntArrayWritable() {
contents = new int[0];
}
public IntArrayWritable(int[] contents) {
this.contents = contents;
this.b = 0;
this.e = contents.length;
}
@Override
public void write(DataOutput d) throws IOException {
WritableUtils.writeVInt(d, e - b);
for (int i = b; i < e; i++) {
WritableUtils.writeVInt(d, contents[i]);
}
}
@Override
public void readFields(DataInput di) throws IOException {
contents = new int[WritableUtils.readVInt(di)];
for (int i = 0; i < contents.length; i++) {
contents[i] = WritableUtils.readVInt(di);
}
b = 0;
e = contents.length;
}
@Override
public int compareTo(Object o) {
IntArrayWritable other = (IntArrayWritable) o;
int length = e - b;
int otherLength = other.e - other.b;
int minLength = (length < otherLength ? length : otherLength);
for (int i = 0; i < minLength; i++) {
int tid = contents[b + i];
int otherTId = other.contents[other.b + i];
if (tid < otherTId) {
return +1;
} else if (tid > otherTId) {
return -1;
}
}
return (otherLength - length);
}
public int[] getContents() {
int[] result = contents;
if (b != 0 || e != contents.length) {
result = new int[e - b];
System.arraycopy(contents, b, result, 0, e - b);
}
return result;
}
public void setContents(int[] contents, int b, int e) {
this.contents = contents;
this.b = b;
this.e = e;
}
public void setContents(int[] contents) {
this.contents = contents;
this.b = 0;
this.e = contents.length;
}
public void setBegin(int b) {
this.b = b;
}
public void setEnd(int e) {
this.e = e;
}
public void setRange(int b, int e) {
this.b = b;
this.e = e;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
IntArrayWritable other = (IntArrayWritable) obj;
if ((e - b) != (other.e - other.b)) {
return false;
}
for (int i = 0, len = e - b; i < len; i++) {
if (contents[b + i] != other.contents[other.b + i]) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
if (contents == null) {
return 0;
}
int result = 1;
for (int i = b; i < e; i++) {
result = 31 * result + contents[i];
}
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = b; i < e; i++) {
sb.append(contents[i]);
if (i != e - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
public static int lcp(int[] a, int[] b) {
int lcp = 0;
while (lcp < a.length && lcp < b.length && a[lcp] == b[lcp]) {
lcp++;
}
return lcp;
}
public static int lcp(IntArrayList a, int[] b) {
int lcp = 0;
while (lcp < a.size() && lcp < b.length && a.get(lcp) == b[lcp]) {
lcp++;
}
return lcp;
}
public static final class Comparator extends WritableComparator {
public Comparator() {
super(IntArrayWritable.class);
}
@Override
public int compare(WritableComparable a, WritableComparable b) {
if (a instanceof IntArrayWritable && b instanceof IntArrayWritable) {
return ((IntArrayWritable) a).compareTo((IntArrayWritable) b);
}
return super.compare(a, b);
}
@Override
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
try {
int firstLength = readVInt(b1, s1);
int p1 = s1 + WritableUtils.decodeVIntSize(b1[s1]);
int secondLength = readVInt(b2, s2);
int p2 = s2 + WritableUtils.decodeVIntSize(b2[s2]);
int minLength = (firstLength < secondLength ? firstLength : secondLength);
for (int i = 0; i < minLength; i++) {
int firstTId = readVInt(b1, p1);
p1 += WritableUtils.decodeVIntSize(b1[p1]);
int secondTId = readVInt(b2, p2);
p2 += WritableUtils.decodeVIntSize(b2[p2]);
if (firstTId < secondTId) {
return +1;
} else if (firstTId > secondTId) {
return -1;
}
}
return (secondLength - firstLength);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}
public static final class ComparatorAscending extends WritableComparator {
public ComparatorAscending() {
super(IntArrayWritable.class);
}
@Override
public int compare(WritableComparable a, WritableComparable b) {
if (a instanceof IntArrayWritable && b instanceof IntArrayWritable) {
int[] aContents = ((IntArrayWritable) a).getContents();
int[] bContents = ((IntArrayWritable) b).getContents();
for (int i = 0, minlen = Math.min(aContents.length, bContents.length); i < minlen; i++) {
if (aContents[i] < bContents[i]) {
return -1;
} else if (aContents[i] > bContents[i]) {
return +1;
}
}
return (aContents.length - bContents.length);
}
return super.compare(a, b);
}
@Override
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
try {
int firstLength = readVInt(b1, s1);
int p1 = s1 + WritableUtils.decodeVIntSize(b1[s1]);
int secondLength = readVInt(b2, s2);
int p2 = s2 + WritableUtils.decodeVIntSize(b2[s2]);
int minLength = (firstLength < secondLength ? firstLength : secondLength);
for (int i = 0; i < minLength; i++) {
int firstTId = readVInt(b1, p1);
p1 += WritableUtils.decodeVIntSize(b1[p1]);
int secondTId = readVInt(b2, p2);
p2 += WritableUtils.decodeVIntSize(b2[p2]);
if (firstTId < secondTId) {
return -1;
} else if (firstTId > secondTId) {
return +1;
}
}
return (firstLength - secondLength);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}
/**
* Partitions based on first element of an <i>IntArrayWritable</i>.
*/
public static final class PartitionerFirstOnly extends Partitioner<IntArrayWritable, Object> {
@Override
public int getPartition(IntArrayWritable key, Object value, int i) {
int result = key.contents[key.b] % i;
return (result < 0 ? -result : result);
}
}
/**
* Partitions based on complete contents of an <i>IntArrayWritable</i>.
*/
public static final class PartitionerComplete extends Partitioner<IntArrayWritable, Object> {
@Override
public int getPartition(IntArrayWritable key, Object value, int i) {
int result = 1;
for (int j = key.b; j < key.e; j++) {
result = result * 31 + key.contents[j];
}
result = result % i;
return (result < 0 ? -result : result);
}
}
public static final class DefaultComparator extends WritableComparator {
public DefaultComparator() {
super(IntArrayWritable.class);
}
@Override
public int compare(WritableComparable a, WritableComparable b) {
if (a instanceof IntArrayWritable && b instanceof IntArrayWritable) {
return ((IntArrayWritable) a).compareTo((IntArrayWritable) b);
}
return super.compare(a, b);
}
@Override
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
try {
int firstLength = readVInt(b1, s1);
int p1 = s1 + WritableUtils.decodeVIntSize(b1[s1]);
int secondLength = readVInt(b2, s2);
int p2 = s2 + WritableUtils.decodeVIntSize(b2[s2]);
int minLength = (firstLength < secondLength ? firstLength : secondLength);
for (int i = 0; i < minLength; i++) {
int firstTId = readVInt(b1, p1);
p1 += WritableUtils.decodeVIntSize(b1[p1]);
int secondTId = readVInt(b2, p2);
p2 += WritableUtils.decodeVIntSize(b2[p2]);
if (firstTId < secondTId) {
return +1;
} else if (firstTId > secondTId) {
return -1;
}
}
return (secondLength - firstLength);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}
public static final class IntArrayPartitioner implements org.apache.hadoop.mapred.Partitioner<IntArrayWritable, Object> {
@Override
public int getPartition(IntArrayWritable k, Object v, int i) {
int result = (31 * k.contents[k.b]) % i;
return (result < 0 ? -result : result);
}
@Override
public void configure(JobConf jc) {
}
}
public static final class IntArrayWritablePartitionerAllButLast extends Partitioner<IntArrayWritable, Object> {
@Override
public int getPartition(IntArrayWritable key, Object value, int i) {
int result = 1;
int[] contents = key.getContents();
for (int j = 0; j < contents.length - 1; j++) {
result = result * 31 + contents[j];
}
result = result % i;
return (result < 0 ? -result : result);
}
}
public static final class IntArrayWritablePartitionerComplete extends Partitioner<IntArrayWritable, Object> {
@Override
public int getPartition(IntArrayWritable key, Object value, int i) {
int result = 1;
int[] contents = key.getContents();
for (int j = 0; j < contents.length; j++) {
result = result * 31 + contents[j];
}
result = result % i;
return (result < 0 ? -result : result);
}
}
public static final class IntArrayWritablePartitionerFirstTwo extends Partitioner<IntArrayWritable, Object> {
@Override
public int getPartition(IntArrayWritable key, Object value, int i) {
int result = 1;
int[] contents = key.getContents();
for (int j = 0; j < contents.length && j < 2; j++) {
result = result * 31 + contents[j];
}
result = result % i;
return (result < 0 ? -result : result);
}
}
public static final class IntArrayWritablePartitionerFirstOnly extends Partitioner<IntArrayWritable, Object> {
@Override
public int getPartition(IntArrayWritable key, Object value, int i) {
int result = (31 * key.getContents()[0]) % i;
return (result < 0 ? -result : result);
}
}
}
| |
/*
* Copyright 2016 Google Inc. 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.
*/
import com.google.api.services.monitoring.v3.Monitoring;
import com.google.api.services.monitoring.v3.model.CreateTimeSeriesRequest;
import com.google.api.services.monitoring.v3.model.LabelDescriptor;
import com.google.api.services.monitoring.v3.model.ListMetricDescriptorsResponse;
import com.google.api.services.monitoring.v3.model.ListTimeSeriesResponse;
import com.google.api.services.monitoring.v3.model.Metric;
import com.google.api.services.monitoring.v3.model.MetricDescriptor;
import com.google.api.services.monitoring.v3.model.MonitoredResource;
import com.google.api.services.monitoring.v3.model.Point;
import com.google.api.services.monitoring.v3.model.TimeInterval;
import com.google.api.services.monitoring.v3.model.TimeSeries;
import com.google.api.services.monitoring.v3.model.TypedValue;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.joda.time.DateTime;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;
/**
* Class to demonstrate creating a custom metric with Cloud Monitoring.
* <p/>
* <p>This class provides a few functions that create a custom GAUGE metric, writes a timeseries
* value to it, then reads that metric's value back within the last 5 minutes to see the value
* written.
*/
public class CreateCustomMetric {
/**
* Cloud Monitoring v3 REST client.
*/
private Monitoring monitoringService;
private static SimpleDateFormat rfc3339 =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
static {
rfc3339.setTimeZone(TimeZone.getTimeZone("UTC"));
}
/**
* Identifier for project resource, in format 'projects/your-project-id'.
*/
private String projectResource;
/**
* All custom metrics should use this domain as their prefix.
*/
static final String CUSTOM_METRIC_DOMAIN = "custom.googleapis.com";
/**
* Name of our custom metric to create.
*/
static final String DEFAULT_METRIC_TYPE = "custom_measurement";
/**
* The specific metric type for the instance of this class. Defaults to DEFAULT_METRIC_TYPE.
*/
private String metricType;
/**
* The specific metric name, which is based on the project resource and the type.
*/
private String metricName;
/**
* GAUGE metrics measure a value at a point in time.
*/
static final String METRIC_KIND = "GAUGE";
/**
* Upper bound for random number to write to metric, defaults to 10.
*/
private int bound = 10;
/**
* Constructs an instance of the class using the default metric name.
*/
public CreateCustomMetric(Monitoring monitoringService, String projectResource) {
this.monitoringService = monitoringService;
this.projectResource = projectResource;
this.metricType = CUSTOM_METRIC_DOMAIN + "/" + DEFAULT_METRIC_TYPE;
this.metricName = projectResource + "/metricDescriptors/" + metricType;
}
/**
* Constructs an instance of the class using the default metric name, and takes in a random
* number generaotr (used for test purposes).
* <p/>
* <p>Package-private to be accessible to tests.
*/
CreateCustomMetric(Monitoring monitoringService, String projectResource,
String metricName, int bound) {
this.monitoringService = monitoringService;
this.projectResource = projectResource;
this.metricType = CUSTOM_METRIC_DOMAIN + "/" + DEFAULT_METRIC_TYPE;
this.metricName = projectResource + "/metricDescriptors/" + metricType;
this.bound = bound;
}
/**
* Constructs an instance of the class with the metric name specified.
*/
public CreateCustomMetric(Monitoring monitoringService, String projectResource,
String metricName) {
this.monitoringService = monitoringService;
this.projectResource = projectResource;
this.metricType = CUSTOM_METRIC_DOMAIN + "/" + metricName;
this.metricName = projectResource + "/metricDescriptors/" + metricType;
}
/**
* Returns now in RFC3339 format. This is the end-time of the window
* this example views the TimeSeries in.
*/
private static String getNow() {
DateTime dt = new DateTime();
return rfc3339.format(dt.toDate());
}
/**
* Returns 5 minutes before now to create a window to view timeseries in.
*/
private static String getStartTime() {
DateTime dt = new DateTime().minusMinutes(5);
return rfc3339.format(dt.toDate());
}
/**
* Dummy method to get an arbitrary data point.
*/
private long getRandomPoint() {
long value = new Random().nextInt(bound);
System.out.println("Returning value " + value);
return value;
}
/**
* This method creates a custom metric with arbitrary names, description,
* and units.
* <p/>
* <p>Package-private to be accessible to tests.
*/
MetricDescriptor createCustomMetric() throws IOException {
MetricDescriptor metricDescriptor = new MetricDescriptor();
metricDescriptor.setName(metricName);
metricDescriptor.setType(metricType);
LabelDescriptor labelDescriptor = new LabelDescriptor();
labelDescriptor.setKey("environment");
labelDescriptor.setValueType("STRING");
labelDescriptor.setDescription("An arbitrary measurement.");
labelDescriptor.setDescription("Custom Metric");
List<LabelDescriptor> labelDescriptorList = new ArrayList<LabelDescriptor>();
labelDescriptorList.add(labelDescriptor);
metricDescriptor.setLabels(labelDescriptorList);
metricDescriptor.setMetricKind(METRIC_KIND);
metricDescriptor.setValueType("INT64");
// Fake custom metric with unit 'items'
metricDescriptor.setUnit("items");
MetricDescriptor descriptorResponse = this.monitoringService.projects()
.metricDescriptors()
.create(projectResource, metricDescriptor)
.execute();
System.out.println("create response" + descriptorResponse.toPrettyString());
return descriptorResponse;
}
/**
* Retrieve the custom metric created by createCustomMetric.
* <p/>
* <p>It can sometimes take a few moments before a new custom metric is ready to have
* TimeSeries written to it, so this method is used
* to check when it is ready.
*/
public MetricDescriptor getCustomMetric() throws IOException {
Monitoring.Projects.MetricDescriptors.List metrics =
monitoringService.projects().metricDescriptors()
.list(projectResource);
metrics.setFilter("metric.type=\"" + metricType + "\"");
ListMetricDescriptorsResponse response = metrics.execute();
List<MetricDescriptor> descriptors = response.getMetricDescriptors();
System.out.println("reading custom metric");
if (descriptors == null || descriptors.isEmpty()) {
System.out.println("No metric descriptor matching that label found.");
return null;
} else {
System.out.println(descriptors.get(0).toPrettyString());
return descriptors.get(0);
}
}
/**
* Writes a timeseries value for the custom metric created.
* <p>The value written is a random integer value for demonstration purposes. It's a GAUGE metric,
* which means its a measure of a value at a point in time, and thus the start
* window and end window times are the same.
*
* @throws IOException On network error.
*/
void writeCustomMetricTimeseriesValue() throws IOException {
Map<String, String> metricLabel = ImmutableMap.of(
"environment", "STAGING"
);
Map<String, String> resourceLabel = ImmutableMap.of(
"instance_id", "test-instance",
"zone", "us-central1-f"
);
CreateTimeSeriesRequest timeSeriesRequest = new CreateTimeSeriesRequest();
TimeSeries timeSeries = new TimeSeries();
Metric metric = new Metric();
metric.setType(metricType);
metric.setLabels(metricLabel);
timeSeries.setMetric(metric);
MonitoredResource monitoredResource = new MonitoredResource();
monitoredResource.setType("gce_instance");
monitoredResource.setLabels(resourceLabel);
timeSeries.setResource(monitoredResource);
timeSeries.setMetricKind(METRIC_KIND);
timeSeries.setValueType("INT64");
Point point = new Point();
TimeInterval ti = new TimeInterval();
String now = getNow();
ti.setStartTime(now);
ti.setEndTime(now);
point.setInterval(ti);
point.setValue(new TypedValue().setInt64Value(getRandomPoint()));
timeSeries.setPoints(Lists.<Point>newArrayList(point));
timeSeriesRequest.setTimeSeries(Lists.<TimeSeries>newArrayList(timeSeries));
monitoringService.projects().timeSeries().create(projectResource, timeSeriesRequest).execute();
}
/**
* Read the TimeSeries value for the custom metrics created within a window of the
* last 5 minutes.
*
* @return The TimeSeries response object reflecting the Timeseries of the custom metrics
* for the last 5 minutes.
* @throws IOException On network error.
*/
ListTimeSeriesResponse readTimeseriesValue() throws IOException {
ListTimeSeriesResponse response =
monitoringService.projects().timeSeries().list(projectResource)
.setFilter("metric.type=\"" + metricType + "\"")
.setPageSize(3)
.setIntervalStartTime(getStartTime())
.setIntervalEndTime(getNow())
.execute();
return response;
}
/**
* Use the Google Cloud Monitoring API to create a custom metric.
*
* @param args The first arg should be the project name you'd like to inspect.
* @throws Exception if something goes wrong.
*/
public static void main(final String[] args) throws Exception {
if (args.length != 1) {
System.err.println(String.format("Usage: %s <project-name>",
CreateCustomMetric.class.getSimpleName()));
return;
}
String project = args[0];
String projectResource = "projects/" + project;
// Create an authorized API client
Monitoring monitoringService = ListResources.authenticate();
CreateCustomMetric metricWriter =
new CreateCustomMetric(monitoringService, projectResource);
MetricDescriptor metricDescriptor = metricWriter.createCustomMetric();
System.out.println("listMetricDescriptors response");
System.out.println(metricDescriptor.toPrettyString());
// wait until custom metric can be read back
while (metricWriter.getCustomMetric() == null) {
Thread.sleep(2000);
}
metricWriter.writeCustomMetricTimeseriesValue();
Thread.sleep(3000);
ListTimeSeriesResponse response = metricWriter.readTimeseriesValue();
System.out.println("reading custom metric timeseries");
System.out.println(response.toPrettyString());
}
}
| |
/*
* Copyright 2000-2015 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.openapi.components.impl.stores;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.StateSplitter;
import com.intellij.openapi.components.StateStorageException;
import com.intellij.openapi.components.TrackingPathMacroSubstitutor;
import com.intellij.openapi.components.store.ReadOnlyModificationException;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.tracker.VirtualFileTracker;
import com.intellij.util.PathUtil;
import com.intellij.util.SystemProperties;
import com.intellij.util.containers.SmartHashSet;
import gnu.trove.TObjectObjectProcedure;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
public class DirectoryBasedStorage extends StateStorageBase<DirectoryStorageData> {
private final File myDir;
private volatile VirtualFile myVirtualFile;
@SuppressWarnings("deprecation")
private final StateSplitter mySplitter;
public DirectoryBasedStorage(@Nullable TrackingPathMacroSubstitutor pathMacroSubstitutor,
@NotNull File dir,
@SuppressWarnings("deprecation") @NotNull StateSplitter splitter,
@NotNull Disposable parentDisposable,
@Nullable final Listener listener) {
super(pathMacroSubstitutor);
myDir = dir;
mySplitter = splitter;
VirtualFileTracker virtualFileTracker = ServiceManager.getService(VirtualFileTracker.class);
if (virtualFileTracker != null && listener != null) {
virtualFileTracker.addTracker(VfsUtilCore.pathToUrl(PathUtil.toSystemIndependentName(myDir.getPath())), new VirtualFileAdapter() {
@Override
public void contentsChanged(@NotNull VirtualFileEvent event) {
notifyIfNeed(event);
}
@Override
public void fileDeleted(@NotNull VirtualFileEvent event) {
if (event.getFile().equals(myVirtualFile)) {
myVirtualFile = null;
}
notifyIfNeed(event);
}
@Override
public void fileCreated(@NotNull VirtualFileEvent event) {
notifyIfNeed(event);
}
private void notifyIfNeed(@NotNull VirtualFileEvent event) {
// storage directory will be removed if the only child was removed
if (event.getFile().isDirectory() || DirectoryStorageData.isStorageFile(event.getFile())) {
listener.storageFileChanged(event, DirectoryBasedStorage.this);
}
}
}, false, parentDisposable);
}
}
@Override
public void analyzeExternalChangesAndUpdateIfNeed(@NotNull Collection<VirtualFile> changedFiles, @NotNull Set<String> componentNames) {
// todo reload only changed file, compute diff
DirectoryStorageData oldData = myStorageData;
DirectoryStorageData newData = loadData();
myStorageData = newData;
if (oldData == null) {
componentNames.addAll(newData.getComponentNames());
}
else {
componentNames.addAll(oldData.getComponentNames());
componentNames.addAll(newData.getComponentNames());
}
}
@Nullable
@Override
protected Element getStateAndArchive(@NotNull DirectoryStorageData storageData, Object component, @NotNull String componentName) {
return storageData.getCompositeStateAndArchive(componentName, mySplitter);
}
@NotNull
@Override
protected DirectoryStorageData loadData() {
DirectoryStorageData storageData = new DirectoryStorageData();
storageData.loadFrom(getVirtualFile(), myPathMacroSubstitutor);
return storageData;
}
@Nullable
private VirtualFile getVirtualFile() {
VirtualFile virtualFile = myVirtualFile;
if (virtualFile == null) {
myVirtualFile = virtualFile = LocalFileSystem.getInstance().findFileByIoFile(myDir);
}
return virtualFile;
}
@Override
@Nullable
public ExternalizationSession startExternalization() {
return checkIsSavingDisabled() ? null : new MySaveSession(this, getStorageData());
}
@NotNull
public static VirtualFile createDir(@NotNull File ioDir, @NotNull Object requestor) throws IOException {
//noinspection ResultOfMethodCallIgnored
ioDir.mkdirs();
String parentFile = ioDir.getParent();
VirtualFile parentVirtualFile = parentFile == null ? null : LocalFileSystem.getInstance().refreshAndFindFileByPath(parentFile.replace(File.separatorChar, '/'));
if (parentVirtualFile == null) {
throw new StateStorageException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile));
}
return getFile(ioDir.getName(), parentVirtualFile, requestor);
}
@NotNull
public static VirtualFile getFile(@NotNull String fileName, @NotNull VirtualFile parent, @NotNull Object requestor) throws IOException {
VirtualFile file = parent.findChild(fileName);
if (file != null) {
return file;
}
AccessToken token = WriteAction.start();
try {
return parent.createChildData(requestor, fileName);
}
finally {
token.finish();
}
}
private static class MySaveSession extends SaveSessionBase {
private final DirectoryBasedStorage storage;
private final DirectoryStorageData originalStorageData;
private DirectoryStorageData copiedStorageData;
private final Set<String> dirtyFileNames = new SmartHashSet<String>();
private final Set<String> removedFileNames = new SmartHashSet<String>();
private MySaveSession(@NotNull DirectoryBasedStorage storage, @NotNull DirectoryStorageData storageData) {
this.storage = storage;
originalStorageData = storageData;
}
@Override
protected void setSerializedState(@NotNull Object component, @NotNull String componentName, @Nullable Element element) {
removedFileNames.addAll(originalStorageData.getFileNames(componentName));
if (JDOMUtil.isEmpty(element)) {
doSetState(componentName, null, null);
}
else {
for (Pair<Element, String> pair : storage.mySplitter.splitState(element)) {
removedFileNames.remove(pair.second);
doSetState(componentName, pair.second, pair.first);
}
if (!removedFileNames.isEmpty()) {
for (String fileName : removedFileNames) {
doSetState(componentName, fileName, null);
}
}
}
}
private void doSetState(@NotNull String componentName, @Nullable String fileName, @Nullable Element subState) {
if (copiedStorageData == null) {
copiedStorageData = DirectoryStorageData.setStateAndCloneIfNeed(componentName, fileName, subState, originalStorageData);
if (copiedStorageData != null && fileName != null) {
dirtyFileNames.add(fileName);
}
}
else if (copiedStorageData.setState(componentName, fileName, subState) != null && fileName != null) {
dirtyFileNames.add(fileName);
}
}
@Override
@Nullable
public SaveSession createSaveSession() {
return storage.checkIsSavingDisabled() || copiedStorageData == null ? null : this;
}
@Override
public void save() throws IOException {
VirtualFile dir = storage.getVirtualFile();
if (copiedStorageData.isEmpty()) {
if (dir != null && dir.exists()) {
StorageUtil.deleteFile(this, dir);
}
storage.myStorageData = copiedStorageData;
return;
}
if (dir == null || !dir.isValid()) {
dir = createDir(storage.myDir, this);
}
if (!dirtyFileNames.isEmpty()) {
saveStates(dir);
}
if (dir.exists() && !removedFileNames.isEmpty()) {
deleteFiles(dir);
}
storage.myVirtualFile = dir;
storage.myStorageData = copiedStorageData;
}
private void saveStates(@NotNull final VirtualFile dir) {
final Element storeElement = new Element(StorageData.COMPONENT);
for (final String componentName : copiedStorageData.getComponentNames()) {
copiedStorageData.processComponent(componentName, new TObjectObjectProcedure<String, Object>() {
@Override
public boolean execute(String fileName, Object state) {
if (!dirtyFileNames.contains(fileName)) {
return true;
}
Element element = copiedStorageData.stateToElement(fileName, state);
if (storage.myPathMacroSubstitutor != null) {
storage.myPathMacroSubstitutor.collapsePaths(element);
}
try {
storeElement.setAttribute(StorageData.NAME, componentName);
storeElement.addContent(element);
BufferExposingByteArrayOutputStream byteOut;
VirtualFile file = getFile(fileName, dir, MySaveSession.this);
if (file.exists()) {
byteOut = StorageUtil.writeToBytes(storeElement, StorageUtil.loadFile(file).second);
}
else {
byteOut = StorageUtil.writeToBytes(storeElement, SystemProperties.getLineSeparator());
}
StorageUtil.writeFile(null, MySaveSession.this, file, byteOut, null);
}
catch (IOException e) {
LOG.error(e);
}
finally {
element.detach();
}
return true;
}
});
}
}
private void deleteFiles(@NotNull VirtualFile dir) throws IOException {
AccessToken token = WriteAction.start();
try {
for (VirtualFile file : dir.getChildren()) {
if (removedFileNames.contains(file.getName())) {
try {
file.delete(this);
}
catch (FileNotFoundException e) {
throw new ReadOnlyModificationException(file, e, null);
}
}
}
}
finally {
token.finish();
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/services/campaign_asset_service.proto
package com.google.ads.googleads.v10.services;
/**
* <pre>
* Response message for a campaign asset mutate.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.services.MutateCampaignAssetsResponse}
*/
public final class MutateCampaignAssetsResponse extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v10.services.MutateCampaignAssetsResponse)
MutateCampaignAssetsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use MutateCampaignAssetsResponse.newBuilder() to construct.
private MutateCampaignAssetsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MutateCampaignAssetsResponse() {
results_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new MutateCampaignAssetsResponse();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private MutateCampaignAssetsResponse(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
com.google.rpc.Status.Builder subBuilder = null;
if (partialFailureError_ != null) {
subBuilder = partialFailureError_.toBuilder();
}
partialFailureError_ = input.readMessage(com.google.rpc.Status.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(partialFailureError_);
partialFailureError_ = subBuilder.buildPartial();
}
break;
}
case 18: {
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
results_ = new java.util.ArrayList<com.google.ads.googleads.v10.services.MutateCampaignAssetResult>();
mutable_bitField0_ |= 0x00000001;
}
results_.add(
input.readMessage(com.google.ads.googleads.v10.services.MutateCampaignAssetResult.parser(), extensionRegistry));
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
results_ = java.util.Collections.unmodifiableList(results_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.services.CampaignAssetServiceProto.internal_static_google_ads_googleads_v10_services_MutateCampaignAssetsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.services.CampaignAssetServiceProto.internal_static_google_ads_googleads_v10_services_MutateCampaignAssetsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse.class, com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse.Builder.class);
}
public static final int PARTIAL_FAILURE_ERROR_FIELD_NUMBER = 1;
private com.google.rpc.Status partialFailureError_;
/**
* <pre>
* Errors that pertain to operation failures in the partial failure mode.
* Returned only when partial_failure = true and all errors occur inside the
* operations. If any errors occur outside the operations (e.g. auth errors),
* we return an RPC level error.
* </pre>
*
* <code>.google.rpc.Status partial_failure_error = 1;</code>
* @return Whether the partialFailureError field is set.
*/
@java.lang.Override
public boolean hasPartialFailureError() {
return partialFailureError_ != null;
}
/**
* <pre>
* Errors that pertain to operation failures in the partial failure mode.
* Returned only when partial_failure = true and all errors occur inside the
* operations. If any errors occur outside the operations (e.g. auth errors),
* we return an RPC level error.
* </pre>
*
* <code>.google.rpc.Status partial_failure_error = 1;</code>
* @return The partialFailureError.
*/
@java.lang.Override
public com.google.rpc.Status getPartialFailureError() {
return partialFailureError_ == null ? com.google.rpc.Status.getDefaultInstance() : partialFailureError_;
}
/**
* <pre>
* Errors that pertain to operation failures in the partial failure mode.
* Returned only when partial_failure = true and all errors occur inside the
* operations. If any errors occur outside the operations (e.g. auth errors),
* we return an RPC level error.
* </pre>
*
* <code>.google.rpc.Status partial_failure_error = 1;</code>
*/
@java.lang.Override
public com.google.rpc.StatusOrBuilder getPartialFailureErrorOrBuilder() {
return getPartialFailureError();
}
public static final int RESULTS_FIELD_NUMBER = 2;
private java.util.List<com.google.ads.googleads.v10.services.MutateCampaignAssetResult> results_;
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
@java.lang.Override
public java.util.List<com.google.ads.googleads.v10.services.MutateCampaignAssetResult> getResultsList() {
return results_;
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.ads.googleads.v10.services.MutateCampaignAssetResultOrBuilder>
getResultsOrBuilderList() {
return results_;
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
@java.lang.Override
public int getResultsCount() {
return results_.size();
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.services.MutateCampaignAssetResult getResults(int index) {
return results_.get(index);
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.services.MutateCampaignAssetResultOrBuilder getResultsOrBuilder(
int index) {
return results_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (partialFailureError_ != null) {
output.writeMessage(1, getPartialFailureError());
}
for (int i = 0; i < results_.size(); i++) {
output.writeMessage(2, results_.get(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (partialFailureError_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, getPartialFailureError());
}
for (int i = 0; i < results_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, results_.get(i));
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse)) {
return super.equals(obj);
}
com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse other = (com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse) obj;
if (hasPartialFailureError() != other.hasPartialFailureError()) return false;
if (hasPartialFailureError()) {
if (!getPartialFailureError()
.equals(other.getPartialFailureError())) return false;
}
if (!getResultsList()
.equals(other.getResultsList())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasPartialFailureError()) {
hash = (37 * hash) + PARTIAL_FAILURE_ERROR_FIELD_NUMBER;
hash = (53 * hash) + getPartialFailureError().hashCode();
}
if (getResultsCount() > 0) {
hash = (37 * hash) + RESULTS_FIELD_NUMBER;
hash = (53 * hash) + getResultsList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Response message for a campaign asset mutate.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.services.MutateCampaignAssetsResponse}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.services.MutateCampaignAssetsResponse)
com.google.ads.googleads.v10.services.MutateCampaignAssetsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.services.CampaignAssetServiceProto.internal_static_google_ads_googleads_v10_services_MutateCampaignAssetsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.services.CampaignAssetServiceProto.internal_static_google_ads_googleads_v10_services_MutateCampaignAssetsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse.class, com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse.Builder.class);
}
// Construct using com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getResultsFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (partialFailureErrorBuilder_ == null) {
partialFailureError_ = null;
} else {
partialFailureError_ = null;
partialFailureErrorBuilder_ = null;
}
if (resultsBuilder_ == null) {
results_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
resultsBuilder_.clear();
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v10.services.CampaignAssetServiceProto.internal_static_google_ads_googleads_v10_services_MutateCampaignAssetsResponse_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse getDefaultInstanceForType() {
return com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse build() {
com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse buildPartial() {
com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse result = new com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse(this);
int from_bitField0_ = bitField0_;
if (partialFailureErrorBuilder_ == null) {
result.partialFailureError_ = partialFailureError_;
} else {
result.partialFailureError_ = partialFailureErrorBuilder_.build();
}
if (resultsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
results_ = java.util.Collections.unmodifiableList(results_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.results_ = results_;
} else {
result.results_ = resultsBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse) {
return mergeFrom((com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse other) {
if (other == com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse.getDefaultInstance()) return this;
if (other.hasPartialFailureError()) {
mergePartialFailureError(other.getPartialFailureError());
}
if (resultsBuilder_ == null) {
if (!other.results_.isEmpty()) {
if (results_.isEmpty()) {
results_ = other.results_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureResultsIsMutable();
results_.addAll(other.results_);
}
onChanged();
}
} else {
if (!other.results_.isEmpty()) {
if (resultsBuilder_.isEmpty()) {
resultsBuilder_.dispose();
resultsBuilder_ = null;
results_ = other.results_;
bitField0_ = (bitField0_ & ~0x00000001);
resultsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getResultsFieldBuilder() : null;
} else {
resultsBuilder_.addAllMessages(other.results_);
}
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private com.google.rpc.Status partialFailureError_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder> partialFailureErrorBuilder_;
/**
* <pre>
* Errors that pertain to operation failures in the partial failure mode.
* Returned only when partial_failure = true and all errors occur inside the
* operations. If any errors occur outside the operations (e.g. auth errors),
* we return an RPC level error.
* </pre>
*
* <code>.google.rpc.Status partial_failure_error = 1;</code>
* @return Whether the partialFailureError field is set.
*/
public boolean hasPartialFailureError() {
return partialFailureErrorBuilder_ != null || partialFailureError_ != null;
}
/**
* <pre>
* Errors that pertain to operation failures in the partial failure mode.
* Returned only when partial_failure = true and all errors occur inside the
* operations. If any errors occur outside the operations (e.g. auth errors),
* we return an RPC level error.
* </pre>
*
* <code>.google.rpc.Status partial_failure_error = 1;</code>
* @return The partialFailureError.
*/
public com.google.rpc.Status getPartialFailureError() {
if (partialFailureErrorBuilder_ == null) {
return partialFailureError_ == null ? com.google.rpc.Status.getDefaultInstance() : partialFailureError_;
} else {
return partialFailureErrorBuilder_.getMessage();
}
}
/**
* <pre>
* Errors that pertain to operation failures in the partial failure mode.
* Returned only when partial_failure = true and all errors occur inside the
* operations. If any errors occur outside the operations (e.g. auth errors),
* we return an RPC level error.
* </pre>
*
* <code>.google.rpc.Status partial_failure_error = 1;</code>
*/
public Builder setPartialFailureError(com.google.rpc.Status value) {
if (partialFailureErrorBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
partialFailureError_ = value;
onChanged();
} else {
partialFailureErrorBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Errors that pertain to operation failures in the partial failure mode.
* Returned only when partial_failure = true and all errors occur inside the
* operations. If any errors occur outside the operations (e.g. auth errors),
* we return an RPC level error.
* </pre>
*
* <code>.google.rpc.Status partial_failure_error = 1;</code>
*/
public Builder setPartialFailureError(
com.google.rpc.Status.Builder builderForValue) {
if (partialFailureErrorBuilder_ == null) {
partialFailureError_ = builderForValue.build();
onChanged();
} else {
partialFailureErrorBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Errors that pertain to operation failures in the partial failure mode.
* Returned only when partial_failure = true and all errors occur inside the
* operations. If any errors occur outside the operations (e.g. auth errors),
* we return an RPC level error.
* </pre>
*
* <code>.google.rpc.Status partial_failure_error = 1;</code>
*/
public Builder mergePartialFailureError(com.google.rpc.Status value) {
if (partialFailureErrorBuilder_ == null) {
if (partialFailureError_ != null) {
partialFailureError_ =
com.google.rpc.Status.newBuilder(partialFailureError_).mergeFrom(value).buildPartial();
} else {
partialFailureError_ = value;
}
onChanged();
} else {
partialFailureErrorBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Errors that pertain to operation failures in the partial failure mode.
* Returned only when partial_failure = true and all errors occur inside the
* operations. If any errors occur outside the operations (e.g. auth errors),
* we return an RPC level error.
* </pre>
*
* <code>.google.rpc.Status partial_failure_error = 1;</code>
*/
public Builder clearPartialFailureError() {
if (partialFailureErrorBuilder_ == null) {
partialFailureError_ = null;
onChanged();
} else {
partialFailureError_ = null;
partialFailureErrorBuilder_ = null;
}
return this;
}
/**
* <pre>
* Errors that pertain to operation failures in the partial failure mode.
* Returned only when partial_failure = true and all errors occur inside the
* operations. If any errors occur outside the operations (e.g. auth errors),
* we return an RPC level error.
* </pre>
*
* <code>.google.rpc.Status partial_failure_error = 1;</code>
*/
public com.google.rpc.Status.Builder getPartialFailureErrorBuilder() {
onChanged();
return getPartialFailureErrorFieldBuilder().getBuilder();
}
/**
* <pre>
* Errors that pertain to operation failures in the partial failure mode.
* Returned only when partial_failure = true and all errors occur inside the
* operations. If any errors occur outside the operations (e.g. auth errors),
* we return an RPC level error.
* </pre>
*
* <code>.google.rpc.Status partial_failure_error = 1;</code>
*/
public com.google.rpc.StatusOrBuilder getPartialFailureErrorOrBuilder() {
if (partialFailureErrorBuilder_ != null) {
return partialFailureErrorBuilder_.getMessageOrBuilder();
} else {
return partialFailureError_ == null ?
com.google.rpc.Status.getDefaultInstance() : partialFailureError_;
}
}
/**
* <pre>
* Errors that pertain to operation failures in the partial failure mode.
* Returned only when partial_failure = true and all errors occur inside the
* operations. If any errors occur outside the operations (e.g. auth errors),
* we return an RPC level error.
* </pre>
*
* <code>.google.rpc.Status partial_failure_error = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder>
getPartialFailureErrorFieldBuilder() {
if (partialFailureErrorBuilder_ == null) {
partialFailureErrorBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder>(
getPartialFailureError(),
getParentForChildren(),
isClean());
partialFailureError_ = null;
}
return partialFailureErrorBuilder_;
}
private java.util.List<com.google.ads.googleads.v10.services.MutateCampaignAssetResult> results_ =
java.util.Collections.emptyList();
private void ensureResultsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
results_ = new java.util.ArrayList<com.google.ads.googleads.v10.services.MutateCampaignAssetResult>(results_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v10.services.MutateCampaignAssetResult, com.google.ads.googleads.v10.services.MutateCampaignAssetResult.Builder, com.google.ads.googleads.v10.services.MutateCampaignAssetResultOrBuilder> resultsBuilder_;
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public java.util.List<com.google.ads.googleads.v10.services.MutateCampaignAssetResult> getResultsList() {
if (resultsBuilder_ == null) {
return java.util.Collections.unmodifiableList(results_);
} else {
return resultsBuilder_.getMessageList();
}
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public int getResultsCount() {
if (resultsBuilder_ == null) {
return results_.size();
} else {
return resultsBuilder_.getCount();
}
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public com.google.ads.googleads.v10.services.MutateCampaignAssetResult getResults(int index) {
if (resultsBuilder_ == null) {
return results_.get(index);
} else {
return resultsBuilder_.getMessage(index);
}
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public Builder setResults(
int index, com.google.ads.googleads.v10.services.MutateCampaignAssetResult value) {
if (resultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureResultsIsMutable();
results_.set(index, value);
onChanged();
} else {
resultsBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public Builder setResults(
int index, com.google.ads.googleads.v10.services.MutateCampaignAssetResult.Builder builderForValue) {
if (resultsBuilder_ == null) {
ensureResultsIsMutable();
results_.set(index, builderForValue.build());
onChanged();
} else {
resultsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public Builder addResults(com.google.ads.googleads.v10.services.MutateCampaignAssetResult value) {
if (resultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureResultsIsMutable();
results_.add(value);
onChanged();
} else {
resultsBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public Builder addResults(
int index, com.google.ads.googleads.v10.services.MutateCampaignAssetResult value) {
if (resultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureResultsIsMutable();
results_.add(index, value);
onChanged();
} else {
resultsBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public Builder addResults(
com.google.ads.googleads.v10.services.MutateCampaignAssetResult.Builder builderForValue) {
if (resultsBuilder_ == null) {
ensureResultsIsMutable();
results_.add(builderForValue.build());
onChanged();
} else {
resultsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public Builder addResults(
int index, com.google.ads.googleads.v10.services.MutateCampaignAssetResult.Builder builderForValue) {
if (resultsBuilder_ == null) {
ensureResultsIsMutable();
results_.add(index, builderForValue.build());
onChanged();
} else {
resultsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public Builder addAllResults(
java.lang.Iterable<? extends com.google.ads.googleads.v10.services.MutateCampaignAssetResult> values) {
if (resultsBuilder_ == null) {
ensureResultsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, results_);
onChanged();
} else {
resultsBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public Builder clearResults() {
if (resultsBuilder_ == null) {
results_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
resultsBuilder_.clear();
}
return this;
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public Builder removeResults(int index) {
if (resultsBuilder_ == null) {
ensureResultsIsMutable();
results_.remove(index);
onChanged();
} else {
resultsBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public com.google.ads.googleads.v10.services.MutateCampaignAssetResult.Builder getResultsBuilder(
int index) {
return getResultsFieldBuilder().getBuilder(index);
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public com.google.ads.googleads.v10.services.MutateCampaignAssetResultOrBuilder getResultsOrBuilder(
int index) {
if (resultsBuilder_ == null) {
return results_.get(index); } else {
return resultsBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public java.util.List<? extends com.google.ads.googleads.v10.services.MutateCampaignAssetResultOrBuilder>
getResultsOrBuilderList() {
if (resultsBuilder_ != null) {
return resultsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(results_);
}
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public com.google.ads.googleads.v10.services.MutateCampaignAssetResult.Builder addResultsBuilder() {
return getResultsFieldBuilder().addBuilder(
com.google.ads.googleads.v10.services.MutateCampaignAssetResult.getDefaultInstance());
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public com.google.ads.googleads.v10.services.MutateCampaignAssetResult.Builder addResultsBuilder(
int index) {
return getResultsFieldBuilder().addBuilder(
index, com.google.ads.googleads.v10.services.MutateCampaignAssetResult.getDefaultInstance());
}
/**
* <pre>
* All results for the mutate.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.MutateCampaignAssetResult results = 2;</code>
*/
public java.util.List<com.google.ads.googleads.v10.services.MutateCampaignAssetResult.Builder>
getResultsBuilderList() {
return getResultsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v10.services.MutateCampaignAssetResult, com.google.ads.googleads.v10.services.MutateCampaignAssetResult.Builder, com.google.ads.googleads.v10.services.MutateCampaignAssetResultOrBuilder>
getResultsFieldBuilder() {
if (resultsBuilder_ == null) {
resultsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v10.services.MutateCampaignAssetResult, com.google.ads.googleads.v10.services.MutateCampaignAssetResult.Builder, com.google.ads.googleads.v10.services.MutateCampaignAssetResultOrBuilder>(
results_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
results_ = null;
}
return resultsBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v10.services.MutateCampaignAssetsResponse)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v10.services.MutateCampaignAssetsResponse)
private static final com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse();
}
public static com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MutateCampaignAssetsResponse>
PARSER = new com.google.protobuf.AbstractParser<MutateCampaignAssetsResponse>() {
@java.lang.Override
public MutateCampaignAssetsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new MutateCampaignAssetsResponse(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<MutateCampaignAssetsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<MutateCampaignAssetsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.MutateCampaignAssetsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.part;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.workspace.util.WorkspaceSynchronizer;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.KeyHandler;
import org.eclipse.gef.KeyStroke;
import org.eclipse.gef.internal.ui.palette.editparts.DrawerEditPart;
import org.eclipse.gef.internal.ui.palette.editparts.ToolEntryEditPart;
import org.eclipse.gef.palette.PaletteContainer;
import org.eclipse.gef.palette.PaletteDrawer;
import org.eclipse.gef.palette.PaletteRoot;
import org.eclipse.gef.palette.ToolEntry;
import org.eclipse.gef.ui.palette.PaletteViewer;
import org.eclipse.gmf.runtime.common.ui.services.marker.MarkerNavigationService;
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
import org.eclipse.gmf.runtime.diagram.ui.actions.ActionIds;
import org.eclipse.gmf.runtime.diagram.ui.internal.parts.DiagramGraphicalViewerKeyHandler;
import org.eclipse.gmf.runtime.diagram.ui.internal.parts.DirectEditKeyHandler;
import org.eclipse.gmf.runtime.diagram.ui.internal.services.palette.PaletteToolEntry;
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
import org.eclipse.gmf.runtime.diagram.ui.resources.editor.document.IDiagramDocument;
import org.eclipse.gmf.runtime.diagram.ui.resources.editor.document.IDocument;
import org.eclipse.gmf.runtime.diagram.ui.resources.editor.document.IDocumentProvider;
import org.eclipse.gmf.runtime.diagram.ui.resources.editor.parts.DiagramDocumentEditor;
import org.eclipse.gmf.runtime.gef.ui.palette.customize.PaletteDrawerState;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.impl.NodeImpl;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorMatchingStrategy;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.ide.IGotoMarker;
import org.eclipse.ui.navigator.resources.ProjectExplorer;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.ShowInContext;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.extensions.CustomPaletteToolTransferDropTargetListener;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.navigator.EsbNavigatorItem;
/**
* @generated
*/
public class EsbDiagramEditor extends DiagramDocumentEditor implements IGotoMarker {
private EsbMultiPageEditor esbEditor;
/**
* @generated
*/
public static final String ID = "org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbDiagramEditorID"; //$NON-NLS-1$
/**
* @generated
*/
public static final String CONTEXT_ID = "org.wso2.developerstudio.eclipse.gmf.esb.diagram.ui.diagramContext"; //$NON-NLS-1$
/**
* @generated
*/
public EsbDiagramEditor() {
super(true);
}
/**
* @generated NOT
*/
public EsbDiagramEditor(EsbMultiPageEditor esbEditor) {
super(true);
this.esbEditor = esbEditor;
}
/**
* @generated
*/
protected String getContextID() {
return CONTEXT_ID;
}
/**
* @generated
*/
protected PaletteRoot createPaletteRoot(PaletteRoot existingPaletteRoot) {
PaletteRoot root = super.createPaletteRoot(existingPaletteRoot);
new EsbPaletteFactory().fillPalette(root);
return root;
}
/**
* @generated
*/
protected PreferencesHint getPreferencesHint() {
return EsbDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT;
}
/**
* @generated
*/
public String getContributorId() {
return EsbDiagramEditorPlugin.ID;
}
/**
* @generated
*/
@SuppressWarnings("rawtypes")
public Object getAdapter(Class type) {
if (type == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { ProjectExplorer.VIEW_ID };
}
};
}
return super.getAdapter(type);
}
/**
* @generated
*/
protected IDocumentProvider getDocumentProvider(IEditorInput input) {
if (input instanceof IFileEditorInput || input instanceof URIEditorInput) {
return EsbDiagramEditorPlugin.getInstance().getDocumentProvider();
}
return super.getDocumentProvider(input);
}
/**
* @generated NOT
*/
public TransactionalEditingDomain getEditingDomain() {
IDocument document = null;
if (getDocumentProvider() != null) {
document = getEditorInput() != null ? getDocumentProvider().getDocument(
getEditorInput()) : null;
} else {
document = getEditorInput() != null ? getDocumentProvider(getEditorInput())
.getDocument(getEditorInput()) : null;
}
if (document instanceof IDiagramDocument) {
return ((IDiagramDocument) document).getEditingDomain();
}
return super.getEditingDomain();
}
/**
* @generated
*/
protected void setDocumentProvider(IEditorInput input) {
if (input instanceof IFileEditorInput || input instanceof URIEditorInput) {
setDocumentProvider(EsbDiagramEditorPlugin.getInstance().getDocumentProvider());
} else {
super.setDocumentProvider(input);
}
}
/**
* @generated
*/
public void gotoMarker(IMarker marker) {
MarkerNavigationService.getInstance().gotoMarker(this, marker);
}
/**
* @generated
*/
public boolean isSaveAsAllowed() {
return true;
}
/**
* @generated
*/
public void doSaveAs() {
performSaveAs(new NullProgressMonitor());
}
/**
* @generated
*/
protected void performSaveAs(IProgressMonitor progressMonitor) {
Shell shell = getSite().getShell();
IEditorInput input = getEditorInput();
SaveAsDialog dialog = new SaveAsDialog(shell);
IFile original = input instanceof IFileEditorInput ? ((IFileEditorInput) input).getFile()
: null;
if (original != null) {
dialog.setOriginalFile(original);
}
dialog.create();
IDocumentProvider provider = getDocumentProvider();
if (provider == null) {
// editor has been programmatically closed while the dialog was open
return;
}
if (provider.isDeleted(input) && original != null) {
String message = NLS.bind(Messages.EsbDiagramEditor_SavingDeletedFile,
original.getName());
dialog.setErrorMessage(null);
dialog.setMessage(message, IMessageProvider.WARNING);
}
if (dialog.open() == Window.CANCEL) {
if (progressMonitor != null) {
progressMonitor.setCanceled(true);
}
return;
}
IPath filePath = dialog.getResult();
if (filePath == null) {
if (progressMonitor != null) {
progressMonitor.setCanceled(true);
}
return;
}
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IFile file = workspaceRoot.getFile(filePath);
final IEditorInput newInput = new FileEditorInput(file);
// Check if the editor is already open
IEditorMatchingStrategy matchingStrategy = getEditorDescriptor()
.getEditorMatchingStrategy();
IEditorReference[] editorRefs = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getEditorReferences();
for (int i = 0; i < editorRefs.length; i++) {
if (matchingStrategy.matches(editorRefs[i], newInput)) {
MessageDialog.openWarning(shell, Messages.EsbDiagramEditor_SaveAsErrorTitle,
Messages.EsbDiagramEditor_SaveAsErrorMessage);
return;
}
}
boolean success = false;
try {
provider.aboutToChange(newInput);
getDocumentProvider(newInput).saveDocument(progressMonitor, newInput,
getDocumentProvider().getDocument(getEditorInput()), true);
success = true;
} catch (CoreException x) {
IStatus status = x.getStatus();
if (status == null || status.getSeverity() != IStatus.CANCEL) {
ErrorDialog.openError(shell, Messages.EsbDiagramEditor_SaveErrorTitle,
Messages.EsbDiagramEditor_SaveErrorMessage, x.getStatus());
}
} finally {
provider.changed(newInput);
if (success) {
setInput(newInput);
}
}
if (progressMonitor != null) {
progressMonitor.setCanceled(!success);
}
}
/**
* @generated
*/
public ShowInContext getShowInContext() {
return new ShowInContext(getEditorInput(), getNavigatorSelection());
}
/**
* @generated
*/
private ISelection getNavigatorSelection() {
IDiagramDocument document = getDiagramDocument();
if (document == null) {
return StructuredSelection.EMPTY;
}
Diagram diagram = document.getDiagram();
if (diagram == null || diagram.eResource() == null) {
return StructuredSelection.EMPTY;
}
IFile file = WorkspaceSynchronizer.getFile(diagram.eResource());
if (file != null) {
EsbNavigatorItem item = new EsbNavigatorItem(diagram, file, false);
return new StructuredSelection(item);
}
return StructuredSelection.EMPTY;
}
/**
* @generated NOT
*/
protected void configureGraphicalViewer() {
super.configureGraphicalViewer();
IDiagramGraphicalViewer viewer = getDiagramGraphicalViewer();
KeyHandler viewerKeyHandler = new CustomDiagramGraphicalViewerKeyHandler(this, viewer);
KeyHandler parentHandler = getKeyHandler();
// CTRL + '=' disable zoom in
parentHandler.remove(KeyStroke.getPressed('=', 0x3d, SWT.CTRL));
// CTRL + '-' * disable zoom out
parentHandler.remove(KeyStroke.getPressed('-', 0x2d, SWT.CTRL));
viewerKeyHandler.setParent(getKeyHandler());
viewer.setKeyHandler(new DirectEditKeyHandler(viewer).setParent(viewerKeyHandler));
// Define key handler for palette viewer.
PaletteViewer paletteViewer = getPaletteViewerProvider().getEditDomain().getPaletteViewer();
KeyHandler paletteViewerKeyHandler = new CustomPaletteViewerKeyHandler(paletteViewer);
paletteViewer.setKeyHandler(paletteViewerKeyHandler);
//This enables the property view to be informed of selection changes in our graphical view,
//when our view is the active workbench part.
esbEditor.getSite().setSelectionProvider(viewer);
DiagramEditorContextMenuProvider provider = new DiagramEditorContextMenuProvider(this,
getDiagramGraphicalViewer());
getDiagramGraphicalViewer().setContextMenu(provider);
getSite().registerContextMenu(ActionIds.DIAGRAM_EDITOR_CONTEXT_MENU, provider,
getDiagramGraphicalViewer());
getDiagramGraphicalViewer().addDropTargetListener(
new CustomPaletteToolTransferDropTargetListener(getGraphicalViewer()));
}
protected int getInitialDockLocation() {
return PositionConstants.WEST;
}
protected int getInitialPaletteSize() {
return 240;
}
public void focusToolBar() {
PaletteViewer paletteViewer = getPaletteViewerProvider().getEditDomain().getPaletteViewer();
DrawerEditPart mediatorsGroupEditpart = null;
//ToolEntryEditPart callMediatorToolEntryEditpart = null;
Boolean mediatorsGroupFound = false;
//Boolean callMediatorFound = false;
for (Iterator ite = paletteViewer.getEditPartRegistry().values().iterator(); ite.hasNext();) {
Object ep = ite.next();
if (ep instanceof DrawerEditPart && !mediatorsGroupFound) {
mediatorsGroupEditpart = (DrawerEditPart) ep;
if (mediatorsGroupEditpart.getModel() instanceof PaletteDrawer) {
PaletteDrawer paletteDrawer = (PaletteDrawer) mediatorsGroupEditpart.getModel();
if (paletteDrawer.getId().equals("createMediators2Group")) {
mediatorsGroupFound = true;
}
}
} /*else if (ep instanceof ToolEntryEditPart && !callMediatorFound) {
callMediatorToolEntryEditpart = (ToolEntryEditPart)ep;
ToolEntry paletteDrawer = (ToolEntry) callMediatorToolEntryEditpart.getModel();
//search for call mediator which is the first mediator listed under mediaotrs
if (paletteDrawer.getId().equals("createCallMediator45CreationTool")) {
callMediatorFound = true;
}
}*/
}
if (mediatorsGroupFound) { // we only need to enable this shortcut for mediators group
if (!mediatorsGroupEditpart.isExpanded()) {
mediatorsGroupEditpart.setExpanded(true);
}
paletteViewer.select(mediatorsGroupEditpart);
paletteViewer.setFocus(mediatorsGroupEditpart);
//paletteViewer.setActiveTool((ToolEntry)callMediatorToolEntryEditpart.getModel());
paletteViewer.getControl().forceFocus();
if (paletteViewer.getKeyHandler() instanceof CustomPaletteViewerKeyHandler) {
CustomPaletteViewerKeyHandler customKeyHandler = (CustomPaletteViewerKeyHandler) paletteViewer
.getKeyHandler();
customKeyHandler.resetSerchString();
}
}
}
}
| |
package org.opencb.hpg.bigdata.analysis.variant;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.MapFunction;
import org.apache.spark.mllib.linalg.Matrix;
import org.apache.spark.mllib.linalg.Vector;
import org.apache.spark.mllib.linalg.Vectors;
import org.apache.spark.mllib.linalg.distributed.RowMatrix;
import org.apache.spark.sql.*;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import org.junit.Test;
import org.opencb.biodata.models.core.pedigree.Pedigree;
import org.opencb.biodata.tools.variant.metadata.VariantMetadataManager;
import org.opencb.hpg.bigdata.core.lib.SparkConfCreator;
import org.opencb.hpg.bigdata.core.lib.VariantDataset;
import scala.Serializable;
import scala.Tuple2;
import scala.collection.Iterator;
import scala.collection.mutable.StringBuilder;
import scala.collection.mutable.WrappedArray;
import java.io.File;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.apache.spark.sql.functions.desc;
// $example on$
// $example off$
/**
* Created by jtarraga on 23/12/16.
*/
public class MLTest implements Serializable {
// SparkConf sparkConf;
// SparkSession sparkSession;
// VariantDataset vd;
// private void init() throws Exception {
// // it doesn't matter what we set to spark's home directory
// sparkConf = SparkConfCreator.getConf("AlignmentDatasetTest", "local", 1, true, "");
// System.out.println("sparkConf = " + sparkConf.toDebugString());
// sparkSession = new SparkSession(new SparkContext(sparkConf));
//
// }
// @Test
public void streaming() throws Exception {
// it doesn't matter what we set to spark's home directory
SparkConf sparkConf = SparkConfCreator.getConf("AlignmentDatasetTest", "local", 1, true, "");
System.out.println("sparkConf = " + sparkConf.toDebugString());
SparkSession sparkSession = new SparkSession(new SparkContext(sparkConf));
VariantDataset vd = new VariantDataset(sparkSession);
// Path inputPath = Paths.get("/tmp/test.vcf.avro");
// Path inputPath = Paths.get("/media/data100/jtarraga/data/spark/100.variants.avro");
// Path inputPath = Paths.get(getClass().getResource("/100.variants.avro").toURI());
Path inputPath = Paths.get("/home/jtarraga/appl/hpg-bigdata/hpg-bigdata-core/src/test/resources/100.variants.avro");
System.out.println(">>>> opening file " + inputPath);
vd.load(inputPath.toString());
vd.createOrReplaceTempView("vcf");
Dataset<Row> rows = vd.sqlContext().sql("SELECT chromosome, start, end FROM vcf");
List<Row> rowList = rows.collectAsList();
List<Integer> list = rows.toJavaRDD().groupBy(new Function<Row, String>() {
@Override
public String call(Row row) throws Exception {
String key;
int start = row.getInt(1);
if (start < 16066000) {
key = "1";
} else if (start < 16067000) {
key = "2";
} else if (start < 16069000) {
key = "3";
} else {
key = "4";
}
return key;
}
}).map(new Function<Tuple2<String, Iterable<Row>>, Integer>() {
@Override
public Integer call(Tuple2<String, Iterable<Row>> keyValue) throws Exception {
System.out.println("key = " + keyValue._1());
int i = 0;
PrintWriter writer = new PrintWriter(new File("/tmp/key-" + keyValue._1()));
java.util.Iterator<Row> iterator = keyValue._2().iterator();
while (iterator.hasNext()) {
Row row = iterator.next();
System.out.println("\t\t" + row.get(0) + "\t" + row.get(1));
writer.println(row.get(0) + "\t" + row.get(1));
i++;
}
writer.close();
return i;
}
}).collect();
list.forEach(i -> System.out.println(i));
}
// @Test
public void streaming00() throws Exception {
// it doesn't matter what we set to spark's home directory
SparkConf sparkConf = SparkConfCreator.getConf("AlignmentDatasetTest", "local", 1, true, "");
System.out.println("sparkConf = " + sparkConf.toDebugString());
// JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, new Duration(1000));
// SparkSession sparkSession = new SparkSession(ssc.sparkContext().sc());
SparkSession sparkSession = new SparkSession(new SparkContext(sparkConf));
VariantDataset vd = new VariantDataset(sparkSession);
// Path inputPath = Paths.get("/tmp/test.vcf.avro");
// Path inputPath = Paths.get("/media/data100/jtarraga/data/spark/100.variants.avro");
// Path inputPath = Paths.get(getClass().getResource("/100.variants.avro").toURI());
Path inputPath = Paths.get("/home/jtarraga/appl/hpg-bigdata/hpg-bigdata-core/src/test/resources/100.variants.avro");
System.out.println(">>>> opening file " + inputPath);
vd.load(inputPath.toString());
vd.createOrReplaceTempView("vcf");
Dataset<Row> rows = vd.sqlContext().sql("SELECT chromosome, start, end FROM vcf");
List<Row> rowList = rows.collectAsList();
// rows.grou
// JavaPairRDD<String, Iterable<Row>> pairs = rows.toJavaRDD().groupBy(new );
//JavaPairRDD<Character, Iterable<String>>
List<Integer> list = rows.toJavaRDD().groupBy(new Function<Row, String>() {
@Override
public String call(Row row) throws Exception {
String key;
int start = row.getInt(1);
if (start < 16066000) {
key = "1";
} else if (start < 16067000) {
key = "2";
} else if (start < 16069000) {
key = "3";
} else {
key = "4";
}
return key;
}
}).map(new Function<Tuple2<String, Iterable<Row>>, Integer>() {
@Override
public Integer call(Tuple2<String, Iterable<Row>> keyValue) throws Exception {
System.out.println("key = " + keyValue._1());
int i = 0;
PrintWriter writer = new PrintWriter(new File("/tmp/key-" + keyValue._1()));
java.util.Iterator<Row> iterator = keyValue._2().iterator();
while (iterator.hasNext()) {
Row row = iterator.next();
System.out.println("\t\t" + row.get(0) + "\t" + row.get(1));
writer.println(row.get(0) + "\t" + row.get(1));
i++;
}
writer.close();
// keyValue._2().forEach(row -> {
// i++;
// System.out.println("\t\t" + row.get(0) + "\t" + row.get(1))
// });
return i;
}
}).collect();
list.forEach(i -> System.out.println(i));
/*
KeyValueGroupedDataset<String, Row> groups = rows.groupByKey(new MapFunction<Row, String>() {
@Override
public String call(Row row) throws Exception {
String key;
int start = row.getInt(1);
if (start < 16066000) {
key = "1";
} else if (start < 16067000) {
key = "2";
} else if (start < 16069000) {
key = "3";
} else {
key = "4";
}
return key;
}
}, Encoders.STRING());
// groups.keys().foreach(k -> System.out.println(k));
/*
groups.mapGroups(new Function2<String, Iterator<Row>, Object>() {
@Override
public Object apply(String s, Iterator<Row> rowIterator) {
return null;
}
/*
r educe(new ReduceFunction<Row>() {
@Override
public Row call(Row row, Row t1) throws Exception {
return null;
}
});
JavaPairRDD<Object, Iterable> keyValues = rows.toJavaRDD().groupBy(new Function<Row, Object>() {
@Override
public Object call(Row row) throws Exception {
return null;
}
});
JavaPairRDD<Object, Iterable> groupMap = productSaleMap.groupBy(new Function<ProductSale, Object>() {
@Override
public Object call(ProductSale productSale) throws Exception {
c.setTime(productSale.getSale().getPurchaseDate());
return c.get(Calendar.YEAR);
}
});
JavaPairRDD<Object, Long> totalSaleData = groupMap.mapValues(new Function<Iterable, Long>() {
@Override
public Long call(Iterable productSales) throws Exception {
Long sumData = 0L;
for (ProductSale productSale : productSales) {
sumData = sumData + (productSale.getProduct().getPrice() * productSale.getSale().getItemPurchased());
}
return sumData;
}
});
JavaPairRDD<String, Row> pairs = rows.toJavaRDD().mapToPair(new PairFunction<Row, String, Row>() {
@Override
public Tuple2<String, Row> call(Row row) throws Exception {
String key = "";
int start = row.getInt(1);
if (start < 16066000) {
key = "1";
} else if (start < 16067000) {
key = "2";
} else if(start < 16069000) {
key = "3";
} else {
key = "4";
}
return new Tuple2<>(key, row);
}
}).reduceByKey()reduce(new Function2<Tuple2<String, Row>, Tuple2<String, Row>, Tuple2<String, Row>>() {
@Override
public Tuple2<String, Row> call(Tuple2<String, Row> stringRowTuple2, Tuple2<String, Row> stringRowTuple22) throws Exception {
return null;
}
});
rows.toJavaRDD((
JavaPairRDD<String, Integer> rddX =
x.mapToPair(e -> new Tuple2<String, Integer>(e, 1));
// New JavaPairRDD
JavaPairRDD<String, Integer> rddY = rddX.reduceByKey(reduceSumFunc);
//Print tuples
for(Tuple2<String, Integer> element : rddY.collect()){
System.out.println("("+element._1+", "+element._2+")");
}
}
}
rows.toJavaRDD().key
rows.mreduce(new ReduceFunction<Row>() {
@Override
public Row call(Row row, Row t1) throws Exception {
return null;
}
});
/*
List<Dataset<Row>> buffer = new ArrayList<>();
//Dataset<Dataset<Row>> datasets;
//Dataset<Row> dataset;
//dataset.gr
Thread thread = new Thread() {
@Override public void run() {
System.out.println("------>>>>> Starting thread");
for (int i = 0; i < 5; i++) {
Dataset<Row> ds = vd.sqlContext().sql("SELECT chromosome, start, end FROM vcf");
//System.out.println("=================> Stream, dataset " + i + " with " + ds.count() + " rows");
System.out.println("------------------------>>>>> adding new dataset");
buffer.add(ds);
}
System.out.println("------>>>>> Ending thread");
}
};
thread.start();
while (thread.isAlive() || buffer.size() > 0) {
System.out.println("Still alive or buffer size " + buffer.size() + "...");
if (buffer.size() > 0) {
Dataset<Row> ds = buffer.remove(0);
List<Row> list = ds.collectAsList();
for (int i = 0; i < list.size(); i++) {
System.out.println(i + "\t" + list.get(i).get(0) + "\t" + list.get(i).get(1) + "\t" + list.get(i).get(2));
}
}
Thread.sleep(1000);
}
//StreamingExamples.setStreamingLogLevels();
// Create the context with a 1 second batch size
//SparkConf sparkConf = new SparkConf().setAppName("JavaCustomReceiver");
//JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, new Duration(1000));
// Create an input stream with the custom receiver on target ip:port and count the
// words in input stream of \n delimited text (eg. generated by 'nc')
// JavaReceiverInputDStream<Dataset<Row>> datasets = ssc.receiverStream(
// new JavaCustomReceiver(vd.sqlContext()));
// JavaDStream<String> words = datasets.map(new Function<Dataset<Row>, String>() {
// @Override
// public String call(Dataset dataset) throws Exception {
// return "toto";
// }
// });
// words.print();
/*
JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
@Override
public Iterator<String> call(String x) {
return Arrays.asList(SPACE.split(x)).iterator();
}
});
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(
new PairFunction<String, String, Integer>() {
@Override public Tuple2<String, Integer> call(String s) {
return new Tuple2<>(s, 1);
}
}).reduceByKey(new Function2<Integer, Integer, Integer>() {
@Override
public Integer call(Integer i1, Integer i2) {
return i1 + i2;
}
});
wordCounts.print();
*/// ssc.start();
// ssc.awaitTermination();
}
// @Test
public void map() throws Exception {
// it doesn't matter what we set to spark's home directory
SparkConf sparkConf = SparkConfCreator.getConf("AlignmentDatasetTest", "local", 1, true, "");
System.out.println("sparkConf = " + sparkConf.toDebugString());
SparkSession sparkSession = new SparkSession(new SparkContext(sparkConf));
VariantDataset vd;
vd = new VariantDataset(sparkSession);
Path inputPath = Paths.get("/tmp/test.vcf.avro");
// Path inputPath = Paths.get("/media/data100/jtarraga/data/spark/100.variants.avro");
//Path inputPath = Paths.get(getClass().getResource("/100.variants.avro").toURI());
System.out.println(">>>> opening file " + inputPath);
vd.load(inputPath.toString());
vd.createOrReplaceTempView("vcf");
//vd.printSchema();
String sql = "SELECT id, chromosome, start, end, study.studyId, study.samplesData FROM vcf LATERAL VIEW explode (studies) act as study ";
// String sql = "SELECT id, chromosome, start, end, study.studyId, study.samplesData FROM vcf LATERAL VIEW explode (studies) act as study "
// + "WHERE (study.studyId = 'hgva@hsapiens_grch37:1000GENOMES_phase_3')";
Dataset<Row> result = vd.sqlContext().sql(sql);
result.show();
SQLContext sqlContext = vd.sqlContext();
Dataset<String> namesDS = result.map(new MapFunction<Row, String>() {
@Override
public String call(Row r) throws Exception {
File file = new File("/tmp/pos-" + r.get(1) + "_" + r.get(2) + ".txt");
Dataset<Row> rows = sqlContext.sql("SELECT chromosome, start");
StringBuilder line = new StringBuilder();
rows.foreach(row -> {line.append(r.get(1)).append("\t").append(r.get(2)).append("\t")
.append(r.get(3)).append("\t").append(r.get(4));});
PrintWriter writer = new PrintWriter(file);
writer.println(line);
writer.close();
return file.toString();
}
}, Encoders.STRING());
namesDS.show(false);
// }
// Encoder<TestResult> testResultEncoder = Encoders.bean(TestResult.class);
// Dataset<TestResult> namesDS = result.map(new MapFunction<Row, TestResult>() {
// @Override
// public TestResult call(Row r) throws Exception {
// TestResult res = new TestResult();
// res.setpValue(0.05);
// res.setMethod("pearson");
// return res;
//// return r.get(0)
//// + " : " + ((WrappedArray) r.getList(5).get(0)).head()
//// + ", " + ((WrappedArray) r.getList(5).get(1)).head();
// }
// }, testResultEncoder);
// namesDS.show(false);
}
// @Test
public void getSamples() throws Exception {
// it doesn't matter what we set to spark's home directory
SparkConf sparkConf = SparkConfCreator.getConf("AlignmentDatasetTest", "local", 1, true, "");
System.out.println("sparkConf = " + sparkConf.toDebugString());
SparkSession sparkSession = new SparkSession(new SparkContext(sparkConf));
VariantDataset vd;
// init();
if (true) {
double[] pValues = new double[]{1.0, 0.03, 1.0, 0.38};
//RowFactory.create("a", Vectors.dense(pValues));
List<Row> rows = new ArrayList<>();
for (int i = 0; i < pValues.length; i++) {
rows.add(RowFactory.create(i, pValues[i]));
}
//Arrays.asList(RowFactory.create("a", org.apache.spark.mllib.linalg.Vectors.dense(1.0, 2.0, 3.0)), RowFactory.create("b", org.apache.spark.mllib.linalg.Vectors.dense(4.0, 5.0, 6.0)));
List<StructField> fields = new ArrayList<>(2);
// fields.add(DataTypes.createStructField("p", DataTypes.StringType, false));
fields.add(DataTypes.createStructField("id", DataTypes.IntegerType, false));
fields.add(DataTypes.createStructField("pValue", DataTypes.DoubleType, false));
StructType schema = DataTypes.createStructType(fields);
Dataset<Row> pValueRows = sparkSession.createDataFrame(rows, schema);
pValueRows.show();
Dataset<Row> sortedRows = pValueRows.sort(desc("pValue"));
//sortedRows.withColumn("newId", null);
sortedRows.show();
return;
}
vd = new VariantDataset(sparkSession);
Path inputPath = Paths.get("/tmp/test.vcf.avro");
// Path inputPath = Paths.get("/media/data100/jtarraga/data/spark/100.variants.avro");
//Path inputPath = Paths.get(getClass().getResource("/100.variants.avro").toURI());
System.out.println(">>>> opening file " + inputPath);
vd.load(inputPath.toString());
vd.createOrReplaceTempView("vcf");
//vd.printSchema();
String sql = "SELECT id, chromosome, start, end, study.studyId, study.samplesData FROM vcf LATERAL VIEW explode (studies) act as study ";
// String sql = "SELECT id, chromosome, start, end, study.studyId, study.samplesData FROM vcf LATERAL VIEW explode (studies) act as study "
// + "WHERE (study.studyId = 'hgva@hsapiens_grch37:1000GENOMES_phase_3')";
Dataset<Row> result = vd.sqlContext().sql(sql);
List list = result.head().getList(5);
System.out.println("list size = " + list.size());
System.out.println(((WrappedArray) list.get(0)).head());
VariantMetadataManager variantMetadataManager = new VariantMetadataManager();
variantMetadataManager.load(Paths.get(inputPath + ".meta.json"));
List<Pedigree> pedigrees = variantMetadataManager.getPedigree("testing-pedigree");
//ChiSquareAnalysis.run(result, pedigree);
// //result.show();
// Encoder<TestResult> testResultEncoder = Encoders.bean(TestResult.class);
// Dataset<TestResult> namesDS = result.map(new MapFunction<Row, TestResult>() {
// @Override
// public TestResult call(Row r) throws Exception {
// TestResult res = new TestResult();
// res.setpValue(0.05);
// res.setMethod("pearson");
// return res;
//// return r.get(0)
//// + " : " + ((WrappedArray) r.getList(5).get(0)).head()
//// + ", " + ((WrappedArray) r.getList(5).get(1)).head();
// }
// }, testResultEncoder);
// namesDS.show(false);
sparkSession.stop();
}
//@Test
public void logistic() throws Exception {
// init();
//
// StructType schema = new StructType(new StructField[]{
// new StructField("label", DataTypes.IntegerType, false, Metadata.empty()),
// new StructField("features", new VectorUDT(), false, Metadata.empty()),
// });
//
// List<Row> data = Arrays.asList(
// RowFactory.create(0, Vectors.dense(1.0, 2.0)),
// RowFactory.create(0, Vectors.dense(1.0, 1.0)),
// RowFactory.create(0, Vectors.dense(1.0, 0.0)),
// RowFactory.create(1, Vectors.dense(1.0, 1.0)),
// RowFactory.create(1, Vectors.dense(1.0, 0.0)),
// RowFactory.create(1, Vectors.dense(1.0, 0.0))
// );
// Dataset<Row> dataset = sparkSession.createDataFrame(data, schema);
// LogisticRegression logistic = new LogisticRegression();
// LogisticRegressionModel model = logistic.fit(dataset);
// // Print the coefficients and intercept for logistic regression
// System.out.println("Coefficients: "
// + model.coefficients() + " Intercept: " + model.intercept());
//
// sparkSession.stop();
}
//@Test
public void linear() throws Exception {
// init();
//
// StructType schema = new StructType(new StructField[]{
// new StructField("label", DataTypes.DoubleType, false, Metadata.empty()),
// new StructField("features", new VectorUDT(), false, Metadata.empty()),
// });
//
// List<Row> data = Arrays.asList(
// RowFactory.create(0.0, Vectors.dense(1.0, 2.0)),
// RowFactory.create(0.0, Vectors.dense(1.0, 1.0)),
// RowFactory.create(0.0, Vectors.dense(1.0, 0.0)),
// RowFactory.create(1.0, Vectors.dense(1.0, 1.0)),
// RowFactory.create(1.0, Vectors.dense(1.0, 0.0)),
// RowFactory.create(1.0, Vectors.dense(1.0, 0.0))
// );
// Dataset<Row> dataset = sparkSession.createDataFrame(data, schema);
// LinearRegression linear = new LinearRegression();
// LinearRegressionModel model = linear.fit(dataset);
// // Print the coefficients and intercept for logistic regression
// System.out.println("Coefficients: "
// + model.coefficients() + " Intercept: " + model.intercept());
//
// sparkSession.stop();
}
//@Test
public void chiSquare() throws Exception {
try {
// init();
//
// long count;
// vd.printSchema();
//
// vd.show(1);
// sparkSession.stop();
//
// //System.exit(0);
//
//
// Row row = vd.head();
// int index = row.fieldIndex("studies");
// System.out.println("studies index = " + index);
// System.out.println("class at index = " + row.get(index).getClass());
// List studies = row.getList(index);
// //List<StudyEntry> studies = row.getList(12);
// System.out.println(studies.get(0).getClass());
// GenericRowWithSchema study = (GenericRowWithSchema) studies.get(0);
// System.out.println("study, field 0 = " + study.getString(0));
// int sdIndex = study.fieldIndex("samplesData");
// System.out.println("samplesData index = " + sdIndex);
// List samplesData = study.getList(sdIndex);
// for (int i = 0; i < samplesData.size(); i++) {
// WrappedArray data = (WrappedArray) samplesData.get(i);
// System.out.println("sample " + i + ": " + data.head());
// }
// samplesData.forEach(sd -> System.out.println(((WrappedArray) ((List) sd).get(0)).head()));
// System.out.println("samplesData size = " + samplesData.size());
// WrappedArray data = (WrappedArray) samplesData.get(0);
// System.out.println("length od data = " + data.length());
//System.out.println("content = " + data.head());
//System.out.println(samplesData.get(0).getClass());
// System.out.println(studies.get(0).getSamplesData().get(0).get(0));
/*
for (int i = 0; i < 13; i++) {
try {
System.out.println(i + " ---> " + row.getString(i));
} catch (Exception e) {
System.out.println(i + " ---> ERROR : " + e.getMessage());
}
}
*/
// Create a contingency matrix ((1.0, 2.0), (3.0, 4.0))
// Matrix mat = Matrices.dense(2, 2, new double[]{1.0, 3.0, 2.0, 4.0});
// first column (case) : allele 1: 2.0, allele 2: 0.0
// second column (control): allele 1: 1.0, allele 2: 1.0
//Matrix mat = Matrices.dense(2, 2, new double[]{2.0, 0.0, 1.0, 1.0});
// conduct Pearson's independence test on the input contingency matrix
//ChiSqTestResult independenceTestResult = Statistics.chiSqTest(mat);
// summary of the test including the p-value, degrees of freedom...
//System.out.println(independenceTestResult + "\n");
// sparkSession.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
@Test
public void pca() {
SparkConf conf = new SparkConf().setAppName("JavaPCAExample").setMaster("local");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext jsql = new SQLContext(jsc);
// $example on$
JavaRDD<Row> data = jsc.parallelize(Arrays.asList(
RowFactory.create(Vectors.sparse(5, new int[]{1, 3}, new double[]{1.0, 7.0})),
RowFactory.create(Vectors.dense(2.0, 0.0, 3.0, 4.0, 5.0)),
RowFactory.create(Vectors.dense(4.0, 0.0, 0.0, 6.0, 7.0))
));
StructType schema = new StructType(new StructField[]{
new StructField("features", new VectorUDT(), false, Metadata.empty()),
});
Dataset<Row> df = jsql.createDataFrame(data, schema);
PCAModel pca = new PCA()
.setInputCol("features")
.setOutputCol("pcaFeatures")
.setK(3)
.fit(df);
DenseMatrix pc = pca.pc();
Dataset<Row> result = pca.transform(df).select("pcaFeatures");
df.show(false);
System.out.println(pc.toString());
result.show(false);
// $example off$
jsc.stop();
}
*/
//@Test
public void pca1() {
SparkConf conf = new SparkConf().setAppName("JavaPCAExample").setMaster("local");
JavaSparkContext jsc = new JavaSparkContext(conf);
List<Vector> data = Arrays.asList(
Vectors.sparse(5, new int[] {1, 3}, new double[] {1.0, 7.0}),
Vectors.dense(2.0, 0.0, 3.0, 4.0, 5.0),
Vectors.dense(4.0, 0.0, 0.0, 6.0, 7.0)
);
JavaRDD<Vector> rows = jsc.parallelize(data);
// Create a RowMatrix from JavaRDD<Vector>.
RowMatrix mat = new RowMatrix(rows.rdd());
// Compute the top 4 principal components.
// Principal components are stored in a local dense matrix.
Matrix pc = mat.computePrincipalComponents(4);
// Project the rows to the linear space spanned by the top 4 principal components.
RowMatrix projected = mat.multiply(pc);
System.out.println(pc.toString());
Iterator<Vector> it = projected.rows().toLocalIterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
| |
package xyz.truenight.utils;
/*
* Copyright (C) 2008 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.
*/
import android.os.SystemClock;
import android.util.Config;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import xyz.truenight.utils.log.Log;
/**
* Simple SNTP client class for retrieving network time.
* <p>
* Sample usage:
* <pre>SntpClient client = new SntpClient();
* if (client.requestTime("time.foo.com")) {
* long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
* }
* </pre>
*/
public class SntpClient {
private static final String TAG = "SntpClient";
private static final int REFERENCE_TIME_OFFSET = 16;
private static final int ORIGINATE_TIME_OFFSET = 24;
private static final int RECEIVE_TIME_OFFSET = 32;
private static final int TRANSMIT_TIME_OFFSET = 40;
private static final int NTP_PACKET_SIZE = 48;
private static final int NTP_PORT = 123;
private static final int NTP_MODE_CLIENT = 3;
private static final int NTP_VERSION = 3;
// Number of seconds between Jan 1, 1900 and Jan 1, 1970
// 70 years plus 17 leap days
private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
// system time computed from NTP server response
private long mNtpTime;
// value of SystemClock.elapsedRealtime() corresponding to mNtpTime
private long mNtpTimeReference;
// round trip time in milliseconds
private long mRoundTripTime;
/**
* Sends an SNTP request to the given host and processes the response.
*
* @param host host name of the server.
* @param timeout network timeout in milliseconds.
* @return true if the transaction was successful.
*/
public boolean requestTime(String host, int timeout) {
try {
DatagramSocket socket = new DatagramSocket();
socket.setSoTimeout(timeout);
InetAddress address = InetAddress.getByName(host);
byte[] buffer = new byte[NTP_PACKET_SIZE];
DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);
// set mode = 3 (client) and version = 3
// mode is in low 3 bits of first byte
// version is in bits 3-5 of first byte
buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
// get current time and write it to the request packet
long requestTime = System.currentTimeMillis();
long requestTicks = SystemClock.elapsedRealtime();
writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
socket.send(request);
// read the response
DatagramPacket response = new DatagramPacket(buffer, buffer.length);
socket.receive(response);
long responseTicks = SystemClock.elapsedRealtime();
long responseTime = requestTime + (responseTicks - requestTicks);
socket.close();
// extract the results
long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
// receiveTime = originateTime + transit + skew
// responseTime = transmitTime + transit - skew
// clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
// = ((originateTime + transit + skew - originateTime) +
// (transmitTime - (transmitTime + transit - skew)))/2
// = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
// = (transit + skew - transit + skew)/2
// = (2 * skew)/2 = skew
long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2;
// if (Config.LOGD) Log.d(TAG, "round trip: " + roundTripTime + " ms");
// if (Config.LOGD) Log.d(TAG, "clock offset: " + clockOffset + " ms");
// save our results - use the times on this side of the network latency
// (response rather than request time)
mNtpTime = responseTime + clockOffset;
mNtpTimeReference = responseTicks;
mRoundTripTime = roundTripTime;
} catch (Exception e) {
if (Config.LOGD) Log.d(TAG, "request time failed: " + e);
return false;
}
return true;
}
/**
* Returns the time computed from the NTP transaction.
*
* @return time value computed from NTP server response.
*/
public long getNtpTime() {
return mNtpTime;
}
/**
* Returns the reference clock value (value of SystemClock.elapsedRealtime())
* corresponding to the NTP time.
*
* @return reference clock corresponding to the NTP time.
*/
public long getNtpTimeReference() {
return mNtpTimeReference;
}
/**
* Returns the round trip time of the NTP transaction
*
* @return round trip time in milliseconds.
*/
public long getRoundTripTime() {
return mRoundTripTime;
}
/**
* Reads an unsigned 32 bit big endian number from the given offset in the buffer.
*/
private long read32(byte[] buffer, int offset) {
byte b0 = buffer[offset];
byte b1 = buffer[offset + 1];
byte b2 = buffer[offset + 2];
byte b3 = buffer[offset + 3];
// convert signed bytes to unsigned values
int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
return ((long) i0 << 24) + ((long) i1 << 16) + ((long) i2 << 8) + (long) i3;
}
/**
* Reads the NTP time stamp at the given offset in the buffer and returns
* it as a system time (milliseconds since January 1, 1970).
*/
private long readTimeStamp(byte[] buffer, int offset) {
long seconds = read32(buffer, offset);
long fraction = read32(buffer, offset + 4);
return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
}
/**
* Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
* at the given offset in the buffer.
*/
private void writeTimeStamp(byte[] buffer, int offset, long time) {
long seconds = time / 1000L;
long milliseconds = time - seconds * 1000L;
seconds += OFFSET_1900_TO_1970;
// write seconds in big endian format
buffer[offset++] = (byte) (seconds >> 24);
buffer[offset++] = (byte) (seconds >> 16);
buffer[offset++] = (byte) (seconds >> 8);
buffer[offset++] = (byte) (seconds >> 0);
long fraction = milliseconds * 0x100000000L / 1000L;
// write fraction in big endian format
buffer[offset++] = (byte) (fraction >> 24);
buffer[offset++] = (byte) (fraction >> 16);
buffer[offset++] = (byte) (fraction >> 8);
// low order bits should be random data
buffer[offset++] = (byte) (Math.random() * 255.0);
}
}
| |
/*
* 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.druid.query;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ListenableFuture;
import org.apache.druid.java.util.common.lifecycle.Lifecycle;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.internal.AssumptionViolatedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
/**
*/
@RunWith(Parameterized.class)
public class PrioritizedExecutorServiceTest
{
private PrioritizedExecutorService exec;
private CountDownLatch latch;
private CountDownLatch finishLatch;
private final boolean useFifo;
private final DruidProcessingConfig config;
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> constructorFeeder()
{
return ImmutableList.of(new Object[]{true}, new Object[]{false});
}
public PrioritizedExecutorServiceTest(final boolean useFifo)
{
this.useFifo = useFifo;
this.config = new DruidProcessingConfig()
{
@Override
public String getFormatString()
{
return null;
}
@Override
public boolean isFifo()
{
return useFifo;
}
};
}
@Before
public void setUp()
{
exec = PrioritizedExecutorService.create(
new Lifecycle(),
new DruidProcessingConfig()
{
@Override
public String getFormatString()
{
return "test";
}
@Override
public int getNumThreads()
{
return 1;
}
@Override
public boolean isFifo()
{
return useFifo;
}
}
);
latch = new CountDownLatch(1);
finishLatch = new CountDownLatch(3);
}
@After
public void tearDown()
{
exec.shutdownNow();
}
/**
* Submits a normal priority task to block the queue, followed by low, high, normal priority tasks.
* Tests to see that the high priority task is executed first, followed by the normal and low priority tasks.
*
* @throws Exception
*/
@Test
public void testSubmit() throws Exception
{
final ConcurrentLinkedQueue<Integer> order = new ConcurrentLinkedQueue<Integer>();
exec.submit(
new AbstractPrioritizedCallable<Void>(0)
{
@Override
public Void call() throws Exception
{
latch.await();
return null;
}
}
);
exec.submit(
new AbstractPrioritizedCallable<Void>(-1)
{
@Override
public Void call()
{
order.add(-1);
finishLatch.countDown();
return null;
}
}
);
exec.submit(
new AbstractPrioritizedCallable<Void>(0)
{
@Override
public Void call()
{
order.add(0);
finishLatch.countDown();
return null;
}
}
);
exec.submit(
new AbstractPrioritizedCallable<Void>(2)
{
@Override
public Void call()
{
order.add(2);
finishLatch.countDown();
return null;
}
}
);
latch.countDown();
finishLatch.await();
Assert.assertTrue(order.size() == 3);
List<Integer> expected = ImmutableList.of(2, 0, -1);
Assert.assertEquals(expected, ImmutableList.copyOf(order));
}
// Make sure entries are processed FIFO
@Test
public void testOrderedExecutionEqualPriorityRunnable() throws ExecutionException, InterruptedException
{
final int numTasks = 100;
final List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(numTasks);
final AtomicInteger hasRun = new AtomicInteger(0);
for (int i = 0; i < numTasks; ++i) {
futures.add(exec.submit(getCheckingPrioritizedRunnable(i, hasRun)));
}
latch.countDown();
checkFutures(futures);
}
@Test
public void testOrderedExecutionEqualPriorityCallable() throws ExecutionException, InterruptedException
{
final int numTasks = 1_000;
final List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(numTasks);
final AtomicInteger hasRun = new AtomicInteger(0);
for (int i = 0; i < numTasks; ++i) {
futures.add(exec.submit(getCheckingPrioritizedCallable(i, hasRun)));
}
latch.countDown();
checkFutures(futures);
}
@Test
public void testOrderedExecutionEqualPriorityMix() throws ExecutionException, InterruptedException
{
exec = new PrioritizedExecutorService(
exec.threadPoolExecutor, true, 0, config
);
final int numTasks = 1_000;
final List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(numTasks);
final AtomicInteger hasRun = new AtomicInteger(0);
final Random random = new Random(789401);
for (int i = 0; i < numTasks; ++i) {
switch (random.nextInt(4)) {
case 0:
futures.add(exec.submit(getCheckingPrioritizedCallable(i, hasRun)));
break;
case 1:
futures.add(exec.submit(getCheckingPrioritizedRunnable(i, hasRun)));
break;
case 2:
futures.add(exec.submit(getCheckingCallable(i, hasRun)));
break;
case 3:
futures.add(exec.submit(getCheckingRunnable(i, hasRun)));
break;
default:
Assert.fail("Bad random result");
}
}
latch.countDown();
checkFutures(futures);
}
@Test
public void testOrderedExecutionMultiplePriorityMix() throws ExecutionException, InterruptedException
{
final int DEFAULT = 0;
final int MIN = -1;
final int MAX = 1;
exec = new PrioritizedExecutorService(exec.threadPoolExecutor, true, DEFAULT, config);
final int numTasks = 999;
final int[] priorities = new int[]{MAX, DEFAULT, MIN};
final int tasksPerPriority = numTasks / priorities.length;
final int[] priorityOffsets = new int[]{0, tasksPerPriority, tasksPerPriority * 2};
final List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(numTasks);
final AtomicInteger hasRun = new AtomicInteger(0);
final Random random = new Random(789401);
for (int i = 0; i < numTasks; ++i) {
final int priorityBucket = i % priorities.length;
final int myPriority = priorities[priorityBucket];
final int priorityOffset = priorityOffsets[priorityBucket];
final int expectedPriorityOrder = i / priorities.length;
if (random.nextBoolean()) {
futures.add(
exec.submit(
getCheckingPrioritizedCallable(
priorityOffset + expectedPriorityOrder,
hasRun,
myPriority
)
)
);
} else {
futures.add(
exec.submit(
getCheckingPrioritizedRunnable(
priorityOffset + expectedPriorityOrder,
hasRun,
myPriority
)
)
);
}
}
latch.countDown();
checkFutures(futures);
}
private void checkFutures(Iterable<ListenableFuture<?>> futures) throws InterruptedException, ExecutionException
{
for (ListenableFuture<?> future : futures) {
try {
future.get();
}
catch (ExecutionException e) {
if (!(e.getCause() instanceof AssumptionViolatedException)) {
throw e;
}
}
}
}
private PrioritizedCallable<Boolean> getCheckingPrioritizedCallable(
final int myOrder,
final AtomicInteger hasRun
)
{
return getCheckingPrioritizedCallable(myOrder, hasRun, 0);
}
private PrioritizedCallable<Boolean> getCheckingPrioritizedCallable(
final int myOrder,
final AtomicInteger hasRun,
final int priority
)
{
final Callable<Boolean> delegate = getCheckingCallable(myOrder, hasRun);
return new AbstractPrioritizedCallable<Boolean>(priority)
{
@Override
public Boolean call() throws Exception
{
return delegate.call();
}
};
}
private Callable<Boolean> getCheckingCallable(
final int myOrder,
final AtomicInteger hasRun
)
{
final Runnable runnable = getCheckingRunnable(myOrder, hasRun);
return new Callable<Boolean>()
{
@Override
public Boolean call()
{
runnable.run();
return true;
}
};
}
private Runnable getCheckingRunnable(
final int myOrder,
final AtomicInteger hasRun
)
{
return new Runnable()
{
@Override
public void run()
{
try {
latch.await();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw Throwables.propagate(e);
}
if (useFifo) {
Assert.assertEquals(myOrder, hasRun.getAndIncrement());
} else {
Assume.assumeTrue(Integer.compare(myOrder, hasRun.getAndIncrement()) == 0);
}
}
};
}
private PrioritizedRunnable getCheckingPrioritizedRunnable(
final int myOrder,
final AtomicInteger hasRun
)
{
return getCheckingPrioritizedRunnable(myOrder, hasRun, 0);
}
private PrioritizedRunnable getCheckingPrioritizedRunnable(
final int myOrder,
final AtomicInteger hasRun,
final int priority
)
{
final Runnable delegate = getCheckingRunnable(myOrder, hasRun);
return new PrioritizedRunnable()
{
@Override
public int getPriority()
{
return priority;
}
@Override
public void run()
{
delegate.run();
}
};
}
}
| |
package com.thinkbiganalytics.ingest;
/*-
* #%L
* thinkbig-nifi-core-processors
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* 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.
* #L%
*/
import com.google.common.collect.ImmutableSet;
import com.klarna.hiverunner.HiveShell;
import com.klarna.hiverunner.StandaloneHiveRunner;
import com.klarna.hiverunner.annotations.HiveProperties;
import com.klarna.hiverunner.annotations.HiveRunnerSetup;
import com.klarna.hiverunner.annotations.HiveSQL;
import com.klarna.hiverunner.config.HiveRunnerConfig;
import com.thinkbiganalytics.util.ColumnSpec;
import com.thinkbiganalytics.util.TableRegisterConfiguration;
import com.thinkbiganalytics.util.TableType;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(StandaloneHiveRunner.class)
public class TableRegisterSupportTest {
/**
* Explicit test class configuration of the HiveRunner runtime. See {@link HiveRunnerConfig} for further details.
*/
@HiveRunnerSetup
public final HiveRunnerConfig CONFIG = new HiveRunnerConfig() {{
setHiveExecutionEngine("mr");
}};
final Connection connection = Mockito.mock(Connection.class);
/**
* Cater for all the parameters in the script that we want to test. Note that the "hadoop.tmp.dir" is one of the dirs defined by the test harness
*/
@HiveProperties
public Map<String, String> hiveProperties = MapUtils.putAll(new HashMap<String, String>(), new String[]{
"MY.HDFS.DIR", "${hadoop.tmp.dir}",
"my.schema", "bar",
});
/**
* Define the script files under test. The files will be loaded in the given order. <p/> The HiveRunner instantiate and inject the HiveShell
*/
@HiveSQL(files = {
"hive-test-support/create_table.sql"
}, encoding = "UTF-8")
private HiveShell hiveShell;
@Test
public void testShowLocation() {
List<Object[]> values = hiveShell.executeStatement("show table extended like foo");
for (Object[] o : values) {
String value = o[0].toString();
if (value.startsWith("location:")) {
System.out.println(value.substring(9));
}
}
}
@Test
public void testSplit() {
// Extract schema vs table
String[] schemaPart = "foo.bar".split("\\.");
assertEquals(schemaPart.length, 2);
String schema = schemaPart[0];
String targetTable = schemaPart[1];
assertNotNull(schema);
assertNotNull(targetTable);
}
@Test
public void testTableCreate() {
ColumnSpec[] specs = ColumnSpec.createFromString("id|bigint|my comment\nname|string\ncompany|string|some description\nzip|string\nphone|string\nemail|string\ncountry|string\nhired|date");
ColumnSpec[] parts = ColumnSpec.createFromString("year|int\ncountry|string");
TableRegisterSupport support = new TableRegisterSupport(connection);
TableType[] tableTypes = new TableType[]{TableType.FEED, TableType.INVALID, TableType.VALID, TableType.MASTER};
for (TableType tableType : tableTypes) {
String
ddl =
support.createDDL("bar", "employee", specs, parts, "ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'", "stored as orc", "tblproperties (\"orc.compress\"=\"SNAPPY\")",
tableType);
// Hack to make a legal file root
ddl = ddl.replace("LOCATION '", "LOCATION '${hiveconf:MY.HDFS.DIR}");
hiveShell.execute(ddl);
}
}
@Test
public void testTableCreateS3() {
ColumnSpec[] specs = ColumnSpec.createFromString("id|bigint|my comment\nname|string\ncompany|string|some description\nzip|string\nphone|string\nemail|string\ncountry|string\nhired|date");
ColumnSpec[] parts = ColumnSpec.createFromString("year|int\ncountry|string");
TableRegisterConfiguration conf = new TableRegisterConfiguration("s3a://testBucket/model.db/", "s3a://testBucket/model.db/", "s3a://testBucket/app/warehouse/");
TableRegisterSupport support = new TableRegisterSupport(connection, conf);
TableType[] tableTypes = new TableType[]{TableType.FEED, TableType.INVALID, TableType.VALID, TableType.MASTER};
for (TableType tableType : tableTypes) {
String ddl =
support.createDDL("bar", "employee", specs, parts, "ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'", "stored as orc", "tblproperties (\"orc.compress\"=\"SNAPPY\")",
tableType);
String location = StringUtils.substringBetween(ddl, "LOCATION '", "'");
if (tableType == TableType.MASTER) {
assertEquals("Master location does not match", "s3a://testBucket/app/warehouse/bar/employee", location);
} else {
assertEquals("Locations do not match", "s3a://testBucket/model.db/bar/employee/" + tableType.toString().toLowerCase(), location);
}
}
}
@Test
public void testRemovingColumns() {
ColumnSpec[] feedSpecs = ColumnSpec.createFromString("id|string|my comment|0|0|0|id\n"
+ "name|string||0|0|0|name\n"
+ "company|string|some description|0|0|0|change_company\n"
+ "zip|string||0|0|0|zip_code\n"
+ "phone|string\n"
+ "email|string\n"
+ "country|string\n"
+ "hired|string");
ColumnSpec[] targetSpecs = ColumnSpec.createFromString("id|bigint|my comment|0|0|0|id\n"
+ "name|string||0|0|0|name\n"
+ "change_company|string|some description|0|0|0|company\n"
+ "zip_code|string||0|0|0|zip\n"
+ "email|string\n"
+ "hired|date||0|0|0|hired");
ColumnSpec[] parts = ColumnSpec.createFromString("year|int\ncountry|string");
TableRegisterConfiguration conf = new TableRegisterConfiguration();
TableRegisterSupport support = new TableRegisterSupport(connection, conf);
ColumnSpec[] invalidColumnSpecs = support.adjustInvalidColumnSpec(feedSpecs,targetSpecs);
assertEquals(targetSpecs.length,invalidColumnSpecs.length);
Map<String,ColumnSpec> feedColumnSpecMap = Arrays.asList(feedSpecs).stream().collect(Collectors.toMap(ColumnSpec::getName, Function.identity()));
for(ColumnSpec invalid: invalidColumnSpecs)
{
if(StringUtils.isNotBlank(invalid.getOtherColumnName())) {
assertEquals(invalid.getDataType(), feedColumnSpecMap.get(invalid.getOtherColumnName()).getDataType());
}
}
TableType[] tableTypes = new TableType[]{TableType.FEED, TableType.INVALID, TableType.VALID, TableType.MASTER};
for (TableType tableType : tableTypes) {
ColumnSpec[] useColumnSpecs = targetSpecs;
if(tableType == TableType.INVALID){
useColumnSpecs = invalidColumnSpecs;
}
else if(tableType == TableType.FEED){
useColumnSpecs = feedSpecs;
}
String ddl = support.createDDL("source_table","target_table",useColumnSpecs,parts, "ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'","stored as orc","tblproperties (\"orc.compress\"=\"SNAPPY\")",tableType);
int i = 0;
}
}
/**
* Verify dropping a table.
*/
@Test
public void testDropTable() throws Exception {
// Mock SQL objects
final Statement statement = Mockito.mock(Statement.class);
Mockito.when(statement.execute(Mockito.anyString())).then(invocation -> {
final String sql = (String) invocation.getArguments()[0];
if (sql.equals("DROP TABLE IF EXISTS `invalid`")) {
throw new SQLException();
}
return true;
});
Mockito.when(connection.createStatement()).thenReturn(statement);
// Test dropping table with success
final TableRegisterSupport support = new TableRegisterSupport(connection);
Assert.assertTrue(support.dropTable("`feed`"));
Mockito.verify(statement).execute("DROP TABLE IF EXISTS `feed`");
// Test dropping table with exception
Assert.assertFalse(support.dropTable("`invalid`"));
}
/**
* Verify exception if the connection is null.
*/
@Test(expected = NullPointerException.class)
public void testDropTableWithNullConnection() {
new TableRegisterSupport(null).dropTable("invalid");
}
/**
* Verify dropping multiple tables.
*/
@Test
public void testDropTables() throws Exception {
// Mock SQL objects
final Statement statement = Mockito.mock(Statement.class);
Mockito.when(statement.execute(Mockito.anyString())).then(invocation -> {
final String sql = (String) invocation.getArguments()[0];
if (sql.startsWith("DROP TABLE IF EXISTS `invalid`")) {
throw new SQLException();
}
return true;
});
final Connection connection = Mockito.mock(Connection.class);
Mockito.when(connection.createStatement()).thenReturn(statement);
// Test dropping tables with success
TableRegisterSupport support = new TableRegisterSupport(connection);
Assert.assertTrue(support.dropTables("cat", "feed", EnumSet.of(TableType.MASTER, TableType.VALID, TableType.INVALID), ImmutableSet.of("backup.feed")));
Mockito.verify(statement).execute("DROP TABLE IF EXISTS `cat`.`feed`");
Mockito.verify(statement).execute("DROP TABLE IF EXISTS `cat`.`feed_valid`");
Mockito.verify(statement).execute("DROP TABLE IF EXISTS `cat`.`feed_invalid`");
Mockito.verify(statement).execute("DROP TABLE IF EXISTS backup.feed");
// Test dropping tables with exception
Assert.assertFalse(support.dropTables("invalid", "feed", EnumSet.allOf(TableType.class), ImmutableSet.of()));
Assert.assertFalse(support.dropTables("cat", "feed", ImmutableSet.of(), ImmutableSet.of("`invalid`")));
}
}
| |
/*
* Copyright 2000-2015 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.psi.impl.source.codeStyle;
import com.intellij.formatting.*;
import com.intellij.injected.editor.DocumentWindow;
import com.intellij.lang.*;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.*;
import com.intellij.psi.codeStyle.Indent;
import com.intellij.psi.codeStyle.autodetect.DetectedIndentOptionsNotificationProvider;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.impl.CheckUtil;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.impl.source.tree.RecursiveTreeElementWalkingVisitor;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.util.CharTable;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class CodeStyleManagerImpl extends CodeStyleManager {
private static final Logger LOG = Logger.getInstance(CodeStyleManagerImpl.class);
private static final ThreadLocal<ProcessingUnderProgressInfo> SEQUENTIAL_PROCESSING_ALLOWED
= new ThreadLocal<ProcessingUnderProgressInfo>()
{
@Override
protected ProcessingUnderProgressInfo initialValue() {
return new ProcessingUnderProgressInfo();
}
};
private final FormatterTagHandler myTagHandler;
private final Project myProject;
@NonNls private static final String DUMMY_IDENTIFIER = "xxx";
public CodeStyleManagerImpl(Project project) {
myProject = project;
myTagHandler = new FormatterTagHandler(getSettings());
}
@Override
@NotNull
public Project getProject() {
return myProject;
}
@Override
@NotNull
public PsiElement reformat(@NotNull PsiElement element) throws IncorrectOperationException {
return reformat(element, false);
}
@Override
@NotNull
public PsiElement reformat(@NotNull PsiElement element, boolean canChangeWhiteSpacesOnly) throws IncorrectOperationException {
CheckUtil.checkWritable(element);
if( !SourceTreeToPsiMap.hasTreeElement( element ) )
{
return element;
}
ASTNode treeElement = SourceTreeToPsiMap.psiElementToTree(element);
final PsiElement formatted = SourceTreeToPsiMap.treeElementToPsi(new CodeFormatterFacade(getSettings(), element.getLanguage()).processElement(treeElement));
if (!canChangeWhiteSpacesOnly) {
return postProcessElement(formatted);
}
return formatted;
}
private PsiElement postProcessElement(@NotNull final PsiElement formatted) {
PsiElement result = formatted;
if (getSettings().FORMATTER_TAGS_ENABLED && formatted instanceof PsiFile) {
postProcessEnabledRanges((PsiFile) formatted, formatted.getTextRange(), getSettings());
}
else {
for (PostFormatProcessor postFormatProcessor : Extensions.getExtensions(PostFormatProcessor.EP_NAME)) {
result = postFormatProcessor.processElement(result, getSettings());
}
}
return result;
}
private void postProcessText(@NotNull final PsiFile file, @NotNull final TextRange textRange) {
if (!getSettings().FORMATTER_TAGS_ENABLED) {
TextRange currentRange = textRange;
for (final PostFormatProcessor myPostFormatProcessor : Extensions.getExtensions(PostFormatProcessor.EP_NAME)) {
currentRange = myPostFormatProcessor.processText(file, currentRange, getSettings());
}
}
else {
postProcessEnabledRanges(file, textRange, getSettings());
}
}
@Override
public PsiElement reformatRange(@NotNull PsiElement element,
int startOffset,
int endOffset,
boolean canChangeWhiteSpacesOnly) throws IncorrectOperationException {
return reformatRangeImpl(element, startOffset, endOffset, canChangeWhiteSpacesOnly);
}
@Override
public PsiElement reformatRange(@NotNull PsiElement element, int startOffset, int endOffset)
throws IncorrectOperationException {
return reformatRangeImpl(element, startOffset, endOffset, false);
}
private static void transformAllChildren(final ASTNode file) {
((TreeElement)file).acceptTree(new RecursiveTreeElementWalkingVisitor() {
});
}
@Override
public void reformatText(@NotNull PsiFile file, int startOffset, int endOffset) throws IncorrectOperationException {
reformatText(file, Collections.singleton(new TextRange(startOffset, endOffset)));
}
@Override
public void reformatText(@NotNull PsiFile file, @NotNull Collection<TextRange> ranges) throws IncorrectOperationException {
reformatText(file, ranges, null);
}
@Override
public void reformatTextWithContext(@NotNull PsiFile file,
@NotNull ChangedRangesInfo info) throws IncorrectOperationException
{
FormatTextRanges formatRanges = new FormatTextRanges(info);
reformatText(file, formatRanges, null, true);
}
public void reformatText(@NotNull PsiFile file, @NotNull Collection<TextRange> ranges, @Nullable Editor editor) throws IncorrectOperationException {
FormatTextRanges formatRanges = new FormatTextRanges();
ranges.forEach((range) -> formatRanges.add(range, true));
reformatText(file, formatRanges, editor, false);
}
private void reformatText(@NotNull PsiFile file,
@NotNull FormatTextRanges ranges,
@Nullable Editor editor,
boolean reformatContext) throws IncorrectOperationException
{
if (ranges.isEmpty()) {
return;
}
boolean isFullReformat = ranges.isFullReformat(file);
ApplicationManager.getApplication().assertWriteAccessAllowed();
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
CheckUtil.checkWritable(file);
if (!SourceTreeToPsiMap.hasTreeElement(file)) {
return;
}
ASTNode treeElement = SourceTreeToPsiMap.psiElementToTree(file);
transformAllChildren(treeElement);
final CodeFormatterFacade codeFormatter = new CodeFormatterFacade(getSettings(), file.getLanguage());
codeFormatter.setReformatContext(reformatContext);
LOG.assertTrue(file.isValid(), "File name: " + file.getName() + " , class: " + file.getClass().getSimpleName());
if (editor == null) {
editor = PsiUtilBase.findEditor(file);
}
CaretPositionKeeper caretKeeper = null;
if (editor != null) {
caretKeeper = new CaretPositionKeeper(editor, getSettings(), file.getLanguage());
}
if (FormatterUtil.isFormatterCalledExplicitly()) {
removeEndingWhiteSpaceFromEachRange(file, ranges);
}
final SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(getProject());
List<RangeFormatInfo> infos = new ArrayList<>();
for (TextRange range : ranges.getTextRanges()) {
final PsiElement start = findElementInTreeWithFormatterEnabled(file, range.getStartOffset());
final PsiElement end = findElementInTreeWithFormatterEnabled(file, range.getEndOffset());
if (start != null && !start.isValid()) {
LOG.error("start=" + start + "; file=" + file);
}
if (end != null && !end.isValid()) {
LOG.error("end=" + start + "; end=" + file);
}
boolean formatFromStart = range.getStartOffset() == 0;
boolean formatToEnd = range.getEndOffset() == file.getTextLength();
infos.add(new RangeFormatInfo(
start == null ? null : smartPointerManager.createSmartPsiElementPointer(start),
end == null ? null : smartPointerManager.createSmartPsiElementPointer(end),
formatFromStart,
formatToEnd
));
}
codeFormatter.processText(file, ranges, true);
for (RangeFormatInfo info : infos) {
final PsiElement startElement = info.startPointer == null ? null : info.startPointer.getElement();
final PsiElement endElement = info.endPointer == null ? null : info.endPointer.getElement();
if ((startElement != null || info.fromStart) && (endElement != null || info.toEnd)) {
postProcessText(file, new TextRange(info.fromStart ? 0 : startElement.getTextRange().getStartOffset(),
info.toEnd ? file.getTextLength() : endElement.getTextRange().getEndOffset()));
}
if (info.startPointer != null) smartPointerManager.removePointer(info.startPointer);
if (info.endPointer != null) smartPointerManager.removePointer(info.endPointer);
}
if (caretKeeper != null) {
caretKeeper.restoreCaretPosition();
}
if (editor instanceof EditorEx && isFullReformat) {
((EditorEx)editor).reinitSettings();
DetectedIndentOptionsNotificationProvider.updateIndentNotification(file, true);
}
}
private static void removeEndingWhiteSpaceFromEachRange(@NotNull PsiFile file, @NotNull FormatTextRanges ranges) {
for (FormatTextRange formatRange : ranges.getRanges()) {
TextRange range = formatRange.getTextRange();
final int rangeStart = range.getStartOffset();
final int rangeEnd = range.getEndOffset();
PsiElement lastElementInRange = findElementInTreeWithFormatterEnabled(file, rangeEnd);
if (lastElementInRange instanceof PsiWhiteSpace && rangeStart < lastElementInRange.getTextRange().getStartOffset()) {
PsiElement prev = lastElementInRange.getPrevSibling();
if (prev != null) {
int newEnd = prev.getTextRange().getEndOffset();
formatRange.setTextRange(new TextRange(rangeStart, newEnd));
}
}
}
}
private PsiElement reformatRangeImpl(final PsiElement element,
final int startOffset,
final int endOffset,
boolean canChangeWhiteSpacesOnly) throws IncorrectOperationException {
LOG.assertTrue(element.isValid());
CheckUtil.checkWritable(element);
if( !SourceTreeToPsiMap.hasTreeElement( element ) )
{
return element;
}
ASTNode treeElement = SourceTreeToPsiMap.psiElementToTree(element);
final CodeFormatterFacade codeFormatter = new CodeFormatterFacade(getSettings(), element.getLanguage());
final PsiElement formatted = SourceTreeToPsiMap.treeElementToPsi(codeFormatter.processRange(treeElement, startOffset, endOffset));
return canChangeWhiteSpacesOnly ? formatted : postProcessElement(formatted);
}
@Override
public void reformatNewlyAddedElement(@NotNull final ASTNode parent, @NotNull final ASTNode addedElement) throws IncorrectOperationException {
LOG.assertTrue(addedElement.getTreeParent() == parent, "addedElement must be added to parent");
final PsiElement psiElement = parent.getPsi();
PsiFile containingFile = psiElement.getContainingFile();
final FileViewProvider fileViewProvider = containingFile.getViewProvider();
if (fileViewProvider instanceof MultiplePsiFilesPerDocumentFileViewProvider) {
containingFile = fileViewProvider.getPsi(fileViewProvider.getBaseLanguage());
}
TextRange textRange = addedElement.getTextRange();
final Document document = fileViewProvider.getDocument();
if (document instanceof DocumentWindow) {
containingFile = InjectedLanguageManager.getInstance(containingFile.getProject()).getTopLevelFile(containingFile);
textRange = ((DocumentWindow)document).injectedToHost(textRange);
}
final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(containingFile);
if (builder != null) {
final FormattingModel model = CoreFormatterUtil.buildModel(builder, containingFile, getSettings(), FormattingMode.REFORMAT);
FormatterEx.getInstanceEx().formatAroundRange(model, getSettings(), containingFile, textRange);
}
adjustLineIndent(containingFile, textRange);
}
@Override
public int adjustLineIndent(@NotNull final PsiFile file, final int offset) throws IncorrectOperationException {
DetectedIndentOptionsNotificationProvider.updateIndentNotification(file, false);
return PostprocessReformattingAspect.getInstance(file.getProject()).disablePostprocessFormattingInside(
() -> doAdjustLineIndentByOffset(file, offset));
}
@Nullable
static PsiElement findElementInTreeWithFormatterEnabled(final PsiFile file, final int offset) {
final PsiElement bottomost = file.findElementAt(offset);
if (bottomost != null && LanguageFormatting.INSTANCE.forContext(bottomost) != null){
return bottomost;
}
final Language fileLang = file.getLanguage();
if (fileLang instanceof CompositeLanguage) {
return file.getViewProvider().findElementAt(offset, fileLang);
}
return bottomost;
}
@Override
public int adjustLineIndent(@NotNull final Document document, final int offset) {
return PostprocessReformattingAspect.getInstance(getProject()).disablePostprocessFormattingInside(() -> {
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
documentManager.commitDocument(document);
PsiFile file = documentManager.getPsiFile(document);
if (file == null) return offset;
return doAdjustLineIndentByOffset(file, offset);
});
}
private int doAdjustLineIndentByOffset(@NotNull PsiFile file, int offset) {
final Integer result = new CodeStyleManagerRunnable<Integer>(this, FormattingMode.ADJUST_INDENT) {
@Override
protected Integer doPerform(int offset, TextRange range) {
return FormatterEx.getInstanceEx().adjustLineIndent(myModel, mySettings, myIndentOptions, offset, mySignificantRange);
}
@Override
protected Integer computeValueInsidePlainComment(PsiFile file, int offset, Integer defaultValue) {
return CharArrayUtil.shiftForward(file.getViewProvider().getContents(), offset, " \t");
}
@Override
protected Integer adjustResultForInjected(Integer result, DocumentWindow documentWindow) {
return result != null ? documentWindow.hostToInjected(result)
: null;
}
}.perform(file, offset, null, null);
return result != null ? result : offset;
}
@Override
public void adjustLineIndent(@NotNull PsiFile file, TextRange rangeToAdjust) throws IncorrectOperationException {
new CodeStyleManagerRunnable<Object>(this, FormattingMode.ADJUST_INDENT) {
@Override
protected Object doPerform(int offset, TextRange range) {
FormatterEx.getInstanceEx().adjustLineIndentsForRange(myModel, mySettings, myIndentOptions, range);
return null;
}
}.perform(file, -1, rangeToAdjust, null);
}
@Override
@Nullable
public String getLineIndent(@NotNull PsiFile file, int offset) {
return new CodeStyleManagerRunnable<String>(this, FormattingMode.ADJUST_INDENT) {
@Override
protected boolean useDocumentBaseFormattingModel() {
return false;
}
@Override
protected String doPerform(int offset, TextRange range) {
return FormatterEx.getInstanceEx().getLineIndent(myModel, mySettings, myIndentOptions, offset, mySignificantRange);
}
}.perform(file, offset, null, null);
}
@Override
@Nullable
public String getLineIndent(@NotNull Document document, int offset) {
PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
if (file == null) return "";
return getLineIndent(file, offset);
}
@Override
public boolean isLineToBeIndented(@NotNull PsiFile file, int offset) {
if (!SourceTreeToPsiMap.hasTreeElement(file)) {
return false;
}
CharSequence chars = file.getViewProvider().getContents();
int start = CharArrayUtil.shiftBackward(chars, offset - 1, " \t");
if (start > 0 && chars.charAt(start) != '\n' && chars.charAt(start) != '\r') {
return false;
}
int end = CharArrayUtil.shiftForward(chars, offset, " \t");
if (end >= chars.length()) {
return false;
}
ASTNode element = SourceTreeToPsiMap.psiElementToTree(findElementInTreeWithFormatterEnabled(file, end));
if (element == null) {
return false;
}
if (element.getElementType() == TokenType.WHITE_SPACE) {
return false;
}
if (element.getElementType() == PlainTextTokenTypes.PLAIN_TEXT) {
return false;
}
/*
if( element.getElementType() instanceof IJspElementType )
{
return false;
}
*/
if (getSettings().KEEP_FIRST_COLUMN_COMMENT && isCommentToken(element)) {
if (IndentHelper.getInstance().getIndent(myProject, file.getFileType(), element, true) == 0) {
return false;
}
}
return true;
}
private static boolean isCommentToken(final ASTNode element) {
final Language language = element.getElementType().getLanguage();
final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(language);
if (commenter instanceof CodeDocumentationAwareCommenter) {
final CodeDocumentationAwareCommenter documentationAwareCommenter = (CodeDocumentationAwareCommenter)commenter;
return element.getElementType() == documentationAwareCommenter.getBlockCommentTokenType() ||
element.getElementType() == documentationAwareCommenter.getLineCommentTokenType();
}
return false;
}
private static boolean isWhiteSpaceSymbol(char c) {
return c == ' ' || c == '\t' || c == '\n';
}
/**
* Formatter trims line that contains white spaces symbols only, however, there is a possible case that we want
* to preserve them for particular line
* (e.g. for live template that defines line with whitespaces that contains $END$ marker: templateText $END$).
* <p/>
* Current approach is to do the following:
* <pre>
* <ol>
* <li>Insert dummy text at the end of the blank line which white space symbols should be preserved;</li>
* <li>Perform formatting;</li>
* <li>Remove dummy text;</li>
* </ol>
* </pre>
* <p/>
* This method inserts that dummy comment (fallback to identifier <code>xxx</code>, see {@link CodeStyleManagerImpl#createDummy(PsiFile)})
* if necessary.
* <p/>
* <b>Note:</b> it's expected that the whole white space region that contains given offset is processed in a way that all
* {@link RangeMarker range markers} registered for the given offset are expanded to the whole white space region.
* E.g. there is a possible case that particular range marker serves for defining formatting range, hence, its start/end offsets
* are updated correspondingly after current method call and whole white space region is reformatted.
*
* @param file target PSI file
* @param document target document
* @param offset offset that defines end boundary of the target line text fragment (start boundary is the first line's symbol)
* @return text range that points to the newly inserted dummy text if any; <code>null</code> otherwise
* @throws IncorrectOperationException if given file is read-only
*/
@Nullable
public static TextRange insertNewLineIndentMarker(@NotNull PsiFile file, @NotNull Document document, int offset) {
CharSequence text = document.getImmutableCharSequence();
if (offset <= 0 || offset >= text.length() || !isWhiteSpaceSymbol(text.charAt(offset))) {
return null;
}
if (!isWhiteSpaceSymbol(text.charAt(offset - 1))) {
return null; // no whitespaces before offset
}
int end = offset;
for (; end < text.length(); end++) {
if (text.charAt(end) == '\n') {
break; // line is empty till the end
}
if (!isWhiteSpaceSymbol(text.charAt(end))) {
return null;
}
}
setSequentialProcessingAllowed(false);
String dummy = createDummy(file);
document.insertString(offset, dummy);
return new TextRange(offset, offset + dummy.length());
}
@NotNull
private static String createDummy(@NotNull PsiFile file) {
Language language = file.getLanguage();
PsiComment comment = null;
try {
comment = PsiParserFacade.SERVICE.getInstance(file.getProject()).createLineOrBlockCommentFromText(language, "");
}
catch (Throwable ignored) {
}
String text = comment != null ? comment.getText() : null;
return text != null ? text : DUMMY_IDENTIFIER;
}
/**
* Allows to check if given offset points to white space element within the given PSI file and return that white space
* element in the case of positive answer.
*
* @param file target file
* @param offset offset that might point to white space element within the given PSI file
* @return target white space element for the given offset within the given file (if any); <code>null</code> otherwise
*/
@Nullable
public static PsiElement findWhiteSpaceNode(@NotNull PsiFile file, int offset) {
return doFindWhiteSpaceNode(file, offset).first;
}
@NotNull
private static Pair<PsiElement, CharTable> doFindWhiteSpaceNode(@NotNull PsiFile file, int offset) {
ASTNode astNode = SourceTreeToPsiMap.psiElementToTree(file);
if (!(astNode instanceof FileElement)) {
return new Pair<>(null, null);
}
PsiElement elementAt = InjectedLanguageUtil.findInjectedElementNoCommit(file, offset);
final CharTable charTable = ((FileElement)astNode).getCharTable();
if (elementAt == null) {
elementAt = findElementInTreeWithFormatterEnabled(file, offset);
}
if( elementAt == null) {
return new Pair<>(null, charTable);
}
ASTNode node = elementAt.getNode();
if (node == null || node.getElementType() != TokenType.WHITE_SPACE) {
return new Pair<>(null, charTable);
}
return Pair.create(elementAt, charTable);
}
@Override
public Indent getIndent(String text, FileType fileType) {
int indent = IndentHelperImpl.getIndent(myProject, fileType, text, true);
int indenLevel = indent / IndentHelperImpl.INDENT_FACTOR;
int spaceCount = indent - indenLevel * IndentHelperImpl.INDENT_FACTOR;
return new IndentImpl(getSettings(), indenLevel, spaceCount, fileType);
}
@Override
public String fillIndent(Indent indent, FileType fileType) {
IndentImpl indent1 = (IndentImpl)indent;
int indentLevel = indent1.getIndentLevel();
int spaceCount = indent1.getSpaceCount();
if (indentLevel < 0) {
spaceCount += indentLevel * getSettings().getIndentSize(fileType);
indentLevel = 0;
if (spaceCount < 0) {
spaceCount = 0;
}
}
else {
if (spaceCount < 0) {
int v = (-spaceCount + getSettings().getIndentSize(fileType) - 1) / getSettings().getIndentSize(fileType);
indentLevel -= v;
spaceCount += v * getSettings().getIndentSize(fileType);
if (indentLevel < 0) {
indentLevel = 0;
}
}
}
return IndentHelperImpl.fillIndent(myProject, fileType, indentLevel * IndentHelperImpl.INDENT_FACTOR + spaceCount);
}
@Override
public Indent zeroIndent() {
return new IndentImpl(getSettings(), 0, 0, null);
}
@NotNull
private CodeStyleSettings getSettings() {
return CodeStyleSettingsManager.getSettings(myProject);
}
@Override
public boolean isSequentialProcessingAllowed() {
return SEQUENTIAL_PROCESSING_ALLOWED.get().isAllowed();
}
/**
* Allows to define if {@link #isSequentialProcessingAllowed() sequential processing} should be allowed.
* <p/>
* Current approach is not allow to stop sequential processing for more than predefine amount of time (couple of seconds).
* That means that call to this method with <code>'true'</code> argument is not mandatory for successful processing even
* if this method is called with <code>'false'</code> argument before.
*
* @param allowed flag that defines if {@link #isSequentialProcessingAllowed() sequential processing} should be allowed
*/
public static void setSequentialProcessingAllowed(boolean allowed) {
ProcessingUnderProgressInfo info = SEQUENTIAL_PROCESSING_ALLOWED.get();
if (allowed) {
info.decrement();
}
else {
info.increment();
}
}
private static class ProcessingUnderProgressInfo {
private static final long DURATION_TIME = TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS);
private int myCount;
private long myEndTime;
public void increment() {
if (myCount > 0 && System.currentTimeMillis() > myEndTime) {
myCount = 0;
}
myCount++;
myEndTime = System.currentTimeMillis() + DURATION_TIME;
}
public void decrement() {
if (myCount <= 0) {
return;
}
myCount--;
}
public boolean isAllowed() {
return myCount <= 0 || System.currentTimeMillis() >= myEndTime;
}
}
@Override
public void performActionWithFormatterDisabled(final Runnable r) {
performActionWithFormatterDisabled(() -> {
r.run();
return null;
});
}
@Override
public <T extends Throwable> void performActionWithFormatterDisabled(final ThrowableRunnable<T> r) throws T {
final Throwable[] throwable = new Throwable[1];
performActionWithFormatterDisabled(() -> {
try {
r.run();
}
catch (Throwable t) {
throwable[0] = t;
}
return null;
});
if (throwable[0] != null) {
//noinspection unchecked
throw (T)throwable[0];
}
}
@Override
public <T> T performActionWithFormatterDisabled(final Computable<T> r) {
return ((FormatterImpl)FormatterEx.getInstance()).runWithFormattingDisabled(() -> {
final PostprocessReformattingAspect component = PostprocessReformattingAspect.getInstance(getProject());
return component.disablePostprocessFormattingInside(r);
});
}
private static class RangeFormatInfo{
private final SmartPsiElementPointer startPointer;
private final SmartPsiElementPointer endPointer;
private final boolean fromStart;
private final boolean toEnd;
RangeFormatInfo(@Nullable SmartPsiElementPointer startPointer,
@Nullable SmartPsiElementPointer endPointer,
boolean fromStart,
boolean toEnd)
{
this.startPointer = startPointer;
this.endPointer = endPointer;
this.fromStart = fromStart;
this.toEnd = toEnd;
}
}
// There is a possible case that cursor is located at the end of the line that contains only white spaces. For example:
// public void foo() {
// <caret>
// }
// Formatter removes such white spaces, i.e. keeps only line feed symbol. But we want to preserve caret position then.
// So, if 'virtual space in editor' is enabled, we save target visual column. Caret indent is ensured otherwise
private static class CaretPositionKeeper {
Editor myEditor;
Document myDocument;
CaretModel myCaretModel;
RangeMarker myBeforeCaretRangeMarker;
String myCaretIndentToRestore;
int myVisualColumnToRestore = -1;
boolean myBlankLineIndentPreserved = true;
CaretPositionKeeper(@NotNull Editor editor, @NotNull CodeStyleSettings settings, @NotNull Language language) {
myEditor = editor;
myCaretModel = editor.getCaretModel();
myDocument = editor.getDocument();
myBlankLineIndentPreserved = isBlankLineIndentPreserved(settings, language);
int caretOffset = getCaretOffset();
int lineStartOffset = getLineStartOffsetByTotalOffset(caretOffset);
int lineEndOffset = getLineEndOffsetByTotalOffset(caretOffset);
boolean shouldFixCaretPosition = rangeHasWhiteSpaceSymbolsOnly(myDocument.getCharsSequence(), lineStartOffset, lineEndOffset);
if (shouldFixCaretPosition) {
initRestoreInfo(caretOffset);
}
}
private static boolean isBlankLineIndentPreserved(@NotNull CodeStyleSettings settings, @NotNull Language language) {
CommonCodeStyleSettings langSettings = settings.getCommonSettings(language);
if (langSettings != null) {
CommonCodeStyleSettings.IndentOptions indentOptions = langSettings.getIndentOptions();
return indentOptions != null && indentOptions.KEEP_INDENTS_ON_EMPTY_LINES;
}
return false;
}
private void initRestoreInfo(int caretOffset) {
int lineStartOffset = getLineStartOffsetByTotalOffset(caretOffset);
myVisualColumnToRestore = myCaretModel.getVisualPosition().column;
myCaretIndentToRestore = myDocument.getText(TextRange.create(lineStartOffset, caretOffset));
myBeforeCaretRangeMarker = myDocument.createRangeMarker(0, lineStartOffset);
}
public void restoreCaretPosition() {
if (isVirtualSpaceEnabled()) {
restoreVisualPosition();
}
else {
restorePositionByIndentInsertion();
}
}
private void restorePositionByIndentInsertion() {
if (myBeforeCaretRangeMarker == null ||
!myBeforeCaretRangeMarker.isValid() ||
myCaretIndentToRestore == null ||
myBlankLineIndentPreserved) {
return;
}
int newCaretLineStartOffset = myBeforeCaretRangeMarker.getEndOffset();
myBeforeCaretRangeMarker.dispose();
if (myCaretModel.getVisualPosition().column == myVisualColumnToRestore) {
return;
}
insertWhiteSpaceIndentIfNeeded(newCaretLineStartOffset);
}
private void restoreVisualPosition() {
if (myVisualColumnToRestore < 0) {
myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
return;
}
VisualPosition position = myCaretModel.getVisualPosition();
if (myVisualColumnToRestore != position.column) {
myCaretModel.moveToVisualPosition(new VisualPosition(position.line, myVisualColumnToRestore));
}
}
private void insertWhiteSpaceIndentIfNeeded(int caretLineOffset) {
int lineToInsertIndent = myDocument.getLineNumber(caretLineOffset);
if (!lineContainsWhiteSpaceSymbolsOnly(lineToInsertIndent))
return;
int lineToInsertStartOffset = myDocument.getLineStartOffset(lineToInsertIndent);
if (lineToInsertIndent != getCurrentCaretLine()) {
myCaretModel.moveToOffset(lineToInsertStartOffset);
}
myDocument.replaceString(lineToInsertStartOffset, caretLineOffset, myCaretIndentToRestore);
}
private boolean rangeHasWhiteSpaceSymbolsOnly(CharSequence text, int lineStartOffset, int lineEndOffset) {
for (int i = lineStartOffset; i < lineEndOffset; i++) {
char c = text.charAt(i);
if (c != ' ' && c != '\t' && c != '\n') {
return false;
}
}
return true;
}
private boolean isVirtualSpaceEnabled() {
return myEditor.getSettings().isVirtualSpace();
}
private int getLineStartOffsetByTotalOffset(int offset) {
int line = myDocument.getLineNumber(offset);
return myDocument.getLineStartOffset(line);
}
private int getLineEndOffsetByTotalOffset(int offset) {
int line = myDocument.getLineNumber(offset);
return myDocument.getLineEndOffset(line);
}
private int getCaretOffset() {
int caretOffset = myCaretModel.getOffset();
caretOffset = Math.max(Math.min(caretOffset, myDocument.getTextLength() - 1), 0);
return caretOffset;
}
private boolean lineContainsWhiteSpaceSymbolsOnly(int lineNumber) {
int startOffset = myDocument.getLineStartOffset(lineNumber);
int endOffset = myDocument.getLineEndOffset(lineNumber);
return rangeHasWhiteSpaceSymbolsOnly(myDocument.getCharsSequence(), startOffset, endOffset);
}
private int getCurrentCaretLine() {
return myDocument.getLineNumber(myCaretModel.getOffset());
}
}
private TextRange postProcessEnabledRanges(@NotNull final PsiFile file, @NotNull TextRange range, CodeStyleSettings settings) {
TextRange result = TextRange.create(range.getStartOffset(), range.getEndOffset());
List<TextRange> enabledRanges = myTagHandler.getEnabledRanges(file.getNode(), result);
int delta = 0;
for (TextRange enabledRange : enabledRanges) {
enabledRange = enabledRange.shiftRight(delta);
for (PostFormatProcessor processor : Extensions.getExtensions(PostFormatProcessor.EP_NAME)) {
TextRange processedRange = processor.processText(file, enabledRange, settings);
delta += processedRange.getLength() - enabledRange.getLength();
}
}
result = result.grown(delta);
return result;
}
}
| |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.jsonSchema.settings.mappings;
import com.intellij.execution.configurations.RuntimeConfigurationWarning;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.NamedConfigurable;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.impl.http.HttpVirtualFile;
import com.intellij.util.Function;
import com.intellij.util.Urls;
import com.jetbrains.jsonSchema.UserDefinedJsonSchemaConfiguration;
import com.jetbrains.jsonSchema.impl.JsonSchemaReader;
import com.jetbrains.jsonSchema.remote.JsonFileResolver;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
/**
* @author Irina.Chernushina on 2/2/2016.
*/
public class JsonSchemaConfigurable extends NamedConfigurable<UserDefinedJsonSchemaConfiguration> {
private final Project myProject;
@NotNull private final String mySchemaFilePath;
@NotNull private final UserDefinedJsonSchemaConfiguration mySchema;
@Nullable private final TreeUpdater myTreeUpdater;
@NotNull private final Function<String, String> myNameCreator;
private JsonSchemaMappingsView myView;
private String myDisplayName;
private String myError;
public JsonSchemaConfigurable(Project project,
@NotNull String schemaFilePath, @NotNull UserDefinedJsonSchemaConfiguration schema,
@Nullable TreeUpdater updateTree,
@NotNull Function<String, String> nameCreator) {
super(true, () -> {
if (updateTree != null) {
updateTree.updateTree(true);
}
});
myProject = project;
mySchemaFilePath = schemaFilePath;
mySchema = schema;
myTreeUpdater = updateTree;
myNameCreator = nameCreator;
myDisplayName = mySchema.getName();
}
@NotNull
public UserDefinedJsonSchemaConfiguration getSchema() {
return mySchema;
}
@Override
public void setDisplayName(String name) {
myDisplayName = name;
}
@Override
public UserDefinedJsonSchemaConfiguration getEditableObject() {
return mySchema;
}
@Override
public String getBannerSlogan() {
return mySchema.getName();
}
@Override
public JComponent createOptionsPanel() {
if (myView == null) {
myView = new JsonSchemaMappingsView(myProject, myTreeUpdater, s -> {
if (myDisplayName.startsWith(JsonSchemaMappingsConfigurable.STUB_SCHEMA_NAME)) {
int lastSlash = Math.max(s.lastIndexOf('/'), s.lastIndexOf('\\'));
if (lastSlash > 0) {
String substring = s.substring(lastSlash + 1);
int dot = substring.lastIndexOf('.');
if (dot != -1) {
substring = substring.substring(0, dot);
}
setDisplayName(myNameCreator.fun(substring));
updateName();
}
}
});
myView.setError(myError, true);
}
return myView.getComponent();
}
@Nls
@Override
public String getDisplayName() {
return myDisplayName;
}
@Nullable
@Override
public String getHelpTopic() {
return JsonSchemaMappingsConfigurable.SETTINGS_JSON_SCHEMA;
}
@Override
public boolean isModified() {
if (myView == null) return false;
if (!FileUtil.toSystemDependentName(mySchema.getRelativePathToSchema()).equals(myView.getSchemaSubPath())) return true;
if (mySchema.getSchemaVersion() != myView.getSchemaVersion()) return true;
return !Comparing.equal(myView.getData(), mySchema.getPatterns());
}
@Override
public void apply() throws ConfigurationException {
if (myView == null) return;
doValidation();
mySchema.setName(myDisplayName);
mySchema.setSchemaVersion(myView.getSchemaVersion());
mySchema.setPatterns(myView.getData());
mySchema.setRelativePathToSchema(myView.getSchemaSubPath());
}
public static boolean isValidURL(@NotNull final String url) {
return JsonFileResolver.isHttpPath(url) && Urls.parse(url, false) != null;
}
private void doValidation() throws ConfigurationException {
String schemaSubPath = myView.getSchemaSubPath();
if (StringUtil.isEmptyOrSpaces(schemaSubPath)) {
throw new ConfigurationException((!StringUtil.isEmptyOrSpaces(myDisplayName) ? (myDisplayName + ": ") : "") + "Schema path is empty");
}
VirtualFile vFile;
String filename;
if (JsonFileResolver.isHttpPath(schemaSubPath)) {
filename = schemaSubPath;
if (!isValidURL(schemaSubPath)) {
throw new ConfigurationException(
(!StringUtil.isEmptyOrSpaces(myDisplayName) ? (myDisplayName + ": ") : "") + "Invalid schema URL");
}
vFile = JsonFileResolver.urlToFile(schemaSubPath);
if (vFile == null) {
throw new ConfigurationException(
(!StringUtil.isEmptyOrSpaces(myDisplayName) ? (myDisplayName + ": ") : "") + "Invalid URL resource");
}
}
else {
File subPath = new File(schemaSubPath);
final File file = subPath.isAbsolute() ? subPath : new File(myProject.getBasePath(), schemaSubPath);
if (!file.exists() || (vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)) == null) {
throw new ConfigurationException(
(!StringUtil.isEmptyOrSpaces(myDisplayName) ? (myDisplayName + ": ") : "") + "Schema file does not exist");
}
filename = file.getName();
}
if (StringUtil.isEmptyOrSpaces(myDisplayName)) throw new ConfigurationException(filename + ": Schema name is empty");
// we don't validate remote schemas while in options dialog
if (vFile instanceof HttpVirtualFile) return;
final String error = JsonSchemaReader.checkIfValidJsonSchema(myProject, vFile);
if (error != null) {
logErrorForUser(error);
throw new RuntimeConfigurationWarning(error);
}
}
private void logErrorForUser(@NotNull final String error) {
JsonSchemaReader.ERRORS_NOTIFICATION.createNotification(error, MessageType.WARNING).notify(myProject);
}
@Override
public void reset() {
if (myView == null) return;
myView.setItems(mySchemaFilePath, mySchema.getSchemaVersion(), mySchema.getPatterns());
setDisplayName(mySchema.getName());
}
public UserDefinedJsonSchemaConfiguration getUiSchema() {
final UserDefinedJsonSchemaConfiguration info = new UserDefinedJsonSchemaConfiguration();
info.setApplicationDefined(mySchema.isApplicationDefined());
if (myView != null && myView.isInitialized()) {
info.setName(getDisplayName());
info.setSchemaVersion(myView.getSchemaVersion());
info.setPatterns(myView.getData());
info.setRelativePathToSchema(myView.getSchemaSubPath());
} else {
info.setName(mySchema.getName());
info.setSchemaVersion(mySchema.getSchemaVersion());
info.setPatterns(mySchema.getPatterns());
info.setRelativePathToSchema(mySchema.getRelativePathToSchema());
}
return info;
}
@Override
public void disposeUIResources() {
if (myView != null) Disposer.dispose(myView);
}
public void setError(String error, boolean showWarning) {
myError = error;
if (myView != null) {
myView.setError(error, showWarning);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.