answer
stringlengths 17
10.2M
|
|---|
package ca.corefacility.bioinformatics.irida.web.controller.api.projects;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Link;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import ca.corefacility.bioinformatics.irida.model.Project;
import ca.corefacility.bioinformatics.irida.model.Sample;
import ca.corefacility.bioinformatics.irida.model.SequenceFile;
import ca.corefacility.bioinformatics.irida.model.joins.Join;
import ca.corefacility.bioinformatics.irida.service.ProjectService;
import ca.corefacility.bioinformatics.irida.service.SampleService;
import ca.corefacility.bioinformatics.irida.service.SequenceFileService;
import ca.corefacility.bioinformatics.irida.web.assembler.resource.LabelledRelationshipResource;
import ca.corefacility.bioinformatics.irida.web.assembler.resource.ResourceCollection;
import ca.corefacility.bioinformatics.irida.web.assembler.resource.RootResource;
import ca.corefacility.bioinformatics.irida.web.assembler.resource.sample.SampleResource;
import ca.corefacility.bioinformatics.irida.web.controller.api.GenericController;
import ca.corefacility.bioinformatics.irida.web.controller.api.samples.SampleSequenceFilesController;
import com.google.common.net.HttpHeaders;
/**
* Controller for managing relationships between {@link Project} and {@link Sample}.
*
* @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
*/
@Controller
public class ProjectSamplesController {
/**
* Rel to get to the project that this sample belongs to.
*/
public static final String REL_PROJECT = "sample/project";
/**
* rel used for accessing the list of samples associated with a project.
*/
public static final String REL_PROJECT_SAMPLES = "project/samples";
/**
* Reference to {@link ProjectService}.
*/
private ProjectService projectService;
/**
* Reference to {@link SampleService}.
*/
private SampleService sampleService;
/**
* Reference to {@link SequenceFileService}.
*/
private SequenceFileService sequenceFileService;
protected ProjectSamplesController() {
}
@Autowired
public ProjectSamplesController(ProjectService projectService, SampleService sampleService, SequenceFileService sequenceFileService) {
this.projectService = projectService;
this.sampleService = sampleService;
this.sequenceFileService = sequenceFileService;
}
/**
* Create a new sample resource and create a relationship between the sample and the project.
*
* @param projectId the identifier of the project that you want to add the sample to.
* @param sample the sample that you want to create.
* @return a response indicating that the sample was created and appropriate location information.
*/
@RequestMapping(value = "/projects/{projectId}/samples", method = RequestMethod.POST)
public ResponseEntity<String> addSampleToProject(@PathVariable Long projectId, @RequestBody SampleResource sample) {
// load the project that we're adding to
Project p = projectService.read(projectId);
// construct the sample that we're going to create
Sample s = sample.getResource();
// add the sample to the project
Join<Project, Sample> r = projectService.addSampleToProject(p, s);
// construct a link to the sample itself on the samples controller
Long sampleId = r.getObject().getId();
String location = linkTo(methodOn(ProjectSamplesController.class)
.getProjectSample(projectId, sampleId)).withSelfRel().getHref();
// construct a set of headers to add to the response
MultiValueMap<String, String> responseHeaders = new LinkedMultiValueMap<>();
responseHeaders.add(HttpHeaders.LOCATION, location);
// respond to the request
return new ResponseEntity<>("success", responseHeaders, HttpStatus.CREATED);
}
/**
* Get the list of {@link Sample} associated with this {@link Project}.
*
* @param projectId the identifier of the {@link Project} to get the {@link Sample}s for.
* @return the list of {@link Sample}s associated with this {@link Project}.
*/
@RequestMapping(value = "/projects/{projectId}/samples", method = RequestMethod.GET)
public ModelMap getProjectSamples(@PathVariable Long projectId) {
ModelMap modelMap = new ModelMap();
Project p = projectService.read(projectId);
List<Join<Project, Sample>> relationships = sampleService.getSamplesForProject(p);
ResourceCollection<SampleResource> sampleResources = new ResourceCollection<>(relationships.size());
for (Join<Project, Sample> r : relationships) {
Sample sample = r.getObject();
SampleResource sr = new SampleResource();
sr.setResource(sample);
sr.add(linkTo(methodOn(ProjectSamplesController.class).
getProjectSample(projectId, sample.getId())).withSelfRel());
sampleResources.add(sr);
}
sampleResources.add(linkTo(methodOn(ProjectSamplesController.class).getProjectSamples(projectId)).withSelfRel());
sampleResources.setTotalResources(relationships.size());
modelMap.addAttribute(GenericController.RESOURCE_NAME, sampleResources);
return modelMap;
}
@RequestMapping(value = "/projects/{projectId}/samples/byExternalId/{externalSampleId}", method = RequestMethod.GET)
public ModelAndView getProjectSampleByExternalId(@PathVariable Long projectId, @PathVariable String externalSampleId){
Project p = projectService.read(projectId);
Sample sampleBySampleId = sampleService.getSampleByExternalSampleId(p, externalSampleId);
SampleResource sr = new SampleResource();
sr.setResource(sampleBySampleId);
Link withSelfRel = linkTo(methodOn(ProjectSamplesController.class).
getProjectSample(projectId, sampleBySampleId.getId())).withSelfRel();
String href = withSelfRel.getHref();
RedirectView redirectView = new RedirectView(href);
return new ModelAndView(redirectView);
}
/**
* Get the representation of a specific sample that's associated with the project.
*
* @param projectId the {@link Project} identifier that the {@link Sample} should be associated with.
* @param sampleId the {@link Sample} identifier that we're looking for.
* @return a representation of the specific sample.
*/
@RequestMapping(value = "/projects/{projectId}/samples/{sampleId}", method = RequestMethod.GET)
public ModelMap getProjectSample(@PathVariable Long projectId, @PathVariable Long sampleId) {
ModelMap modelMap = new ModelMap();
// load the project
Project p = projectService.read(projectId);
// get the sample for the project.
Sample s = sampleService.getSampleForProject(p, sampleId);
// prepare the sample for serializing to the client
SampleResource sr = new SampleResource();
sr.setResource(s);
// add a link to: 1) self, 2) sequenceFiles, 3) project
sr.add(linkTo(methodOn(ProjectSamplesController.class).getProjectSample(projectId, sampleId)).withSelfRel());
sr.add(linkTo(ProjectsController.class).slash(projectId).withRel(REL_PROJECT));
sr.add(linkTo(methodOn(SampleSequenceFilesController.class).getSampleSequenceFiles(projectId, sampleId))
.withRel(SampleSequenceFilesController.REL_SAMPLE_SEQUENCE_FILES));
// add the sample resource to the response
modelMap.addAttribute(GenericController.RESOURCE_NAME, sr);
// get some related sequence files for the sample
List<Join<Sample, SequenceFile>> relationships = sequenceFileService.getSequenceFilesForSample(s);
ResourceCollection<LabelledRelationshipResource<Sample, SequenceFile>> sequenceFileResources =
new ResourceCollection<>(relationships.size());
for (Join<Sample, SequenceFile> r : relationships) {
SequenceFile sf = r.getObject();
LabelledRelationshipResource<Sample, SequenceFile> resource = new LabelledRelationshipResource<>(sf.getLabel(), r);
resource.add(linkTo(methodOn(SampleSequenceFilesController.class).getSequenceFileForSample(projectId,
sampleId, sf.getId())).withSelfRel());
sequenceFileResources.add(resource);
}
sequenceFileResources.add(linkTo(methodOn(SampleSequenceFilesController.class)
.getSampleSequenceFiles(projectId, sampleId)).withSelfRel());
Map<String, ResourceCollection<LabelledRelationshipResource<Sample, SequenceFile>>> relatedResources = new HashMap<>();
relatedResources.put("sequenceFiles", sequenceFileResources);
modelMap.addAttribute(GenericController.RELATED_RESOURCES_NAME, relatedResources);
return modelMap;
}
/**
* Remove a specific {@link Sample} from the collection of {@link Sample}s associated with a {@link Project}.
*
* @param projectId the {@link Project} identifier.
* @param sampleId the {@link Sample} identifier.
* @return a response including links back to the specific {@link Project} and collection of {@link Sample}.
*/
@RequestMapping(value = "/projects/{projectId}/samples/{sampleId}", method = RequestMethod.DELETE)
public ModelMap removeSampleFromProject(@PathVariable Long projectId, @PathVariable Long sampleId) {
ModelMap modelMap = new ModelMap();
// load the sample and project
Project p = projectService.read(projectId);
Sample s = sampleService.read(sampleId);
// remove the relationship.
projectService.removeSampleFromProject(p, s);
// respond to the client.
RootResource resource = new RootResource();
// add links back to the collection of samples and to the project itself.
resource.add(linkTo(methodOn(ProjectSamplesController.class)
.getProjectSamples(projectId)).withRel(REL_PROJECT_SAMPLES));
resource.add(linkTo(ProjectsController.class).slash(projectId).withRel(ProjectsController.REL_PROJECT));
// add the links to the response.
modelMap.addAttribute(GenericController.RESOURCE_NAME, resource);
return modelMap;
}
/**
* Update a {@link Sample} details.
*
* @param projectId the identifier of the {@link Project} that the {@link Sample} belongs to.
* @param sampleId the identifier of the {@link Sample}.
* @param updatedFields the updated fields of the {@link Sample}.
* @return a response including links to the {@link Project} and {@link Sample}.
*/
@RequestMapping(value = "/projects/{projectId}/samples/{sampleId}", method = RequestMethod.PATCH,
consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ModelMap updateSample(@PathVariable Long projectId, @PathVariable Long sampleId,
@RequestBody Map<String, Object> updatedFields) {
ModelMap modelMap = new ModelMap();
// confirm that the project is related to the sample
Project p = projectService.read(projectId);
sampleService.getSampleForProject(p, sampleId);
// issue an update request
sampleService.update(sampleId, updatedFields);
// respond to the client with a link to self, sequence files collection and project.
RootResource resource = new RootResource();
resource.add(linkTo(methodOn(ProjectSamplesController.class).getProjectSample(projectId, sampleId))
.withSelfRel());
resource.add(linkTo(methodOn(SampleSequenceFilesController.class).getSampleSequenceFiles(projectId, sampleId))
.withRel(SampleSequenceFilesController.REL_SAMPLE_SEQUENCE_FILES));
resource.add(linkTo(ProjectsController.class).slash(projectId).withRel(ProjectsController.REL_PROJECT));
modelMap.addAttribute(GenericController.RESOURCE_NAME, resource);
return modelMap;
}
}
|
package uk.gov.register.db;
import uk.gov.register.core.Entry;
import uk.gov.register.core.Record;
import uk.gov.register.store.BackingStoreDriver;
import java.util.*;
public class RecordIndex {
private final BackingStoreDriver backingStoreDriver;
public RecordIndex(BackingStoreDriver backingStoreDriver) {
this.backingStoreDriver = backingStoreDriver;
}
public void updateRecordIndex(String registerName, Record record) {
backingStoreDriver.insertRecord(record, registerName);
}
public Optional<Record> getRecord(String key) {
return backingStoreDriver.getRecord(key);
}
public int getTotalRecords() {
return backingStoreDriver.getTotalRecords();
}
public List<Record> getRecords(int limit, int offset) {
return backingStoreDriver.getRecords(limit, offset);
}
public List<Record> findMax100RecordsByKeyValue(String key, String value) {
return backingStoreDriver.findMax100RecordsByKeyValue(key, value);
}
public Collection<Entry> findAllEntriesOfRecordBy(String registerName, String key) {
return backingStoreDriver.findAllEntriesOfRecordBy(registerName, key);
}
}
|
package net.finmath.tests.montecarlo.assetderivativevaluation;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import net.finmath.exception.CalculationException;
import net.finmath.montecarlo.assetderivativevaluation.AssetModelMonteCarloSimulationInterface;
import net.finmath.montecarlo.assetderivativevaluation.MonteCarloBlackScholesModel;
import net.finmath.montecarlo.assetderivativevaluation.products.AsianOption;
import net.finmath.montecarlo.assetderivativevaluation.products.BermudanOption;
import net.finmath.montecarlo.assetderivativevaluation.products.EuropeanOption;
import net.finmath.stochastic.RandomVariableInterface;
import net.finmath.time.TimeDiscretization;
import net.finmath.time.TimeDiscretizationInterface;
import org.junit.Test;
/**
* This class represents a collection of several "tests" illustrating different aspects
* related to the Monte-Carlo Simulation and derivative pricing (using a simple
* Black-Scholes model.
*
* @author Christian Fries
*/
public class BlackScholesMonteCarloValuationTest {
// Model properties
private final double initialValue = 1.0;
private final double riskFreeRate = 0.05;
private final double volatility = 0.30;
// Process discretization properties
private final int numberOfPaths = 20000;
private final int numberOfTimeSteps = 10;
private final double deltaT = 0.5;
private AssetModelMonteCarloSimulationInterface model = null;
/**
* This main method will test a Monte-Carlo simulation of a Black-Scholes model and some valuations
* performed with this model.
*
* @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, CalculationException, InterruptedException
{
BlackScholesMonteCarloValuationTest pricingTest = new BlackScholesMonteCarloValuationTest();
/*
* Read input
*/
int testNumber = readTestNumber();
long start = System.currentTimeMillis();
switch(testNumber) {
case 1:
// This test requires a MonteCarloBlackScholesModel and will not work with others models
pricingTest.testEuropeanCall();
break;
case 2:
pricingTest.testModelProperties();
break;
case 3:
pricingTest.testModelRandomVariable();
break;
case 4:
pricingTest.testEuropeanAsianBermudanOption();
break;
case 5:
pricingTest.testMultiThreaddedValuation();
break;
case 6:
// This test requires a MonteCarloBlackScholesModel and will not work with others models
pricingTest.testEuropeanCallDelta();
break;
case 7:
// This test requires a MonteCarloBlackScholesModel and will not work with others models
pricingTest.testEuropeanCallVega();
break;
}
long end = System.currentTimeMillis();
System.out.println("\nCalculation time required: " + ((double)(end-start))/1000.0 + " seconds.");
}
public BlackScholesMonteCarloValuationTest() {
super();
// Create a Model (see method getModel)
model = getModel();
}
private static int readTestNumber() {
System.out.println("Please select a test to run (click in this window and enter a number):");
System.out.println("\t 1: Valuation of European call options (with different strikes).");
System.out.println("\t 2: Some model properties.");
System.out.println("\t 3: Print some realizations of the S(1).");
System.out.println("\t 4: Valuation of European, Asian, Bermudan option.");
System.out.println("\t 5: Multi-Threadded valuation of some ten thousand Asian options.");
System.out.println("\t 6: Sensitivity (Delta) of European call options (with different strikes) using different methods.");
System.out.println("\t 7: Sensitivity (Vega) of European call options (with different strikes) using different methods.");
System.out.println("");
System.out.print("Test to run: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testNumber = 0;
try {
String test = br.readLine();
testNumber = Integer.valueOf(test);
} catch (IOException ioe) {
System.out.println("IO error trying to read test number!");
System.exit(1);
}
System.out.println("");
return testNumber;
}
public AssetModelMonteCarloSimulationInterface getModel()
{
// Create the time discretization
TimeDiscretizationInterface timeDiscretization = new TimeDiscretization(0.0, numberOfTimeSteps, deltaT);
// Create an instance of a black scholes monte carlo model
AssetModelMonteCarloSimulationInterface model = new MonteCarloBlackScholesModel(
timeDiscretization,
numberOfPaths,
initialValue,
riskFreeRate,
volatility);
return model;
}
@Test
public void testEuropeanCall() throws CalculationException
{
MonteCarloBlackScholesModel blackScholesModel = (MonteCarloBlackScholesModel)model;
// Java DecimalFormat for our output format
DecimalFormat numberFormatStrike = new DecimalFormat(" 0.00 ");
DecimalFormat numberFormatValue = new DecimalFormat(" 0.00E00");
DecimalFormat numberFormatDeviation = new DecimalFormat(" 0.00E00; -0.00E00");
// Test options with different strike
System.out.println("Valuation of European Options");
System.out.println(" Strike \t Monte-Carlo \t Analytic \t Deviation");
double initialValue = blackScholesModel.getAssetValue(0.0, 0).get(0);
double riskFreeRate = blackScholesModel.getRiskFreeRate();
double volatility = blackScholesModel.getVolatility();
double optionMaturity = 1.0;
for(double optionStrike = 0.60; optionStrike < 1.50; optionStrike += 0.05) {
// Create a product
EuropeanOption callOption = new EuropeanOption(optionMaturity, optionStrike);
// Value the product with Monte Carlo
double valueMonteCarlo = callOption.getValue(blackScholesModel);
// Calculate the analytic value
double valueAnalytic = net.finmath.functions.AnalyticFormulas.blackScholesOptionValue(initialValue, riskFreeRate, volatility, optionMaturity, optionStrike);
// Print result
System.out.println(numberFormatStrike.format(optionStrike) +
"\t" + numberFormatValue.format(valueMonteCarlo) +
"\t" + numberFormatValue.format(valueAnalytic) +
"\t" + numberFormatDeviation.format(valueMonteCarlo-valueAnalytic));
assertTrue(Math.abs(valueMonteCarlo-valueAnalytic) < 1E-02);
}
}
/**
* Test some properties of the model
*/
@Test
public void testModelProperties() throws CalculationException {
System.out.println("Time \tAverage \t\tVariance");
TimeDiscretizationInterface modelTimeDiscretization = model.getTimeDiscretization();
for(double time : modelTimeDiscretization) {
RandomVariableInterface assetValue = model.getAssetValue(time, 0);
double average = assetValue.getAverage();
double variance = assetValue.getVariance();
double error = assetValue.getStandardError();
DecimalFormat formater2Digits = new DecimalFormat("0.00");
DecimalFormat formater4Digits = new DecimalFormat("0.0000");
System.out.println(formater2Digits.format(time) + " \t" + formater4Digits.format(average) + "\t+/- " + formater4Digits.format(error) + "\t" + formater4Digits.format(variance));
}
}
@Test
public void testModelRandomVariable() throws CalculationException {
RandomVariableInterface stockAtTimeOne = model.getAssetValue(1.0, 0);
System.out.println("The first 100 realizations of the " + stockAtTimeOne.size() + " realizations of S(1) are:");
System.out.println("Path\tValue");
for(int i=0; i<100;i++) {
System.out.println(i + "\t" + stockAtTimeOne.get(i));
}
}
/**
* Evaluates different options (European, Asian, Bermudan) using the given model.
*/
@Test
public void testEuropeanAsianBermudanOption() throws CalculationException {
double[] averagingPoints = { 1.0, 1.5, 2.0, 2.5 , 3.0 };
double maturity = 3.0;
double strike = 1.07;
AsianOption myAsianOption = new AsianOption(maturity,strike, new TimeDiscretization(averagingPoints));
double valueOfAsianOption = myAsianOption.getValue(model);
EuropeanOption myEuropeanOption = new EuropeanOption(maturity,strike);
double valueOfEuropeanOption = myEuropeanOption.getValue(model);
double[] exerciseDates = { 1.0, 2.0, 3.0};
double[] notionals = { 1.04, 1.02, 1.0};
double[] strikes = { 1.04, 1.08, 1.15 };
BermudanOption myBermudanOptionLowerBound = new BermudanOption(exerciseDates, notionals, strikes, BermudanOption.ExerciseMethod.ESTIMATE_COND_EXPECTATION);
double valueOfBermudanOptionLowerBound = myBermudanOptionLowerBound.getValue(model);
BermudanOption myBermudanOptionUpperBound = new BermudanOption(exerciseDates, notionals, strikes, BermudanOption.ExerciseMethod.UPPER_BOUND_METHOD);
double valueOfBermudanOptionUpperBound = myBermudanOptionUpperBound.getValue(model);
System.out.println("Value of Asian Option is \t" + valueOfAsianOption);
System.out.println("Value of European Option is \t" + valueOfEuropeanOption);
System.out.println("Value of Bermudan Option is \t" + "(" + valueOfBermudanOptionLowerBound + "," + valueOfBermudanOptionUpperBound + ")");
assertTrue(valueOfAsianOption < valueOfEuropeanOption);
assertTrue(valueOfBermudanOptionLowerBound < valueOfBermudanOptionUpperBound);
assertTrue(valueOfBermudanOptionUpperBound < valueOfEuropeanOption);
}
/**
* Evaluates 100000 Asian options in 10 parallel threads (each valuing 10000 options)
*
* @throws InterruptedException
*/
public void testMultiThreaddedValuation() throws InterruptedException {
final double[] averagingPoints = { 0.5, 1.0, 1.5, 2.0, 2.5, 2.5, 3.0, 3.0 , 3.0, 3.5, 4.5, 5.0 };
final double maturity = 5.0;
final double strike = 1.07;
int numberOfThreads = 10;
Thread[] myThreads = new Thread[numberOfThreads];
for(int k=0; k<myThreads.length; k++) {
final int threadNummer = k;
// Create a runnable - piece of code which can be run in parallel.
Runnable myRunnable = new Runnable() {
@Override
public void run() {
try {
for(int i=0;i<10000; i++) {
AsianOption myAsianOption = new AsianOption(maturity,strike, new TimeDiscretization(averagingPoints));
double valueOfAsianOption = myAsianOption.getValue(model);
System.out.println("Thread " + threadNummer + ": Value of Asian Option " + i + " is " + valueOfAsianOption);
}
} catch (CalculationException e) {
}
}
};
// Create a thread (will run asynchronously)
myThreads[k] = new Thread(myRunnable);
myThreads[k].start();
}
// Wait for all threads to complete
for(int i=0; i<myThreads.length; i++) {
myThreads[i].join();
}
// Threads are completed at this point
}
@Test
public void testEuropeanCallDelta() throws CalculationException
{
MonteCarloBlackScholesModel blackScholesModel = (MonteCarloBlackScholesModel)model;
// Java DecimalFormat for our output format
DecimalFormat numberFormatStrike = new DecimalFormat(" 0.00 ");
DecimalFormat numberFormatValue = new DecimalFormat(" 0.00E00");
DecimalFormat numberFormatDeviation = new DecimalFormat(" 0.00E00; -0.00E00");
double initialValue = blackScholesModel.getAssetValue(0.0, 0).get(0);
double riskFreeRate = blackScholesModel.getRiskFreeRate();
double volatility = blackScholesModel.getVolatility();
// Test options with different strike
System.out.println("Calculation of Option Delta (European options with maturity 1.0):");
System.out.println(" Strike \t MC Fin.Diff.\t MC Pathwise\t MC Likelihood\t Analytic \t Diff MC-FD \t Diff MC-PW \t Diff MC-LR");
double optionMaturity = 1.0;
for(double optionStrike = 0.60; optionStrike < 1.50; optionStrike += 0.05) {
// Create a product
EuropeanOption callOption = new EuropeanOption(optionMaturity, optionStrike);
// Value the product with Monte Carlo
double shift = initialValue * 1E-6;
Map<String,Object> dataUpShift = new HashMap<String,Object>();
dataUpShift.put("initialValue", initialValue + shift);
double valueUpShift = (Double)(callOption.getValuesForModifiedData(blackScholesModel, dataUpShift).get("value"));
Map<String,Object> dataDownShift = new HashMap<String,Object>();
dataDownShift.put("initialValue", initialValue - shift);
double valueDownShift = (Double)(callOption.getValuesForModifiedData(blackScholesModel, dataDownShift).get("value"));
// Calculate the finite difference of the monte-carlo value
double delta = (valueUpShift-valueDownShift) / ( 2 * shift );
// Calculate the finite difference of the analytic value
double deltaFiniteDiffAnalytic =
(
net.finmath.functions.AnalyticFormulas.blackScholesOptionValue(initialValue+shift, riskFreeRate, volatility, optionMaturity, optionStrike)
- net.finmath.functions.AnalyticFormulas.blackScholesOptionValue(initialValue-shift, riskFreeRate, volatility, optionMaturity, optionStrike)
)/(2*shift);
// Calculate the analytic value
double deltaAnalytic = net.finmath.functions.AnalyticFormulas.blackScholesOptionDelta(initialValue, riskFreeRate, volatility, optionMaturity, optionStrike);
// Print result
System.out.println(numberFormatStrike.format(optionStrike) +
"\t" + numberFormatValue.format(delta) +
"\t" + numberFormatValue.format(deltaAnalytic) +
"\t" + numberFormatDeviation.format(delta-deltaAnalytic));
assertTrue(Math.abs(delta-deltaAnalytic) < 1E-02);
}
System.out.println("__________________________________________________________________________________________\n");
}
@Test
public void testEuropeanCallVega() throws CalculationException
{
MonteCarloBlackScholesModel blackScholesModel = (MonteCarloBlackScholesModel)model;
// Java DecimalFormat for our output format
DecimalFormat numberFormatStrike = new DecimalFormat(" 0.00 ");
DecimalFormat numberFormatValue = new DecimalFormat(" 0.00E00");
DecimalFormat numberFormatDeviation = new DecimalFormat(" 0.00E00; -0.00E00");
double initialValue = blackScholesModel.getAssetValue(0.0, 0).get(0);
double riskFreeRate = blackScholesModel.getRiskFreeRate();
double volatility = blackScholesModel.getVolatility();
// Test options with different strike
System.out.println("Calculation of Option Vega (European options with maturity 1.0):");
System.out.println(" Strike \t MC Fin.Diff.\t Analytic \t Diff MC-FD");
double optionMaturity = 5.0;
for(double optionStrike = 0.60; optionStrike < 1.50; optionStrike += 0.05) {
// Create a product
EuropeanOption callOption = new EuropeanOption(optionMaturity, optionStrike);
// Value the product with Monte Carlo
double shift = volatility * 1E-6;
Map<String,Object> dataUpShift = new HashMap<String,Object>();
dataUpShift.put("volatility", volatility + shift);
double valueUpShift = (Double)(callOption.getValuesForModifiedData(blackScholesModel, dataUpShift).get("value"));
Map<String,Object> dataDownShift = new HashMap<String,Object>();
dataDownShift.put("volatility", volatility - shift);
double valueDownShift = (Double)(callOption.getValuesForModifiedData(blackScholesModel, dataDownShift).get("value"));
// Calculate the finite difference of the monte-carlo value
double vega = (valueUpShift-valueDownShift) / ( 2 * shift );
// Calculate the finite difference of the analytic value
double vegaFiniteDiffAnalytic =
(
net.finmath.functions.AnalyticFormulas.blackScholesOptionValue(initialValue+shift, riskFreeRate, volatility, optionMaturity, optionStrike)
- net.finmath.functions.AnalyticFormulas.blackScholesOptionValue(initialValue-shift, riskFreeRate, volatility, optionMaturity, optionStrike)
)/(2*shift);
// Calculate the analytic value
double vegaAnalytic = net.finmath.functions.AnalyticFormulas.blackScholesOptionVega(initialValue, riskFreeRate, volatility, optionMaturity, optionStrike);
// Print result
System.out.println(numberFormatStrike.format(optionStrike) +
"\t" + numberFormatValue.format(vega) +
"\t" + numberFormatValue.format(vegaAnalytic) +
"\t" + numberFormatDeviation.format(vega-vegaAnalytic));
assertTrue(Math.abs(vega-vegaAnalytic) < 1E-01);
}
System.out.println("__________________________________________________________________________________________\n");
}
}
|
package lombok.ast.grammar;
import lombok.ast.Node;
import org.parboiled.BaseParser;
import org.parboiled.Parboiled;
import org.parboiled.Rule;
public class StructuresParser extends BaseParser<Node, StructuresAction> {
private final ParserGroup group;
public StructuresParser(ParserGroup group) {
super(Parboiled.createActions(StructuresAction.class));
this.group = group;
}
public Rule classBody() {
return enforcedSequence(
ch('{'), group.basics.optWS(), ch('}'), group.basics.optWS());
}
public Rule methodArguments() {
return enforcedSequence(
ch('('),
group.basics.optWS(),
optional(sequence(
group.literals.anyLiteral(),
zeroOrMore(sequence(
ch(','),
group.basics.optWS(),
group.operators.anyExpression())))),
ch(')'),
group.basics.optWS());
}
}
|
package com.facebook.stetho.inspector.elements.android.window;
import android.support.annotation.NonNull;
import android.view.View;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
class WindowRootViewCompactV19Impl extends WindowRootViewCompat {
private List<View> mRootViews;
WindowRootViewCompactV19Impl() {
try {
Class wmClz = Class.forName("android.view.WindowManagerGlobal");
Method getInstanceMethod = wmClz.getDeclaredMethod("getInstance");
Object managerGlobal = getInstanceMethod.invoke(wmClz);
Field mViewsField = wmClz.getDeclaredField("mViews");
mViewsField.setAccessible(true);
mRootViews = (List<View>) mViewsField.get(managerGlobal);
mViewsField.setAccessible(false);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
@NonNull
@Override
public List<View> getRootViews() {
return Collections.unmodifiableList(mRootViews);
}
}
|
package org.codehaus.groovy.runtime;
import groovy.lang.Closure;
import groovy.lang.GroovyInterceptable;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyRuntimeException;
import groovy.lang.MetaClass;
import groovy.lang.MetaClassRegistry;
import groovy.lang.MissingMethodException;
import java.util.Map;
/**
* A helper class to invoke methods or extract properties on arbitrary Java objects dynamically
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @version $Revision$
*/
public class Invoker {
protected static final Object[] EMPTY_ARGUMENTS = {
};
protected static final Class[] EMPTY_TYPES = {
};
public MetaClassRegistry getMetaRegistry() {
return metaRegistry;
}
private MetaClassRegistry metaRegistry = new MetaClassRegistry();
public MetaClass getMetaClass(Object object) {
return metaRegistry.getMetaClass(object.getClass());
}
/**
* Invokes the given method on the object.
*
* @param object
* @param methodName
* @param arguments
* @return
*/
public Object invokeMethod(Object object, String methodName, Object arguments) {
/*
System
.out
.println(
"Invoker - Invoking method on object: "
+ object
+ " method: "
+ methodName
+ " arguments: "
+ InvokerHelper.toString(arguments));
*/
if (object == null) {
object = NullObject.getNullObject();
//throw new NullPointerException("Cannot invoke method " + methodName + "() on null object");
}
// if the object is a Class, call a static method from that class
if (object instanceof Class) {
Class theClass = (Class) object;
MetaClass metaClass = metaRegistry.getMetaClass(theClass);
return metaClass.invokeStaticMethod(object, methodName, asArray(arguments));
}
else // it's an instance
{
// if it's not an object implementing GroovyObject (thus not builder, nor a closure)
if (!(object instanceof GroovyObject)) {
return invokePojoMethod(object, methodName, arguments);
}
// it's an object implementing GroovyObject
else {
return invokePogoMethod(object, methodName, arguments);
}
}
}
private Object invokePojoMethod(Object object, String methodName, Object arguments) {
Class theClass = object.getClass();
MetaClass metaClass = metaRegistry.getMetaClass(theClass);
return metaClass.invokeMethod(object, methodName, asArray(arguments));
}
private Object invokePogoMethod(Object object, String methodName, Object arguments) {
GroovyObject groovy = (GroovyObject) object;
try {
// if it's a pure interceptable object (even intercepting toString(), clone(), ...)
if (groovy instanceof GroovyInterceptable) {
return groovy.invokeMethod(methodName, asArray(arguments));
}
//else try a statically typed method or a GDK method
return groovy.getMetaClass().invokeMethod(object, methodName, asArray(arguments));
} catch (MissingMethodException e) {
if (e.getMethod().equals(methodName) && object.getClass() == e.getType()) {
// in case there's nothing else, invoke the object's own invokeMethod()
return groovy.invokeMethod(methodName, asArray(arguments));
}
throw e;
}
}
public Object invokeSuperMethod(Object object, String methodName, Object arguments) {
if (object == null) {
throw new NullPointerException("Cannot invoke method " + methodName + "() on null object");
}
Class theClass = object.getClass();
MetaClass metaClass = metaRegistry.getMetaClass(theClass.getSuperclass());
return metaClass.invokeMethod(object, methodName, asArray(arguments));
}
public Object invokeStaticMethod(Class type, String method, Object arguments) {
MetaClass metaClass = metaRegistry.getMetaClass(type);
return metaClass.invokeStaticMethod(type, method, asArray(arguments));
}
public Object invokeConstructorOf(Class type, Object arguments) {
MetaClass metaClass = metaRegistry.getMetaClass(type);
return metaClass.invokeConstructor(asArray(arguments));
}
/**
* Converts the given object into an array; if its an array then just
* cast otherwise wrap it in an array
*/
public Object[] asArray(Object arguments) {
if (arguments == null) {
return EMPTY_ARGUMENTS;
}
if (arguments instanceof Object[]) {
return (Object[]) arguments;
}
return new Object[]{arguments};
}
/**
* Looks up the given property of the given object
*/
public Object getProperty(Object object, String property) {
if (object == null) {
throw new NullPointerException("Cannot get property: " + property + " on null object");
}
if (object instanceof GroovyObject) {
GroovyObject pogo = (GroovyObject) object;
return pogo.getProperty(property);
}
if (object instanceof Map) {
Map map = (Map) object;
return map.get(property);
}
if (object instanceof Class) {
Class c = (Class) object;
return metaRegistry.getMetaClass(c).getProperty(object, property);
}
return metaRegistry.getMetaClass(object.getClass()).getProperty(object, property);
}
/**
* Sets the property on the given object
*/
public void setProperty(Object object, String property, Object newValue) {
if (object == null) {
throw new GroovyRuntimeException("Cannot set property on null object");
}
if (object instanceof GroovyObject) {
GroovyObject pogo = (GroovyObject) object;
pogo.setProperty(property, newValue);
}
else if (object instanceof Map) {
Map map = (Map) object;
map.put(property, newValue);
}
else {
if (object instanceof Class)
metaRegistry.getMetaClass((Class) object).setProperty((Class) object, property, newValue);
else
metaRegistry.getMetaClass(object.getClass()).setProperty(object, property, newValue);
}
}
/**
* Looks up the given attribute (field) on the given object
*/
public Object getAttribute(Object object, String attribute) {
if (object == null) {
throw new NullPointerException("Cannot get attribute: " + attribute + " on null object");
/**
} else if (object instanceof GroovyObject) {
GroovyObject pogo = (GroovyObject) object;
return pogo.getAttribute(attribute);
} else if (object instanceof Map) {
Map map = (Map) object;
return map.get(attribute);
*/
}
else {
if (object instanceof Class) {
return metaRegistry.getMetaClass((Class) object).getAttribute(object, attribute);
} else if (object instanceof GroovyObject) {
return ((GroovyObject)object).getMetaClass().getAttribute(object, attribute);
} else {
return metaRegistry.getMetaClass(object.getClass()).getAttribute(object, attribute);
}
}
}
/**
* Sets the given attribute (field) on the given object
*/
public void setAttribute(Object object, String attribute, Object newValue) {
if (object == null) {
throw new GroovyRuntimeException("Cannot set attribute on null object");
/*
} else if (object instanceof GroovyObject) {
GroovyObject pogo = (GroovyObject) object;
pogo.setProperty(attribute, newValue);
} else if (object instanceof Map) {
Map map = (Map) object;
map.put(attribute, newValue);
*/
}
else {
if (object instanceof Class) {
metaRegistry.getMetaClass((Class) object).setAttribute(object, attribute, newValue);
} else if (object instanceof GroovyObject) {
((GroovyObject)object).getMetaClass().setAttribute(object, attribute, newValue);
} else {
metaRegistry.getMetaClass(object.getClass()).setAttribute(object, attribute, newValue);
}
}
}
/**
* Returns the method pointer for the given object name
*/
public Closure getMethodPointer(Object object, String methodName) {
if (object == null) {
throw new NullPointerException("Cannot access method pointer for '" + methodName + "' on null object");
}
return MetaClassHelper.getMethodPointer(object, methodName);
}
public void removeMetaClass(Class clazz) {
getMetaRegistry().removeMetaClass(clazz);
}
}
|
package uk.ac.bolton.archimate.editor.diagram.editparts.diagram;
import java.util.List;
import org.eclipse.draw2d.ChopboxAnchor;
import org.eclipse.draw2d.ConnectionAnchor;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.SnapToHelper;
import org.eclipse.gef.editpolicies.SnapFeedbackPolicy;
import org.eclipse.gef.requests.LocationRequest;
import org.eclipse.gef.tools.DirectEditManager;
import uk.ac.bolton.archimate.editor.diagram.directedit.LabelCellEditorLocator;
import uk.ac.bolton.archimate.editor.diagram.directedit.LabelDirectEditManager;
import uk.ac.bolton.archimate.editor.diagram.editparts.AbstractConnectedEditPart;
import uk.ac.bolton.archimate.editor.diagram.editparts.IColoredEditPart;
import uk.ac.bolton.archimate.editor.diagram.editparts.ITextEditPart;
import uk.ac.bolton.archimate.editor.diagram.editparts.SnapEditPartAdapter;
import uk.ac.bolton.archimate.editor.diagram.figures.IContainerFigure;
import uk.ac.bolton.archimate.editor.diagram.figures.IDiagramModelObjectFigure;
import uk.ac.bolton.archimate.editor.diagram.figures.IEditableLabelFigure;
import uk.ac.bolton.archimate.editor.diagram.figures.diagram.GroupFigure;
import uk.ac.bolton.archimate.editor.diagram.policies.BasicContainerEditPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.ContainerHighlightEditPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.DiagramConnectionPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.DiagramLayoutPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.GroupContainerComponentEditPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.PartDirectEditTitlePolicy;
import uk.ac.bolton.archimate.editor.ui.ViewManager;
import uk.ac.bolton.archimate.model.IDiagramModelContainer;
import uk.ac.bolton.archimate.model.IDiagramModelObject;
/**
* Group Edit Part
*
* @author Phillip Beauvoir
*/
public class GroupEditPart extends AbstractConnectedEditPart
implements IColoredEditPart, ITextEditPart {
private ConnectionAnchor fAnchor;
private DirectEditManager fManager;
@Override
protected List<?> getModelChildren() {
return ((IDiagramModelContainer)getModel()).getChildren();
}
@Override
protected void createEditPolicies() {
// Allow parts to be connected
installEditPolicy(EditPolicy.GRAPHICAL_NODE_ROLE, new DiagramConnectionPolicy());
// Add a policy to handle directly editing the Parts (for example, directly renaming a part)
installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE, new PartDirectEditTitlePolicy());
// Add a policy to handle editing the Parts (for example, deleting a part)
installEditPolicy(EditPolicy.COMPONENT_ROLE, new GroupContainerComponentEditPolicy());
// Install a custom layout policy that handles dragging things around and creating new objects
installEditPolicy(EditPolicy.LAYOUT_ROLE, new DiagramLayoutPolicy());
// Orphaning
installEditPolicy(EditPolicy.CONTAINER_ROLE, new BasicContainerEditPolicy());
// Snap to Geometry feedback
installEditPolicy("Snap Feedback", new SnapFeedbackPolicy()); //$NON-NLS-1$
// Selection Feedback
installEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE, new ContainerHighlightEditPolicy());
}
@Override
protected IFigure createFigure() {
GroupFigure figure = new GroupFigure((IDiagramModelObject)getModel());
return figure;
}
@Override
public IFigure getContentPane() {
return ((IContainerFigure)getFigure()).getContentPane();
}
@Override
protected void refreshFigure() {
// Refresh the figure if necessary
((IDiagramModelObjectFigure)getFigure()).refreshVisuals();
}
/**
* Edit Requests are handled here
*/
@Override
public void performRequest(Request request) {
if(request.getType() == RequestConstants.REQ_DIRECT_EDIT || request.getType() == RequestConstants.REQ_OPEN) {
// Edit the label if we clicked on it
if(((IEditableLabelFigure)getFigure()).didClickLabel(((LocationRequest)request).getLocation().getCopy())) {
if(fManager == null) {
Label label = ((IEditableLabelFigure)getFigure()).getLabel();
fManager = new LabelDirectEditManager(this, new LabelCellEditorLocator(label), label);
}
fManager.show();
}
// Open Properties view
else if(request.getType() == RequestConstants.REQ_OPEN) {
ViewManager.showViewPart(ViewManager.PROPERTIES_VIEW, true);
}
}
}
@Override
protected ConnectionAnchor getConnectionAnchor() {
if(fAnchor == null) {
fAnchor = new ChopboxAnchor(getFigure());
}
return fAnchor;
}
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class adapter) {
if(adapter == SnapToHelper.class) {
return new SnapEditPartAdapter(this).getSnapToHelper();
}
return super.getAdapter(adapter);
}
}
|
package won.node.camel.processor.fixed;
import java.net.URI;
import java.util.Optional;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import won.node.camel.processor.AbstractCamelProcessor;
import won.node.camel.processor.annotation.FixedMessageReactionProcessor;
import won.node.camel.processor.general.ConnectionStateChangeBuilder;
import won.node.socket.ConnectionStateChange;
import won.protocol.message.WonMessage;
import won.protocol.message.WonMessageDirection;
import won.protocol.message.processor.camel.WonCamelConstants;
import won.protocol.model.Atom;
import won.protocol.model.Connection;
/**
* Configured to react to any message, checking whether the message caused a
* connection state change, then Compares the connection state found in the
* header of the 'in' message with the state the connection is in now and
* triggers the data derivation.
*/
@Component
@FixedMessageReactionProcessor()
public class ConnectionStateChangeReactionProcessor extends AbstractCamelProcessor {
Logger logger = LoggerFactory.getLogger(getClass());
public ConnectionStateChangeReactionProcessor() {
}
@Override
public void process(Exchange exchange) throws Exception {
Optional<Connection> con = Optional.empty();
ConnectionStateChangeBuilder stateChangeBuilder = (ConnectionStateChangeBuilder) exchange.getIn()
.getHeader(WonCamelConstants.CONNECTION_STATE_CHANGE_BUILDER_HEADER);
if (stateChangeBuilder == null) {
logger.info("no stateChangeBuilder found in exchange header, cannot check for state change");
return;
}
// first, try to find the connection uri in the header:
URI conUri = (URI) exchange.getIn().getHeader(WonCamelConstants.CONNECTION_URI_HEADER);
if (conUri == null) {
// not found. get it from the message and put it in the header
WonMessage wonMessage = (WonMessage) exchange.getIn().getHeader(WonCamelConstants.MESSAGE_HEADER);
conUri = wonMessage.getEnvelopeType() == WonMessageDirection.FROM_EXTERNAL ? wonMessage.getRecipientURI()
: wonMessage.getSenderURI();
}
if (conUri != null) {
// found a connection. Put its URI in the header and load it
con = Optional.of(connectionRepository.findOneByConnectionURI(conUri));
if (!stateChangeBuilder.canBuild()) {
stateChangeBuilder.newState(con.get().getState());
}
} else {
// found no connection. don't modify the builder
}
// only if there is enough data to make a connectionStateChange object, make it
// and pass it to the data
// derivation service.
if (stateChangeBuilder.canBuild()) {
ConnectionStateChange connectionStateChange = stateChangeBuilder.build();
if (!con.isPresent()) {
con = Optional.of(connectionRepository.findOneByConnectionURI(conUri));
}
Atom atom = atomRepository.findOneByAtomURI(con.get().getAtomURI());
if (connectionStateChange.isConnect() || connectionStateChange.isDisconnect()) {
// trigger rematch
matcherProtocolMatcherClient.atomModified(atom.getAtomURI(), null);
logger.info("matchers notified of connection state change");
} else {
logger.debug("no relevant connection state change, not notifying matchers");
}
} else {
logger.info("Could collect ConnectionStateChange information, not checking for state change");
}
}
}
|
package wicket.extensions.ajax.markup.html.autocomplete;
import wicket.RequestCycle;
import wicket.Response;
import wicket.ajax.AbstractDefaultAjaxBehavior;
import wicket.ajax.AjaxRequestTarget;
import wicket.markup.html.PackageResourceReference;
import wicket.util.string.JavascriptUtils;
/**
* @since 1.2
*
* @author Janne Hietamäki (jannehietamaki)
*/
public abstract class AbstractAutoCompleteBehavior extends AbstractDefaultAjaxBehavior
{
private static final PackageResourceReference AUTOCOMPLETE_JS = new PackageResourceReference(AutoCompleteBehavior.class, "wicket-autocomplete.js");
private static final long serialVersionUID = 1L;
protected void onRenderHeadInitContribution(Response response)
{
super.onRenderHeadInitContribution(response);
writeJsReference(response, AUTOCOMPLETE_JS);
}
protected void onComponentRendered()
{
Response response=getComponent().getResponse();
final String id = getComponent().getMarkupId();
response.write(JavascriptUtils.SCRIPT_OPEN_TAG);
response.write("new WicketAutoComplete('"+id+"','"+getCallbackUrl()+"');");
response.write(JavascriptUtils.SCRIPT_CLOSE_TAG);
}
protected void respond(AjaxRequestTarget target){
final RequestCycle requestCycle = RequestCycle.get();
final String val = requestCycle.getRequest().getParameter("q");
onRequest(val, requestCycle);
}
/**
* Callback for the ajax event generated by the javascript. This is
* where we need to generate our response.
*
* @param input
* the input entered so far
* @param requestCycle
* current request cycle
*/
protected abstract void onRequest(String input, RequestCycle requestCycle);
}
|
package org.knowm.xchange.cryptofacilities;
import java.io.IOException;
import java.math.BigDecimal;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.knowm.xchange.cryptofacilities.dto.account.CryptoFacilitiesAccounts;
import org.knowm.xchange.cryptofacilities.dto.marketdata.CryptoFacilitiesCancel;
import org.knowm.xchange.cryptofacilities.dto.marketdata.CryptoFacilitiesFills;
import org.knowm.xchange.cryptofacilities.dto.marketdata.CryptoFacilitiesOpenOrders;
import org.knowm.xchange.cryptofacilities.dto.marketdata.CryptoFacilitiesOpenPositions;
import org.knowm.xchange.cryptofacilities.dto.marketdata.CryptoFacilitiesOrder;
import si.mazi.rescu.ParamsDigest;
import si.mazi.rescu.SynchronizedValueFactory;
/** @author Jean-Christophe Laruelle */
@Path("/api/v3")
@Produces(MediaType.APPLICATION_JSON)
public interface CryptoFacilitiesAuthenticated extends CryptoFacilities {
@GET
@Path("/accounts")
CryptoFacilitiesAccounts accounts(
@HeaderParam("APIKey") String apiKey,
@HeaderParam("Authent") ParamsDigest signer,
@HeaderParam("Nonce") SynchronizedValueFactory<Long> nonce)
throws IOException;
@GET
@Path("/sendorder")
CryptoFacilitiesOrder sendOrder(
@HeaderParam("APIKey") String apiKey,
@HeaderParam("Authent") ParamsDigest signer,
@HeaderParam("Nonce") SynchronizedValueFactory<Long> nonce,
@QueryParam("orderType") String orderType,
@QueryParam("symbol") String symbol,
@QueryParam("side") String side,
@QueryParam("size") BigDecimal size,
@QueryParam("limitPrice") BigDecimal limitPrice)
throws IOException;
@GET
@Path("/cancelorder")
CryptoFacilitiesCancel cancelOrder(
@HeaderParam("APIKey") String apiKey,
@HeaderParam("Authent") ParamsDigest signer,
@HeaderParam("Nonce") SynchronizedValueFactory<Long> nonce,
@QueryParam("order_id") String order_id)
throws IOException;
@GET
@Path("/openorders")
CryptoFacilitiesOpenOrders openOrders(
@HeaderParam("APIKey") String apiKey,
@HeaderParam("Authent") ParamsDigest signer,
@HeaderParam("Nonce") SynchronizedValueFactory<Long> nonce)
throws IOException;
@GET
@Path("/fills")
CryptoFacilitiesFills fills(
@HeaderParam("APIKey") String apiKey,
@HeaderParam("Authent") ParamsDigest signer,
@HeaderParam("Nonce") SynchronizedValueFactory<Long> nonce)
throws IOException;
@GET
@Path("/openpositions")
CryptoFacilitiesOpenPositions openPositions(
@HeaderParam("APIKey") String apiKey,
@HeaderParam("Authent") ParamsDigest signer,
@HeaderParam("Nonce") SynchronizedValueFactory<Long> nonce)
throws IOException;
}
|
package org.jfree.chart.block;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.text.TextBlock;
import org.jfree.chart.text.TextBlockAnchor;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.RectangleAnchor;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.chart.util.Size2D;
/**
* A block containing a label.
*/
public class LabelBlock extends AbstractBlock
implements Block, PublicCloneable {
/** For serialization. */
static final long serialVersionUID = 249626098864178017L;
/**
* The text for the label - retained in case the label needs
* regenerating (for example, to change the font).
*/
private String text;
/** The label. */
private TextBlock label;
/** The font. */
private Font font;
/** The tool tip text (can be <code>null</code>). */
private String toolTipText;
/** The URL text (can be <code>null</code>). */
private String urlText;
/** The default color. */
public static final Paint DEFAULT_PAINT = Color.black;
/** The paint. */
private transient Paint paint;
/**
* The content alignment point.
*
* @since 1.0.13
*/
private TextBlockAnchor contentAlignmentPoint;
/**
* The anchor point for the text.
*
* @since 1.0.13
*/
private RectangleAnchor textAnchor;
/**
* Creates a new label block.
*
* @param label the label (<code>null</code> not permitted).
*/
public LabelBlock(String label) {
this(label, new Font("Tahoma", Font.PLAIN, 10), DEFAULT_PAINT);
}
/**
* Creates a new label block.
*
* @param text the text for the label (<code>null</code> not permitted).
* @param font the font (<code>null</code> not permitted).
*/
public LabelBlock(String text, Font font) {
this(text, font, DEFAULT_PAINT);
}
/**
* Creates a new label block.
*
* @param text the text for the label (<code>null</code> not permitted).
* @param font the font (<code>null</code> not permitted).
* @param paint the paint (<code>null</code> not permitted).
*/
public LabelBlock(String text, Font font, Paint paint) {
this.text = text;
this.paint = paint;
this.label = TextUtilities.createTextBlock(text, font, this.paint);
this.font = font;
this.toolTipText = null;
this.urlText = null;
this.contentAlignmentPoint = TextBlockAnchor.CENTER;
this.textAnchor = RectangleAnchor.CENTER;
}
/**
* Returns the font.
*
* @return The font (never <code>null</code>).
*
* @see #setFont(Font)
*/
public Font getFont() {
return this.font;
}
/**
* Sets the font and regenerates the label.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getFont()
*/
public void setFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.font = font;
this.label = TextUtilities.createTextBlock(this.text, font, this.paint);
}
/**
* Returns the paint.
*
* @return The paint (never <code>null</code>).
*
* @see #setPaint(Paint)
*/
public Paint getPaint() {
return this.paint;
}
/**
* Sets the paint and regenerates the label.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getPaint()
*/
public void setPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.paint = paint;
this.label = TextUtilities.createTextBlock(this.text, this.font,
this.paint);
}
/**
* Returns the tool tip text.
*
* @return The tool tip text (possibly <code>null</code>).
*
* @see #setToolTipText(String)
*/
public String getToolTipText() {
return this.toolTipText;
}
/**
* Sets the tool tip text.
*
* @param text the text (<code>null</code> permitted).
*
* @see #getToolTipText()
*/
public void setToolTipText(String text) {
this.toolTipText = text;
}
/**
* Returns the URL text.
*
* @return The URL text (possibly <code>null</code>).
*
* @see #setURLText(String)
*/
public String getURLText() {
return this.urlText;
}
/**
* Sets the URL text.
*
* @param text the text (<code>null</code> permitted).
*
* @see #getURLText()
*/
public void setURLText(String text) {
this.urlText = text;
}
/**
* Returns the content alignment point.
*
* @return The content alignment point (never <code>null</code>).
*
* @since 1.0.13
*/
public TextBlockAnchor getContentAlignmentPoint() {
return this.contentAlignmentPoint;
}
/**
* Sets the content alignment point.
*
* @param anchor the anchor used to determine the alignment point (never
* <code>null</code>).
*
* @since 1.0.13
*/
public void setContentAlignmentPoint(TextBlockAnchor anchor) {
if (anchor == null) {
throw new IllegalArgumentException("Null 'anchor' argument.");
}
this.contentAlignmentPoint = anchor;
}
/**
* Returns the text anchor (never <code>null</code>).
*
* @return The text anchor.
*
* @since 1.0.13
*/
public RectangleAnchor getTextAnchor() {
return this.textAnchor;
}
/**
* Sets the text anchor.
*
* @param anchor the anchor (<code>null</code> not permitted).
*
* @since 1.0.13
*/
public void setTextAnchor(RectangleAnchor anchor) {
this.textAnchor = anchor;
}
/**
* Arranges the contents of the block, within the given constraints, and
* returns the block size.
*
* @param g2 the graphics device.
* @param constraint the constraint (<code>null</code> not permitted).
*
* @return The block size (in Java2D units, never <code>null</code>).
*/
public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) {
g2.setFont(this.font);
Size2D s = this.label.calculateDimensions(g2);
return new Size2D(calculateTotalWidth(s.getWidth()),
calculateTotalHeight(s.getHeight()));
}
/**
* Draws the block.
*
* @param g2 the graphics device.
* @param area the area.
*/
public void draw(Graphics2D g2, Rectangle2D area) {
draw(g2, area, null);
}
/**
* Draws the block within the specified area.
*
* @param g2 the graphics device.
* @param area the area.
* @param params ignored (<code>null</code> permitted).
*
* @return Always <code>null</code>.
*/
public Object draw(Graphics2D g2, Rectangle2D area, Object params) {
area = trimMargin(area);
drawBorder(g2, area);
area = trimBorder(area);
area = trimPadding(area);
// check if we need to collect chart entities from the container
EntityBlockParams ebp = null;
StandardEntityCollection sec = null;
Shape entityArea = null;
if (params instanceof EntityBlockParams) {
ebp = (EntityBlockParams) params;
if (ebp.getGenerateEntities()) {
sec = new StandardEntityCollection();
entityArea = (Shape) area.clone();
}
}
g2.setPaint(this.paint);
g2.setFont(this.font);
Point2D pt = RectangleAnchor.coordinates(area, this.textAnchor);
this.label.draw(g2, (float) pt.getX(), (float) pt.getY(),
this.contentAlignmentPoint);
BlockResult result = null;
if (ebp != null && sec != null) {
if (this.toolTipText != null || this.urlText != null) {
ChartEntity entity = new ChartEntity(entityArea,
this.toolTipText, this.urlText);
sec.add(entity);
result = new BlockResult();
result.setEntityCollection(sec);
}
}
return result;
}
/**
* Tests this <code>LabelBlock</code> for equality with an arbitrary
* object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (!(obj instanceof LabelBlock)) {
return false;
}
LabelBlock that = (LabelBlock) obj;
if (!this.text.equals(that.text)) {
return false;
}
if (!this.font.equals(that.font)) {
return false;
}
if (!PaintUtilities.equal(this.paint, that.paint)) {
return false;
}
if (!ObjectUtilities.equal(this.toolTipText, that.toolTipText)) {
return false;
}
if (!ObjectUtilities.equal(this.urlText, that.urlText)) {
return false;
}
if (!this.contentAlignmentPoint.equals(that.contentAlignmentPoint)) {
return false;
}
if (!this.textAnchor.equals(that.textAnchor)) {
return false;
}
return super.equals(obj);
}
/**
* Returns a clone of this <code>LabelBlock</code> instance.
*
* @return A clone.
*
* @throws CloneNotSupportedException if there is a problem cloning.
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.paint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.paint = SerialUtilities.readPaint(stream);
}
}
|
package jcavern;
import jcavern.ui.*;
import jcavern.thing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Enumeration;
/**
* KeyboardCommandListener receives keypress events, tracks input modes, and causes the Player
* to do the appropriate actions.
*
* @author Bill Walker
* @version $Id$
*/
public class KeyboardCommandListener extends KeyAdapter
{
/** * A model of the game world */
private World mWorld;
/** * The representation of the player */
private Player mPlayer;
/**
* The current mode of the KeyboardCommandListener.
* Should be one of the symbolic constants defined in this class.
*/
private int mCurrentMode;
/** * In normal command mode (movement, etc) */
private static final int NORMAL_MODE = 1;
/** * In ranged attack mode */
private static final int RANGED_ATTACK_MODE = 3;
/** * In castle visiting mode */
private static final int CASTLE_MODE = 4;
/** * In start using mode */
private static final int USE_MODE = 5;
/** * In start using mode */
private static final int UNUSE_MODE = 6;
/**
* Creates a new KeyboardCommandListener for the given world and player.
*
* @param aWorld the World in which the player is playing
* @param aPlayer the Player being controlled from the keyboard
*/
public KeyboardCommandListener(World aWorld, Player aPlayer)
{
mWorld = aWorld;
mPlayer = aPlayer;
mCurrentMode = NORMAL_MODE;
}
/**
* Returns a direction code for a direction key
*
* @param e a non-null KeyEvent
* @return a direction code from the Location class
*/
private int parseDirectionKey(KeyEvent e)
{
switch (e.getKeyChar())
{
case 'q' : return Location.NORTHWEST;
case 'w' : return Location.NORTH;
case 'e' : return Location.NORTHEAST;
case 'a' : return Location.WEST;
case 'd' : return Location.EAST;
case 'z' : return Location.SOUTHWEST;
case 'x' : return Location.SOUTH;
case 'c' : return Location.SOUTHEAST;
}
throw new IllegalArgumentException("not a movement key!");
}
/**
* Handles keyboard commands.
*
* @param e a non-null KeyEvent
*/
public void keyTyped(KeyEvent e)
{
if (mCurrentMode == NORMAL_MODE)
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.TURN_START));
}
try
{
switch (mCurrentMode)
{
case NORMAL_MODE: keyTypedNormalMode(e); break;
case CASTLE_MODE: keyTypedCastleMode(e); mCurrentMode = NORMAL_MODE; break;
case RANGED_ATTACK_MODE: keyTypedRangedAttackMode(e); mCurrentMode = NORMAL_MODE; break;
case USE_MODE: keyTypedUseMode(e); mCurrentMode = NORMAL_MODE; break;
case UNUSE_MODE: keyTypedUnuseMode(e); mCurrentMode = NORMAL_MODE; break;
}
// and now, the monsters get a turn
if (mCurrentMode == NORMAL_MODE)
{
mWorld.doTurn();
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.TURN_STOP));
}
}
catch(JCavernInternalError jcie)
{
System.out.println("internal error " + jcie);
}
}
/**
* Handles keyboard commands when in normal mode.
*
* @param e a non-null KeyEvent
* @exception JCavernInternalError trouble doing normal mode actions
*/
private void keyTypedNormalMode(KeyEvent e) throws JCavernInternalError
{
switch (e.getKeyChar())
{
// movement commands
case 'q' :
case 'w' :
case 'e' :
case 'a' :
case 'd' :
case 'z' :
case 'x' :
case 'c' :
doMove(parseDirectionKey(e));
break;
case 'b' :
mCurrentMode = RANGED_ATTACK_MODE;
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "ranged attack, direction?"));
break;
case 'v' :
if (mPlayer.getCastle() != null)
{
mCurrentMode = CASTLE_MODE;
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "visiting Castle, command? (q, a, A)"));
}
else
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "no castle to visit"));
}
break;
case '.' :
//mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "sit"));
break;
case 'o' :
doOpen();
break;
case 'u' :
mCurrentMode = USE_MODE;
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "start using which item?"));
break;
case 'U' :
mCurrentMode = UNUSE_MODE;
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "stop using which item?"));
break;
default :
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.ERROR_MESSAGE, "unknown command"));
}
}
/**
* Handles keyboard commands when in castle mode.
*
* @param e a non-null KeyEvent
* @exception JCavernInternalError trouble doing castle actions
*/
private void keyTypedCastleMode(KeyEvent e) throws JCavernInternalError
{
switch (e.getKeyChar())
{
case 'q' :
doEndMission();
break;
case 'a' :
doBuyArrows(1);
break;
case 'A' :
doBuyArrows(10);
break;
default :
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "Unknown castle visit command"));
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "q = quit mission, a = buy an arrow, A = buy 10 arrows"));
}
}
/**
* Handles keyboard commands when in sword mode.
*
* @param e a non-null KeyEvent
* @exception JCavernInternalError trouble doing sword attack
*/
private void keyTypedSwordMode(KeyEvent e) throws JCavernInternalError
{
switch (e.getKeyChar())
{
// direction keys
case 'q' :
case 'w' :
case 'e' :
case 'a' :
case 'd' :
case 'z' :
case 'x' :
case 'c' :
doAttack(parseDirectionKey(e));
break;
default :
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "Unknown attack direction"));
}
}
/**
* Handles keyboard commands when in ranged attack mode.
*
* @param e a non-null KeyEvent
* @exception JCavernInternalError trouble doing ranged attack
*/
private void keyTypedRangedAttackMode(KeyEvent e) throws JCavernInternalError
{
switch (e.getKeyChar())
{
// direction keys
case 'q' :
case 'w' :
case 'e' :
case 'a' :
case 'd' :
case 'z' :
case 'x' :
case 'c' : doRangedAttack(parseDirectionKey(e)); break;
default : mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "Unknown attack direction"));
}
}
/**
* Handles keyboard commands when managing Treasure items.
*
* @param e a non-null KeyEvent
* @exception JCavernInternalError trouble managing treasure items
*/
private void keyTypedUseMode(KeyEvent e) throws JCavernInternalError
{
switch (e.getKeyChar())
{
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' : doUse(Character.getNumericValue(e.getKeyChar()));
}
}
/**
* Handles keyboard commands when managing Treasure items.
*
* @param e a non-null KeyEvent
* @exception JCavernInternalError trouble managing treasure items
*/
private void keyTypedUnuseMode(KeyEvent e) throws JCavernInternalError
{
switch (e.getKeyChar())
{
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' : doUnuse(Character.getNumericValue(e.getKeyChar()));
}
}
/**
* Causes the player to start using a Treasure
*
* @param anIndex which unused Treasure to start using
* @exception JCavernInternalError could not use treasure
*/
private void doUse(int anIndex) throws JCavernInternalError
{
try
{
mPlayer.getUnusedTreasureAt(anIndex).startUseBy(mPlayer, mWorld);
}
catch (IllegalArgumentException iae)
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "There's no item " + anIndex + " to use!"));
}
}
/**
* Causes the player to stop using a Treasure
*
* @param anIndex which in used Treasure to stop using
*/
private void doUnuse(int anIndex)
{
try
{
mPlayer.getInUseTreasureAt(anIndex).stopUseBy(mPlayer, mWorld);
}
catch (IllegalArgumentException iae)
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "There's no item " + anIndex + " to stop using!"));
}
}
/**
* Causes the player to end the current mission
*
* @exception JCavernInternalError could not end the mission
*/
private void doEndMission() throws JCavernInternalError
{
if (mPlayer.getMission().getCompleted())
{
mWorld.eventHappened(WorldEvent.missionEnd(mWorld.getLocation(mPlayer), mPlayer, "Congratulations, you completed your mission!"));
}
else
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "Sorry, " + mPlayer.getName() + ", you have not completed your mission"));
}
}
/**
* Causes the player to make a ranged attack in the given direction
*
* @param direction in which direction to attack
* @exception JCavernInternalError could not attack
*/
private void doRangedAttack(int direction) throws JCavernInternalError
{
if (mPlayer.getArrows() > 0)
{
try
{
mPlayer.rangedAttack(mWorld, direction);
}
catch(NonCombatantException nce)
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "you can't attack that!"));
}
catch(IllegalLocationException ile)
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "you shot arrow of the edge of the world!"));
}
}
else
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "you has no more arrows!"));
}
mCurrentMode = NORMAL_MODE;
}
/**
* Causes the player to make an attack in the given direction
*
* @param direction in which direction to attack
* @exception JCavernInternalError could not attack
*/
private void doAttack(int direction) throws JCavernInternalError
{
try
{
mPlayer.attack(mWorld, direction);
}
catch(IllegalLocationException nce)
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "you can't attack off the edge of the world!"));
}
catch(EmptyLocationException nce)
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "you have nothing to attack!"));
}
catch(NonCombatantException nce)
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "you can't attack that!"));
}
mCurrentMode = NORMAL_MODE;
}
/**
* Causes the player to open an adjacent TreasureChest.
*
* @exception JCavernInternalError could not find adjacent TreasureChest
*/
private void doOpen() throws JCavernInternalError
{
try
{
TreasureChest aChest = (TreasureChest) mWorld.getNeighboring(mWorld.getLocation(mPlayer), new TreasureChest(null, 0));
mWorld.remove(aChest);
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "you found " + aChest));
if (aChest.getGold() > 0)
{
mPlayer.receiveGold(aChest.getGold());
}
if (aChest.getContents() != null)
{
mPlayer.receiveItem(aChest.getContents());
}
}
catch(IllegalArgumentException iae)
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "you have no neighboring treasure chest to open!"));
}
}
/**
* Causes the player to buy arrows
*
* @param numberOfArrows how many arrows to buy
* @exception JCavernInternalError could not buy arrows
*/
private void doBuyArrows(int numberOfArrows) throws JCavernInternalError
{
if (mPlayer.getGold() < numberOfArrows)
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "you doesn't have " + numberOfArrows + " gold to buy arrows"));
}
else
{
mPlayer.spendGold(numberOfArrows);
mPlayer.receiveArrows(numberOfArrows);
}
}
/**
* Causes the player to move to an adjacent Location
*
* @param direction which direction to move
* @exception JCavernInternalError could not move
*/
private void doMove(int direction) throws JCavernInternalError
{
try
{
Location oldLocation = mWorld.getLocation(mPlayer);
mWorld.move(mPlayer, direction);
}
catch (ThingCollisionException tce)
{
if (tce.getMovee() instanceof Castle)
{
Castle theCastle = (Castle) tce.getMovee();
mWorld.remove(theCastle);
doMove(direction);
mPlayer.setCastle(theCastle);
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "you entered the castle"));
}
else if (tce.getMovee() instanceof Combatant)
{
doAttack(direction);
}
else if (tce.getMovee() instanceof TreasureChest)
{
doOpen();
}
else
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "you collided with " + tce.getMovee().getName()));
}
}
catch (IllegalLocationException tce)
{
mWorld.eventHappened(new WorldEvent(mPlayer, WorldEvent.INFO_MESSAGE, "you can't move off the edge of the world!"));
}
}
}
|
package com.rho.net;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.Connection;
import javax.microedition.io.SocketConnection;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.RadioInfo;
import com.rho.BBVersionSpecific;
import com.rho.RhoEmptyLogger;
import com.rho.RhoLogger;
import com.rho.RhoConf;
import com.rho.RhodesApp;
import com.rho.net.bb.BBHttpConnection;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.servicebook.ServiceBook;
public class NetworkAccess implements INetworkAccess {
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("NetworkAccess");
private static String URLsuffix = "";
private static String WIFIsuffix = "";
private static boolean networkConfigured = false;
private static boolean bes = true;
private static long m_nMaxPacketSize = 0;
void checkWAP(ServiceRecord[] records)
{
for(int i=0; i < records.length; i++)
{
//Search through all service records to find the
//valid non-Wi-Fi and non-MMS
//WAP 2.0 Gateway Service Record.
if (records[i].isValid() && !records[i].isDisabled())
{
if (records[i].getUid() != null && records[i].getUid().length() != 0)
{
if ((records[i].getUid().toLowerCase().indexOf("wifi") == -1) &&
(records[i].getUid().toLowerCase().indexOf("mms") == -1))
{
URLsuffix = ";ConnectionUID=" + records[i].getUid();
networkConfigured = true;
LOG.INFO("Found WAP2 provider. Suffix: " + URLsuffix);
break;
}
}
}
}
}
public void configure()
{
networkConfigured = false;
bes = false;
URLsuffix = "";
WIFIsuffix = "";
String strDeviceside = ";deviceside=true";
if ( com.rho.RhoConf.getInstance().getInt("no_deviceside_postfix") == 1 )
strDeviceside = "";
if (DeviceInfo.isSimulator())
{
URLsuffix = strDeviceside;
WIFIsuffix = ";interface=wifi";
networkConfigured = true;
}else
{
ServiceBook sb = ServiceBook.getSB();
if (sb != null) {
ServiceRecord[] wifis = sb.findRecordsByCid("WPTCP");
for ( int i = 0; i < wifis.length; i++ ){
if (/*srs[i].isDisabled() ||*/ !wifis[i].isValid())
continue;
WIFIsuffix = ";interface=wifi";// + strDeviceside;
//";deviceside=true;ConnectionUID=" +
//wifis[i].getUid();
LOG.TRACE("WIFI :" + WIFIsuffix );
break;
}
checkWAP(wifis);
ServiceRecord[] srs = sb.getRecords();
// search for BIS-B transport
for (int i = 0; i < srs.length; i++) {
if (srs[i].isDisabled() || !srs[i].isValid())
continue;
if (srs[i].getCid().equals("IPPP")
&& srs[i].getName().equals("IPPP for BIBS")) {
LOG.INFO("SRS: CID: " + srs[i].getCid() + " NAME: " + srs[i].getName());
URLsuffix = ";deviceside=false;ConnectionType=mds-public";
networkConfigured = true;
break;
}
}
// search for BES transport
for (int i = 0; i < srs.length; i++) {
LOG.INFO("SB: " + srs[i].getName() + ";UID: " + srs[i].getUid() +
";CID: " + srs[i].getCid() +
";APN: " + srs[i].getAPN() + ";Descr: " + srs[i].getDataSourceId() +
";Valid: " + (srs[i].isValid() ? "true" : "false") +
";Disabled: "+ (srs[i].isDisabled()? "true" : "false") );
if (srs[i].isDisabled() || !srs[i].isValid())
continue;
if (srs[i].getCid().equals("IPPP")
&& srs[i].getName().equals("Desktop")) {
URLsuffix = "";
networkConfigured = true;
bes = true;
break;
}
}
}
}
String strConfPostfix = com.rho.RhoConf.getInstance().getString("bb_connection_postfix");
if ( strConfPostfix != null && strConfPostfix.length() > 0 )
{
URLsuffix = strConfPostfix;
networkConfigured = true;
}else if (networkConfigured == false) {
URLsuffix = strDeviceside;//";deviceside=true";
networkConfigured = true;
}
LOG.INFO("Postfix: " + URLsuffix + ";Wifi: " + WIFIsuffix);
}
/*public IHttpConnection doLocalRequest(String strUrl, String strBody)
{
HttpHeaders headers = new HttpHeaders();
headers.addProperty("Content-Type", "application/x-www-form-urlencoded");
HttpConnection http = Utilities.makeConnection(strUrl, headers, strBody.getBytes());
// RhodesApplication.getInstance().postUrl(strUrl, strBody, headers);
return new BBHttpConnection(http);
}*/
public long getMaxPacketSize()
{
if ( WIFIsuffix != null && isWifiActive() )
return 0;
m_nMaxPacketSize = RhoConf.getInstance().getInt("bb_net_maxpacketsize_kb")*1024;
if ( (/*DeviceInfo.isSimulator() ||*/ URLsuffix.indexOf(";deviceside=true") < 0) && m_nMaxPacketSize == 0 )
{
//avoid 403 error on BES/BIS
m_nMaxPacketSize = 1024*250;
}
return m_nMaxPacketSize;
}
public boolean isWifiActive()
{
return BBVersionSpecific.isWifiActive();
}
public IHttpConnection connect(String url, boolean ignoreSuffixOnSim) throws IOException
{
if ( RhodesApp.getInstance().isRhodesAppUrl(url) )
{
URI uri = new URI(url);
return new RhoConnection(uri);
}
int fragment = url.indexOf('
if (-1 != fragment) {
url = url.substring(0, fragment);
}
boolean ignoreSuffix = !URI.isLocalHost(url) && ignoreSuffixOnSim && DeviceInfo.isSimulator();
HttpConnection http = (HttpConnection)baseConnect(url, ignoreSuffix );
return new BBHttpConnection(http);
}
public SocketConnection socketConnect(String strHost, int nPort) throws IOException
{
return socketConnect("socket", strHost, nPort);
}
public SocketConnection socketConnect(String proto, String strHost, int nPort) throws IOException
{
boolean ignoreSuffix = DeviceInfo.isSimulator();// && proto.equals("ssl") &&
//URLsuffix.indexOf("deviceside=true") != -1;
String strUrl = proto + "://" + strHost + ":" + Integer.toString(nPort);
return (SocketConnection)baseConnect(strUrl, ignoreSuffix);
}
private Connection doConnect(String urlArg, boolean bThrowIOException) throws IOException
{
Connection conn = null;
try
{
String url = new String(urlArg);
if (url.startsWith("https"))
url += ";EndToEndDesired;RdHTTPS";
LOG.INFO("Connect to url: " + url);
conn = Connector.open(url, Connector.READ_WRITE, true);
} catch (java.io.InterruptedIOException ioe)
{
LOG.ERROR("Connector.open InterruptedIOException", ioe );
if (conn != null)
conn.close();
conn = null;
throw ioe;
} catch (IOException ioe)
{
LOG.ERROR("Connector.open exception", ioe );
String strMsg = ioe.getMessage();
boolean bTimeout = strMsg != null && (strMsg.indexOf("timed out") >= 0 || strMsg.indexOf("Timed out") >= 0);
boolean bDNS = strMsg != null && (strMsg.equalsIgnoreCase("Error trying to resolve") || strMsg.indexOf("DNS") >= 0);
if ( bTimeout || bDNS || bThrowIOException )
{
if (conn != null)
conn.close();
conn = null;
throw ioe;
}
}catch(Exception exc)
{
throw new IOException("Could not open network connection.");
}
return conn;
}
public Connection baseConnect(String strUrl, boolean ignoreSuffix) throws IOException
{
Connection conn = null;
//Try wifi first
if ( WIFIsuffix != null && isWifiActive() )
{
conn = doConnect(strUrl + WIFIsuffix + (URLsuffix.startsWith(";ConnectionUID=")? "":URLsuffix), false);
//if ( conn == null )
// conn = doConnect(strUrl + WIFIsuffix, false);
}
if ( conn == null )
{
conn = doConnect(strUrl + URLsuffix, false);
//if ( conn == null && URLsuffix != null && URLsuffix.length() > 0 )
// conn = doConnect(strUrl, true);
}
return conn;
}
public void close() {
}
public boolean isNetworkAvailable() {
if (!(RadioInfo.getState() == RadioInfo.STATE_ON))
return false;
if ((RadioInfo.getNetworkService() & RadioInfo.NETWORK_SERVICE_DATA) == 0)
return false;
if (bes)
return true;
if (URLsuffix == null)
return false;
return networkConfigured;
}
}
|
package nl.mvdr.snake.solver;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import nl.mvdr.snake.model.Snake;
import nl.mvdr.snake.model.TurnDirection;
import nl.mvdr.snake.util.Primes;
/**
* Creates a prime snake using brute force methods.
*
* @author Martijn van de Rijdt
*/
public class LimitedBruteForceSolver implements Supplier<Snake> {
/** Comparator for increasing score values. */
private static final Comparator<Snake> SCORE_COMPARATOR = (left, right) -> Integer.compare(left.getScore(), right.getScore());
/** Maximum number of intermediate results. */
private static final int MAX_INTERMEDIATE_RESULTS = 2_000;
/** Intended length of the snake. */
private final int length;
/**
* Constructor.
*
* @param length intended length for the snake
*/
public LimitedBruteForceSolver(int length) {
super();
if (length < 2) {
throw new IllegalArgumentException("Length must be at least 2, was " + length);
}
this.length = length;
}
/** {@inheritDoc} */
@Override
public Snake get() {
// solutions are symmetrical in the first turn; just pick a direction
Snake startSnake = new Snake()
.step().get()
.step().get()
.turn(TurnDirection.LEFT);
Set<Snake> results = Collections.singleton(startSnake);
List<Integer> primeGaps = Primes.sieveGaps(length);
int stepsTaken = 2;
for (int i = 1; i < primeGaps.size(); i++) {
int stepsUntilNextTurn = primeGaps.get(i);
results = results.parallelStream()
.map(snake -> snake.step(stepsUntilNextTurn))
.filter(optional -> optional.isPresent())
.map(Optional::get)
.flatMap(snake -> Stream.of(snake.turn(TurnDirection.LEFT), snake.turn(TurnDirection.RIGHT)))
// In order to keep the data set from growing exponentially,
// only keep the first MAX_INTERMEDIATE_RESULTS snakes with the lowest scores.
// Note that this means this algorithm is not guaranteed to provide a minimal score answer!
// The result will be a local minimum.
.sorted(SCORE_COMPARATOR)
.limit(MAX_INTERMEDIATE_RESULTS)
.collect(Collectors.toSet());
stepsTaken += stepsUntilNextTurn;
System.out.println(stepsTaken + " / " + length + " steps");
}
int stepsLeft = length - stepsTaken;
// Take the final steps to create a snake of the desired total length, and find one with the lowest score
return results.parallelStream()
.map(snake -> snake.step(stepsLeft))
.filter(optional -> optional.isPresent())
.map(Optional::get)
.min(SCORE_COMPARATOR)
.orElseThrow(() -> new IllegalStateException("Failed to calculate a fitting snake."));
}
}
|
package net.sf.jaer.util.avioutput;
import java.awt.image.BufferedImage;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import java.awt.Color;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
/**
* Writes AVI file from displayed AEViewer frames, The AVI file is in RAW
* format.
*
* @author Tobi
*/
@Description("Writes AVI file AEViewer displayed OpenGL graphics")
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
public class JaerAviWriter extends AbstractAviWriter {
private boolean showTimeFactor = getBoolean("showTimeFactor", false);
private float showTimeFactorTextScale = getFloat("showTimeFactorTextScale", .2f);
private float timeExpansionFactor = 1;
public JaerAviWriter(AEChip chip) {
super(chip);
setPropertyTooltip("showTimeFactor", "Displays the realtime slowdown or speedup factor");
setPropertyTooltip("showTimeFactorTextScale", "Font size for time scaling factor");
}
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
super.filterPacket(in);
if (in.getDurationUs() > 0) {
timeExpansionFactor = in.getDurationUs() * 1e-6f * getFrameRate();
}
return in;
}
@Override
public void annotate(GLAutoDrawable drawable) {
if (showTimeFactor) {
String s = null;
if (timeExpansionFactor < 1) {
s = String.format("%.1fX slow-down", 1 / timeExpansionFactor);
} else {
s = String.format("%.1fX speed-up", timeExpansionFactor);
}
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .1f);
MultilineAnnotationTextRenderer.setScale(showTimeFactorTextScale);
MultilineAnnotationTextRenderer.setColor(Color.blue);
MultilineAnnotationTextRenderer.renderMultilineString(s);
}
if (getAviOutputStream() == null) {
return;
}
if (isWriteEnabled()) {
GL2 gl = drawable.getGL().getGL2();
BufferedImage bi = toImage(gl, drawable.getNativeSurface().getSurfaceWidth(), drawable.getNativeSurface().getSurfaceHeight());
try {
getAviOutputStream().writeFrame(bi);
if (isWriteTimecodeFile()) {
writeTimecode(chip.getAeViewer().getAePlayer().getTime());
}
incrementFramecountAndMaybeCloseOutput();
} catch (Exception e) {
log.warning("While writing AVI frame, caught exception, closing file: " + e.toString());
doCloseFile();
}
}
}
/**
* @return the showTimeFactor
*/
public boolean isShowTimeFactor() {
return showTimeFactor;
}
/**
* @param showTimeFactor the showTimeFactor to set
*/
public void setShowTimeFactor(boolean showTimeFactor) {
this.showTimeFactor = showTimeFactor;
putBoolean("showTimeFactor", showTimeFactor);
}
/**
* @return the showTimeFactorTextScale
*/
public float getShowTimeFactorTextScale() {
return showTimeFactorTextScale;
}
/**
* @param showTimeFactorTextScale the showTimeFactorTextScale to set
*/
public void setShowTimeFactorTextScale(float showTimeFactorTextScale) {
this.showTimeFactorTextScale = showTimeFactorTextScale;
putFloat("showTimeFactorTextScale", showTimeFactorTextScale);
}
}
|
package net.wurstclient.features.mods;
import net.wurstclient.compatibility.WMinecraft;
import net.wurstclient.events.listeners.UpdateListener;
@Mod.Info(description = "Automatically swims like a dolphin.",
name = "Dolphin",
tags = "AutoSwim, auto swim",
help = "Mods/Dolphin")
@Mod.Bypasses
public final class DolphinMod extends Mod implements UpdateListener
{
@Override
public void onEnable()
{
wurst.events.add(UpdateListener.class, this);
}
@Override
public void onDisable()
{
wurst.events.remove(UpdateListener.class, this);
}
@Override
public void onUpdate()
{
if(WMinecraft.getPlayer().isInWater()
&& !mc.gameSettings.keyBindSneak.pressed)
WMinecraft.getPlayer().motionY += 0.04;
}
}
|
package nl.mpi.arbil.clarin;
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.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import nl.mpi.arbil.GuiHelper;
import nl.mpi.arbil.LinorgSessionStorage;
import nl.mpi.arbil.LinorgWindowManager;
import nl.mpi.arbil.data.ImdiTreeObject;
import org.apache.xmlbeans.SchemaProperty;
import org.apache.xmlbeans.SchemaType;
import org.apache.xmlbeans.SchemaTypeSystem;
import org.apache.xmlbeans.XmlBeans;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class CmdiComponentBuilder {
private Document getDocument(File inputFile) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(false);
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document;
if (inputFile == null) {
document = documentBuilder.newDocument();
} else {
document = documentBuilder.parse(inputFile);
}
return document;
}
// private Document createDocument(File inputFile) throws ParserConfigurationException, SAXException, IOException {
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// documentBuilderFactory.setValidating(false);
// DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
// Document document = documentBuilder.newDocument();
// return document;
private void savePrettyFormatting(Document document, File outputFile) {
try {
// set up input and output
DOMSource dOMSource = new DOMSource(document);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
StreamResult xmlOutput = new StreamResult(fileOutputStream);
// configure transformer
Transformer transformer = TransformerFactory.newInstance().newTransformer();
//transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(dOMSource, xmlOutput);
xmlOutput.getOutputStream().close();
//System.out.println(xmlOutput.getWriter().toString());
} catch (IllegalArgumentException illegalArgumentException) {
GuiHelper.linorgBugCatcher.logError(illegalArgumentException);
} catch (TransformerException transformerException) {
GuiHelper.linorgBugCatcher.logError(transformerException);
} catch (TransformerFactoryConfigurationError transformerFactoryConfigurationError) {
System.out.println(transformerFactoryConfigurationError.getMessage());
} catch (FileNotFoundException notFoundException) {
GuiHelper.linorgBugCatcher.logError(notFoundException);
} catch (IOException iOException) {
GuiHelper.linorgBugCatcher.logError(iOException);
}
}
public URI insertChildComponent(ImdiTreeObject targetNode, String targetXmlPath, String cmdiComponentId) {
System.out.println("insertChildComponent: " + cmdiComponentId);
//String targetXpath = targetNode.getURI().getFragment();
//System.out.println("targetXpath: " + targetXpath);
File cmdiNodeFile = targetNode.getFile();
String nodeFragment = "";
try {
// load the schema
SchemaType schemaType = getFirstSchemaType(targetNode.getNodeTemplate().templateFile);
// load the dom
Document targetDocument = getDocument(cmdiNodeFile);
// insert the new section
try {
// printoutDocument(targetDocument);
nodeFragment = insertSectionToXpath(targetDocument, targetDocument.getFirstChild(), schemaType, targetXmlPath, cmdiComponentId);
} catch (Exception exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
// bump the history
targetNode.bumpHistory();
// save the dom
savePrettyFormatting(targetDocument, cmdiNodeFile); // note that we want to make sure that this gets saved even without changes because we have bumped the history ant there will be no file otherwise
} catch (IOException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
} catch (ParserConfigurationException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
} catch (SAXException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
// diff_match_patch diffTool= new diff_match_patch();
// diffTool.diff_main(targetXpath, targetXpath);
try {
System.out.println("nodeFragment: " + nodeFragment);
// return the child node url and path in the xml
// first strip off any fragment then add the full node fragment
return new URI(targetNode.getURI().toString().split("#")[0] + "#" + nodeFragment);
} catch (URISyntaxException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
return null;
}
}
private String insertSectionToXpath(Document targetDocument, Node documentNode, SchemaType schemaType, String targetXpath, String xsdPath) throws Exception {
System.out.println("insertSectionToXpath");
System.out.println("xsdPath: " + xsdPath);
System.out.println("targetXpath: " + targetXpath);
Node foundNode = null;
Node foundPreviousNode = null;
SchemaProperty foundProperty = null;
try {
// convert the syntax inherited from the imdi api into xpath
String tempXpath = targetXpath.replaceAll("\\.", "/:");
tempXpath = tempXpath.replaceAll("\\(", "[");
tempXpath = tempXpath.replaceAll("\\)", "]");
// tempXpath = "/CMD/Components/Session/MDGroup/Actors";
System.out.println("tempXpath: " + tempXpath);
// find the target node of the xml
documentNode = org.apache.xpath.XPathAPI.selectSingleNode(targetDocument, tempXpath);
} catch (TransformerException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
return null;
}
// at this point we have the xml node that the user acted on but next must get any additional nodes with the next section
String strippedXpath = targetXpath.replaceAll("\\(\\d+\\)", "");
System.out.println("strippedXpath: " + strippedXpath);
for (String currentPathComponent : xsdPath.split("\\.")) {
if (currentPathComponent.length() > 0) {
System.out.println("currentPathComponent: " + currentPathComponent);
//System.out.println("documentNode: " + documentNode.getChildNodes());
// get the starting point in the schema
foundProperty = null;
for (SchemaProperty schemaProperty : schemaType.getProperties()) {
String currentName = schemaProperty.getName().getLocalPart();
if (currentPathComponent.equals(currentName)) {
foundProperty = schemaProperty;
break;
}
}
if (foundProperty == null) {
throw new Exception("failed to find the path in the schema: " + currentPathComponent);
} else {
schemaType = foundProperty.getType();
System.out.println("foundProperty: " + foundProperty.getName().getLocalPart());
}
// get the starting node in the xml document
// TODO: this will not navigate to the nth child node when the xpath is provided
//if (foundNode != null) {
// // keep the last node found in the chain
if (strippedXpath.startsWith("." + currentPathComponent)) {
strippedXpath = strippedXpath.substring(currentPathComponent.length() + 1);
System.out.println("strippedXpath: " + strippedXpath);
foundPreviousNode = documentNode;
foundNode = documentNode;
} else {
foundPreviousNode = foundNode;
foundNode = null;
while (documentNode != null) {
System.out.println("documentNode: " + documentNode.getNodeName());
// System.out.println("documentNode: " + documentNode.toString());
if (currentPathComponent.equals(documentNode.getNodeName())) {
foundNode = documentNode;
documentNode = documentNode.getFirstChild();
break;
} else {
documentNode = documentNode.getNextSibling();
}
}
if (foundNode == null && foundPreviousNode == null) {
throw new Exception("failed to find the node path in the document: " + currentPathComponent);
}
}
}
}
// System.out.println("Adding marker node");
// Element currentElement = targetDocument.createElement("AddedChildNode");
// currentElement.setTextContent(xsdPath);
// foundPreviousNode.appendChild(currentElement);
System.out.println("Adding destination node");
Element childStartElement = appendNode(targetDocument, null, foundPreviousNode, foundProperty);
System.out.println("Adding destination sub nodes node");
constructXml(foundProperty.getType(), xsdPath, targetDocument, null, childStartElement);
System.out.println("Calculating the added fragment");
String nodeFragment = childStartElement.getTagName();
Node parentNode = childStartElement.getParentNode();
while (parentNode != null) {
// TODO: handle sibbling node counts
System.out.println("nodeFragment: " + nodeFragment);
nodeFragment = parentNode.getNodeName() + "." + nodeFragment;
if (parentNode.isSameNode(targetDocument.getDocumentElement())) {
break;
}
parentNode = parentNode.getParentNode();
}
nodeFragment = "." + nodeFragment;
System.out.println("nodeFragment: " + nodeFragment);
return nodeFragment;
//return childStartElement.
}
public URI createComponentFile(URI cmdiNodeFile, URI xsdFile) {
System.out.println("createComponentFile: " + cmdiNodeFile + " : " + xsdFile);
try {
Document workingDocument = getDocument(null);
readSchema(workingDocument, xsdFile);
savePrettyFormatting(workingDocument, new File(cmdiNodeFile));
} catch (IOException e) {
GuiHelper.linorgBugCatcher.logError(e);
} catch (ParserConfigurationException e) {
GuiHelper.linorgBugCatcher.logError(e);
} catch (SAXException e) {
GuiHelper.linorgBugCatcher.logError(e);
}
return cmdiNodeFile;
}
private SchemaType getFirstSchemaType(File schemaFile) {
try {
InputStream inputStream = new FileInputStream(schemaFile);
//Since we're dealing with xml schema files here the character encoding is assumed to be UTF-8
XmlOptions options = new XmlOptions();
options.setCharacterEncoding("UTF-8");
SchemaTypeSystem sts = XmlBeans.compileXsd(new XmlObject[]{XmlObject.Factory.parse(inputStream, options)}, XmlBeans.getBuiltinTypeSystem(), null);
// there can only be a single root node so we just get the first one, note that the IMDI schema specifies two (METATRANSCRIPT and VocabularyDef)
return sts.documentTypes()[0];
} catch (IOException e) {
GuiHelper.linorgBugCatcher.logError(e);
} catch (XmlException e) {
// TODO: this is not really a good place to message this so modify to throw
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Could not read the XML Schema", "Error inserting node");
GuiHelper.linorgBugCatcher.logError(e);
}
return null;
}
private void readSchema(Document workingDocument, URI xsdFile) {
File schemaFile = LinorgSessionStorage.getSingleInstance().updateCache(xsdFile.toString(), 5);
SchemaType schemaType = getFirstSchemaType(schemaFile);
constructXml(schemaType, "documentTypes", workingDocument, xsdFile.toString(), null);
}
private Element appendNode(Document workingDocument, String nameSpaceUri, Node parentElement, SchemaProperty schemaProperty) {
Element currentElement = workingDocument.createElementNS("http:
SchemaType currentSchemaType = schemaProperty.getType();
for (SchemaProperty attributesProperty : currentSchemaType.getAttributeProperties()) {
currentElement.setAttribute(attributesProperty.getName().getLocalPart(), attributesProperty.getDefaultText());
}
if (parentElement == null) {
// this is probably not the way to set these, however this will do for now (many other methods have been tested and all failed to function correctly)
currentElement.setAttribute("xmlns:xsi", "http:
currentElement.setAttribute("xsi:schemaLocation", "http:
workingDocument.appendChild(currentElement);
} else {
parentElement.appendChild(currentElement);
}
//currentElement.setTextContent(schemaProperty.getMinOccurs() + ":" + schemaProperty.getMinOccurs());
return currentElement;
}
private void constructXml(SchemaType schemaType, String pathString, Document workingDocument, String nameSpaceUri, Node parentElement) {
//System.out.println("printSchemaType " + schemaType.toString());
// for (SchemaType schemaSubType : schemaType.getAnonymousTypes()) {
// System.out.println("getAnonymousTypes:");
// constructXml(schemaSubType, pathString + ".*getAnonymousTypes*", workingDocument, parentElement);
// for (SchemaType schemaSubType : schemaType.getUnionConstituentTypes()) {
// System.out.println("getUnionConstituentTypes:");
// printSchemaType(schemaSubType);
// for (SchemaType schemaSubType : schemaType.getUnionMemberTypes()) {
// System.out.println("getUnionMemberTypes:");
// constructXml(schemaSubType, pathString + ".*getUnionMemberTypes*", workingDocument, parentElement);
// for (SchemaType schemaSubType : schemaType.getUnionSubTypes()) {
// System.out.println("getUnionSubTypes:");
// printSchemaType(schemaSubType);
//SchemaType childType =schemaType.
for (SchemaProperty schemaProperty : schemaType.getElementProperties()) {
//for (int childCounter = 0; childCounter < schemaProperty.getMinOccurs().intValue(); childCounter++) {
// if the searched element is a child node of the given node return
// its SchemaType
//if (properties[i].getName().toString().equals(element)) {
pathString = pathString + "." + schemaProperty.getName().getLocalPart();
System.out.println("Found Element: " + pathString);
SchemaType currentSchemaType = schemaProperty.getType();
// if the searched element was not a child of the given Node
// then again for each of these child nodes search recursively in
// their child nodes, in the case they are a complex type, because
// only complex types have child nodes
//currentSchemaType.getAttributeProperties();
if (schemaProperty.getMinOccurs() != BigInteger.ZERO) {
Element currentElement = appendNode(workingDocument, nameSpaceUri, parentElement, schemaProperty);
// if ((schemaProperty.getType() != null) && (!(currentSchemaType.isSimpleType()))) {
constructXml(currentSchemaType, pathString, workingDocument, nameSpaceUri, currentElement);
}
}
}
private void printoutDocument(Document workingDocument) {
try {
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer transformer = tranFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
Source src = new DOMSource(workingDocument);
Result dest = new StreamResult(System.out);
transformer.transform(src, dest);
} catch (Exception e) {
GuiHelper.linorgBugCatcher.logError(e);
}
}
public void testWalk() {
try {
//new CmdiComponentBuilder().readSchema();
Document workingDocument = getDocument(null);
//Create instance of DocumentBuilderFactory
//DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//Get the DocumentBuilder
//DocumentBuilder docBuilder = factory.newDocumentBuilder();
//Create blank DOM Document
//Document doc = docBuilder.newDocument();
//create the root element
// Element root = workingDocument.createElement("root");
// //all it to the xml tree
// workingDocument.appendChild(root);
// //create a comment
// Comment comment = workingDocument.createComment("This is comment");
// //add in the root element
// root.appendChild(comment);
// //create child element
// Element childElement = workingDocument.createElement("Child");
// //Add the atribute to the child
// childElement.setAttribute("attribute1", "The value of Attribute 1");
// root.appendChild(childElement);
readSchema(workingDocument, new URI("http://catalog.clarin.eu/ds/ComponentRegistry/rest/registry/profiles/clarin.eu:cr1:p_1264769926773/xsd"));
printoutDocument(workingDocument);
} catch (Exception e) {
GuiHelper.linorgBugCatcher.logError(e);
}
}
public static void main(String args[]) {
new CmdiComponentBuilder().testWalk();
}
}
|
package com.rnfs;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import android.util.Log;
import android.os.AsyncTask;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
public class Downloader extends AsyncTask<DownloadParams, int[], DownloadResult> {
private DownloadParams mParam;
private AtomicBoolean mAbort = new AtomicBoolean(false);
DownloadResult res;
protected DownloadResult doInBackground(DownloadParams... params) {
mParam = params[0];
res = new DownloadResult();
new Thread(new Runnable() {
public void run() {
try {
download(mParam, res);
mParam.onTaskCompleted.onTaskCompleted(res);
} catch (Exception ex) {
res.exception = ex;
mParam.onTaskCompleted.onTaskCompleted(res);
}
}
}).start();
return res;
}
private void download(DownloadParams param, DownloadResult res) throws Exception {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection)param.src.openConnection();
ReadableMapKeySetIterator iterator = param.headers.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
String value = param.headers.getString(key);
connection.setRequestProperty(key, value);
}
connection.setConnectTimeout(param.connectionTimeout);
connection.setReadTimeout(param.readTimeout);
connection.connect();
int statusCode = connection.getResponseCode();
int lengthOfFile = connection.getContentLength();
boolean isRedirect = (
statusCode != HttpURLConnection.HTTP_OK &&
(
statusCode == HttpURLConnection.HTTP_MOVED_PERM ||
statusCode == HttpURLConnection.HTTP_MOVED_TEMP ||
statusCode == 307 ||
statusCode == 308
)
);
if (isRedirect) {
String redirectURL = connection.getHeaderField("Location");
connection.disconnect();
connection = (HttpURLConnection) new URL(redirectURL).openConnection();
connection.setConnectTimeout(5000);
connection.connect();
statusCode = connection.getResponseCode();
lengthOfFile = connection.getContentLength();
}
if(statusCode >= 200 && statusCode < 300) {
Map<String, List<String>> headers = connection.getHeaderFields();
Map<String, String> headersFlat = new HashMap<String, String>();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String headerKey = entry.getKey();
String valueKey = entry.getValue().get(0);
if (headerKey != null && valueKey != null) {
headersFlat.put(headerKey, valueKey);
}
}
mParam.onDownloadBegin.onDownloadBegin(statusCode, lengthOfFile, headersFlat);
input = new BufferedInputStream(connection.getInputStream(), 8 * 1024);
output = new FileOutputStream(param.dest);
byte data[] = new byte[8 * 1024];
int total = 0;
int count;
double lastProgressValue = 0;
while ((count = input.read(data)) != -1) {
if (mAbort.get()) throw new Exception("Download has been aborted");
total += count;
if (param.progressDivider <= 0) {
publishProgress(new int[]{lengthOfFile, total});
} else {
double progress = Math.round(((double) total * 100) / lengthOfFile);
if (progress % param.progressDivider == 0) {
if ((progress != lastProgressValue) || (total == lengthOfFile)) {
Log.d("Downloader", "EMIT: " + String.valueOf(progress) + ", TOTAL:" + String.valueOf(total));
lastProgressValue = progress;
publishProgress(new int[]{lengthOfFile, total});
}
}
}
output.write(data, 0, count);
}
output.flush();
res.bytesWritten = total;
}
res.statusCode = statusCode;
} finally {
if (output != null) output.close();
if (input != null) input.close();
if (connection != null) connection.disconnect();
}
}
protected void stop() {
mAbort.set(true);
}
@Override
protected void onProgressUpdate(int[]... values) {
super.onProgressUpdate(values);
mParam.onDownloadProgress.onDownloadProgress(values[0][0], values[0][1]);
}
protected void onPostExecute(Exception ex) {
}
}
|
package org.jboss.xnio;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.CancellationException;
import java.io.IOException;
/**
* The future result of an asynchronous request. Use instances of this interface to retrieve the final status of
* an asynchronous operation.
*
* @param <T> the type of result that this operation produces
*/
public interface IoFuture<T> {
/**
* The current status of an asynchronous operation.
*/
enum Status {
/**
* The operation is still in progress.
*/
WAITING,
/**
* The operation has completed successfully.
*/
DONE,
/**
* The operation was cancelled.
*/
CANCELLED,
/**
* The operation did not succeed.
*/
FAILED,
/**
* The request timed out before the operation was complete; otherwise equivalent to status {@link #WAITING}.
*/
TIMED_OUT,
}
/**
* Cancel an operation. The actual cancel may be synchronous or asynchronous.
*
* @return this {@code IoFuture} instance
*/
IoFuture<T> cancel();
/**
* Get the current status.
*
* @return the current status
*/
Status getStatus();
/**
* Wait for the operation to complete. This method will block until the status changes from {@link Status#WAITING}.
*
* @return the new status
*/
Status await();
/**
* Wait for the operation to complete, with a timeout. This method will block until the status changes from {@link Status#WAITING},
* or the given time elapses. If the time elapses before the operation is complete, {@link Status#TIMED_OUT} is
* returned.
*
* @param timeUnit the time unit
* @param time the amount of time to wait
* @return the new status, or {@link Status#TIMED_OUT} if the timeout expired
*/
Status await(TimeUnit timeUnit, long time);
/**
* Wait for the operation to complete. This method will block until the status changes from {@link Status#WAITING},
* or the current thread is interrupted.
*
* @return the new status
* @throws InterruptedException if the operation is interrupted
*/
Status awaitInterruptibly() throws InterruptedException;
/**
* Wait for the operation to complete, with a timeout. This method will block until the status changes from {@link Status#WAITING},
* the given time elapses, or the current thread is interrupted. If the time elapses before the operation is complete, {@link Status#TIMED_OUT} is
* returned.
*
* @param timeUnit the time unit
* @param time the amount of time to wait
* @return the new status, or {@link Status#TIMED_OUT} if the timeout expired
* @throws InterruptedException if the operation is interrupted
*/
Status awaitInterruptibly(TimeUnit timeUnit, long time) throws InterruptedException;
/**
* Get the result of the operation. If the operation is not complete, blocks until the operation completes. If
* the operation fails, or has already failed at the time this method is called, the failure reason is thrown.
*
* @return the result of the operation
* @throws IOException if the operation failed
* @throws CancellationException if the operation was cancelled
*/
T get() throws IOException, CancellationException;
/**
* Get the result of the operation. If the operation is not complete, blocks until the operation completes. If
* the operation fails, or has already failed at the time this method is called, the failure reason is thrown. If
* the current thread is interrupted while waiting, an exception is thrown.
*
* @return the result of the operation
* @throws IOException if the operation failed
* @throws InterruptedException if the operation is interrupted
* @throws CancellationException if the operation was cancelled
*/
T getInterruptibly() throws IOException, InterruptedException, CancellationException;
IOException getException() throws IllegalStateException;
/**
* Add a notifier to be called when this operation is complete. If the operation is already complete, the notifier
* is called immediately, possibly in the caller's thread.
*
* @param notifier the notifier to be called
*/
void addNotifier(Notifier<T> notifier);
/**
* A notifier that handles changes in the status of an {@code IoFuture}.
*/
interface Notifier<T> {
/**
* Receive notification of the completion of an outstanding operation.
*
* @param ioFuture the future corresponding to this operation
*/
void notify(IoFuture<T> ioFuture);
}
}
|
package openmods.gui.component;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import openmods.sync.SyncableString;
import org.lwjgl.opengl.GL11;
public class GuiComponentLabel extends BaseComponent {
private String text;
private SyncableString textObj;
private float scale = 1f;
private String textDelta;
private String[] formattedText;
private int maxHeight, maxWidth;
private int additionalLineHeight = 0;
private static FontRenderer getFontRenderer() {
return Minecraft.getMinecraft().fontRenderer;
}
public GuiComponentLabel(int x, int y, int width, int height, SyncableString txt) {
this(x, y, width, height, txt.getValue());
textObj = txt;
}
public GuiComponentLabel(int x, int y, String text) {
this(x, y, getFontRenderer().getStringWidth(text), getFontRenderer().FONT_HEIGHT, text);
}
public GuiComponentLabel(int x, int y, SyncableString txt) {
this(x, y, txt.getValue());
textObj = txt;
}
public GuiComponentLabel(int x, int y, int width, int height, String text) {
super(x, y);
this.text = text;
this.formattedText = new String[10];
setMaxHeight(height);
setMaxWidth(width);
}
@SuppressWarnings("unchecked")
private void compileFormattedText(FontRenderer fr) {
if (textDelta != null && textDelta.equals(getText())) return;
textDelta = getText();
if (textDelta == null) return;
formattedText = (String[])fr.listFormattedStringToWidth(textDelta, maxWidth).toArray(formattedText);
}
@Override
public void render(Minecraft minecraft, int offsetX, int offsetY, int mouseX, int mouseY) {
super.render(minecraft, offsetX, offsetY, mouseX, mouseY);
if (getMaxHeight() < minecraft.fontRenderer.FONT_HEIGHT) return;
if (getMaxWidth() < minecraft.fontRenderer.getCharWidth('m')) return;
GL11.glPushMatrix();
GL11.glTranslated(offsetX + x, offsetY + y, 1);
GL11.glScalef(scale, scale, scale);
compileFormattedText(minecraft.fontRenderer);
int offset = 0;
int lineCount = 0;
for (String s : formattedText) {
if (s == null) break;
minecraft.fontRenderer.drawString(s, 0, offset, 4210752);
offset += getFontHeight();
if (++lineCount >= getMaxLines()) break;
}
GL11.glPopMatrix();
}
private int calculateHeight() {
FontRenderer fr = getFontRenderer();
compileFormattedText(fr);
int offset = 0;
int lineCount = 0;
for (String s : formattedText) {
if (s == null) break;
offset += getFontHeight();
if (++lineCount >= getMaxLines()) break;
}
return offset;
}
private int calculateWidth() {
FontRenderer fr = getFontRenderer();
compileFormattedText(fr);
float maxWidth = 0;
for (String s : formattedText) {
if (s == null) break;
float width = fr.getStringWidth(s);
if (width > maxWidth) maxWidth = width;
}
return (int)maxWidth;
}
public GuiComponentLabel setScale(float scale) {
this.scale = scale;
return this;
}
public float getScale() {
return scale;
}
public GuiComponentLabel setMaxHeight(int maxHeight) {
this.maxHeight = maxHeight;
return this;
}
public void setAdditionalLineHeight(int lh) {
this.additionalLineHeight = lh;
}
public int getFontHeight() {
return getFontRenderer().FONT_HEIGHT + additionalLineHeight;
}
public int getMaxHeight() {
return maxHeight;
}
public GuiComponentLabel setMaxWidth(int maxWidth) {
this.maxWidth = maxWidth;
return this;
}
public int getMaxLines() {
return (int)Math.floor(getMaxHeight() / scale
/ getFontHeight());
}
public int getMaxWidth() {
return this.maxWidth;
}
@Override
public int getHeight() {
return (int)(Math.min(getMaxHeight(), calculateHeight()) + 0.5);
}
@Override
public int getWidth() {
return (int)(Math.min(getMaxWidth(), calculateWidth()) + 0.5);
}
public String getText() {
String pre = (textObj != null? textObj.getValue() : text);
return pre == null? "" : pre;
}
}
|
package org.encog.cloud;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import org.encog.bot.BotUtil;
import org.encog.util.http.FormUtility;
public class AsynchronousCloudRequest implements Runnable {
private final URL url;
private final Map<String, String> params;
public AsynchronousCloudRequest(URL url) {
this.url = url;
this.params = new HashMap<String, String>();
}
public AsynchronousCloudRequest(URL url, Map<String, String> params) {
this.url = url;
this.params = params;
}
public URL getUrl() {
return url;
}
public Map<String, String> getParams() {
return params;
}
public void run() {
try {
if (this.params.size() > 0) {
URLConnection u = url.openConnection();
u.setDoOutput(true);
OutputStream os = u.getOutputStream();
FormUtility form = new FormUtility(os, null);
for (String key : params.keySet()) {
form.add(key, params.get(key));
}
form.complete();
BotUtil.loadPage(u.getInputStream());
} else {
URLConnection u = this.url.openConnection();
BotUtil.loadPage(u.getInputStream());
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
|
package org.mtransit.android.commons;
import java.util.regex.Pattern;
import org.mtransit.android.commons.api.SupportFactory;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
@SuppressWarnings({"unused", "WeakerAccess"})
public final class StringUtils implements MTLog.Loggable {
private static final String LOG_TAG = StringUtils.class.getSimpleName();
@NonNull
@Override
public String getLogTag() {
return LOG_TAG;
}
public static final String EMPTY = "";
public static final char SPACE_CAR = ' ';
public static final String SPACE_STRING = " ";
private static final String ELLIPSIZE = "\u2026";
private static final Pattern ONE_LINE = Pattern.compile("[\\n\\r]+");
private static final Pattern NEW_LINE = Pattern.compile("[\\n]+");
private static final Pattern DUPLICATE_WHITESPACES = Pattern.compile("[\\s]{2,}");
@Nullable
public static String oneLine(@Nullable String string) {
if (string == null || string.isEmpty()) {
return string;
}
return ONE_LINE.matcher(string).replaceAll(SPACE_STRING);
}
@Nullable
public static String removeDuplicateWhitespaces(@Nullable String string) {
if (string == null || string.isEmpty()) {
return string;
}
return DUPLICATE_WHITESPACES.matcher(string).replaceAll(SPACE_STRING);
}
@Nullable
public static String oneLineOneSpace(@Nullable String string) {
if (string == null || string.isEmpty()) {
return string;
}
string = NEW_LINE.matcher(string).replaceAll(SPACE_STRING);
string = DUPLICATE_WHITESPACES.matcher(string).replaceAll(SPACE_STRING);
return string.trim();
}
@Nullable
public static String ellipsize(@Nullable String string, int size) {
if (string == null || string.length() < size) {
return string;
}
return string.substring(0, size - ELLIPSIZE.length()) + ELLIPSIZE;
}
@Nullable
public static String trim(@Nullable String string) {
if (string == null) {
return null;
}
return string.trim();
}
public static boolean equals(@Nullable String str1, @Nullable String str2) {
return str1 == null ? str2 == null : str1.equals(str2);
}
public static boolean equalsAlphabeticsAndDigits(@Nullable String str1, @Nullable String str2) {
if (str1 == null) {
return str2 == null;
} else if (str2 == null) {
return false;
}
if (str1.equals(str2)) {
return true;
}
int str1Count = str1.length();
if (str1Count != str2.length()) {
return false;
}
for (int i = 0; i < str1Count; ++i) {
char c1 = str1.charAt(i);
char c2 = str2.charAt(i);
if ((SupportFactory.get().isCharacterAlphabetic(c1) || Character.isDigit(c1))
&& (SupportFactory.get().isCharacterAlphabetic(c2) || Character.isDigit(c2))) {
if (c1 != c2 && foldCase(c1) != foldCase(c2)) {
return false;
}
}
}
return true;
}
@Deprecated
public static boolean hasDigits(@NonNull CharSequence str, @SuppressWarnings("unused") boolean allowWhitespace) {
return hasDigits(str);
}
public static boolean hasDigits(@NonNull CharSequence str) {
final int len = str.length();
for (int i = 0; i < len; i++) {
if (Character.isDigit(str.charAt(i))) {
return true;
}
}
return false;
}
public static boolean isDigitsOnly(@NonNull CharSequence str, boolean allowWhitespace) {
final int len = str.length();
for (int i = 0; i < len; i++) {
if (!Character.isDigit(str.charAt(i))) {
if (allowWhitespace && Character.isWhitespace(str.charAt(i))) {
continue;
}
return false;
}
}
return true;
}
public static boolean isAlphabeticsOnly(@NonNull CharSequence str, boolean allowWhitespace) {
final int len = str.length();
for (int i = 0; i < len; i++) {
if (!SupportFactory.get().isCharacterAlphabetic(str.charAt(i))) {
if (allowWhitespace && Character.isWhitespace(str.charAt(i))) {
continue;
}
return false;
}
}
return true;
}
private static char foldCase(char ch) {
if (ch < 128) {
if ('A' <= ch && ch <= 'Z') {
return (char) (ch + ('a' - 'A'));
}
return ch;
}
return Character.toLowerCase(Character.toUpperCase(ch));
}
public static boolean equalsIgnoreCase(@Nullable String str1, @Nullable String str2) {
return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
}
public static int getStringIdentifier(@NonNull Context context, @NonNull String name) {
return context.getResources().getIdentifier(name, "string", context.getPackageName());
}
public static int getPluralsIdentifier(@NonNull Context context, @NonNull String name) {
return context.getResources().getIdentifier(name, "plurals", context.getPackageName());
}
@NonNull
public static String getEmptyOrPlurals(@NonNull Context context, int emptyRes, int pluralsRes, int quantity) {
if (quantity == 0) {
return context.getString(emptyRes);
} else {
return context.getResources().getQuantityString(pluralsRes, quantity, quantity);
}
}
@NonNull
public static String getEmptyOrPluralsIdentifier(@NonNull Context context, @NonNull String emptyRes, @NonNull String pluralsRes, int quantity) {
if (quantity == 0) {
return context.getString(getStringIdentifier(context, emptyRes));
} else {
return context.getResources().getQuantityString(getPluralsIdentifier(context, pluralsRes), quantity, quantity);
}
}
@Nullable
public static String removeNewLine(@Nullable String string) {
if (string == null) {
return null;
}
return string.replaceAll("[\n\r]", EMPTY);
}
@Nullable
public static String removeStartWith(@Nullable String string, @Nullable String[] removeChars) {
if (string == null || string.length() == 0) {
return string;
}
if (removeChars != null) {
for (String removeChar : removeChars) {
if (string.startsWith(removeChar)) {
return string.substring(removeChar.length());
}
}
}
return string;
}
@Nullable
public static String replaceStartWith(@Nullable String string, @Nullable String[] removeChars, @NonNull String replacement) {
if (string == null || string.length() == 0) {
return string;
}
if (removeChars != null) {
for (String removeChar : removeChars) {
if (string.startsWith(removeChar)) {
return replacement + string.substring(removeChar.length());
}
}
}
return string;
}
@Nullable
public static String removeStartWith(@Nullable String string, @Nullable String[] removeChars, int keepLast) {
if (string == null || string.length() == 0) {
return string;
}
if (removeChars != null) {
for (String removeChar : removeChars) {
if (string.startsWith(removeChar)) {
return string.substring(removeChar.length() - keepLast);
}
}
}
return string;
}
@Nullable
public static String replaceAll(@Nullable String string, @Nullable String[] replaceChars, @NonNull String replacement) {
if (string == null || string.length() == 0) {
return string;
}
if (replaceChars != null) {
for (String replaceChar : replaceChars) {
string = string.replace(replaceChar, replacement);
}
}
return string;
}
}
|
package org.nutz.dao.entity.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Dao
*
* @author zozoh(zozohtnt@gmail.com)
* @author wendal(wendal1985@gmail.com)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@Documented
public @interface ColDefine {
/**
*
*
* @see org.nutz.dao.entity.annotation.ColType
*/
ColType type() default ColType.VARCHAR;
/**
* /, 1024 width=1024
*/
int width() default 0;
int precision() default 2;
/**
* ,false
*/
boolean notNull() default false;
/**
* ,false
*/
boolean unsigned() default false;
/**
* @Id @Id
*/
boolean auto() default false;
/**
* , customType="image"
* @return
*/
String customType() default "";
boolean insert() default true;
boolean update() default true;
}
|
package org.objectweb.asm.tree.analysis;
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.Constants;
import org.objectweb.asm.Label;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.IincInsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LookupSwitchInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TableSwitchInsnNode;
import org.objectweb.asm.tree.TryCatchBlockNode;
import org.objectweb.asm.tree.VarInsnNode;
/**
* A semantic bytecode analyzer.
*
* @author Eric Bruneton
*/
public class Analyzer implements Constants {
private Interpreter interpreter;
private int n;
private IntMap indexes;
private List[] handlers;
private Frame[] frames;
private Subroutine[] subroutines;
private boolean[] queued;
private int[] queue;
private int top;
/**
* Constructs a new {@link Analyzer}.
*
* @param interpreter the interpreter to be used to symbolically interpret
* the bytecode instructions.
*/
public Analyzer (final Interpreter interpreter) {
this.interpreter = interpreter;
}
/**
* Analyzes the given method.
*
* @param c the class to which the method belongs.
* @param m the method to be analyzed.
* @return the symbolic state of the execution stack frame at each bytecode
* instruction of the method. The size of the returned array is equal to
* the number of instructions (and labels) of the method. A given frame is
* <tt>null</tt> if and only if the corresponding instruction cannot be
* reached (dead code).
*/
public Frame[] analyze (final ClassNode c, final MethodNode m) {
n = m.instructions.size();
indexes = new IntMap(2*n);
handlers = new List[n];
frames = new Frame[n];
subroutines = new Subroutine[n];
queued = new boolean[n];
queue = new int[n];
top = 0;
// computes instruction indexes
for (int i = 0; i < n; ++i) {
indexes.put(m.instructions.get(i), i);
}
// computes exception handlers for each instruction
for (int i = 0; i < m.tryCatchBlocks.size(); ++i) {
TryCatchBlockNode tcb = (TryCatchBlockNode)m.tryCatchBlocks.get(i);
int begin = indexes.get(tcb.start);
int end = indexes.get(tcb.end);
for (int j = begin; j < end; ++j) {
List insnHandlers = handlers[j];
if (insnHandlers == null) {
insnHandlers = new ArrayList();
handlers[j] = insnHandlers;
}
insnHandlers.add(tcb);
}
}
// initializes the data structures for the control flow analysis algorithm
Frame current = newFrame(m.maxLocals, m.maxStack);
Frame handler = newFrame(m.maxLocals, m.maxStack);
Type[] args = Type.getArgumentTypes(m.desc);
int local = 0;
if ((m.access & ACC_STATIC) == 0) {
Type ctype = Type.getType("L" + c.name + ";");
current.setLocal(local++, interpreter.newValue(ctype));
}
for (int i = 0; i < args.length; ++i) {
current.setLocal(local++, interpreter.newValue(args[i]));
if (args[i].getSize() == 2) {
current.setLocal(local++, interpreter.newValue(null));
}
}
while (local < m.maxLocals) {
current.setLocal(local++, interpreter.newValue(null));
}
merge(0, current, null);
// control flow analysis
while (top > 0) {
int insn = queue[--top];
Frame f = frames[insn];
Subroutine subroutine = subroutines[insn];
queued[insn] = false;
try {
Object o = m.instructions.get(insn);
if (o instanceof Label) {
merge(insn + 1, f, subroutine);
} else {
AbstractInsnNode insnNode = (AbstractInsnNode)o;
int insnOpcode = insnNode.getOpcode();
current.init(f).execute(insnNode, interpreter);
subroutine = subroutine == null ? null : subroutine.copy();
if (insnNode instanceof JumpInsnNode) {
JumpInsnNode j = (JumpInsnNode)insnNode;
if (insnOpcode != GOTO && insnOpcode != JSR) {
merge(insn + 1, current, subroutine);
}
if (insnOpcode == JSR) {
subroutine = new Subroutine(j.label, m.maxLocals, j);
}
merge(indexes.get(j.label), current, subroutine);
} else if (insnNode instanceof LookupSwitchInsnNode) {
LookupSwitchInsnNode lsi = (LookupSwitchInsnNode)insnNode;
merge(indexes.get(lsi.dflt), current, subroutine);
for (int j = 0; j < lsi.labels.size(); ++j) {
Label label = (Label)lsi.labels.get(j);
merge(indexes.get(label), current, subroutine);
}
} else if (insnNode instanceof TableSwitchInsnNode) {
TableSwitchInsnNode tsi = (TableSwitchInsnNode)insnNode;
merge(indexes.get(tsi.dflt), current, subroutine);
for (int j = 0; j < tsi.labels.size(); ++j) {
Label label = (Label)tsi.labels.get(j);
merge(indexes.get(label), current, subroutine);
}
} else if (insnOpcode == RET) {
if (subroutine == null) {
throw new RuntimeException(
"RET instruction outside of a sub routine");
} else {
for (int i = 0; i < subroutine.callers.size(); ++i) {
int caller = indexes.get(subroutine.callers.get(i));
merge(caller + 1, frames[caller], current, subroutine.access);
}
}
} else if (insnOpcode != ATHROW && (insnOpcode < IRETURN || insnOpcode > RETURN)) {
if (subroutine != null) {
if (insnNode instanceof VarInsnNode) {
int var = ((VarInsnNode)insnNode).var;
subroutine.access[var] = true;
if (insnOpcode == LLOAD ||
insnOpcode == DLOAD ||
insnOpcode == LSTORE ||
insnOpcode == DSTORE)
{
subroutine.access[var + 1] = true;
}
} else if (insnNode instanceof IincInsnNode) {
int var = ((IincInsnNode)insnNode).var;
subroutine.access[var] = true;
}
}
merge(insn + 1, current, subroutine);
}
}
List insnHandlers = handlers[insn];
if (insnHandlers != null) {
for (int i = 0; i < insnHandlers.size(); ++i) {
TryCatchBlockNode tcb = (TryCatchBlockNode)insnHandlers.get(i);
Type type;
if (tcb.type == null) {
type = Type.getType("Ljava/lang/Throwable;");
} else {
type = Type.getType("L" + tcb.type + ";");
}
handler.init(f);
handler.clearStack();
handler.push(interpreter.newValue(type));
merge(indexes.get(tcb.handler), handler, subroutine);
}
}
} catch (Exception e) {
throw new RuntimeException(
"Error at instruction " + insn + ": " + e.getMessage());
}
}
return frames;
}
/**
* Returns the symbolic stack frame for each instruction of the last recently
* analyzed method.
*
* @return the symbolic state of the execution stack frame at each bytecode
* instruction of the method. The size of the returned array is equal to
* the number of instructions (and labels) of the method. A given frame is
* <tt>null</tt> if the corresponding instruction cannot be reached, or if
* an error occured during the analysis of the method.
*/
public Frame[] getFrames () {
return frames;
}
/**
* Returns the index of the given instruction.
*
* @param insn a {@link Label} or {@link AbstractInsnNode} of the last
* recently analyzed method.
* @return the index of the given instruction of the last recently analyzed
* method.
*/
public int getIndex (final Object insn) {
return indexes.get(insn);
}
/**
* Returns the exception handlers for the given instruction.
*
* @param insn the index of an instruction of the last recently analyzed
* method.
* @return a list of {@link TryCatchBlockNode} objects.
*/
public List getHandlers (final int insn) {
return handlers[insn];
}
/**
* Constructs a new frame with the given size.
*
* @param nLocals the maximum number of local variables of the frame.
* @param nStack the maximum stack size of the frame.
* @return the created frame.
*/
protected Frame newFrame (final int nLocals, final int nStack) {
return new Frame(nLocals, nStack);
}
/**
* Constructs a new frame that is identical to the given frame.
*
* @param src a frame.
* @return the created frame.
*/
protected Frame newFrame (final Frame src) {
return new Frame(src);
}
/**
* Creates a control flow graph edge. The default implementation of this
* method does nothing. It can be overriden in order to construct the control
* flow graph of a method (this method is called by the
* {@link #analyze analyze} method during its visit of the method's code).
*
* @param frame the frame corresponding to an instruction.
* @param successor the frame corresponding to a successor instruction.
*/
protected void newControlFlowEdge (final Frame frame, final Frame successor) {
}
private void merge (
final int insn,
final Frame frame,
final Subroutine subroutine)
{
if (insn > n - 1) {
throw new RuntimeException("Execution can fall off end of the code");
} else {
Frame oldFrame = frames[insn];
Subroutine oldSubroutine = subroutines[insn];
boolean changes = false;
if (oldFrame == null) {
frames[insn] = newFrame(frame);
changes = true;
} else {
changes |= oldFrame.merge(frame);
}
newControlFlowEdge(frame, oldFrame);
if (oldSubroutine == null) {
if (subroutine != null) {
subroutines[insn] = subroutine.copy();
changes = true;
}
} else {
if (subroutine != null) {
changes |= oldSubroutine.merge(subroutine);
}
}
if (changes && !queued[insn]) {
queued[insn] = true;
queue[top++] = insn;
}
}
}
private void merge (
final int insn,
final Frame beforeJSR,
final Frame afterRET,
final boolean[] access)
{
if (insn > n - 1) {
throw new RuntimeException("Execution can fall off end of the code");
} else {
Frame oldFrame = frames[insn];
boolean changes = false;
afterRET.merge(beforeJSR, access);
if (oldFrame == null) {
frames[insn] = newFrame(afterRET);
changes = true;
} else {
changes |= oldFrame.merge(afterRET, access);
}
newControlFlowEdge(afterRET, oldFrame);
if (changes && !queued[insn]) {
queued[insn] = true;
queue[top++] = insn;
}
}
}
private static class IntMap {
private int size;
private Object[] keys;
private int[] values;
private IntMap (final int size) {
this.size = size;
this.keys = new Object[size];
this.values = new int[size];
}
public int get (final Object key) {
int n = size;
int i = (key.hashCode() & 0x7FFFFFFF)%n;
while (keys[i] != key) {
i = (i+1)%n;
}
return values[i];
}
public void put (final Object key, final int value) {
int n = size;
int i = (key.hashCode() & 0x7FFFFFFF)%n;
while (keys[i] != null) {
i = (i+1)%n;
}
keys[i] = key;
values[i] = value;
}
}
private static class Subroutine {
Label start;
boolean[] access;
List callers;
private Subroutine () {
}
public Subroutine (final Label start, final int maxLocals, final JumpInsnNode caller) {
this.start = start;
this.access = new boolean[maxLocals];
this.callers = new ArrayList();
callers.add(caller);
}
public Subroutine copy () {
Subroutine result = new Subroutine();
result.start = start;
result.access = new boolean[access.length];
System.arraycopy(access, 0, result.access, 0, access.length);
result.callers = new ArrayList(callers);
return result;
}
public boolean merge (final Subroutine subroutine) {
if (subroutine.start != start) {
throw new RuntimeException("Overlapping sub routines");
}
boolean changes = false;
for (int i = 0; i < access.length; ++i) {
if (subroutine.access[i] && !access[i]) {
access[i] = true;
changes = true;
}
}
for (int i = 0; i < subroutine.callers.size(); ++i) {
Object caller = subroutine.callers.get(i);
if (!callers.contains(caller)) {
callers.add(caller);
changes = true;
}
}
return changes;
}
}
}
|
// This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
package org.sosy_lab.java_smt.api;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.List;
import java.util.Map;
import org.sosy_lab.common.Appender;
import org.sosy_lab.java_smt.api.visitors.FormulaTransformationVisitor;
import org.sosy_lab.java_smt.api.visitors.FormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.TraversalProcess;
/** FormulaManager class contains all operations which can be performed on formulas. */
public interface FormulaManager {
/**
* Returns the Integer-Theory. Because most SAT-solvers support automatic casting between Integer-
* and Rational-Theory, the Integer- and the RationalFormulaManager both return the same Formulas
* for numeric operations like ADD, SUBTRACT, TIMES, LESSTHAN, EQUAL and others.
*
* @throws UnsupportedOperationException If the theory is not supported by the solver.
*/
IntegerFormulaManager getIntegerFormulaManager();
/**
* Returns the Rational-Theory. Because most SAT-solvers support automatic casting between
* Integer- and Rational-Theory, the Integer- and the RationalFormulaManager both return the same
* Formulas for numeric operations like ADD, SUBTRACT, TIMES, LESSTHAN, EQUAL, etc.
*
* @throws UnsupportedOperationException If the theory is not supported by the solver.
*/
RationalFormulaManager getRationalFormulaManager();
/** Returns the Boolean-Theory. */
BooleanFormulaManager getBooleanFormulaManager();
/**
* Returns the Array-Theory.
*
* @throws UnsupportedOperationException If the theory is not supported by the solver.
*/
ArrayFormulaManager getArrayFormulaManager();
/**
* Returns the Bitvector-Theory.
*
* @throws UnsupportedOperationException If the theory is not supported by the solver.
*/
BitvectorFormulaManager getBitvectorFormulaManager();
/**
* Returns the Floating-Point-Theory.
*
* @throws UnsupportedOperationException If the theory is not supported by the solver.
*/
FloatingPointFormulaManager getFloatingPointFormulaManager();
/** Returns the function for dealing with uninterpreted functions (UFs). */
UFManager getUFManager();
/**
* Returns the Seperation-Logic-Theory.
*
* @throws UnsupportedOperationException If the theory is not supported by the solver.
*/
SLFormulaManager getSLFormulaManager();
/**
* Returns the interface for handling quantifiers.
*
* @throws UnsupportedOperationException If the theory is not supported by the solver.
*/
QuantifiedFormulaManager getQuantifiedFormulaManager();
/**
* Returns the String Theory.
*
* @throws UnsupportedOperationException If the theory is not supported by the solver.
*/
StringFormulaManager getStringFormulaManager();
/**
* Create variable of the type equal to {@code formulaType}.
*
* @param formulaType the type of the variable.
* @param name the name of the variable.
* @return the created variable.
*/
<T extends Formula> T makeVariable(FormulaType<T> formulaType, String name);
/**
* Create a function application to the given list of arguments.
*
* @param declaration Function declaration
* @param args List of arguments
* @return Constructed formula
*/
<T extends Formula> T makeApplication(
FunctionDeclaration<T> declaration, List<? extends Formula> args);
/**
* Create a function application to the given list of arguments.
*
* @param declaration Function declaration
* @param args List of arguments
* @return Constructed formula
*/
<T extends Formula> T makeApplication(FunctionDeclaration<T> declaration, Formula... args);
/** Returns the type of the given Formula. */
<T extends Formula> FormulaType<T> getFormulaType(T formula);
BooleanFormula parse(String s) throws IllegalArgumentException;
/**
* Serialize an input formula to an SMT-LIB format. Very useful when passing formulas between
* different solvers.
*
* <p>To get a String, simply call {@link Object#toString()} on the returned object. This method
* is lazy and does not create an output string until the returned object is actually used.
*
* @return SMT-LIB formula serialization.
*/
Appender dumpFormula(BooleanFormula pT);
/**
* Apply a tactic which performs formula transformation. The available tactics depend on the used
* solver.
*/
BooleanFormula applyTactic(BooleanFormula input, Tactic tactic) throws InterruptedException;
/**
* Simplify an input formula, while ensuring equivalence.
*
* <p>For solvers that do not provide a simplification API, an original formula is returned.
*
* @param input The input formula
* @return Simplified version of the formula
*/
<T extends Formula> T simplify(T input) throws InterruptedException;
/**
* Visit the formula with a given visitor.
*
* <p>This method does <b>not recursively visit</b> sub-components of a formula its own, so the
* given {@link FormulaVisitor} needs to call such visitation on its own.
*
* <p>Please be aware that calling this method might cause extensive stack usage depending on the
* nesting of the given formula and the given {@link FormulaVisitor}. Additionally, sub-formulas
* that are used several times in the formula might be visited several times. For an efficient
* formula traversing, we also provide {@link #visitRecursively(Formula, FormulaVisitor)}.
*
* @param f formula to be visited
* @param rFormulaVisitor an implementation that provides steps for each kind of formula.
*/
@CanIgnoreReturnValue
<R> R visit(Formula f, FormulaVisitor<R> rFormulaVisitor);
/**
* Visit the formula recursively with a given {@link FormulaVisitor}. This method traverses
* sub-components of a formula automatically, depending on the return value of the {@link
* TraversalProcess} in the given {@link FormulaVisitor}.
*
* <p>This method guarantees that the traversal is done iteratively, without using Java recursion,
* and thus is not prone to StackOverflowErrors.
*
* <p>Furthermore, this method also guarantees that every equal part of the formula is visited
* only once. Thus, it can be used to traverse DAG-like formulas efficiently.
*
* <p>The traversal is done in PRE-ORDER manner with regard to caching identical subtrees, i.e., a
* parent will be visited BEFORE its children. The unmodified child-formulas are passed as
* argument to the parent's visitation.
*/
void visitRecursively(Formula f, FormulaVisitor<TraversalProcess> rFormulaVisitor);
/**
* Visit the formula recursively with a given {@link FormulaVisitor}.
*
* <p>This method guarantees that the traversal is done iteratively, without using Java recursion,
* and thus is not prone to StackOverflowErrors.
*
* <p>Furthermore, this method also guarantees that every equal part of the formula is visited
* only once. Thus, it can be used to traverse DAG-like formulas efficiently.
*
* <p>The traversal is done in POST-ORDER manner with regard to caching identical subtrees, i.e.,
* a parent will be visited AFTER its children. The result of the child-visitation is passed as
* argument to the parent's visitation.
*
* @param pFormulaVisitor Transformation described by the user.
*/
<T extends Formula> T transformRecursively(T f, FormulaTransformationVisitor pFormulaVisitor);
/**
* Extract the names of all free variables and UFs in a formula.
*
* @param f The input formula
* @return Map from variable names to the corresponding formulas.
*/
Map<String, Formula> extractVariables(Formula f);
/**
* Extract the names of all free variables and UFs in a formula.
*
* @param f The input formula
* @return Map from variable names to the corresponding formulas. If an UF occurs multiple times
* in the input formula, an arbitrary instance of an application of this UF is in the map.
*/
Map<String, Formula> extractVariablesAndUFs(Formula f);
/**
* Substitute every occurrence of any item from {@code changeFrom} in formula {@code f} to the
* corresponding occurrence from {@code changeTo}.
*
* <p>E.g. if {@code changeFrom} contains a variable {@code a} and {@code changeTo} contains a
* variable {@code b} all occurrences of {@code a} will be changed to {@code b} in the returned
* formula.
*
* @param f Formula to change.
* @param fromToMapping Mapping of old and new formula parts.
* @return Formula with parts replaced.
*/
<T extends Formula> T substitute(T f, Map<? extends Formula, ? extends Formula> fromToMapping);
/**
* Translates the formula from another context into the context represented by {@code this}.
* Default implementation relies on string serialization ({@link #dumpFormula(BooleanFormula)} and
* {@link #parse(String)}), but each solver may implement more efficient translation between its
* own contexts.
*
* @param formula Formula belonging to {@code otherContext}.
* @param otherManager Formula manager belonging to the other context.
* @return Formula belonging to {@code this} context.
*/
BooleanFormula translateFrom(BooleanFormula formula, FormulaManager otherManager);
/**
* Check whether the given String can be used as symbol/name for variables or undefined functions.
*
* <p>We explicitly state that with further development of SMT solvers and the SMTLib
* specification, the list of forbidden variable names may change in the future. Users should if
* possible not use logical or mathematical operators, or keywords strongly depending on SMTlib.
*
* <p>If a variable name is rejected, a possibility is escaping, e.g. either substituting the
* whole variable name or just every invalid character with an escaped form. We recommend using an
* escape sequence based on the token "JAVASMT", because it might be unusual enough to appear when
* encoding a user's problem in SMT. Please note that you might also have to handle escaping the
* escape sequence. Examples:
*
* <ul>
* <li>the invalid variable name <code>"="</code> (logical operator for equality) can be
* replaced with a string <code>"JAVASMT_EQUALS"</code>.
* <li>the invalid SMTlib-escaped variable name <code>"|test|"</code> (the solver SMTInterpol
* does not allow the pipe symbol <code>"|"</code> in names) can be replaced with <code>
* "JAVASMT_PIPEtestJAVASMT_PIPE"</code>.
* </ul>
*/
boolean isValidName(String variableName);
/**
* Get an escaped symbol/name for variables or undefined functions, if necessary.
*
* <p>See {@link #isValidName(String)} for further details.
*/
String escape(String variableName);
/**
* Unescape the symbol/name for variables or undefined functions, if necessary.
*
* <p>The result is undefined for Strings that are not properly escaped.
*
* <p>See {@link #isValidName(String)} for further details.
*/
String unescape(String variableName);
}
|
package org.torproject.onionoo;
import java.io.*;
import java.text.*;
import java.util.*;
/* Read and write relay and bridge summary data from/to disk. */
public class SummaryDataWriter {
private File internalRelaySearchDataFile =
new File("status/summary.csv");
private File relaySearchDataFile = new File("out/summary.json");
private File relaySearchDataBackupFile =
new File("out/summary.json.bak");
/* Read the internal relay search data file from disk. */
public CurrentNodes readRelaySearchDataFile() {
CurrentNodes result = new CurrentNodes();
if (this.relaySearchDataBackupFile.exists()) {
System.err.println("Found '"
+ relaySearchDataBackupFile.getAbsolutePath() + "' which "
+ "indicates that a previous execution did not terminate "
+ "cleanly. Please investigate the problem, delete this file, "
+ "and try again. Exiting.");
System.exit(1);
}
if (this.internalRelaySearchDataFile.exists() &&
!this.internalRelaySearchDataFile.isDirectory()) {
try {
BufferedReader br = new BufferedReader(new FileReader(
this.internalRelaySearchDataFile));
String line;
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
while ((line = br.readLine()) != null) {
if (line.startsWith("r ")) {
String[] parts = line.split(" ");
if (parts.length < 9) {
System.err.println("Line '" + line + "' in '"
+ this.internalRelaySearchDataFile.getAbsolutePath()
+ " is invalid. Exiting.");
System.exit(1);
}
String nickname = parts[1];
String fingerprint = parts[2];
String address = parts[3];
long validAfterMillis = dateTimeFormat.parse(parts[4] + " "
+ parts[5]).getTime();
int orPort = Integer.parseInt(parts[6]);
int dirPort = Integer.parseInt(parts[7]);
SortedSet<String> relayFlags = new TreeSet<String>(
Arrays.asList(parts[8].split(",")));
result.addRelay(nickname, fingerprint, address,
validAfterMillis, orPort, dirPort, relayFlags);
} else if (line.startsWith("b ")) {
String[] parts = line.split(" ");
if (parts.length < 7) {
System.err.println("Line '" + line + "' in '"
+ this.internalRelaySearchDataFile.getAbsolutePath()
+ " is invalid. Exiting.");
System.exit(1);
}
String hashedFingerprint = parts[1];
long publishedMillis = dateTimeFormat.parse(parts[2] + " "
+ parts[3]).getTime();
int orPort = Integer.parseInt(parts[4]);
int dirPort = Integer.parseInt(parts[5]);
SortedSet<String> relayFlags = new TreeSet<String>(
Arrays.asList(parts[6].split(",")));
result.addBridge(hashedFingerprint, publishedMillis, orPort,
dirPort, relayFlags);
}
}
br.close();
} catch (IOException e) {
System.err.println("Could not read "
+ this.internalRelaySearchDataFile.getAbsolutePath()
+ ". Exiting.");
e.printStackTrace();
System.exit(1);
} catch (ParseException e) {
System.err.println("Could not read "
+ this.internalRelaySearchDataFile.getAbsolutePath()
+ ". Exiting.");
e.printStackTrace();
System.exit(1);
}
}
return result;
}
/* Write the relay search data file to disk. */
public void writeRelaySearchDataFile(CurrentNodes sd) {
/* TODO Check valid-after times and warn if we're missing one or more
* network status consensuses. The user should know, so that she can
* download and import missing network status consensuses. */
/* Write internal relay search data file to disk. */
try {
this.internalRelaySearchDataFile.getParentFile().mkdirs();
BufferedWriter bw = new BufferedWriter(new FileWriter(
this.internalRelaySearchDataFile));
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
for (Node entry : sd.getCurrentRelays().values()) {
String nickname = entry.getNickname();
String fingerprint = entry.getFingerprint();
String address = entry.getAddress();
String validAfter = dateTimeFormat.format(
entry.getLastSeenMillis());
String orPort = String.valueOf(entry.getOrPort());
String dirPort = String.valueOf(entry.getDirPort());
StringBuilder sb = new StringBuilder();
for (String relayFlag : entry.getRelayFlags()) {
sb.append("," + relayFlag);
}
String relayFlags = sb.toString().substring(1);
bw.write("r " + nickname + " " + fingerprint + " " + address + " "
+ validAfter + " " + orPort + " " + dirPort + " " + relayFlags
+ "\n");
}
for (Node entry : sd.getCurrentBridges().values()) {
String fingerprint = entry.getFingerprint();
String published = dateTimeFormat.format(
entry.getLastSeenMillis());
String orPort = String.valueOf(entry.getOrPort());
String dirPort = String.valueOf(entry.getDirPort());
StringBuilder sb = new StringBuilder();
for (String relayFlag : entry.getRelayFlags()) {
sb.append("," + relayFlag);
}
String relayFlags = sb.toString().substring(1);
bw.write("b " + fingerprint + " " + published + " "
+ orPort + " " + dirPort + " " + relayFlags + "\n");
}
bw.close();
} catch (IOException e) {
System.err.println("Could not write '"
+ this.internalRelaySearchDataFile.getAbsolutePath()
+ "' to disk. Exiting.");
e.printStackTrace();
System.exit(1);
}
/* Make a backup before overwriting the relay search data file. */
if (this.relaySearchDataFile.exists() &&
!this.relaySearchDataFile.isDirectory()) {
try {
BufferedReader br = new BufferedReader(new FileReader(
this.relaySearchDataFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(
this.relaySearchDataBackupFile));
String line;
while ((line = br.readLine()) != null) {
bw.write(line + "\n");
}
bw.close();
br.close();
} catch (IOException e) {
System.err.println("Could not create backup of '"
+ this.relaySearchDataFile.getAbsolutePath() + "'. "
+ "Exiting.");
e.printStackTrace();
System.exit(1);
}
}
/* (Over-)write relay search data file. */
try {
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
long now = System.currentTimeMillis();
String validAfterString = dateTimeFormat.format(now);
String freshUntilString = dateTimeFormat.format(now
+ 75L * 60L * 1000L);
this.relaySearchDataFile.getParentFile().mkdirs();
BufferedWriter bw = new BufferedWriter(new FileWriter(
this.relaySearchDataFile));
bw.write("{\"version\":1,\n"
+ "\"valid_after\":\"" + validAfterString + "\",\n"
+ "\"fresh_until\":\"" + freshUntilString + "\",\n"
+ "\"relays\":[");
int written = 0;
for (Node entry : sd.getCurrentRelays().values()) {
String nickname = !entry.getNickname().equals("Unnamed") ?
entry.getNickname() : null;
String fingerprint = entry.getFingerprint();
String running = entry.getRunning() ? "true" : "false";
String address = entry.getAddress();
if (written++ > 0) {
bw.write(",");
}
bw.write("\n{"
+ (nickname == null ? "" : "\"n\":\"" + nickname + "\",")
+ "\"f\":\"" + fingerprint + "\","
+ "\"a\":[\"" + address + "\"],"
+ "\"r\":" + running + "}");
}
bw.write("\n],\n\"bridges\":[");
written = 0;
for (Node entry : sd.getCurrentBridges().values()) {
String hashedFingerprint = entry.getFingerprint();
String running = entry.getRunning() ? "true" : "false";
if (written++ > 0) {
bw.write(",");
}
bw.write("\n{"
+ "\"h\":\"" + hashedFingerprint + "\","
+ "\"r\":" + running + "}");
}
bw.write("\n]}\n");
bw.close();
} catch (IOException e) {
System.err.println("Could not write "
+ this.relaySearchDataFile.getAbsolutePath() + ". Exiting.");
e.printStackTrace();
System.exit(1);
}
this.relaySearchDataBackupFile.delete();
}
}
|
package h2o.testng.db;
import h2o.testng.utils.CommonHeaders;
import java.sql.Statement;
import java.util.HashMap;
import water.H2O;
public class MySQL {
private static MySQLConfig config = MySQLConfig.initConfig();
public final static String defaults = "defaults";
public final static String tuned = "tuned";
public final static String tuned_or_defaults = "tuned_or_defaults";
public static boolean createTable() {
if (!config.isUsedDB()) {
System.out.println("Program is configured don't use database");
return false;
}
final String sql = "create table if not exists " + config.getTableName() + "("
+ "test_case_id VARCHAR(125),"
+ "training_frame_id VARCHAR(125),"
+ "validation_frame_id VARCHAR(125),"
+ "mse_result DOUBLE,"
+ "auc_result DOUBLE,"
+ "date datetime,"
+ "interpreter_version VARCHAR(125),"
+ "machine_name VARCHAR(125),"
+ "total_hosts INT,"
+ "cpus_per_hosts INT,"
+ "total_nodes INT,"
+ "source VARCHAR(125),"
+ "parameter_list VARCHAR(2048),"
+ "git_hash_number VARCHAR(125),"
+ "tuned_or_defaults VARCHAR(125)"
+ ")";
MySQLConnection connection = new MySQLConnection();
Statement statement = null;
try {
statement = connection.createStatement();
statement.executeUpdate(sql);
}
catch (Exception ex) {
System.out.println("Can't create table: " + config.getTableName());
ex.printStackTrace();
return false;
}
finally {
connection.closeConnection();
}
System.out.println("Create successfully table");
return true;
}
public static boolean save(String mse_result, String auc_result, HashMap<String, String> rawInput) {
if (!config.isUsedDB()) {
System.out.println("Program is configured don't use database");
return false;
}
final String testcaseId = rawInput.get(CommonHeaders.testcase_id);
final String trainingFrameId = rawInput.get(CommonHeaders.train_dataset_id);
final String validationFrameId = rawInput.get(CommonHeaders.validate_dataset_id);
final String currentTime = "NOW()";
final String interpreterVersion = "JVM";
final String machineName = H2O.ABV.compiledBy();
final String gitHashNumber = H2O.ABV.lastCommitHash();
final String source = H2O.ABV.projectVersion();
final String tuned_or_defaults = rawInput.get(MySQL.tuned_or_defaults);
// TODO verify it
int totalHosts = 0;
int cpusPerHost = H2O.NUMCPUS;
int totalNodes = H2O.CLOUD.size();
if (mse_result == null || mse_result.toLowerCase().equals("na") || mse_result.toLowerCase().equals("nan")) {
mse_result = "NULL";
}
if (auc_result == null || auc_result.toLowerCase().equals("na") || auc_result.toLowerCase().equals("nan")) {
auc_result = "NULL";
}
MySQLConnection connection = new MySQLConnection();
Statement statement = null;
String sql = String.format(
"insert into %s values('%s','%s','%s',%s,%s,%s,'%s','%s',%s,%s,%s,'%s','%s','%s','%s')",
config.getTableName(), testcaseId, trainingFrameId, validationFrameId, mse_result, auc_result,
currentTime, interpreterVersion, machineName, totalHosts, cpusPerHost, totalNodes, source,
rawInput.toString(), gitHashNumber, tuned_or_defaults);
System.out.println("saved script SQL:");
System.out.println(sql);
try {
statement = connection.createStatement();
statement.executeUpdate(sql);
}
catch (Exception ex) {
System.out.println("Can't insert into table: " + config.getTableName());
ex.printStackTrace();
return false;
}
finally {
connection.closeConnection();
}
System.out.println("The result is saved successfully in database");
return true;
}
}
|
package components.installer;
import de.uniulm.omi.cloudiator.sword.api.remote.RemoteConnection;
import play.Logger;
import play.Play;
public class WindowsInstaller extends AbstractInstaller {
private final String homeDir;
private final String javaExe = "jre8.exe";
private final String sevenZipArchive = "7zip.zip";
private final String sevenZipDir = "7zip";
private final String visorBat = "startVisor.bat";
private final String javaDonwload = Play.application().configuration().getString("colosseum.installer.windows.java.download");
private final String zip7Donwload = Play.application().configuration().getString("colosseum.installer.windows.java.download");
public WindowsInstaller(RemoteConnection remoteConnection, String user) {
super(remoteConnection);
this.homeDir = "C:\\Users\\" + user;
}
@Override
public void initSources() {
//java
this.sourcesList.add("powershell -command (new-object System.Net.WebClient).DownloadFile('" + this.javaDonwload + "','"+this.homeDir+"\\"+this.javaExe+"')");
//7zip
this.sourcesList.add("powershell -command (new-object System.Net.WebClient).DownloadFile('http://7-zip.org/a/7za920.zip','"+this.homeDir+"\\"+this.sevenZipArchive+"')");
//download visor
this.sourcesList.add("powershell -command (new-object System.Net.WebClient).DownloadFile('" + this.visorDownload + "','" + this.homeDir + "\\" + this.visorJar + "')");
//download kairosDB
this.sourcesList.add("powershell -command (new-object System.Net.WebClient).DownloadFile('" + this.kairosDbDownload + "','"+this.homeDir+"\\"+this.kairosDbArchive+"')");
}
@Override
public void installJava() {
Logger.debug("Installing Java...");
this.remoteConnection.executeCommand("powershell -command " + this.homeDir + "\\jre8.exe /s INSTALLDIR=" + this.homeDir + "\\" + this.javaDir);
//Set JAVA envirnonment vars
remoteConnection.executeCommand("SET PATH="+this.homeDir+"\\"+this.javaDir + "\\bin;%PATH%");
remoteConnection.executeCommand("SET JAVA_HOME=" + this.homeDir + "\\" + this.javaDir);
}
private void install7Zip(){
Logger.debug("Unzipping 7zip...");
this.remoteConnection.executeCommand("powershell -command & { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('" + this.homeDir + "7zip.zip', '" + this.homeDir + "\\"+ this.sevenZipDir+ "'); }");
Logger.debug("7zip successfully unzipped!");
}
@Override
public void installVisor() {
Logger.debug("Setting up and starting Visor");
//create properties file
this.remoteConnection.writeFile(this.homeDir + "\\" + this.visorProperties, this.buildDefaultVisorConfig(), false);
//id of the visor schtasks
String visorJobId = "visor";
//create a .bat file to start visor, because it is not possible to pass schtasks paramters using overthere
String startCommand = "java -jar " + this.homeDir + "\\" + this.visorJar + " -conf " + this.homeDir + "\\" + this.visorProperties;
this.remoteConnection.writeFile(this.homeDir + "\\" + this.visorBat, startCommand, false );
//TODO: open WindowsFirewall Ports if Rest/Telnet ports need to be remote accessible
//create schtaks
this.remoteConnection.executeCommand("schtasks.exe /create /st 00:00 /sc ONCE /tn " + visorJobId + " /tr \"java -jar " + this.homeDir + "\\" + this.visorBat + "\"");
//run schtask
this.remoteConnection.executeCommand("schtasks.exe /run /tn " + visorJobId );
Logger.debug("Visor started successfully!");
}
@Override
public void installKairosDb() {
Logger.debug("Extract, setup and start KairosDB...");
//extract kairosdb
this.remoteConnection.executeCommand("powershell -command " + this.homeDir +"\\"+ this.sevenZipDir +"\\7za.exe e " + this.homeDir + "\\"+ this.kairosDbArchive + " -o" + this.homeDir);
String kairosDbTar = this.kairosDbArchive.replace(".gz", "");
this.remoteConnection.executeCommand("powershell -command " + this.homeDir + "\\" + this.sevenZipDir + "\7za.exe x " + this.homeDir + "\\" + kairosDbTar + " -o" + this.homeDir);
//set firewall rule
this.remoteConnection.executeCommand("powershell -command netsh advfirewall firewall add rule name = 'Open Kairos Port 8080' dir = in action = allow protocol=TCP localport=8080");
//start kairosdb in backround
String kairosJobId = "kairosDB";
this.remoteConnection.executeCommand("schtasks.exe /create /st 00:00 /sc ONCE /tn "+ kairosJobId +" /tr \""+this.homeDir+"\\kairosdb\\bin\\kairosdb.bat run\"");
this.remoteConnection.executeCommand("schtasks.exe /run /tn " + kairosJobId);
Logger.debug("KairosDB successfully started!");
}
@Override
public void installLifecycleAgent() {
Logger.error("InstallLifecycleAgent currently not supported...");
}
@Override
public void installAll() {
Logger.debug("Starting installation of all tools on WINDOWS...");
this.initSources();
this.downloadSources();
this.installJava();
this.install7Zip();
this.installKairosDb();
this.installVisor();
this.finishInstallation();
}
}
|
package proy.logica.gestores.filtros;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import proy.datos.clases.EstadoStr;
import proy.datos.entidades.Maquina;
import proy.datos.entidades.Parte;
import proy.datos.servicios.Filtro;
public class FiltroParte extends Filtro {
private String consulta = "";
private String namedQuery = "";
private EstadoStr estado;
private Maquina maquina;
private ArrayList<Parte> partes;
private Boolean conTareas;
public static class Builder {
private String nombreEntidad = "a";
private EstadoStr estado = EstadoStr.ALTA;
private Maquina maquina = null;
private ArrayList<Parte> partes = null;
private Boolean conTareas = null;
public Builder() {
super();
}
public Builder nombreEntidad(String nombreEntidad) {
this.nombreEntidad = nombreEntidad;
return this;
}
public Builder maquina(Maquina maquina) {
this.maquina = maquina;
return this;
}
public Builder maquina(ArrayList<Parte> partes) {
this.partes = partes;
return this;
}
public Builder conTareas(){
this.conTareas = true;
return this;
}
public FiltroParte build() {
return new FiltroParte(this);
}
}
private FiltroParte(Builder builder) {
this.estado = builder.estado;
this.maquina = builder.maquina;
this.partes = builder.partes;
this.conTareas = builder.conTareas;
setConsulta(builder);
setNamedQuery(builder);
}
private void setConsulta(Builder builder) {
consulta = this.getSelect(builder) + this.getFrom(builder) + this.getWhere(builder) + this.getGroupBy(builder) + this.getHaving(builder) + this.getOrderBy(builder);
}
private void setNamedQuery(Builder builder) {
if(estado != EstadoStr.ALTA){
}
if(maquina != null){
return;
}
if(partes != null){
return;
}
if(conTareas != null){
return;
}
namedQuery = "listarPartes";
}
private String getSelect(Builder builder) {
String select = "SELECT " + builder.nombreEntidad;
return select;
}
private String getFrom(Builder builder) {
String from;
if(conTareas == true){
from = " FROM Parte " + builder.nombreEntidad + " inner join " + builder.nombreEntidad + ".procesos proc inner join proc.tareas tar";
}
else{
from = " FROM Parte " + builder.nombreEntidad;
}
return from;
}
private String getWhere(Builder builder) {
String where =
((builder.estado != null) ? (builder.nombreEntidad + ".estado.nombre = :est AND ") : (""))
+ ((builder.maquina != null) ? (builder.nombreEntidad + ".maquina = :maq AND ") : (""))
+ ((builder.partes != null) ? (builder.nombreEntidad + " in :pts AND ") : (""));
if(!where.isEmpty()){
where = " WHERE " + where;
where = where.substring(0, where.length() - 4);
}
return where;
}
private String getGroupBy(Builder builder) {
String groupBy = "";
return groupBy;
}
private String getHaving(Builder builder) {
String having = "";
return having;
}
private String getOrderBy(Builder builder) {
String orderBy = " ORDER BY " + builder.nombreEntidad + ".nombre ";
return orderBy;
}
@Override
public Query setParametros(Query query) {
if(estado != null){
query.setParameter("est", estado);
}
if(maquina != null){
query.setParameter("maq", maquina);
}
if(partes != null){
query.setParameterList("pts", partes);
}
return query;
}
@Override
public void updateParametros(Session session) {
if(maquina != null){
session.update(maquina);
}
}
@Override
public String getConsultaDinamica() {
return consulta;
}
@Override
public String getNamedQueryName() {
return namedQuery;
}
}
|
package com.openxc;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;
import java.util.Map;
import com.google.common.base.Objects;
import com.openxc.remote.RawMeasurement;
import com.openxc.sinks.VehicleDataSink;
import com.openxc.sources.SourceCallback;
import com.openxc.sources.VehicleDataSource;
/**
* A pipeline that ferries data from VehicleDataSources to VehicleDataSinks.
*
* A DataPipeline accepts two types of components - sources and sinks. The
* sources (implementing {@link VehicleDataSource} call the
* {@link #receive(String, Object, Object)} method on the this class when new
* values arrive. The DataPipeline then passes this value on to all currently
* registered data sinks.
*/
public class DataPipeline implements SourceCallback {
private int mMessagesReceived = 0;
private Map<String, RawMeasurement> mMeasurements;
private CopyOnWriteArrayList<VehicleDataSink> mSinks;
private CopyOnWriteArrayList<VehicleDataSource> mSources;
public DataPipeline() {
mMeasurements = new ConcurrentHashMap<String, RawMeasurement>();
mSinks = new CopyOnWriteArrayList<VehicleDataSink>();
mSources = new CopyOnWriteArrayList<VehicleDataSource>();
}
/**
* Accept new values from data sources.
*
* This method is required to implement the SourceCallback interface.
*/
public void receive(RawMeasurement measurement) {
mMeasurements.put(measurement.getName(), measurement);
for(Iterator<VehicleDataSink> i = mSinks.iterator(); i.hasNext();) {
(i.next()).receive(measurement);
}
mMessagesReceived++;
}
/**
* Add a new sink to the pipeline.
*/
public VehicleDataSink addSink(VehicleDataSink sink) {
mSinks.add(sink);
return sink;
}
/**
* Remove a previously added sink from the pipeline.
*
* Once removed, the sink will no longer receive any new measurements from
* the pipeline's sources. The sink's {@link VehicleDataSink#stop()} method
* is also called.
*
* @param sink if the value is null, it is ignored.
*/
public void removeSink(VehicleDataSink sink) {
if(sink != null) {
mSinks.remove(sink);
sink.stop();
}
}
/**
* Add a new source to the pipeline.
*
* The source is given a reference to this DataPipeline as its callback.
*/
public VehicleDataSource addSource(VehicleDataSource source) {
source.setCallback(this);
mSources.add(source);
return source;
}
/**
* Remove a previously added source from the pipeline.
*
* Once removed, the source should no longer use this pipeline for its
* callback.
*
* @param source if the value is null, it is ignored.
*/
public void removeSource(VehicleDataSource source) {
if(source != null) {
mSources.remove(source);
source.stop();
}
}
/**
* Clear all sources and sinks from the pipeline and stop all of them.
*/
public void stop() {
clearSources();
clearSinks();
}
/**
* Remove and stop all sources in the pipeline.
*/
public void clearSources() {
for(Iterator<VehicleDataSource> i = mSources.iterator(); i.hasNext();) {
(i.next()).stop();
}
mSources.clear();
}
/**
* Remove and stop all sinks in the pipeline.
*/
public void clearSinks() {
for(Iterator<VehicleDataSink> i = mSinks.iterator(); i.hasNext();) {
(i.next()).stop();
}
mSinks.clear();
}
/**
* Return the last received value for the measurement if known.
*
* @return a RawMeasurement with the last known value, or null if no value
* has been received.
*/
public RawMeasurement get(String measurementId) {
return mMeasurements.get(measurementId);
}
/**
* Determine if a type of measurement has yet been received.
*
* @return true if any value is known for the measurement ID.
*/
public boolean containsMeasurement(String measurementId) {
return mMeasurements.containsKey(measurementId);
}
/**
* @return number of messages received since instantiation.
*/
public int getMessageCount() {
return mMessagesReceived;
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("sources", mSources)
.add("sinks", mSinks)
.add("numMeasurementTypes", mMeasurements.size())
.toString();
}
}
|
package org.postgresql.jdbc2;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;
import org.postgresql.core.*;
import org.postgresql.Driver;
import org.postgresql.PGConnection;
import org.postgresql.PGNotification;
import org.postgresql.fastpath.Fastpath;
import org.postgresql.largeobject.LargeObjectManager;
import org.postgresql.util.PSQLState;
import org.postgresql.util.PGobject;
import org.postgresql.util.PSQLException;
import org.postgresql.util.GT;
/**
* This class defines methods of the jdbc2 specification.
* The real Connection class (for jdbc2) is org.postgresql.jdbc2.Jdbc2Connection
*/
public abstract class AbstractJdbc2Connection implements BaseConnection
{
// Data initialized on construction:
/* URL we were created via */
private final String creatingURL;
private final String openStackTrace;
/* Actual network handler */
private final ProtocolConnection protoConnection;
/* Compatibility version */
private final String compatible;
/* Actual server version */
private final String dbVersionNumber;
/* Query that runs COMMIT */
private final Query commitQuery;
/* Query that runs ROLLBACK */
private final Query rollbackQuery;
private TypeInfoCache _typeCache;
// Default statement prepare threshold.
protected int prepareThreshold;
// Connection's autocommit state.
public boolean autoCommit = true;
// Connection's readonly state.
public boolean readOnly = false;
// Current warnings; there might be more on protoConnection too.
public SQLWarning firstWarning = null;
public abstract DatabaseMetaData getMetaData() throws SQLException;
// Ctor.
protected AbstractJdbc2Connection(String host, int port, String user, String database, Properties info, String url) throws SQLException
{
this.creatingURL = url;
//Read loglevel arg and set the loglevel based on this value
//in addition to setting the log level enable output to
//standard out if no other printwriter is set
// XXX revisit: need a debug level *per connection*.
int logLevel = 0;
try
{
logLevel = Integer.parseInt(info.getProperty("loglevel", "0"));
if (logLevel > Driver.DEBUG || logLevel < Driver.INFO)
{
logLevel = 0;
}
}
catch (Exception l_e)
{
// XXX revisit
// invalid value for loglevel; ignore it
}
if (logLevel > 0)
{
Driver.setLogLevel(logLevel);
enableDriverManagerLogging();
}
prepareThreshold = 5;
try
{
prepareThreshold = Integer.parseInt(info.getProperty("prepareThreshold", "5"));
if (prepareThreshold < 0)
prepareThreshold = 0;
}
catch (Exception e)
{
}
//Print out the driver version number
if (Driver.logInfo)
Driver.info(Driver.getVersion());
// Now make the initial connection and set up local state
this.protoConnection = ConnectionFactory.openConnection(host, port, user, database, info);
this.dbVersionNumber = protoConnection.getServerVersion();
this.compatible = info.getProperty("compatible", Driver.MAJORVERSION + "." + Driver.MINORVERSION);
if (Driver.logDebug)
{
Driver.debug(" compatible = " + compatible);
Driver.debug(" loglevel = " + logLevel);
Driver.debug(" prepare threshold = " + prepareThreshold);
}
// Initialize timestamp stuff
timestampUtils = new TimestampUtils(haveMinimumServerVersion("7.4"));
// Initialize common queries.
commitQuery = getQueryExecutor().createSimpleQuery("COMMIT");
rollbackQuery = getQueryExecutor().createSimpleQuery("ROLLBACK");
// Initialize object handling
_typeCache = new TypeInfoCache(this);
initObjectTypes(info);
if (Boolean.valueOf(info.getProperty("logUnclosedConnections")).booleanValue()) {
java.io.CharArrayWriter caw = new java.io.CharArrayWriter(1024);
Exception e = new Exception();
e.printStackTrace(new java.io.PrintWriter(caw));
openStackTrace = caw.toString();
enableDriverManagerLogging();
} else {
openStackTrace = null;
}
}
private final TimestampUtils timestampUtils;
public TimestampUtils getTimestampUtils() { return timestampUtils; }
/*
* The current type mappings
*/
protected java.util.Map typemap;
public java.sql.Statement createStatement() throws SQLException
{
// We now follow the spec and default to TYPE_FORWARD_ONLY.
return createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
}
public abstract java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException;
public java.sql.PreparedStatement prepareStatement(String sql) throws SQLException
{
return prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
}
public abstract java.sql.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException;
public java.sql.CallableStatement prepareCall(String sql) throws SQLException
{
return prepareCall(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
}
public abstract java.sql.CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException;
public java.util.Map getTypeMap() throws SQLException
{
return typemap;
}
// Query executor associated with this connection.
public QueryExecutor getQueryExecutor() {
return protoConnection.getQueryExecutor();
}
/*
* This adds a warning to the warning chain.
* @param warn warning to add
*/
public void addWarning(SQLWarning warn)
{
// Add the warning to the chain
if (firstWarning != null)
firstWarning.setNextWarning(warn);
else
firstWarning = warn;
}
/**
* Simple query execution.
*/
public ResultSet execSQLQuery(String s) throws SQLException {
BaseStatement stat = (BaseStatement) createStatement();
boolean hasResultSet = stat.executeWithFlags(s, QueryExecutor.QUERY_SUPPRESS_BEGIN);
while (!hasResultSet && stat.getUpdateCount() != -1)
hasResultSet = stat.getMoreResults();
if (!hasResultSet)
throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA);
// Transfer warnings to the connection, since the user never
// has a chance to see the statement itself.
SQLWarning warnings = stat.getWarnings();
if (warnings != null)
addWarning(warnings);
return stat.getResultSet();
}
public void execSQLUpdate(String s) throws SQLException {
BaseStatement stmt = (BaseStatement) createStatement();
if (stmt.executeWithFlags(s, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN))
throw new PSQLException(GT.tr("A result was returned when none was expected."),
PSQLState.TOO_MANY_RESULTS);
// Transfer warnings to the connection, since the user never
// has a chance to see the statement itself.
SQLWarning warnings = stmt.getWarnings();
if (warnings != null)
addWarning(warnings);
stmt.close();
}
/*
* In SQL, a result table can be retrieved through a cursor that
* is named. The current row of a result can be updated or deleted
* using a positioned update/delete statement that references the
* cursor name.
*
* We do not support positioned update/delete, so this is a no-op.
*
* @param cursor the cursor name
* @exception SQLException if a database access error occurs
*/
public void setCursorName(String cursor) throws SQLException
{
// No-op.
}
/*
* getCursorName gets the cursor name.
*
* @return the current cursor name
* @exception SQLException if a database access error occurs
*/
public String getCursorName() throws SQLException
{
return null;
}
/*
* We are required to bring back certain information by
* the DatabaseMetaData class. These functions do that.
*
* Method getURL() brings back the URL (good job we saved it)
*
* @return the url
* @exception SQLException just in case...
*/
public String getURL() throws SQLException
{
return creatingURL;
}
/*
* Method getUserName() brings back the User Name (again, we
* saved it)
*
* @return the user name
* @exception SQLException just in case...
*/
public String getUserName() throws SQLException
{
return protoConnection.getUser();
}
/*
* This returns the Fastpath API for the current connection.
*
* <p><b>NOTE:</b> This is not part of JDBC, but allows access to
* functions on the org.postgresql backend itself.
*
* <p>It is primarily used by the LargeObject API
*
* <p>The best way to use this is as follows:
*
* <p><pre>
* import org.postgresql.fastpath.*;
* ...
* Fastpath fp = ((org.postgresql.Connection)myconn).getFastpathAPI();
* </pre>
*
* <p>where myconn is an open Connection to org.postgresql.
*
* @return Fastpath object allowing access to functions on the org.postgresql
* backend.
* @exception SQLException by Fastpath when initialising for first time
*/
public Fastpath getFastpathAPI() throws SQLException
{
if (fastpath == null)
fastpath = new Fastpath(this);
return fastpath;
}
// This holds a reference to the Fastpath API if already open
private Fastpath fastpath = null;
/*
* This returns the LargeObject API for the current connection.
*
* <p><b>NOTE:</b> This is not part of JDBC, but allows access to
* functions on the org.postgresql backend itself.
*
* <p>The best way to use this is as follows:
*
* <p><pre>
* import org.postgresql.largeobject.*;
* ...
* LargeObjectManager lo = ((org.postgresql.Connection)myconn).getLargeObjectAPI();
* </pre>
*
* <p>where myconn is an open Connection to org.postgresql.
*
* @return LargeObject object that implements the API
* @exception SQLException by LargeObject when initialising for first time
*/
public LargeObjectManager getLargeObjectAPI() throws SQLException
{
if (largeobject == null)
largeobject = new LargeObjectManager(this);
return largeobject;
}
// This holds a reference to the LargeObject API if already open
private LargeObjectManager largeobject = null;
/*
* This method is used internally to return an object based around
* org.postgresql's more unique data types.
*
* <p>It uses an internal Hashtable to get the handling class. If the
* type is not supported, then an instance of org.postgresql.util.PGobject
* is returned.
*
* You can use the getValue() or setValue() methods to handle the returned
* object. Custom objects can have their own methods.
*
* @return PGobject for this type, and set to value
* @exception SQLException if value is not correct for this type
*/
public Object getObject(String type, String value) throws SQLException
{
if (typemap != null)
{
SQLData d = (SQLData) typemap.get(type);
if (d != null)
{
// Handle the type (requires SQLInput & SQLOutput classes to be implemented)
if (Driver.logDebug)
Driver.debug("getObject(String,String) with custom typemap");
throw org.postgresql.Driver.notImplemented(this.getClass(), "getObject(String,String)");
}
}
PGobject obj = null;
if (Driver.logDebug)
Driver.debug("Constructing object from type=" + type + " value=<" + value + ">");
try
{
Class klass = _typeCache.getPGobject(type);
// If className is not null, then try to instantiate it,
// It must be basetype PGobject
// This is used to implement the org.postgresql unique types (like lseg,
// point, etc).
if (klass != null)
{
obj = (PGobject) (klass.newInstance());
obj.setType(type);
obj.setValue(value);
}
else
{
// If className is null, then the type is unknown.
// so return a PGobject with the type set, and the value set
obj = new PGobject();
obj.setType( type );
obj.setValue( value );
}
return obj;
}
catch (SQLException sx)
{
// rethrow the exception. Done because we capture any others next
throw sx;
}
catch (Exception ex)
{
throw new PSQLException(GT.tr("Failed to create object for: {0}.", type), PSQLState.CONNECTION_FAILURE, ex);
}
}
public void addDataType(String type, String name)
{
try
{
addDataType(type, Class.forName(name));
}
catch (Exception e)
{
throw new RuntimeException("Cannot register new type: " + e);
}
}
public void addDataType(String type, Class klass) throws SQLException
{
_typeCache.addDataType(type, klass);
}
// This initialises the objectTypes hashtable
private void initObjectTypes(Properties info) throws SQLException
{
// Add in the types that come packaged with the driver.
// These can be overridden later if desired.
addDataType("box", org.postgresql.geometric.PGbox.class);
addDataType("circle", org.postgresql.geometric.PGcircle.class);
addDataType("line", org.postgresql.geometric.PGline.class);
addDataType("lseg", org.postgresql.geometric.PGlseg.class);
addDataType("path", org.postgresql.geometric.PGpath.class);
addDataType("point", org.postgresql.geometric.PGpoint.class);
addDataType("polygon", org.postgresql.geometric.PGpolygon.class);
addDataType("money", org.postgresql.util.PGmoney.class);
addDataType("interval", org.postgresql.util.PGInterval.class);
for (Enumeration e = info.propertyNames(); e.hasMoreElements(); )
{
String propertyName = (String)e.nextElement();
if (propertyName.startsWith("datatype."))
{
String typeName = propertyName.substring(9);
String className = info.getProperty(propertyName);
Class klass;
try
{
klass = Class.forName(className);
}
catch (ClassNotFoundException cnfe)
{
throw new PSQLException(GT.tr("Unable to load the class {0} responsible for the datatype {1}", new Object[] { className, typeName }),
PSQLState.SYSTEM_ERROR, cnfe);
}
addDataType(typeName, klass);
}
}
}
/**
* In some cases, it is desirable to immediately release a Connection's
* database and JDBC resources instead of waiting for them to be
* automatically released.
*
* <B>Note:</B> A Connection is automatically closed when it is
* garbage collected. Certain fatal errors also result in a closed
* connection.
*
* @exception SQLException if a database access error occurs
*/
public void close()
{
protoConnection.close();
}
/*
* A driver may convert the JDBC sql grammar into its system's
* native SQL grammar prior to sending it; nativeSQL returns the
* native form of the statement that the driver would have sent.
*
* @param sql a SQL statement that may contain one or more '?'
* parameter placeholders
* @return the native form of this statement
* @exception SQLException if a database access error occurs
*/
public String nativeSQL(String sql) throws SQLException
{
StringBuffer buf = new StringBuffer(sql.length());
AbstractJdbc2Statement.parseSql(sql,0,buf,false);
return buf.toString();
}
/*
* The first warning reported by calls on this Connection is
* returned.
*
* <B>Note:</B> Sebsequent warnings will be changed to this
* SQLWarning
*
* @return the first SQLWarning or null
* @exception SQLException if a database access error occurs
*/
public synchronized SQLWarning getWarnings()
throws SQLException
{
SQLWarning newWarnings = protoConnection.getWarnings(); // NB: also clears them.
if (firstWarning == null)
firstWarning = newWarnings;
else
firstWarning.setNextWarning(newWarnings); // Chain them on.
return firstWarning;
}
/*
* After this call, getWarnings returns null until a new warning
* is reported for this connection.
*
* @exception SQLException if a database access error occurs
*/
public synchronized void clearWarnings()
throws SQLException
{
protoConnection.getWarnings(); // Clear and discard.
firstWarning = null;
}
/*
* You can put a connection in read-only mode as a hunt to enable
* database optimizations
*
* <B>Note:</B> setReadOnly cannot be called while in the middle
* of a transaction
*
* @param readOnly - true enables read-only mode; false disables it
* @exception SQLException if a database access error occurs
*/
public void setReadOnly(boolean readOnly) throws SQLException
{
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
throw new PSQLException(GT.tr("Cannot change transaction read-only property in the middle of a transaction."),
PSQLState.ACTIVE_SQL_TRANSACTION);
if (haveMinimumServerVersion("7.4") && readOnly != this.readOnly)
{
String readOnlySql = "SET SESSION CHARACTERISTICS AS TRANSACTION " + (readOnly ? "READ ONLY" : "READ WRITE");
execSQLUpdate(readOnlySql); // nb: no BEGIN triggered.
}
this.readOnly = readOnly;
}
/*
* Tests to see if the connection is in Read Only Mode.
*
* @return true if the connection is read only
* @exception SQLException if a database access error occurs
*/
public boolean isReadOnly() throws SQLException
{
return readOnly;
}
/*
* If a connection is in auto-commit mode, than all its SQL
* statements will be executed and committed as individual
* transactions. Otherwise, its SQL statements are grouped
* into transactions that are terminated by either commit()
* or rollback(). By default, new connections are in auto-
* commit mode. The commit occurs when the statement completes
* or the next execute occurs, whichever comes first. In the
* case of statements returning a ResultSet, the statement
* completes when the last row of the ResultSet has been retrieved
* or the ResultSet has been closed. In advanced cases, a single
* statement may return multiple results as well as output parameter
* values. Here the commit occurs when all results and output param
* values have been retrieved.
*
* @param autoCommit - true enables auto-commit; false disables it
* @exception SQLException if a database access error occurs
*/
public void setAutoCommit(boolean autoCommit) throws SQLException
{
if (this.autoCommit == autoCommit)
return ;
if (!this.autoCommit)
commit();
this.autoCommit = autoCommit;
}
/*
* gets the current auto-commit state
*
* @return Current state of the auto-commit mode
* @see setAutoCommit
*/
public boolean getAutoCommit()
{
return this.autoCommit;
}
private void executeTransactionCommand(Query query) throws SQLException {
getQueryExecutor().execute(query, null, new TransactionCommandHandler(),
0, 0, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN);
}
/*
* The method commit() makes all changes made since the previous
* commit/rollback permanent and releases any database locks currently
* held by the Connection. This method should only be used when
* auto-commit has been disabled. (If autoCommit == true, then we
* just return anyhow)
*
* @exception SQLException if a database access error occurs
* @see setAutoCommit
*/
public void commit() throws SQLException
{
if (autoCommit)
return ;
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
executeTransactionCommand(commitQuery);
}
/*
* The method rollback() drops all changes made since the previous
* commit/rollback and releases any database locks currently held by
* the Connection.
*
* @exception SQLException if a database access error occurs
* @see commit
*/
public void rollback() throws SQLException
{
if (autoCommit)
return ;
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
executeTransactionCommand(rollbackQuery);
}
/*
* Get this Connection's current transaction isolation mode.
*
* @return the current TRANSACTION_* mode value
* @exception SQLException if a database access error occurs
*/
public int getTransactionIsolation() throws SQLException
{
String level = null;
if (haveMinimumServerVersion("7.3"))
{
// 7.3+ returns the level as a query result.
ResultSet rs = execSQLQuery("SHOW TRANSACTION ISOLATION LEVEL"); // nb: no BEGIN triggered
if (rs.next())
level = rs.getString(1);
rs.close();
}
else
{
// 7.2 returns the level as an INFO message. Ew.
// We juggle the warning chains a bit here.
// Swap out current warnings.
SQLWarning saveWarnings = getWarnings();
clearWarnings();
// Run the query any examine any resulting warnings.
execSQLUpdate("SHOW TRANSACTION ISOLATION LEVEL"); // nb: no BEGIN triggered
SQLWarning warning = getWarnings();
if (warning != null)
level = warning.getMessage();
// Swap original warnings back.
clearWarnings();
if (saveWarnings != null)
addWarning(saveWarnings);
}
// XXX revisit: throw exception instead of silently eating the error in unkwon cases?
if (level == null)
return Connection.TRANSACTION_READ_COMMITTED; // Best guess.
level = level.toUpperCase();
if (level.indexOf("READ COMMITTED") != -1)
return Connection.TRANSACTION_READ_COMMITTED;
if (level.indexOf("READ UNCOMMITTED") != -1)
return Connection.TRANSACTION_READ_UNCOMMITTED;
if (level.indexOf("REPEATABLE READ") != -1)
return Connection.TRANSACTION_REPEATABLE_READ;
if (level.indexOf("SERIALIZABLE") != -1)
return Connection.TRANSACTION_SERIALIZABLE;
return Connection.TRANSACTION_READ_COMMITTED; // Best guess.
}
/*
* You can call this method to try to change the transaction
* isolation level using one of the TRANSACTION_* values.
*
* <B>Note:</B> setTransactionIsolation cannot be called while
* in the middle of a transaction
*
* @param level one of the TRANSACTION_* isolation values with
* the exception of TRANSACTION_NONE; some databases may
* not support other values
* @exception SQLException if a database access error occurs
* @see java.sql.DatabaseMetaData#supportsTransactionIsolationLevel
*/
public void setTransactionIsolation(int level) throws SQLException
{
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
throw new PSQLException(GT.tr("Cannot change transaction isolation level in the middle of a transaction."),
PSQLState.ACTIVE_SQL_TRANSACTION);
String isolationLevelName = getIsolationLevelName(level);
if (isolationLevelName == null)
throw new PSQLException(GT.tr("Transaction isolation level {0} not supported.", new Integer(level)), PSQLState.NOT_IMPLEMENTED);
String isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " + isolationLevelName;
execSQLUpdate(isolationLevelSQL); // nb: no BEGIN triggered
}
protected String getIsolationLevelName(int level)
{
boolean pg80 = haveMinimumServerVersion("8.0");
if (level == Connection.TRANSACTION_READ_COMMITTED)
{
return "READ COMMITTED";
}
else if (level == Connection.TRANSACTION_SERIALIZABLE)
{
return "SERIALIZABLE";
}
else if (pg80 && level == Connection.TRANSACTION_READ_UNCOMMITTED)
{
return "READ UNCOMMITTED";
}
else if (pg80 && level == Connection.TRANSACTION_REPEATABLE_READ)
{
return "REPEATABLE READ";
}
return null;
}
/*
* A sub-space of this Connection's database may be selected by
* setting a catalog name. If the driver does not support catalogs,
* it will silently ignore this request
*
* @exception SQLException if a database access error occurs
*/
public void setCatalog(String catalog) throws SQLException
{
//no-op
}
/*
* Return the connections current catalog name, or null if no
* catalog name is set, or we dont support catalogs.
*
* @return the current catalog name or null
* @exception SQLException if a database access error occurs
*/
public String getCatalog() throws SQLException
{
return protoConnection.getDatabase();
}
/*
* Overides finalize(). If called, it closes the connection.
*
* This was done at the request of Rachel Greenham
* <rachel@enlarion.demon.co.uk> who hit a problem where multiple
* clients didn't close the connection, and once a fortnight enough
* clients were open to kill the org.postgres server.
*/
public void finalize() throws Throwable
{
if (openStackTrace != null && !isClosed()) {
DriverManager.println(GT.tr("Finalizing a Connection that was never closed. Connection was opened here:"));
DriverManager.println(openStackTrace);
}
close();
}
/*
* Get server version number
*/
public String getDBVersionNumber()
{
return dbVersionNumber;
}
// Parse a "dirty" integer surrounded by non-numeric characters
private static int integerPart(String dirtyString)
{
int start, end;
for (start = 0; start < dirtyString.length() && !Character.isDigit(dirtyString.charAt(start)); ++start)
;
for (end = start; end < dirtyString.length() && Character.isDigit(dirtyString.charAt(end)); ++end)
;
if (start == end)
return 0;
return Integer.parseInt(dirtyString.substring(start, end));
}
/*
* Get server major version
*/
public int getServerMajorVersion()
{
try
{
StringTokenizer versionTokens = new StringTokenizer(dbVersionNumber, "."); // aaXbb.ccYdd
return integerPart(versionTokens.nextToken()); // return X
}
catch (NoSuchElementException e)
{
return 0;
}
}
/*
* Get server minor version
*/
public int getServerMinorVersion()
{
try
{
StringTokenizer versionTokens = new StringTokenizer(dbVersionNumber, "."); // aaXbb.ccYdd
versionTokens.nextToken(); // Skip aaXbb
return integerPart(versionTokens.nextToken()); // return Y
}
catch (NoSuchElementException e)
{
return 0;
}
}
/**
* Is the server we are connected to running at least this version?
* This comparison method will fail whenever a major or minor version
* goes to two digits (10.3.0) or (7.10.1).
*/
public boolean haveMinimumServerVersion(String ver)
{
return (dbVersionNumber.compareTo(ver) >= 0);
}
/*
* This method returns true if the compatible level set in the connection
* (which can be passed into the connection or specified in the URL)
* is at least the value passed to this method. This is used to toggle
* between different functionality as it changes across different releases
* of the jdbc driver code. The values here are versions of the jdbc client
* and not server versions. For example in 7.1 get/setBytes worked on
* LargeObject values, in 7.2 these methods were changed to work on bytea
* values. This change in functionality could be disabled by setting the
* "compatible" level to be 7.1, in which case the driver will revert to
* the 7.1 functionality.
*/
public boolean haveMinimumCompatibleVersion(String ver)
{
return (compatible.compareTo(ver) >= 0);
}
public Encoding getEncoding() {
return protoConnection.getEncoding();
}
public byte[] encodeString(String str) throws SQLException {
try
{
return getEncoding().encode(str);
}
catch (IOException ioe)
{
throw new PSQLException(GT.tr("Unable to translate data into the desired encoding."), PSQLState.DATA_ERROR, ioe);
}
}
/*
* This returns the java.sql.Types type for a PG type oid
*
* @param oid PostgreSQL type oid
* @return the java.sql.Types type
* @exception SQLException if a database access error occurs
*/
public int getSQLType(int oid) throws SQLException
{
return _typeCache.getSQLType(oid);
}
public Iterator getPGTypeNamesWithSQLTypes()
{
return _typeCache.getPGTypeNamesWithSQLTypes();
}
/*
* This returns the oid for a given PG data type
* @param typeName PostgreSQL type name
* @return PostgreSQL oid value for a field of this type, or 0 if not found
*/
public int getPGType(String typeName) throws SQLException
{
return _typeCache.getPGType(typeName);
}
public String getJavaClass(int oid) throws SQLException
{
return _typeCache.getJavaClass(oid);
}
/*
* We also need to get the PG type name as returned by the back end.
*
* @return the String representation of the type, or null if not fould
* @exception SQLException if a database access error occurs
*/
public String getPGType(int oid) throws SQLException
{
return _typeCache.getPGType(oid);
}
// This is a cache of the DatabaseMetaData instance for this connection
protected java.sql.DatabaseMetaData metadata;
/*
* Tests to see if a Connection is closed
*
* @return the status of the connection
* @exception SQLException (why?)
*/
public boolean isClosed() throws SQLException
{
return protoConnection.isClosed();
}
public void cancelQuery() throws SQLException
{
protoConnection.sendQueryCancel();
}
public PGNotification[] getNotifications() throws SQLException
{
// Backwards-compatibility hand-holding.
PGNotification[] notifications = protoConnection.getNotifications();
return (notifications.length == 0 ? null : notifications);
}
// Handler for transaction queries
private class TransactionCommandHandler implements ResultHandler {
private SQLException error;
public void handleResultRows(Query fromQuery, Field[] fields, Vector tuples, ResultCursor cursor) {
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
}
public void handleWarning(SQLWarning warning) {
AbstractJdbc2Connection.this.addWarning(warning);
}
public void handleError(SQLException newError) {
if (error == null)
error = newError;
else
error.setNextException(newError);
}
public void handleCompletion() throws SQLException {
if (error != null)
throw error;
}
}
public int getPrepareThreshold() {
return prepareThreshold;
}
public void setPrepareThreshold(int newThreshold) {
this.prepareThreshold = (newThreshold <= 0 ? 0 : newThreshold);
}
public void setTypeMapImpl(java.util.Map map) throws SQLException
{
typemap = map;
}
//Because the get/setLogStream methods are deprecated in JDBC2
//we use the get/setLogWriter methods here for JDBC2 by overriding
//the base version of this method
protected void enableDriverManagerLogging()
{
if (DriverManager.getLogWriter() == null)
{
DriverManager.setLogWriter(new PrintWriter(System.out));
}
}
public int getSQLType(String pgTypeName)
{
return _typeCache.getSQLType(pgTypeName);
}
public int getProtocolVersion()
{
return protoConnection.getProtocolVersion();
}
}
|
package org.postgresql.jdbc3;
import java.util.Properties;
import java.sql.*;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.GT;
/**
* This class defines methods of the jdbc3 specification. This class extends
* org.postgresql.jdbc2.AbstractJdbc2Connection which provides the jdbc2
* methods. The real Connection class (for jdbc3) is org.postgresql.jdbc3.Jdbc3Connection
*/
public abstract class AbstractJdbc3Connection extends org.postgresql.jdbc2.AbstractJdbc2Connection
{
private int rsHoldability = ResultSet.CLOSE_CURSORS_AT_COMMIT;
private int savepointId = 0;
protected AbstractJdbc3Connection(String host, int port, String user, String database, Properties info, String url) throws SQLException {
super(host, port, user, database, info, url);
}
/**
* Changes the holdability of <code>ResultSet</code> objects
* created using this <code>Connection</code> object to the given
* holdability.
*
* @param holdability a <code>ResultSet</code> holdability constant; one of
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @throws SQLException if a database access occurs, the given parameter
* is not a <code>ResultSet</code> constant indicating holdability,
* or the given holdability is not supported
* @see #getHoldability
* @see ResultSet
* @since 1.4
*/
public void setHoldability(int holdability) throws SQLException
{
switch (holdability)
{
case ResultSet.CLOSE_CURSORS_AT_COMMIT:
rsHoldability = holdability;
break;
case ResultSet.HOLD_CURSORS_OVER_COMMIT:
rsHoldability = holdability;
break;
default:
throw new PSQLException(GT.tr("Unknown ResultSet holdability setting: {0}.", new Integer(holdability)),
PSQLState.INVALID_PARAMETER_VALUE);
}
}
/**
* Retrieves the current holdability of <code>ResultSet</code> objects
* created using this <code>Connection</code> object.
*
* @return the holdability, one of
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @throws SQLException if a database access occurs
* @see #setHoldability
* @see ResultSet
* @since 1.4
*/
public int getHoldability() throws SQLException
{
return rsHoldability;
}
/**
* Creates an unnamed savepoint in the current transaction and
* returns the new <code>Savepoint</code> object that represents it.
*
* @return the new <code>Savepoint</code> object
* @exception SQLException if a database access error occurs
* or this <code>Connection</code> object is currently in
* auto-commit mode
* @see Savepoint
* @since 1.4
*/
public Savepoint setSavepoint() throws SQLException
{
if (!haveMinimumServerVersion("8.0"))
throw new PSQLException(GT.tr("Server versions prior to 8.0 do not support savepoints."), PSQLState.NOT_IMPLEMENTED);
if (getAutoCommit())
throw new PSQLException(GT.tr("Cannot establish a savepoint in auto-commit mode."),
PSQLState.NO_ACTIVE_SQL_TRANSACTION);
PSQLSavepoint savepoint = new PSQLSavepoint(savepointId++);
// Note we can't use execSQLUpdate because we don't want
// to suppress BEGIN.
Statement stmt = createStatement();
stmt.executeUpdate("SAVEPOINT " + savepoint.getPGName());
stmt.close();
return savepoint;
}
/**
* Creates a savepoint with the given name in the current transaction
* and returns the new <code>Savepoint</code> object that represents it.
*
* @param name a <code>String</code> containing the name of the savepoint
* @return the new <code>Savepoint</code> object
* @exception SQLException if a database access error occurs
* or this <code>Connection</code> object is currently in
* auto-commit mode
* @see Savepoint
* @since 1.4
*/
public Savepoint setSavepoint(String name) throws SQLException
{
if (!haveMinimumServerVersion("8.0"))
throw new PSQLException(GT.tr("Server versions prior to 8.0 do not support savepoints."), PSQLState.NOT_IMPLEMENTED);
if (getAutoCommit())
throw new PSQLException(GT.tr("Cannot establish a savepoint in auto-commit mode."),
PSQLState.NO_ACTIVE_SQL_TRANSACTION);
PSQLSavepoint savepoint = new PSQLSavepoint(name);
// Note we can't use execSQLUpdate because we don't want
// to suppress BEGIN.
Statement stmt = createStatement();
stmt.executeUpdate("SAVEPOINT " + savepoint.getPGName());
stmt.close();
return savepoint;
}
/**
* Undoes all changes made after the given <code>Savepoint</code> object
* was set.
* <P>
* This method should be used only when auto-commit has been disabled.
*
* @param savepoint the <code>Savepoint</code> object to roll back to
* @exception SQLException if a database access error occurs,
* the <code>Savepoint</code> object is no longer valid,
* or this <code>Connection</code> object is currently in
* auto-commit mode
* @see Savepoint
* @see #rollback
* @since 1.4
*/
public void rollback(Savepoint savepoint) throws SQLException
{
if (!haveMinimumServerVersion("8.0"))
throw new PSQLException(GT.tr("Server versions prior to 8.0 do not support savepoints."), PSQLState.NOT_IMPLEMENTED);
PSQLSavepoint pgSavepoint = (PSQLSavepoint)savepoint;
execSQLUpdate("ROLLBACK TO SAVEPOINT " + pgSavepoint.getPGName());
}
/**
* Removes the given <code>Savepoint</code> object from the current
* transaction. Any reference to the savepoint after it have been removed
* will cause an <code>SQLException</code> to be thrown.
*
* @param savepoint the <code>Savepoint</code> object to be removed
* @exception SQLException if a database access error occurs or
* the given <code>Savepoint</code> object is not a valid
* savepoint in the current transaction
* @since 1.4
*/
public void releaseSavepoint(Savepoint savepoint) throws SQLException
{
if (!haveMinimumServerVersion("8.0"))
throw new PSQLException(GT.tr("Server versions prior to 8.0 do not support savepoints."), PSQLState.NOT_IMPLEMENTED);
PSQLSavepoint pgSavepoint = (PSQLSavepoint)savepoint;
execSQLUpdate("RELEASE SAVEPOINT " + pgSavepoint.getPGName());
pgSavepoint.invalidate();
}
/**
* Creates a <code>Statement</code> object that will generate
* <code>ResultSet</code> objects with the given type, concurrency,
* and holdability.
* This method is the same as the <code>createStatement</code> method
* above, but it allows the default result set
* type, concurrency, and holdability to be overridden.
*
* @param resultSetType one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @param resultSetConcurrency one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @param resultSetHoldability one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @return a new <code>Statement</code> object that will generate
* <code>ResultSet</code> objects with the given type,
* concurrency, and holdability
* @exception SQLException if a database access error occurs
* or the given parameters are not <code>ResultSet</code>
* constants indicating type, concurrency, and holdability
* @see ResultSet
* @since 1.4
*/
public abstract Statement createStatement(int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException;
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return createStatement(resultSetType, resultSetConcurrency, getHoldability());
}
/**
* Creates a <code>PreparedStatement</code> object that will generate
* <code>ResultSet</code> objects with the given type, concurrency,
* and holdability.
* <P>
* This method is the same as the <code>prepareStatement</code> method
* above, but it allows the default result set
* type, concurrency, and holdability to be overridden.
*
* @param sql a <code>String</code> object that is the SQL statement to
* be sent to the database; may contain one or more ? IN
* parameters
* @param resultSetType one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @param resultSetConcurrency one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @param resultSetHoldability one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @return a new <code>PreparedStatement</code> object, containing the
* pre-compiled SQL statement, that will generate
* <code>ResultSet</code> objects with the given type,
* concurrency, and holdability
* @exception SQLException if a database access error occurs
* or the given parameters are not <code>ResultSet</code>
* constants indicating type, concurrency, and holdability
* @see ResultSet
* @since 1.4
*/
public abstract PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException;
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return prepareStatement(sql, resultSetType, resultSetConcurrency, getHoldability());
}
/**
* Creates a <code>CallableStatement</code> object that will generate
* <code>ResultSet</code> objects with the given type and concurrency.
* This method is the same as the <code>prepareCall</code> method
* above, but it allows the default result set
* type, result set concurrency type and holdability to be overridden.
*
* @param sql a <code>String</code> object that is the SQL statement to
* be sent to the database; may contain on or more ? parameters
* @param resultSetType one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @param resultSetConcurrency one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @param resultSetHoldability one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @return a new <code>CallableStatement</code> object, containing the
* pre-compiled SQL statement, that will generate
* <code>ResultSet</code> objects with the given type,
* concurrency, and holdability
* @exception SQLException if a database access error occurs
* or the given parameters are not <code>ResultSet</code>
* constants indicating type, concurrency, and holdability
* @see ResultSet
* @since 1.4
*/
public abstract CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency,
int resultSetHoldability) throws SQLException;
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
return prepareCall(sql, resultSetType, resultSetConcurrency, getHoldability());
}
/**
* Creates a default <code>PreparedStatement</code> object that has
* the capability to retrieve auto-generated keys. The given constant
* tells the driver whether it should make auto-generated keys
* available for retrieval. This parameter is ignored if the SQL
* statement is not an <code>INSERT</code> statement.
* <P>
* <B>Note:</B> This method is optimized for handling
* parametric SQL statements that benefit from precompilation. If
* the driver supports precompilation,
* the method <code>prepareStatement</code> will send
* the statement to the database for precompilation. Some drivers
* may not support precompilation. In this case, the statement may
* not be sent to the database until the <code>PreparedStatement</code>
* object is executed. This has no direct effect on users; however, it does
* affect which methods throw certain SQLExceptions.
* <P>
* Result sets created using the returned <code>PreparedStatement</code>
* object will by default be type <code>TYPE_FORWARD_ONLY</code>
* and have a concurrency level of <code>CONCUR_READ_ONLY</code>.
*
* @param sql an SQL statement that may contain one or more '?' IN
* parameter placeholders
* @param autoGeneratedKeys a flag indicating whether auto-generated keys
* should be returned; one of the following <code>Statement</code>
* constants:
* <code>Statement.RETURN_GENERATED_KEYS</code> or
* <code>Statement.NO_GENERATED_KEYS</code>.
* @return a new <code>PreparedStatement</code> object, containing the
* pre-compiled SQL statement, that will have the capability of
* returning auto-generated keys
* @exception SQLException if a database access error occurs
* or the given parameter is not a <code>Statement</code>
* constant indicating whether auto-generated keys should be
* returned
* @since 1.4
*/
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
throws SQLException
{
if (autoGeneratedKeys != Statement.NO_GENERATED_KEYS)
sql = AbstractJdbc3Statement.addReturning(this, sql, new String[]{"*"}, false);
PreparedStatement ps = prepareStatement(sql);
if (autoGeneratedKeys != Statement.NO_GENERATED_KEYS)
((AbstractJdbc3Statement)ps).wantsGeneratedKeysAlways = true;
return ps;
}
/**
* Creates a default <code>PreparedStatement</code> object capable
* of returning the auto-generated keys designated by the given array.
* This array contains the indexes of the columns in the target
* table that contain the auto-generated keys that should be made
* available. This array is ignored if the SQL
* statement is not an <code>INSERT</code> statement.
* <P>
* An SQL statement with or without IN parameters can be
* pre-compiled and stored in a <code>PreparedStatement</code> object. This
* object can then be used to efficiently execute this statement
* multiple times.
* <P>
* <B>Note:</B> This method is optimized for handling
* parametric SQL statements that benefit from precompilation. If
* the driver supports precompilation,
* the method <code>prepareStatement</code> will send
* the statement to the database for precompilation. Some drivers
* may not support precompilation. In this case, the statement may
* not be sent to the database until the <code>PreparedStatement</code>
* object is executed. This has no direct effect on users; however, it does
* affect which methods throw certain SQLExceptions.
* <P>
* Result sets created using the returned <code>PreparedStatement</code>
* object will by default be type <code>TYPE_FORWARD_ONLY</code>
* and have a concurrency level of <code>CONCUR_READ_ONLY</code>.
*
* @param sql an SQL statement that may contain one or more '?' IN
* parameter placeholders
* @param columnIndexes an array of column indexes indicating the columns
* that should be returned from the inserted row or rows
* @return a new <code>PreparedStatement</code> object, containing the
* pre-compiled statement, that is capable of returning the
* auto-generated keys designated by the given array of column
* indexes
* @exception SQLException if a database access error occurs
*
* @since 1.4
*/
public PreparedStatement prepareStatement(String sql, int columnIndexes[])
throws SQLException
{
if (columnIndexes == null || columnIndexes.length == 0)
return prepareStatement(sql);
throw new PSQLException(GT.tr("Returning autogenerated keys is not supported."), PSQLState.NOT_IMPLEMENTED);
}
/**
* Creates a default <code>PreparedStatement</code> object capable
* of returning the auto-generated keys designated by the given array.
* This array contains the names of the columns in the target
* table that contain the auto-generated keys that should be returned.
* This array is ignored if the SQL
* statement is not an <code>INSERT</code> statement.
* <P>
* An SQL statement with or without IN parameters can be
* pre-compiled and stored in a <code>PreparedStatement</code> object. This
* object can then be used to efficiently execute this statement
* multiple times.
* <P>
* <B>Note:</B> This method is optimized for handling
* parametric SQL statements that benefit from precompilation. If
* the driver supports precompilation,
* the method <code>prepareStatement</code> will send
* the statement to the database for precompilation. Some drivers
* may not support precompilation. In this case, the statement may
* not be sent to the database until the <code>PreparedStatement</code>
* object is executed. This has no direct effect on users; however, it does
* affect which methods throw certain SQLExceptions.
* <P>
* Result sets created using the returned <code>PreparedStatement</code>
* object will by default be type <code>TYPE_FORWARD_ONLY</code>
* and have a concurrency level of <code>CONCUR_READ_ONLY</code>.
*
* @param sql an SQL statement that may contain one or more '?' IN
* parameter placeholders
* @param columnNames an array of column names indicating the columns
* that should be returned from the inserted row or rows
* @return a new <code>PreparedStatement</code> object, containing the
* pre-compiled statement, that is capable of returning the
* auto-generated keys designated by the given array of column
* names
* @exception SQLException if a database access error occurs
*
* @since 1.4
*/
public PreparedStatement prepareStatement(String sql, String columnNames[])
throws SQLException
{
if (columnNames != null && columnNames.length != 0)
sql = AbstractJdbc3Statement.addReturning(this, sql, columnNames, true);
PreparedStatement ps = prepareStatement(sql);
if (columnNames != null && columnNames.length != 0)
((AbstractJdbc3Statement)ps).wantsGeneratedKeysAlways = true;
return ps;
}
}
|
package swarm.client.navigation;
import java.util.ArrayList;
import java.util.logging.Logger;
import com.google.gwt.dom.client.Document;
import swarm.client.app.AppContext;
import swarm.client.entities.BufferCell;
import swarm.client.entities.Camera;
import swarm.client.input.BrowserHistoryManager;
import swarm.client.input.BrowserAddressManager;
import swarm.client.managers.CameraManager;
import swarm.client.managers.CellBufferManager;
import swarm.client.states.camera.Action_Camera_SnapToPoint;
import swarm.client.states.camera.Action_Camera_SetInitialPosition;
import swarm.client.states.camera.Action_Camera_SnapToAddress;
import swarm.client.states.camera.Action_Camera_SnapToCoordinate;
import swarm.client.states.camera.Event_Camera_OnAddressResponse;
import swarm.client.states.camera.Event_GettingMapping_OnResponse;
import swarm.client.states.camera.StateMachine_Camera;
import swarm.client.states.camera.State_CameraFloating;
import swarm.client.states.camera.State_CameraSnapping;
import swarm.client.states.camera.State_ViewingCell;
import swarm.client.view.ViewContext;
import swarm.client.view.tooltip.ToolTipManager;
import swarm.client.view.widget.Magnifier;
import swarm.shared.debugging.U_Debug;
import swarm.shared.json.A_JsonFactory;
import swarm.shared.json.I_JsonObject;
import swarm.shared.statemachine.A_Action;
import swarm.shared.statemachine.A_State;
import swarm.shared.statemachine.I_StateEventListener;
import swarm.shared.statemachine.StateContext;
import swarm.shared.statemachine.StateEvent;
import swarm.shared.structs.CellAddress;
import swarm.shared.structs.CellAddressMapping;
import swarm.shared.structs.E_CellAddressParseError;
import swarm.shared.structs.E_GetCellAddressMappingError;
import swarm.shared.structs.GetCellAddressMappingResult;
import swarm.shared.structs.GridCoordinate;
import swarm.shared.structs.Point;
import swarm.shared.utils.ListenerManager;
/**
* Responsible for piping user navigation to the state machine via the browser back/forward/refresh buttons and address bar.
*
* @author Doug
*
*/
public class BrowserNavigator implements I_StateEventListener
{
public interface I_StateChangeListener
{
void onStateChange();
}
private static final Logger s_logger = Logger.getLogger(BrowserNavigator.class.getName());
private final static String FLOATING_STATE_PATH = "/";
private final HistoryStateManager m_historyManager;
private final BrowserAddressManager m_addressManager;
private Event_Camera_OnAddressResponse.Args m_args_OnAddressResponse = null;
private Event_GettingMapping_OnResponse.Args m_args_OnMappingResponse = null;
private final Action_Camera_SnapToPoint.Args m_args_SnapToPoint = new Action_Camera_SnapToPoint.Args();
private final Action_Camera_SnapToAddress.Args m_args_SnapToAddress = new Action_Camera_SnapToAddress.Args();
private final Action_Camera_SnapToCoordinate.Args m_args_SnapToCoordinate = new Action_Camera_SnapToCoordinate.Args();
private Class<? extends A_Action> m_lastSnapAction = null;
private boolean m_pushHistoryStateForFloating = true;
private boolean m_receivedFloatingStateEntered = false;
private boolean m_stateAlreadyPushedForViewingExit = false;
private double m_lastTimeFloatingStateSet = 0;
private final HistoryStateManager.I_Listener m_historyStateListener;
private final double m_floatingHistoryUpdateRate;
private final CameraManager m_cameraMngr;
private final StateContext m_stateContext;
private final ViewContext m_viewContext;
private final Point m_utilPoint1 = new Point();
private final ListenerManager<I_StateChangeListener> m_listenerManager = new ListenerManager<I_StateChangeListener>();
public BrowserNavigator(ViewContext viewContext, String defaultPageTitle, double floatingHistoryUpdateRate_seconds)
{
m_viewContext = viewContext;
m_stateContext = m_viewContext.stateContext;
m_cameraMngr = m_viewContext.appContext.cameraMngr;
m_floatingHistoryUpdateRate = floatingHistoryUpdateRate_seconds;
m_args_SnapToCoordinate.set(this.getClass());
m_args_SnapToPoint.set(this.getClass());
m_historyStateListener = new HistoryStateManager.I_Listener()
{
@Override
public void onStateChange(String url, HistoryState state)
{
//TODO: The 'repushState' conditions here are fringe cases that haven't been tested, and will most likely
// not do anything useful. They hit if, for example, a blocking modal dialog is up (e.g. connection error)
// and the user hits the browser back button to go to a previous cell. Currently the modal will prevent the action
// from being performed...in order to repush that history state, we'd need to track the last history state here manually
// because 'url' parameter points to the destination cell...that's arguably a broken UX though...best option might be to
// somehow dismiss the modal in this specific case, but there could be other reasons that the snap action is not performable...
// sticky situation!
if( state == null )
{
U_Debug.ASSERT(false, "History state shouldn't be null.");
return;
}
if( state.getMapping() != null )
{
m_args_SnapToCoordinate.init(state.getMapping().getCoordinate());
if( !m_stateContext.isPerformable(Action_Camera_SnapToCoordinate.class, m_args_SnapToCoordinate) )
{
m_historyManager.pushState(url, state.getMapping());
}
else
{
m_stateContext.perform(Action_Camera_SnapToCoordinate.class, m_args_SnapToCoordinate);
}
}
else if( state.getPoint() != null )
{
if( !m_stateContext.isPerformable(Action_Camera_SnapToPoint.class) )
{
m_historyManager.pushState(url, state.getPoint());
}
else
{
/*m_args_SetInitialPosition.init(state.getPoint());
if( m_stateContext.performAction(Action_Camera_SetInitialPosition.class, m_args_SetInitialPosition) )
{
//s_logger.info("SETTING INITIAL POINT: " + state.getPoint());
}
else*/
{
A_State cameraMachine = m_stateContext.getEntered(StateMachine_Camera.class);
boolean instant = cameraMachine != null && cameraMachine.getUpdateCount() == 0;
m_args_SnapToPoint.init(state.getPoint(), instant, true);
m_stateContext.perform(Action_Camera_SnapToPoint.class, m_args_SnapToPoint);
//s_logger.info("SETTING TARGET POINT: " + state.getPoint());
}
}
}
else
{
}
dispatchStateChange();
}
};
m_addressManager = new BrowserAddressManager();
m_historyManager = new HistoryStateManager(m_viewContext.appContext.jsonFactory, defaultPageTitle, m_historyStateListener, m_addressManager);
}
public void addStateChangeListener(I_StateChangeListener listener)
{
m_listenerManager.addListenerToBack(listener);
}
private void dispatchStateChange()
{
ArrayList<I_StateChangeListener> m_listeners = m_listenerManager.getListeners();
for( int i = 0; i < m_listeners.size(); i++ )
{
m_listeners.get(i).onStateChange();
}
}
public void go(int offset)
{
m_historyManager.go(offset);
}
private CellAddress getBrowserCellAddress()
{
String path = m_addressManager.getCurrentPath();
CellAddress address = new CellAddress(path);
E_CellAddressParseError parseError = address.getParseError();
if( parseError != E_CellAddressParseError.EMPTY )
{
return address;
}
else
{
return null;
}
}
private void setViewingEnterHistory(CellAddress address, CellAddressMapping mapping)
{
if( m_stateAlreadyPushedForViewingExit )
{
m_historyManager.setState(address, mapping);
}
else
{
m_historyManager.pushState(address, mapping);
}
}
@Override
public void onStateEvent(StateEvent event)
{
switch(event.getType())
{
case DID_ENTER:
{
if ( event.getState() instanceof StateMachine_Camera )
{
HistoryState currentHistoryState = m_historyManager.getCurrentState();
CellAddress address = getBrowserCellAddress();
if( currentHistoryState == null || currentHistoryState.isEmpty() )
{
if( address != null )
{
m_pushHistoryStateForFloating = false;
m_stateAlreadyPushedForViewingExit = true;
m_historyManager.setState(address, new HistoryState()); // set empty state
m_args_SnapToAddress.init(address);
event.getContext().perform(Action_Camera_SnapToAddress.class, m_args_SnapToAddress);
}
else
{
m_pushHistoryStateForFloating = false;
m_historyManager.setState(FLOATING_STATE_PATH, m_cameraMngr.getCamera().getPosition());
m_utilPoint1.copy(m_cameraMngr.getCamera().getPosition());
m_utilPoint1.incZ(-m_viewContext.config.initialBumpDistance);
m_args_SnapToPoint.init(m_utilPoint1, false, false);
event.getContext().perform(Action_Camera_SnapToPoint.class, m_args_SnapToPoint);
}
}
else
{
String path;
if( address == null )
{
path = FLOATING_STATE_PATH;
}
else
{
path = address.getCasedRawLeadSlash();
Document.get().setTitle(path); // manually doing this because for some reason history api sometimes won't set the title
}
m_historyStateListener.onStateChange(path, currentHistoryState);
}
}
else if( event.getState() instanceof State_ViewingCell )
{
State_ViewingCell viewingState = event.getState();
if( m_lastSnapAction == null )
{
BufferCell cell = viewingState.getCell();
CellAddress address = cell.getAddress();
if( address != null )
{
m_historyManager.setState(address, new CellAddressMapping(cell.getCoordinate()));
}
}
else
{
if( m_lastSnapAction == Action_Camera_SnapToCoordinate.class )
{
U_Debug.ASSERT(m_args_OnMappingResponse == null, "sm_bro_nav_112389");
boolean pushEmptyState = false;
BufferCell cell = viewingState.getCell();
CellAddressMapping mapping = new CellAddressMapping(cell.getCoordinate());
if( m_args_OnAddressResponse != null )
{
if( m_args_OnAddressResponse.getType() == Event_Camera_OnAddressResponse.E_Type.ON_FOUND )
{
this.setViewingEnterHistory(m_args_OnAddressResponse.getAddress(), mapping);
}
else
{
pushEmptyState = true;
}
}
else
{
if( cell.getAddress() != null )
{
this.setViewingEnterHistory(cell.getAddress(), mapping);
}
else
{
pushEmptyState = true;
}
}
if( pushEmptyState )
{
if( m_stateAlreadyPushedForViewingExit )
{
m_historyManager.setState(FLOATING_STATE_PATH, mapping);
}
else
{
m_historyManager.pushState(FLOATING_STATE_PATH, mapping);
}
}
}
else if( m_lastSnapAction == Action_Camera_SnapToAddress.class )
{
//U_Debug.ASSERT(m_args_OnAddressResponse == null, "sm_bro_nav_112387");
if( m_args_OnMappingResponse != null )
{
if( m_args_OnMappingResponse.getType() == Event_GettingMapping_OnResponse.E_Type.ON_FOUND )
{
if( m_historyManager.getCurrentState() == null )
{
CellAddress address = this.getBrowserCellAddress();
if( address != null )
{
m_historyManager.setState(address, m_args_OnMappingResponse.getMapping());
}
else
{
U_Debug.ASSERT(false, "with current history state null with last snap action being to address, browser address should have existed");
}
}
else
{
this.setViewingEnterHistory(m_args_OnMappingResponse.getAddress(), m_args_OnMappingResponse.getMapping());
}
}
else
{
U_Debug.ASSERT(false, "sm_bro_nav_asaswwewe");
}
}
else
{
U_Debug.ASSERT(false, "sm_bro_nav_87654332");
}
}
else
{
U_Debug.ASSERT(false, "sm_bro_nav_193498");
}
}
m_args_OnAddressResponse = null;
m_args_OnMappingResponse = null;
m_lastSnapAction = null;
m_stateAlreadyPushedForViewingExit = false;
}
else if( event.getState() instanceof State_CameraFloating )
{
m_receivedFloatingStateEntered = true;
m_lastTimeFloatingStateSet = 0;
if( m_historyManager.getCurrentState() == null )
{
m_historyManager.setState(FLOATING_STATE_PATH, m_cameraMngr.getCamera().getPosition());
}
else
{
if( m_pushHistoryStateForFloating )
{
StateMachine_Camera machine = m_stateContext.getEntered(StateMachine_Camera.class);
if( m_stateAlreadyPushedForViewingExit || event.getState().getPreviousState() == State_CameraSnapping.class )
{
m_historyManager.setState(FLOATING_STATE_PATH, m_cameraMngr.getTargetPosition());
}
else
{
m_historyManager.pushState(FLOATING_STATE_PATH, m_cameraMngr.getTargetPosition());
}
}
}
}
else if( event.getState() instanceof State_CameraSnapping )
{
if( event.getState().getPreviousState() == State_ViewingCell.class )
{
//StateMachine_Camera machine = smA_State.getEnteredInstance(StateMachine_Camera.class);
if( m_lastSnapAction != null )
{
m_historyManager.pushState(FLOATING_STATE_PATH, m_cameraMngr.getCamera().getPosition());
m_stateAlreadyPushedForViewingExit = true;
}
}
}
break;
}
case DID_UPDATE:
{
if( event.getState() instanceof State_CameraFloating )
{
if( event.getState().isEntered() ) // just to make sure
{
if( m_cameraMngr.didCameraJustComeToRest() )
{
this.setPositionForFloatingState(event.getState(), m_cameraMngr.getCamera().getPosition(), true);
}
}
}
break;
}
case DID_EXIT:
{
if( event.getState() instanceof State_CameraFloating )
{
if( m_lastSnapAction != null )
{
A_State state = m_stateContext.getEntered(StateMachine_Camera.class);
if( state != null && state.getUpdateCount() > 0 ) // dunno why it would be null, just being paranoid before a deploy
{
this.setPositionForFloatingState(event.getState(), m_cameraMngr.getCamera().getPosition(), true);
}
m_receivedFloatingStateEntered = false;
}
}
break;
}
case DID_PERFORM_ACTION:
{
if( event.getAction() == Event_Camera_OnAddressResponse.class )
{
Event_Camera_OnAddressResponse.Args args = event.getActionArgs();
if( event.getContext().isEntered(State_CameraSnapping.class) )
{
m_args_OnAddressResponse = args;
}
else if( event.getContext().isEntered(State_ViewingCell.class) )
{
m_args_OnAddressResponse = null;
State_ViewingCell viewingState = event.getContext().getEntered(State_ViewingCell.class);
if( viewingState.getCell().getCoordinate().isEqualTo(args.getMapping().getCoordinate()) )
if( args.getType() == Event_Camera_OnAddressResponse.E_Type.ON_FOUND )
{
m_historyManager.setState(args.getAddress(), args.getMapping());
}
}
else
{
U_Debug.ASSERT(false, "sm_nav_1");
}
}
else if( event.getAction() == Event_GettingMapping_OnResponse.class )
{
Event_GettingMapping_OnResponse.Args args = event.getActionArgs();
m_args_OnMappingResponse = args;
if( args.getType() != Event_GettingMapping_OnResponse.E_Type.ON_FOUND )
{
m_historyManager.setState(FLOATING_STATE_PATH, m_cameraMngr.getCamera().getPosition());
}
}
else if( event.getAction() == Action_Camera_SnapToAddress.class ||
event.getAction() == Action_Camera_SnapToCoordinate.class )
{
m_args_OnAddressResponse = null;
if( event.getAction() == Action_Camera_SnapToCoordinate.class )
{
Action_Camera_SnapToCoordinate.Args args = event.getActionArgs();
Object userData = event.getActionArgs().get();
if( userData == this.getClass() ) // signifies that snap was because of browser navigation event.
{
m_lastSnapAction = null;
return;
}
if( args.onlyCausedRefresh() )
{
m_lastSnapAction = null;
return;
}
if( args.historyShouldIgnore )
{
//m_lastSnapAction = Action_Camera_SnapToAddress.class;
}
else
{
m_lastSnapAction = event.getAction();
m_args_OnMappingResponse = null;
}
}
else if( event.getAction() == Action_Camera_SnapToAddress.class )
{
m_args_OnMappingResponse = null;
Action_Camera_SnapToAddress.Args args = event.getActionArgs();
if( args.onlyCausedRefresh() )
{
m_lastSnapAction = null;
return;
}
m_lastSnapAction = event.getAction();
}
}
else if( event.getAction() == Action_Camera_SnapToPoint.class )
{
State_CameraFloating floatingState = m_stateContext.getEntered(State_CameraFloating.class);
m_pushHistoryStateForFloating = true;
if( floatingState != null )
{
Action_Camera_SnapToPoint.Args args = event.getActionArgs();
if( args != null )
{
m_pushHistoryStateForFloating = args.get() != this.getClass();
if( m_receivedFloatingStateEntered )
{
Point point = args.getPoint();
if( point != null )
{
//setPositionForFloatingState(floatingState, point, false);
}
}
}
}
else
{
//smU_Debug.ASSERT(false, "floating state should have been entered.");
}
}
break;
}
}
}
public boolean hasBack()
{
return m_historyManager.hasBack();
}
public boolean hasForward()
{
return m_historyManager.hasForward();
}
public void setPositionForFloatingState(A_State state, Point point, boolean force)
{
double timeInState = state.getTotalTimeInState();
if( force || timeInState - m_lastTimeFloatingStateSet >= m_floatingHistoryUpdateRate )
{
m_historyManager.setState(FLOATING_STATE_PATH, point);
m_lastTimeFloatingStateSet = timeInState;
}
}
}
|
package org.gluewine.console;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
/**
* Defines a command that can be entered through the console.
*
* @author fks/Serge de Schaetzen
*
*/
public class CLICommand
{
/**
* The name of the command.
* <br>(without leading underscore '_')
*/
private String name = null;
/**
* The description of the command.
*/
private String description = null;
/**
* Set of required options.
*/
private Set<CLIOption> options = new HashSet<CLIOption>();
/**
* Creates an instance.
*
* @param name The name of the command.
* @param description The command description.
*/
public CLICommand(String name, String description)
{
this.name = name;
this.description = description;
}
/**
* Returns the name of the command.
*
* @return The name of the command.
*/
public String getName()
{
return name;
}
/**
* Returns the description.
*
* @return The description.
*/
public String getDescription()
{
return description;
}
/**
* Adds an option.
*
* @param option The option to add.
*/
public void addOption(CLIOption option)
{
options.add(option);
}
/**
* Adds an option. This is a convenience method and is identical to:
* <br>addOption(new CLIOption(name, description, required, needsValue).
*
* @param name The name of the option.
* @param description The description.
* @param required True if the option is required.
* @param needsValue True if the option requires a value.
*/
public void addOption(String name, String description, boolean required, boolean needsValue)
{
options.add(new CLIOption(name, description, required, needsValue));
}
/**
* Returns the (sorted) set of options. If the command has no options, an
* empty set is returned.
*
* @return The set of options.
*/
public Set<CLIOption> getOptions()
{
Set<CLIOption> s = new TreeSet<CLIOption>();
s.addAll(options);
return s;
}
}
|
package test.blog.distrib;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import blog.distrib.UnivarGaussian;
/**
* Unit tests for Univariate Gaussian
*/
@RunWith(JUnit4.class)
public class TestUnivariateGaussian {
private HashMap<Double, Double> probVals;
private final double MEAN = 0.5;
private final double VARIANCE = 2.25;
private final double ERROR = 1e-9;
/** Univariate Gaussian, MEAN = 0.5, VARIANCe = 2.25. */
public void testGaussian(UnivarGaussian gaussian) {
assertEquals(0.25158881846199549, gaussian.getProb(0.0), ERROR);
assertEquals(0.26360789392387846, gaussian.getProb(0.3), ERROR);
assertEquals(0.25667124973067595, gaussian.getProb(0.9), ERROR);
assertEquals(0.082088348017233054, gaussian.getProb(2.8), ERROR);
assertEquals(0.023649728564154305, gaussian.getProb(3.8), ERROR);
assertEquals(0.00032018043441388045, gaussian.getProb(6.0), ERROR);
assertEquals(Math.log(0.25158881846199549), gaussian.getLogProb(0.0), ERROR);
assertEquals(Math.log(0.26360789392387846), gaussian.getLogProb(0.3), ERROR);
assertEquals(Math.log(0.25667124973067595), gaussian.getLogProb(0.9), ERROR);
assertEquals(Math.log(0.082088348017233054), gaussian.getLogProb(2.8),
ERROR);
assertEquals(Math.log(0.023649728564154305), gaussian.getLogProb(3.8),
ERROR);
assertEquals(Math.log(0.00032018043441388045), gaussian.getLogProb(6.0),
ERROR);
}
/** Univariate Gaussian, MEAN = 0.0, VARIANCE = 1.0. */
public void testGaussian2(UnivarGaussian gaussian) {
assertEquals(0.24197072451914337, gaussian.getProb(-1.0), ERROR);
assertEquals(0.35206532676429952, gaussian.getProb(-0.5), ERROR);
assertEquals(0.3989422804014327, gaussian.getProb(0), ERROR);
assertEquals(Math.log(0.24197072451914337), gaussian.getLogProb(-1.0),
ERROR);
assertEquals(Math.log(0.35206532676429952), gaussian.getLogProb(-0.5),
ERROR);
assertEquals(Math.log(0.3989422804014327), gaussian.getLogProb(0), ERROR);
}
public TestUnivariateGaussian() {
// We have a normal random variable Z ~ N(0.5, 1.5)
probVals = new HashMap<Double, Double>();
probVals.put(0.0, 0.25158881846199549);
probVals.put(0.3, 0.26360789392387846);
probVals.put(0.9, 0.25667124973067595);
probVals.put(2.8, 0.082088348017233054);
probVals.put(3.8, 0.023649728564154305);
probVals.put(6.0, 0.00032018043441388045);
}
@Test
public void testFixedMeanFixedVariance() {
Double[] params = { MEAN, VARIANCE };
UnivarGaussian gaussian = new UnivarGaussian();
gaussian.setParams(params);
testGaussian(gaussian);
}
@Test
public void testRandomMeanFixedVariance() {
Double[] params = { null, VARIANCE };
UnivarGaussian gaussian = new UnivarGaussian();
gaussian.setParams(params);
gaussian.setParams(MEAN, null);
testGaussian(gaussian);
}
@Test
public void testFixedMeanRandomVariance() {
Double[] params = { MEAN, null };
UnivarGaussian gaussian = new UnivarGaussian();
gaussian.setParams(params);
gaussian.setParams(null, VARIANCE);
testGaussian(gaussian);
}
@Test
public void testRandomMeanRandomVariance() {
Double[] params = { null, null };
UnivarGaussian gaussian = new UnivarGaussian();
gaussian.setParams(params);
gaussian.setParams(MEAN, VARIANCE);
testGaussian(gaussian);
}
@Test
public void testDoubleSet() {
UnivarGaussian gaussian = new UnivarGaussian();
gaussian.setParams(MEAN, null);
gaussian.setParams(null, VARIANCE);
testGaussian(gaussian);
}
@Test
public void testSetParamsIntegerArguments() {
// Tests that providing integer arguments to mean and variance works
// correctly.
UnivarGaussian gaussian = new UnivarGaussian();
gaussian.setParams(0, 1);
testGaussian2(gaussian);
}
public void testGetProbIntegerArguments() {
// Tests providing integer arguments to getProb
UnivarGaussian gaussian = new UnivarGaussian();
gaussian.setParams(0, 1);
assertEquals(0.3989422804014327, gaussian.getProb(0), ERROR);
assertEquals(Math.log(0.3989422804014327), gaussian.getLogProb(0), ERROR);
}
@Test(expected = IllegalArgumentException.class)
public void testInSufficientArguments1() {
UnivarGaussian gaussian = new UnivarGaussian();
gaussian.setParams(null, VARIANCE);
testGaussian(gaussian);
}
@Test(expected = IllegalArgumentException.class)
public void testInSufficientArguments2() {
UnivarGaussian gaussian = new UnivarGaussian();
gaussian.setParams(MEAN, null);
testGaussian(gaussian);
}
@Test(expected = IllegalArgumentException.class)
public void testIncorrectNumberArguments() {
Double[] params = new Double[1];
UnivarGaussian gaussian = new UnivarGaussian();
gaussian.setParams(params);
testGaussian(gaussian);
}
}
|
package com.jcabi.github;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Test;
/**
* Integration case for {@link Issue}.
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @checkstyle ClassDataAbstractionCoupling (500 lines)
*/
public final class RtIssueITCase {
/**
* RtIssue can talk in github.
* @throws Exception If some problem inside
*/
@Test
public void talksInGithubProject() throws Exception {
final Issue issue = RtIssueITCase.issue();
final Comment comment = issue.comments().post("hey, works?");
MatcherAssert.assertThat(
new Comment.Smart(comment).body(),
Matchers.startsWith("hey, ")
);
MatcherAssert.assertThat(
issue.comments().iterate(),
Matchers.<Comment>iterableWithSize(1)
);
final User.Smart author = new User.Smart(
new Comment.Smart(comment)
.author()
);
final User.Smart self = new User.Smart(
issue.repo().github().users().self()
);
if (author.hasName() && self.hasName()) {
MatcherAssert.assertThat(
author.name(),
Matchers.equalTo(
self.name()
)
);
}
comment.remove();
}
/**
* RtIssue can change title and body.
* @throws Exception If some problem inside
*/
@Test
public void changesTitleAndBody() throws Exception {
final Issue issue = RtIssueITCase.issue();
new Issue.Smart(issue).title("test one more time");
MatcherAssert.assertThat(
new Issue.Smart(issue).title(),
Matchers.startsWith("test o")
);
new Issue.Smart(issue).body("some new body of the issue");
MatcherAssert.assertThat(
new Issue.Smart(issue).body(),
Matchers.startsWith("some new ")
);
}
/**
* RtIssue can change issue state.
* @throws Exception If some problem inside
*/
@Test
public void changesIssueState() throws Exception {
final Issue issue = RtIssueITCase.issue();
new Issue.Smart(issue).close();
MatcherAssert.assertThat(
new Issue.Smart(issue).isOpen(),
Matchers.is(false)
);
new Issue.Smart(issue).open();
MatcherAssert.assertThat(
new Issue.Smart(issue).isOpen(),
Matchers.is(true)
);
}
/**
* RtIssue can fetch assignee.
*
* @throws Exception if any problem inside.
* @todo #802 RtIssueITCase.identifyAssignee() fails during Rultor build
*/
@Test
@Ignore
public void identifyAssignee() throws Exception {
final Issue issue = RtIssueITCase.issue();
final String login = issue.repo().github().users().self().login();
new Issue.Smart(issue).assign(login);
final User assignee = new Issue.Smart(issue).assignee();
MatcherAssert.assertThat(
assignee.login(),
Matchers.equalTo(login)
);
}
/**
* RtIssue can check whether it is a pull request.
* @throws Exception If some problem inside
*/
@Test
public void checksForPullRequest() throws Exception {
final Issue issue = RtIssueITCase.issue();
MatcherAssert.assertThat(
new Issue.Smart(issue).isPull(),
Matchers.is(false)
);
}
/**
* GhIssue can list issue events.
* @throws Exception If some problem inside
*/
@Test
public void listsIssueEvents() throws Exception {
final Issue issue = RtIssueITCase.issue();
new Issue.Smart(issue).close();
MatcherAssert.assertThat(
new Event.Smart(issue.events().iterator().next()).type(),
Matchers.equalTo(Event.CLOSED)
);
}
/**
* Issue.Smart can find the latest event.
* @throws Exception If some problem inside
*/
@Test
public void findsLatestEvent() throws Exception {
final Issue.Smart issue = new Issue.Smart(RtIssueITCase.issue());
issue.close();
MatcherAssert.assertThat(
new Event.Smart(
new Issue.Smart(issue).latestEvent(Event.CLOSED)
).author().login(),
Matchers.equalTo(issue.author().login())
);
}
/**
* Create and return issue to test.
* @return Issue
* @throws Exception If some problem inside
*/
private static Issue issue() throws Exception {
final String key = System.getProperty("failsafe.github.key");
Assume.assumeThat(key, Matchers.notNullValue());
return new RtGithub(key).repos().get(
new Coordinates.Simple(System.getProperty("failsafe.github.repo"))
).issues().create("test issue title", "test issue body");
}
}
|
package guitests;
import javafx.scene.control.ComboBox;
import javafx.scene.input.KeyCode;
import org.junit.Test;
import ui.UI;
import ui.components.KeyboardShortcuts;
import ui.listpanel.ListPanel;
import util.events.IssueSelectedEventHandler;
import util.events.PanelClickedEventHandler;
import util.events.testevents.UIComponentFocusEvent;
import util.events.testevents.UIComponentFocusEventHandler;
import static org.junit.Assert.assertEquals;
import static ui.components.KeyboardShortcuts.DOUBLE_PRESS;
public class KeyboardShortcutsTest extends UITest {
private UIComponentFocusEvent.EventType uiComponentFocusEventType;
private int selectedIssueId;
private int panelIndex;
@Test
public void keyboardShortcutsTest() {
UI.events.registerEvent((IssueSelectedEventHandler) e -> selectedIssueId = e.id);
UI.events.registerEvent((UIComponentFocusEventHandler) e -> uiComponentFocusEventType = e.eventType);
UI.events.registerEvent((PanelClickedEventHandler) e -> panelIndex = e.panelIndex);
clearSelectedIssueId();
clearUiComponentFocusEventType();
clearPanelIndex();
// maximize
assertEquals(false, stage.getMinWidth() > 500);
press(KeyCode.CONTROL).press(KeyCode.X).release(KeyCode.X).release(KeyCode.CONTROL);
assertEquals(true, stage.getMinWidth() > 500);
// mid-sized window
press(KeyCode.CONTROL).press(KeyCode.D).release(KeyCode.D).release(KeyCode.CONTROL);
assertEquals(false, stage.getMinWidth() > 500);
// jump from filter box to first issue
press(KeyCode.CONTROL).press(KeyCode.DOWN).release(KeyCode.DOWN).release(KeyCode.CONTROL);
assertEquals(10, selectedIssueId);
clearSelectedIssueId();
// jump from issue list to filter box
press(KeyCode.CONTROL).press(KeyCode.UP).release(KeyCode.UP).release(KeyCode.CONTROL);
assertEquals(UIComponentFocusEvent.EventType.FILTER_BOX, uiComponentFocusEventType);
clearUiComponentFocusEventType();
// jump from filter box to first issue
push(DOUBLE_PRESS).push(DOUBLE_PRESS);
assertEquals(10, selectedIssueId);
clearSelectedIssueId();
// jump from issue list to filter box
push(DOUBLE_PRESS).push(DOUBLE_PRESS);
assertEquals(UIComponentFocusEvent.EventType.FILTER_BOX, uiComponentFocusEventType);
clearUiComponentFocusEventType();
push(DOUBLE_PRESS).push(DOUBLE_PRESS);
// jump to last issue
push(KeyCode.END);
assertEquals(1, selectedIssueId);
clearSelectedIssueId();
// jump to first issue
push(KeyCode.HOME);
sleep(1000);
assertEquals(10, selectedIssueId);
clearSelectedIssueId();
push(getKeyCode("DOWN_ISSUE"));
assertEquals(9, selectedIssueId);
clearSelectedIssueId();
push(getKeyCode("DOWN_ISSUE"));
assertEquals(8, selectedIssueId);
clearSelectedIssueId();
push(getKeyCode("UP_ISSUE"));
assertEquals(9, selectedIssueId);
clearSelectedIssueId();
press(KeyCode.CONTROL).press(KeyCode.P).release(KeyCode.P).release(KeyCode.CONTROL);
push(DOUBLE_PRESS).push(DOUBLE_PRESS);
push(getKeyCode("RIGHT_PANEL"));
assertEquals(0, panelIndex);
clearPanelIndex();
push(getKeyCode("LEFT_PANEL"));
assertEquals(1, panelIndex);
clearPanelIndex();
push(getKeyCode("RIGHT_PANEL"));
assertEquals(0, panelIndex);
clearPanelIndex();
push(getKeyCode("LEFT_PANEL"));
assertEquals(1, panelIndex);
clearPanelIndex();
// remove focus from repo selector
ComboBox<String> comboBox = find("#repositorySelector");
doubleClick(comboBox);
assertEquals(true, comboBox.isFocused());
press(KeyCode.ESCAPE).release(KeyCode.ESCAPE);
assertEquals(false, comboBox.isFocused());
clearUiComponentFocusEventType();
click("#dummy/dummy_col1_1");
// mark as read
ListPanel issuePanel = find("#dummy/dummy_col1");
// mark as read an issue that has another issue below it
push(KeyCode.HOME);
// focus should change to the issue below
int issueIdBeforeMark = selectedIssueId;
int issueIdExpected = issueIdBeforeMark - 1;
push(getKeyCode("MARK_AS_READ"));
assertEquals(issueIdExpected, selectedIssueId);
push(getKeyCode("UP_ISSUE")); //required since focus has changed to next issue
assertEquals(true, issuePanel.getSelectedIssue().isCurrentlyRead());
// mark as read an issue at the bottom
push(KeyCode.END);
push(getKeyCode("MARK_AS_READ"));
// focus should remain at bottom issue
assertEquals(1, selectedIssueId);
assertEquals(true, issuePanel.getSelectedIssue().isCurrentlyRead());
// mark as unread
push(getKeyCode("MARK_AS_UNREAD"));
assertEquals(false, issuePanel.getSelectedIssue().isCurrentlyRead());
clearSelectedIssueId();
// testing corner case for mark as read where there is only one issue displayed
click("#dummy/dummy_col1_filterTextField");
type("id");
press(KeyCode.SHIFT).press(KeyCode.SEMICOLON).release(KeyCode.SEMICOLON).release(KeyCode.SHIFT);
type("5");
push(KeyCode.ENTER);
push(KeyCode.SPACE).push(KeyCode.SPACE);
push(getKeyCode("MARK_AS_READ"));
// focus should remain at the only issue shown
assertEquals(5, selectedIssueId);
// minimize window
press(KeyCode.CONTROL).press(KeyCode.N).release(KeyCode.N).release(KeyCode.CONTROL); // run this last
assertEquals(true, stage.isIconified());
}
public KeyCode getKeyCode(String shortcut) {
return KeyCode.getKeyCode(KeyboardShortcuts.getDefaultKeyboardShortcuts().get(shortcut));
}
public void clearSelectedIssueId() {
selectedIssueId = 0;
}
public void clearPanelIndex() {
panelIndex = -1;
}
public void clearUiComponentFocusEventType() {
uiComponentFocusEventType = UIComponentFocusEvent.EventType.NONE;
}
}
|
package io.vertx.ext.mail;
import io.vertx.core.Context;
import io.vertx.core.Vertx;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.impl.LoggerFactory;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.subethamail.wiser.Wiser;
/*
first implementation of a SMTP client
*/
@RunWith(VertxUnitRunner.class)
public class MailPoolTest {
private static final Logger log = LoggerFactory.getLogger(MailPoolTest.class);
@Ignore
@Test
public void mailTest(TestContext context) {
Vertx vertx = Vertx.vertx();
log.info("starting");
Async async = context.async();
MailService mailService = MailService.create(vertx, mailConfig());
MailMessage email = new MailMessage().setFrom("user@example.com").setTo("user@example.com")
.setSubject("Test email").setText("this is a message");
mailService.sendMail(email, result -> {
log.info("mail finished");
if (result.succeeded()) {
log.info(result.result().toString());
mailService.sendMail(email, result2 -> {
log.info("mail finished");
if (result2.succeeded()) {
log.info(result2.result().toString());
async.complete();
} else {
log.warn("got exception", result2.cause());
throw new RuntimeException(result2.cause());
}
});
} else {
log.warn("got exception", result.cause());
throw new RuntimeException(result.cause());
}
});
}
@Ignore
@Test
public void mailConcurrentTest(TestContext context) {
Vertx vertx = Vertx.vertx();
log.info("starting");
Async mail1 = context.async();
Async mail2 = context.async();
MailService mailService = MailService.create(vertx, mailConfig());
MailMessage email = new MailMessage().setFrom("user@example.com").setTo("user@example.com")
.setSubject("Test email").setText("this is a message");
mailService.sendMail(email, result -> {
log.info("mail finished");
if (result.succeeded()) {
log.info(result.result().toString());
mail1.complete();
} else {
log.warn("got exception", result.cause());
throw new RuntimeException(result.cause());
}
});
mailService.sendMail(email, result2 -> {
log.info("mail finished");
if (result2.succeeded()) {
log.info(result2.result().toString());
mail2.complete();
} else {
log.warn("got exception", result2.cause());
throw new RuntimeException(result2.cause());
}
});
}
@Test
public void mailConcurrent2Test(TestContext context) {
Vertx vertx = Vertx.vertx();
Async mail1 = context.async();
Async mail2 = context.async();
vertx.getOrCreateContext().runOnContext(v -> {
log.info("starting");
MailService mailService = MailService.create(vertx, mailConfig());
MailMessage email = new MailMessage().setFrom("user@example.com").setTo("user@example.com")
.setSubject("Test email").setText("this is a message");
log.info("starting mail 1");
mailService.sendMail(email, result -> {
log.info("mail finished");
if (result.succeeded()) {
log.info(result.result().toString());
mailService.sendMail(email, result2 -> {
log.info("mail finished");
if (result2.succeeded()) {
log.info(result2.result().toString());
mail1.complete();
} else {
log.warn("got exception", result2.cause());
throw new RuntimeException(result2.cause());
}
});
} else {
log.warn("got exception", result.cause());
throw new RuntimeException(result.cause());
}
});
log.info("starting mail 2");
mailService.sendMail(email, result -> {
log.info("mail finished");
if (result.succeeded()) {
log.info(result.result().toString());
mailService.sendMail(email, result2 -> {
log.info("mail finished");
if (result2.succeeded()) {
log.info(result2.result().toString());
mail2.complete();
} else {
log.warn("got exception", result2.cause());
throw new RuntimeException(result2.cause());
}
});
} else {
log.warn("got exception", result.cause());
throw new RuntimeException(result.cause());
}
});
});
}
/**
* @return
*/
private MailConfig mailConfig() {
return new MailConfig("localhost", 1587, StarttlsOption.DISABLED, LoginOption.DISABLED);
}
Wiser wiser;
@Before
public void startSMTP() {
wiser = new Wiser();
wiser.setPort(1587);
wiser.start();
}
@After
public void stopSMTP() {
if (wiser != null) {
wiser.stop();
}
// // TODO: ugly hack to make the unit tests work independent of each other
// MailServiceImpl.resetConnectionPool();
}
}
|
package jdungeonquest.test;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Server;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jdungeonquest.Game;
import jdungeonquest.gui.GUI;
import jdungeonquest.network.Network;
import jdungeonquest.network.NetworkClient;
import jdungeonquest.network.NetworkServer;
import jdungeonquest.network.RegistrationRequest;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static org.mockito.Mockito.*;
/**
* Tests for NetworkClient and NetworkServer.
*
* @author gman-x
*/
@RunWith(JUnit4.class)
public class NetworkTest {
@Test
public void NetworkClientConnectionSuccess() throws IOException{
final String clientName = "TestClient1";
final int port = 3335;
GUI guiMock = mock(GUI.class);
NetworkClient client = new NetworkClient(clientName, "127.0.0.1", port, guiMock);
Server server = new Server();
Network.registerClasses(server);
server.addListener(new Listener(){
@Override
public void received(Connection c, Object o){
if(o instanceof RegistrationRequest){
assertEquals(clientName, ((RegistrationRequest)o).getName());
c.sendTCP(new RegistrationRequest(clientName));
}
}
});
server.bind(port);
server.start();
client.run();
client.registerOnServer();
while(!client.isRegistered){}
boolean resultClient = client.isRegistered;
assertEquals(true, resultClient);
client.stop();
server.stop();
}
@Test
public void NetworkRegistrationSuccess() throws InterruptedException{
final String clientName = "TestClient1";
final int port = 3335;
GUI guiMock = mock(GUI.class);
NetworkClient client = new NetworkClient(clientName, "127.0.0.1", port, guiMock);
NetworkServer server = new NetworkServer(port);
server.run();
client.run();
client.registerOnServer();
Thread.sleep(100);
assertEquals(true, server.getGame().isPlayerRegistered(clientName));
client.stop();
server.stop();
}
}
|
package org.fosstrak.tdt;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import junit.framework.Assert;
import junit.framework.TestCase;
import net.sf.csv4j.CSVFieldMapProcessor;
import net.sf.csv4j.CSVFileProcessor;
import net.sf.csv4j.ParseException;
import net.sf.csv4j.ProcessingException;
import org.epcglobalinc.tdt.LevelTypeList;
public class TestCaseSgtin extends TestCase
{
private TDTEngine engine = null;
private Map<String,String> params;
protected void setUp() {
params = new HashMap<String,String>();
if (engine == null) {
try {
String s = System.getenv("TDT_PATH");
if (s == null) s = "target/classes";
engine = new TDTEngine();
}
catch (Exception e) {
e.printStackTrace(System.err);
//System.exit(1);
}
}
}
public void testPage13Staged() {
// this test follows fig 4 on page 13 of TDT Spec
// jpb trying this version using a staged approach, only going one level at a time.
params.put("taglength", "96");
params.put("filter", "3");
params.put("companyprefixlength", "7");
String orig = "gtin=00037000302414;serial=1041970";
String s = engine.convert(orig,
params,
LevelTypeList.BINARY);
String expect = "001100000111010000000010010000100010000000011101100010000100000000000000000011111110011000110010";
Assert.assertEquals(expect, s);
String s2 = engine.convert(s,
params,
LevelTypeList.TAG_ENCODING);
expect = "urn:epc:tag:sgtin-96:3.0037000.030241.1041970";
Assert.assertEquals(expect, s2);
System.out.println("te " + s2);
String s3 = engine.convert(s2,
params,
LevelTypeList.PURE_IDENTITY);
expect = "urn:epc:id:sgtin:0037000.030241.1041970";
Assert.assertEquals(expect, s3);
System.out.println("pi " + s3);
String s4 = engine.convert(s3,
params,
LevelTypeList.LEGACY);
Assert.assertEquals(orig, s4);
}
public void testPage13() {
// this test follows fig 4 on page 13 of TDT Spec
params.put("taglength", "96");
params.put("filter", "3");
params.put("companyprefixlength", "7");
String orig = "gtin=00037000302414;serial=1041970";
String s = engine.convert(orig,
params,
LevelTypeList.BINARY);
String expect = "001100000111010000000010010000100010000000011101100010000100000000000000000011111110011000110010";
Assert.assertEquals(expect, s);
String s2 = engine.convert(s,
params,
LevelTypeList.LEGACY);
Assert.assertEquals(orig, s2);
}
public void testPage26() {
// table 3 on page 26 has some legacy codes. Check that they
// convert back and forth to binary.
params.put("taglength", "96");
params.put("filter", "3");
params.put("companyprefixlength", "7");
String legacy [] =
{"gtin=00037000302414;serial=10419703",
"sscc=000370003024147856",
"gln=0003700030247;serial=1041970",
"grai=00037000302414274877906943",
"giai=00370003024149267890123",
"generalmanager=5;objectclass=17;serial=23",
"cageordodaac=AB123;serial=3789156"
};
for (String s : legacy) {
String s2 = engine.convert(s,
params,
LevelTypeList.BINARY);
System.out.println(" " + s + " -> " + s2);
String s3 = engine.convert(s2,
params,
LevelTypeList.LEGACY);
System.out.println(" -> " + s3);
Assert.assertEquals(s, s3);
}
}
public void testSgtin64() {
params.put("taglength", "64");
params.put("filter", "3");
params.put("companyprefixlength", "7");
String orig = "gtin=20073796510026;serial=1";
String s = engine.convert(orig,
params,
LevelTypeList.BINARY);
String expect = "1001100000010011110001111010100011110100000000000000000000000001";
// 9 8 1 3 c 7 a 8 f 4 0 0 0 0 0 1
Assert.assertEquals(expect, s);
}
public void testUsDod96() {
params.put("taglength", "96");
params.put("filter", "0");
String orig = "cageordodaac=2S194;serial=12345678901";
String s = engine.convert(orig,
params,
LevelTypeList.BINARY);
String expect = "001011110000001000000011001001010011001100010011100100110100001011011111110111000001110000110101";
// 2 f 0 2 0 3 2 5 3 3 1 3 9 3 4 2 d f d c 1 c 3 5
Assert.assertEquals(expect, s);
}
public void testUsDod64() {
params.put("taglength", "64");
params.put("filter", "1");
String orig = "cageordodaac=1D381;serial=16522293";
String s = engine.convert(orig,
params,
LevelTypeList.BINARY);
String expect = "1100111001110001000100110011111000110001111111000001110000110101";
// c e 7 1 1 3 3 e 3 1 f c 1 c 3 5
Assert.assertEquals(expect, s);
}
public void testCSVTestSet() throws ParseException, IOException, ProcessingException {
String testFile = "src/test/resources/TestCases1.csv";
File file = new File(testFile);
if (file.exists()) {
final CSVFileProcessor fp = new CSVFileProcessor();
fp.processFile( testFile, new CSVFieldMapProcessor() {
public void processDataLine( final int linenumber, final Map<String,String> fields ) {
System.out.println("Line: " + linenumber);
System.out.println("hex: " + fields.get("hex"));
System.out.println("urn: " + fields.get("urn"));
System.out.println("unknown: " + fields.get("unknown"));
System.out.println("status: " + fields.get("status"));
// print out the field names and values
// for ( final Entry field : fields.entrySet() ) {
//System.out.println( String.format( "Line #%d: field: %s=%s", linenumber, field.getKey(), field.getValue() ));
}
public boolean continueProcessing()
{
return true;
}
} );
}
}
/*
public void testNoGEPCSpecified() throws IOException, JAXBException {
File file = new File("target/auxiliary/ManagerTranslation.xml");
URL auxurl = file.toURL();
System.err.println(auxurl);
URL schemeurl = new URL("file:\\\\C:\\Documents and Settings\\floerkem\\Desktop\\tdttrunk\\target\\classes\\schemes");
engine = new TDTEngine(schemeurl,schemeurl);
System.err.println("My code is executed");
}
*/
}
|
package org.jdbdt.tutorial;
// Java/JDBC API imports
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;
//JUnit imports
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
// JDBDT import
import static org.jdbdt.JDBDT.*;
import org.jdbdt.Conversion;
import org.jdbdt.DB;
import org.jdbdt.DataSet;
import org.jdbdt.Table;
@SuppressWarnings("javadoc")
public class UserDAOTest {
// We'll make use of a H2 database
private static final String
JDBC_DRIVER_CLASS = "org.h2.Driver";
// H2 database URL
private static final String
DATABASE_URL = "jdbc:h2:./jdbdtTutorialDB";
// JDBDT handle for the database
static DB theDB;
// DAO (the SUT)
static UserDAO theDAO;
// User table.
static Table theTable;
// Fixed date used for test data
static final Date FIXED_DATE = Date.valueOf("2016-01-01");
// Data set that we use for populating the table.
// (we need this as a field so it can be referred to in a few test methods)
static DataSet theInitialData;
@BeforeClass
public static void globalSetup() throws Throwable {
// Setup
Class.forName(JDBC_DRIVER_CLASS);
theDB = database(DATABASE_URL);
theDB.getConnection().setAutoCommit(false);
theDAO = new UserDAO(theDB.getConnection());
theDAO.createTable();
theTable = table(theDB, "USERS")
.columns("ID",
"LOGIN",
"NAME",
"PASSWORD",
"CREATED" );
// Initial data
theInitialData
= builder(theTable)
.sequence("ID", 0)
.sequence("PASSWORD", i -> "pass" + i)
.value("LOGIN", "root")
.value("NAME", "Root user")
.value("CREATED", FIXED_DATE)
.generate(1)
.sequence("LOGIN", "alice", "bob", "charles")
.sequence("NAME", "Alice", "Bob", "Charles")
.generate(3)
.sequence("LOGIN", i -> "guest" + i)
.sequence("NAME", i -> "Guest User " + i)
.generate(2)
.data();
populate(theInitialData);
}
@AfterClass
public static void globalTeardown() {
truncate(theTable);
teardown(theDB, true);
}
private static final Conversion<User> CONVERSION =
u -> new Object[] {
u.getId(),
u.getLogin(),
u.getName(),
u.getPassword(),
u.getCreated()
};
static DataSet userSet(User... users) {
return data(theTable, CONVERSION).rows(users);
}
@Before
public void saveState() {
// Set save point
save(theDB);
}
@After
public void restoreState() {
// Restore state to save point
restore(theDB);
}
static User existingUser() {
return new User(0, "root", "Root user", "pass0", FIXED_DATE);
}
static User nonExistingUser() {
return new User(99, "john99", "John Doe 99", "doeit 99", FIXED_DATE);
}
@Test
public void testNonExistingUserInsertion() throws SQLException {
User u = nonExistingUser();
theDAO.insertUser(u);
assertInserted("DB change", userSet(u));
}
@Test
public void testExistingUserInsertion() {
try {
User u = existingUser();
theDAO.insertUser(u);
fail("Expected " + SQLException.class);
}
catch (SQLException e) {
assertUnchanged("No DB changes", theTable);
}
}
@Test
public void testExistingUserDelete() throws SQLException {
User u = existingUser();
boolean deleted = theDAO.deleteUser(u);
assertTrue("return value", deleted);
assertDeleted("DB change", userSet(u));
}
@Test
public void testNonExistingUserDelete() throws SQLException {
User u = nonExistingUser();
boolean deleted = theDAO.deleteUser(u);
assertFalse("return value", deleted);
assertUnchanged("No DB changes", theTable);
}
@Test
public void testDeleteAll() throws SQLException {
int n = theDAO.deleteAllUsers();
assertEquals("deleted users", n, theInitialData.size());
assertEmpty("DB cleaned up", theTable);
}
@Test
public void testExistingUserUpdate() throws SQLException {
User u = existingUser();
u.setPassword("new pass");
u.setName("new name");
boolean updated = theDAO.updateUser(u);
assertTrue("return value", updated);
assertDelta("DB change", userSet(existingUser()), userSet(u));
}
@Test
public void testNonExistingUserUpdate() throws SQLException {
User u = nonExistingUser();
boolean updated = theDAO.updateUser(u);
assertFalse("return value", updated);
assertUnchanged("No DB changes", theTable);
}
@Test
public void testGetAllUsers() throws SQLException {
List<User> list = theDAO.getAllUsers();
DataSet expected = theInitialData;
DataSet actual = data(theTable, CONVERSION).rows(list);
assertEquals("User list", expected, actual);
assertUnchanged("No DB changes", theTable);
}
@Test
public void testGetUserById() throws SQLException {
User expected = existingUser();
User actual = theDAO.getUser(expected.getId());
assertEquals("User", expected, actual);
assertUnchanged("No DB changes", theTable);
}
@Test
public void testGetUserByLogin() throws SQLException {
User expected = existingUser();
User actual = theDAO.getUser(expected.getLogin());
assertEquals("User", expected, actual);
assertUnchanged("No DB changes", theTable);
}
}
|
package seedu.ezdo.model.task;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import seedu.ezdo.model.todo.Name;
public class NameTest {
@Test
public void isValidName() {
// invalid name
assertFalse(Name.isValidName("")); // empty string
assertFalse(Name.isValidName(" ")); // spaces only
assertFalse(Name.isValidName(" ")); // whitespace only
assertFalse(Name.isValidName("^")); // only non-alphanumeric characters
// valid name (at least 1 alphanumeric character)
assertTrue(Name.isValidName("peter jack")); // alphabets only
assertTrue(Name.isValidName("12345")); // numbers only
assertTrue(Name.isValidName("peter the 2nd")); // alphanumeric characters
assertTrue(Name.isValidName("Capital Tan")); // with capital letters
assertTrue(Name.isValidName("David Roger Jackson Ray Jr 2nd")); // long names
assertTrue(Name.isValidName("$1")); // one symbol and one number
assertTrue(Name.isValidName("$a")); // one symbol and one alphabet
assertTrue(Name.isValidName("#!@#%!$^!@&#^!*@&#^!&*#^!&^#*!@^#b")); // a lot of symbols and one alphabet
assertTrue(Name.isValidName("#!@#%!$^!@&#^!*@&#^!&*#^!&^#*!@^#1")); // a lot of symbols and one number
}
}
|
package timeBench.data.relational;
import prefuse.data.Schema;
import prefuse.data.Table;
import prefuse.data.column.Column;
import prefuse.data.event.ColumnListener;
import prefuse.data.event.EventConstants;
import prefuse.data.event.GraphListener;
import prefuse.data.event.TableListener;
import prefuse.data.tuple.CompositeTupleSet;
import prefuse.data.tuple.TupleSet;
import prefuse.data.util.Index;
import prefuse.util.PrefuseConfig;
import prefuse.util.TypeLib;
import prefuse.util.collections.CopyOnWriteArrayList;
import prefuse.util.collections.IntArrayIterator;
import prefuse.util.collections.IntIterator;
/**
* A bipartite-graph implemented in analogy to {@link Graph}.
*
* <p> Storage
* It maintain two node tables stored as tuple sets under the names
* {@link BipartiteGraph#NODES_1} and {@link BipartiteGraph#NODES_2},
* as well as an edges-table which stores edges from the first to the second table.
* Additionally, for performance reasons, it stores the outgoing links from the first set
* in adjacency lists (which store the row index of the target nodes), and the incoming
* links in the same way (where the adjacency lists store the source nodes).
*
* <p> Graph specification
* While the graph is implemented as directed (edge source always from the first tuple set
* and edge target always to the second tuple set), but conceptually it is treated as undirected.
* Multiple edges are supported.
*
* @author bilal
*/
public class BipartiteGraph extends CompositeTupleSet {
public static interface BipartiteGraphListener {
/**
* Notification that a graph has changed.
* @param g the graph that has changed
* @param table the particular table within the graph that has changed
* @param start the starting row index of the changed table region
* @param end the ending row index of the changed table region
* @param col the column that has changed, or
* {@link EventConstants#ALL_COLUMNS} if the operation affects all
* columns
* @param type the type of modification, one of
* {@link EventConstants#INSERT}, {@link EventConstants#DELETE}, or
* {@link EventConstants#UPDATE}.
*/
public void graphChanged(BipartiteGraph g, String table,
int start, int end, int col, int type);
}
/** Default data field used to uniquely identify a node */
public static final String DEFAULT_NODE_KEY = PrefuseConfig
.get("data.graph.nodeKey");
/** Default data field used to denote the source node in an edge table */
public static final String DEFAULT_SOURCE_KEY = PrefuseConfig
.get("data.graph.sourceKey");
/** Default data field used to denote the target node in an edge table */
public static final String DEFAULT_TARGET_KEY = PrefuseConfig
.get("data.graph.targetKey");
/** Data group name to identify the nodes of this graph */
public static final String NODES_1 = "data.graph.nodeGroup1";
public static final String NODES_2 = "data.graph.nodeGroup2";
/** Data group name to identify the edges of this graph */
public static final String EDGES = PrefuseConfig
.get("data.graph.edgeGroup");
/** Table containing the adjacency lists for the graph */
protected Table m_links1;
protected Table m_links2;
/** The node key field (for the first Node table) */
protected String m_n1key;
/** The node key field (for the second Node table) */
protected String m_n2key;
/** The source node key field (for the Edge table) */
protected String m_skey;
/** The target node key field (for the Edge table) */
protected String m_tkey;
/** Reference to an index over the node key field in first Node table */
protected Index m_n1idx;
/** Reference to an index over the node key field in second Node table */
protected Index m_n2idx;
/** Indicates if the key values are of type long */
protected boolean m_longKey1 = false;
/** Indicates if the key values are of type long */
protected boolean m_longKey2 = false;
/** Update listener */
private Listener m_listener;
/** Listener list */
private CopyOnWriteArrayList m_listeners = new CopyOnWriteArrayList();
// Constructors
/**
* Creates a new, empty Graph.
*/
public BipartiteGraph() {
this(new Table(), new Table());
}
/**
* Create a new Graph using the provided table of node data and an empty set
* of edges.
*
* @param nodes
* the backing table to use for node data. Node instances of this
* graph will get their data from this table.
* @param directed
* true for directed edges, false for undirected
*/
public BipartiteGraph(Table nodes1, Table nodes2) {
this(nodes1, nodes2, DEFAULT_NODE_KEY, DEFAULT_NODE_KEY,
DEFAULT_SOURCE_KEY, DEFAULT_TARGET_KEY);
}
/**
* Create a new Graph using the provided table of node data and an empty set
* of edges.
*
* @param nodes
* the backing table to use for node data. Node instances of this
* graph will get their data from this table.
* @param directed
* true for directed edges, false for undirected
* @param nodeKey
* data field used to uniquely identify a node. If this field is
* null, the node table row numbers will be used
* @param sourceKey
* data field used to denote the source node in an edge table
* @param targetKey
* data field used to denote the target node in an edge table
*/
public BipartiteGraph(Table nodes1, Table nodes2, String node1Key,
String node2Key, String sourceKey, String targetKey) {
Table edges = new Table();
edges.addColumn(sourceKey, int.class, new Integer(-1));
edges.addColumn(targetKey, int.class, new Integer(-1));
init(nodes1, nodes2, edges, node1Key, node2Key, sourceKey, targetKey);
}
/**
* Create a new Graph, using node table row numbers to uniquely identify
* nodes in the edge table's source and target fields.
*
* @param nodes
* the backing table to use for node data. Node instances of this
* graph will get their data from this table.
* @param edges
* the backing table to use for edge data. Edge instances of this
* graph will get their data from this table.
* @param directed
* true for directed edges, false for undirected
*/
public BipartiteGraph(Table nodes1, Table nodes2, Table edges) {
this(nodes1, nodes2, edges, DEFAULT_NODE_KEY, DEFAULT_NODE_KEY,
DEFAULT_SOURCE_KEY, DEFAULT_TARGET_KEY);
}
/**
* Create a new Graph, using node table row numbers to uniquely identify
* nodes in the edge table's source and target fields.
*
* @param nodes
* the backing table to use for node data. Node instances of this
* graph will get their data from this table.
* @param edges
* the backing table to use for edge data. Edge instances of this
* graph will get their data from this table.
* @param directed
* true for directed edges, false for undirected
* @param sourceKey
* data field used to denote the source node in an edge table
* @param targetKey
* data field used to denote the target node in an edge table
*/
public BipartiteGraph(Table nodes1, Table nodes2, Table edges,
String sourceKey, String targetKey) {
init(nodes1, nodes2, edges, DEFAULT_NODE_KEY, DEFAULT_NODE_KEY,
sourceKey, targetKey);
}
/**
* Create a new Graph.
*
* @param nodes
* the backing table to use for node data. Node instances of this
* graph will get their data from this table.
* @param edges
* the backing table to use for edge data. Edge instances of this
* graph will get their data from this table.
* @param directed
* true for directed edges, false for undirected
* @param nodeKey
* data field used to uniquely identify a node. If this field is
* null, the node table row numbers will be used
* @param sourceKey
* data field used to denote the source node in an edge table
* @param targetKey
* data field used to denote the target node in an edge table
*/
public BipartiteGraph(Table nodes1, Table nodes2, Table edges,
String node1Key, String node2Key, String sourceKey, String targetKey) {
init(nodes1, nodes2, edges, node1Key, node2Key, sourceKey, targetKey);
}
// Initialization
/**
* Initialize this Graph instance.
*
* @param nodes
* the node table
* @param edges
* the edge table
* @param directed
* the edge directionality
* @param nodeKey
* data field used to uniquely identify a node
* @param sourceKey
* data field used to denote the source node in an edge table
* @param targetKey
* data field used to denote the target node in an edge table
*/
protected void init(Table nodes1, Table nodes2, Table edges,
String node1Key, String node2Key, String sourceKey, String targetKey) {
// sanity check
if ((node1Key != null && !TypeLib.isIntegerType(nodes1
.getColumnType(node1Key)))
|| (node2Key != null && !TypeLib.isIntegerType(nodes2
.getColumnType(node2Key)))
|| !TypeLib.isIntegerType(edges.getColumnType(sourceKey))
|| !TypeLib.isIntegerType(edges.getColumnType(targetKey))) {
throw new IllegalArgumentException(
"Incompatible column types for graph keys");
}
removeAllSets();
super.addSet(EDGES, edges);
super.addSet(NODES_1, nodes1);
super.addSet(NODES_2, nodes2);
// INVARIANT: these three should all reference the same type
// currently limited to int
m_n1key = node1Key;
m_n2key = node2Key;
m_skey = sourceKey;
m_tkey = targetKey;
// set a tuple manager for the edge table
// so that its tuples are instances of BipartiteEdge
this.getEdgeTable().setTupleManager(
new BipartiteEdgeManager(this.getEdgeTable(), this,
BipartiteEdge.class));
// set up indices
if (node1Key != null) {
if (nodes1.getColumnType(node1Key) == long.class)
m_longKey1 = true;
nodes1.index(node1Key);
m_n1idx = nodes1.getIndex(node1Key);
}
// set up indices
if (node2Key != null) {
if (nodes2.getColumnType(node2Key) == long.class)
m_longKey2 = true;
nodes2.index(node1Key);
m_n2idx = nodes2.getIndex(node1Key);
}
// set up node attribute optimization
initLinkTable();
// set up listening
if (m_listener == null)
m_listener = new Listener();
nodes1.addTableListener(m_listener);
nodes2.addTableListener(m_listener);
edges.addTableListener(m_listener);
m_listener.setEdgeTable(edges);
}
/**
* Dispose of this graph. Unregisters this graph as a listener to its
* included tables.
*/
public void dispose() {
getNode1Table().removeTableListener(m_listener);
getNode2Table().removeTableListener(m_listener);
getEdgeTable().removeTableListener(m_listener);
}
/**
* Updates this graph to use a different edge structure for the same nodes.
* All other settings will remain the same (e.g., directionality, keys)
*
* @param edges
* the new edge table.
*/
public void setEdgeTable(Table edges) {
Table oldEdges = getEdgeTable();
oldEdges.removeTableListener(m_listener);
m_links1.clear();
m_links2.clear();
init(getNode1Table(), getNode2Table(), edges, m_n1key, m_n2key, m_skey,
m_tkey);
}
// Data Access Optimization
/**
* Initialize the link table, which holds adjacency lists for this graph.
*/
protected void initLinkTable() {
// set up cache of node data
m_links1 = createLinkTable(getNode1Table().getMaximumRow() + 1);
m_links2 = createLinkTable(getNode2Table().getMaximumRow() + 1);
IntIterator edges = getEdgeTable().rows();
while (edges.hasNext()) {
updateDegrees(edges.nextInt(), 1);
}
}
/**
* Instantiate and return the link table.
*
* @return the created link table
*/
protected Table createLinkTable(int size) {
return LINKS_SCHEMA.instantiate(size);
}
/**
* Internal method for updating the linkage of this graph.
*
* @param e
* the edge id for the updated link
* @param incr
* the increment value, 1 for an added link, -1 for a removed
* link
*/
protected void updateDegrees(int e, int incr) {
if (!getEdgeTable().isValidRow(e))
return;
int s = getSourceNode(e);
int t = getTargetNode(e);
if (s < 0 || t < 0)
return;
updateDegrees(e, s, t, incr);
}
/**
* Internal method for updating the linkage of this graph.
*
* @param e
* the edge id for the updated link
* @param s
* the source node id for the updated link
* @param t
* the target node id for the updated link
* @param incr
* the increment value, 1 for an added link, -1 for a removed
* link
*/
protected void updateDegrees(int e, int s, int t, int incr) {
int d1 = m_links1.getInt(s, DEGREE);
int d2 = m_links2.getInt(t, DEGREE);
// update adjacency lists
if (incr > 0) {
// add links
addLink(m_links1, d1, s, e);
addLink(m_links2, d2, t, e);
} else if (incr < 0) {
// remove links
remLink(m_links1, d1, s, e);
remLink(m_links1, d2, t, e);
}
// update degree counts
m_links1.setInt(s, DEGREE, d1 + incr);
m_links2.setInt(t, DEGREE, d2 + incr);
}
/**
* Internal method for adding a link to an adjacency list
*
* @param field
* which adjacency list (inlinks or outlinks) to use
* @param len
* the length of the adjacency list
* @param n
* the node id of the adjacency list to use
* @param e
* the edge to add to the list
*/
protected void addLink(Table links, int len, int n, int e) {
int[] array = (int[]) links.get(n, LINKS);
if (array == null) {
array = new int[] { e };
links.set(n, LINKS, array);
return;
} else if (len == array.length) {
int[] narray = new int[Math.max(3 * array.length / 2, len + 1)];
System.arraycopy(array, 0, narray, 0, array.length);
array = narray;
links.set(n, LINKS, array);
}
array[len] = e;
}
/**
* Internal method for removing a link from an adjacency list
*
* @param field
* which adjacency list (inlinks or outlinks) to use
* @param len
* the length of the adjacency list
* @param n
* the node id of the adjacency list to use
* @param e
* the edge to remove from the list
* @return true if the link was removed successfully, false otherwise
*/
protected boolean remLink(Table links, int len, int n, int e) {
int[] array = (int[]) links.get(n, LINKS);
for (int i = 0; i < len; ++i) {
if (array[i] == e) {
System.arraycopy(array, i + 1, array, i, len - i - 1);
return true;
}
}
return false;
}
/**
* Update the link table to accomodate an inserted or deleted node
*
* @param r
* the node id, also the row number into the link table
* @param added
* indicates if a node was added or removed
*/
protected void updateNodeData(Table links, int r, boolean added) {
if (added) {
links.addRow();
} else {
links.removeRow(r);
}
}
// Key Transforms
/**
* Get the data field used to uniquely identify a node
*
* @return the data field used to uniquely identify a node
*/
public String getNode1KeyField() {
return m_n1key;
}
/**
* Get the data field used to uniquely identify a node
*
* @return the data field used to uniquely identify a node
*/
public String getNode2KeyField() {
return m_n2key;
}
/**
* Get the data field used to denote the source node in an edge table.
*
* @return the data field used to denote the source node in an edge table.
*/
public String getEdgeSourceField() {
return m_skey;
}
/**
* Get the data field used to denote the target node in an edge table.
*
* @return the data field used to denote the target node in an edge table.
*/
public String getEdgeTargetField() {
return m_tkey;
}
/**
* Given a node id (a row number in the node table), get the value of the
* node key field.
*
* @param node
* the node id
* @return the value of the node key field for the given node
*/
public long get1Key(int node) {
return m_n1key == null ? node : getNode1Table().getLong(node, m_n1key);
}
/**
* Given a node id (a row number in the node table), get the value of the
* node key field.
*
* @param node
* the node id
* @return the value of the node key field for the given node
*/
public long get2Key(int node) {
return m_n2key == null ? node : getNode2Table().getLong(node, m_n2key);
}
/**
* Given a value of the node key field, get the node id (the row number in
* the node table).
*
* @param key
* a node key field value
* @return the node id (the row number in the node table)
*/
public int getNode1Index(long key) {
if (m_n1idx == null) {
return (int) key;
} else {
int idx = m_longKey1 ? m_n1idx.get(key) : m_n1idx.get((int) key);
return idx < 0 ? -1 : idx;
}
}
/**
* Given a value of the node key field, get the node id (the row number in
* the node table).
*
* @param key
* a node key field value
* @return the node id (the row number in the node table)
*/
public int getNode2Index(long key) {
if (m_n2idx == null) {
return (int) key;
} else {
int idx = m_longKey2 ? m_n2idx.get(key) : m_n2idx.get((int) key);
return idx < 0 ? -1 : idx;
}
}
// Graph Mutators
/**
* Add row to the node table, thereby adding a node to the graph.
*
* @return the node id (node table row number) of the added node
*/
public int addNode1Row() {
return getNode1Table().addRow();
}
/**
* Add row to the node table, thereby adding a node to the graph.
*
* @return the node id (node table row number) of the added node
*/
public int addNode2Row() {
return getNode2Table().addRow();
}
/**
* Add an edge to the graph. Both multiple edges between two nodes and edges
* from a node to itself are allowed.
*
* @param s
* the source node id
* @param t
* the target node id
* @return the edge id (edge table row number) of the added edge
*/
public int addEdge(int s, int t) {
// get keys for the nodes
long key1 = get1Key(s);
long key2 = get2Key(t);
// add edge row, set source/target fields
Table edges = getEdgeTable();
int r = edges.addRow();
if (m_longKey1) {
edges.setLong(r, m_skey, key1);
} else {
edges.setInt(r, m_skey, (int) key1);
}
if (m_longKey2) {
edges.setLong(r, m_tkey, key2);
} else {
edges.setInt(r, m_tkey, (int) key2);
}
return r;
}
// /**
// * Remove a node from the graph, also removing all incident edges.
// * @param node the node id (node table row number) of the node to remove
// * @return true if the node was successfully removed, false if the
// * node id was not found or was not valid
// */
// public boolean removeNode(int node) {
// Table nodeTable = getNodeTable();
// if ( nodeTable.isValidRow(node) ) {
// int id = getInDegree(node);
// if ( id > 0 ) {
// int[] links = (int[])m_links.get(node, INLINKS);
// for ( int i=id; --i>=0; )
// removeEdge(links[i]);
// int od = getOutDegree(node);
// if ( od > 0 ) {
// int[] links = (int[])m_links.get(node, OUTLINKS);
// for ( int i=od; --i>=0; )
// removeEdge(links[i]);
// return nodeTable.removeRow(node);
/**
* Remove an edge from the graph.
*
* @param edge
* the edge id (edge table row number) of the edge to remove
* @return true if the edge was successfully removed, false if the edge was
* not found or was not valid
*/
public boolean removeEdge(int edge) {
return getEdgeTable().removeRow(edge);
}
/**
* Internal method for clearing the edge table, removing all edges.
*/
protected void clearEdges() {
getEdgeTable().clear();
}
// Node Accessor Methods
/**
* Get the collection of nodes as a TupleSet. Returns the same result as
* {@link CompositeTupleSet#getSet(String)} using {@link #NODES} as the
* parameter.
*
* @return the nodes of this graph as a TupleSet instance
*/
public TupleSet getNodes1() {
return getSet(NODES_1);
}
/**
* Get the collection of nodes as a TupleSet. Returns the same result as
* {@link CompositeTupleSet#getSet(String)} using {@link #NODES} as the
* parameter.
*
* @return the nodes of this graph as a TupleSet instance
*/
public TupleSet getNodes2() {
return getSet(NODES_2);
}
/**
* Get the backing node table.
*
* @return the table of node values
*/
public Table getNode1Table() {
return (Table) getSet(NODES_1);
}
/**
* Get the backing node table.
*
* @return the table of node values
*/
public Table getNode2Table() {
return (Table) getSet(NODES_2);
}
/**
* Get the number of nodes in this graph.
*
* @return the number of nodes
*/
public int getNode1Count() {
return getNode1Table().getRowCount();
}
/**
* Get the number of nodes in this graph.
*
* @return the number of nodes
*/
public int getNode2Count() {
return getNode2Table().getRowCount();
}
/**
* Get the degree of a node, the number of edges for which a node is either
* the source or the target.
*
* @param node
* the node id (node table row number)
* @return the total degree of the node
*/
public int getDegree1(int node) {
return m_links1.getInt(node, DEGREE);
}
/**
* Get the degree of a node, the number of edges for which a node is either
* the source or the target.
*
* @param node
* the node id (node table row number)
* @return the total degree of the node
*/
public int getDegree2(int node) {
return m_links2.getInt(node, DEGREE);
}
// Edge Accessor Methods
/**
* Get the collection of edges as a TupleSet. Returns the same result as
* {@link CompositeTupleSet#getSet(String)} using {@link #EDGES} as the
* parameter.
*
* @return the edges of this graph as a TupleSet instance
*/
public TupleSet getEdges() {
return getSet(EDGES);
}
/**
* Get the backing edge table.
*
* @return the table of edge values
*/
public Table getEdgeTable() {
return (Table) getSet(EDGES);
}
/**
* Get the number of edges in this graph.
*
* @return the number of edges
*/
public int getEdgeCount() {
return getEdgeTable().getRowCount();
}
/**
* Returns an edge from the source node to the target node. This method
* returns the first such edge found; in the case of multiple edges there
* may be more.
*/
public int getEdge(int source, int target) {
int outd = getDegree1(source);
if (outd > 0) {
int[] edges = (int[]) m_links1.get(source, LINKS);
for (int i = 0; i < outd; ++i) {
if (getTargetNode(edges[i]) == target)
return edges[i];
}
}
return -1;
}
/**
* Get the source node id (node table row number) for the given edge id
* (edge table row number).
*
* @param edge
* an edge id (edge table row number)
* @return the source node id (node table row number)
*/
public int getSourceNode(int edge) {
return getNode1Index(getEdgeTable().getLong(edge, m_skey));
}
/**
* Get the target node id (node table row number) for the given edge id
* (edge table row number).
*
* @param edge
* an edge id (edge table row number)
* @return the target node id (node table row number)
*/
public int getTargetNode(int edge) {
return getNode2Index(getEdgeTable().getLong(edge, m_tkey));
}
// Iterators
/**
* Get an iterator over all node ids (node table row numbers).
*
* @return an iterator over all node ids (node table row numbers)
*/
public IntIterator nodeRows1() {
return getNode1Table().rows();
}
/**
* Get an iterator over all node ids (node table row numbers).
*
* @return an iterator over all node ids (node table row numbers)
*/
public IntIterator nodeRows2() {
return getNode2Table().rows();
}
/**
* Get an iterator over all edge ids (edge table row numbers).
*
* @return an iterator over all edge ids (edge table row numbers)
*/
public IntIterator edgeRows() {
return getEdgeTable().rows();
}
/**
* Get an iterator edge ids for edges incident on the given node.
*
* @param node
* a node id (node table row number)
* @return an iterator over all edge ids for edges incident on the given
* node
*/
public IntIterator edgeRows1(int node) {
int[] edges = (int[]) m_links1.get(node, LINKS);
return new IntArrayIterator(edges, 0, getDegree1(node));
}
/**
* Get an iterator edge ids for edges incident on the given node.
*
* @param node
* a node id (node table row number)
* @return an iterator over all edge ids for edges incident on the given
* node
*/
public IntIterator edgeRows2(int node) {
int[] edges = (int[]) m_links2.get(node, LINKS);
return new IntArrayIterator(edges, 0, getDegree2(node));
}
// TupleSet Interface
/**
* Clear this graph, removing all nodes and edges.
*
* @see prefuse.data.tuple.TupleSet#clear()
*/
public void clear() {
super.clear();
m_links1.clear();
m_links2.clear();
}
// Graph Listeners
/**
* Add a listener to be notified of changes to the graph.
*
* @param listnr
* the listener to add
*/
public void addGraphModelListener(GraphListener listnr) {
if (!m_listeners.contains(listnr))
m_listeners.add(listnr);
}
/**
* Remove a listener from this graph.
*
* @param listnr
* the listener to remove
*/
public void removeGraphModelListener(GraphListener listnr) {
m_listeners.remove(listnr);
}
/**
* Removes all listeners on this graph
*/
public void removeAllGraphModelListeners() {
m_listeners.clear();
}
/**
* Fire a graph change event
*
* @param t
* the backing table where the change occurred (either a node
* table or an edge table)
* @param first
* the first modified table row
* @param last
* the last (inclusive) modified table row
* @param col
* the number of the column modified, or
* {@link prefuse.data.event.EventConstants#ALL_COLUMNS} for
* operations affecting all columns
* @param type
* the type of modification, one of
* {@link prefuse.data.event.EventConstants#INSERT},
* {@link prefuse.data.event.EventConstants#DELETE}, or
* {@link prefuse.data.event.EventConstants#UPDATE}.
*/
protected void fireGraphEvent(Table t, int first, int last, int col,
int type) {
String table = (t == getNode1Table() ? NODES_1
: t == getNode1Table() ? NODES_2 : EDGES);
if (type != EventConstants.UPDATE) {
// fire event to all tuple set listeners
fireTupleEvent(t, first, last, type);
}
if (!m_listeners.isEmpty()) {
// fire event to all listeners
Object[] lstnrs = m_listeners.getArray();
for (int i = 0; i < lstnrs.length; ++i) {
((BipartiteGraphListener)lstnrs[i]).graphChanged(
this, table, first, last, col, type);
}
}
}
// Table and Column Listener
/**
* Listener class for tracking updates from node and edge tables, and their
* columns that determine the graph linkage structure.
*/
protected class Listener implements TableListener, ColumnListener {
private Table m_edges;
private Column m_scol, m_tcol;
private int m_sidx, m_tidx;
public void setEdgeTable(Table edges) {
// remove any previous listeners
if (m_scol != null)
m_scol.removeColumnListener(this);
if (m_tcol != null)
m_tcol.removeColumnListener(this);
m_scol = m_tcol = null;
m_sidx = m_tidx = -1;
m_edges = edges;
// register listeners
if (m_edges != null) {
m_sidx = edges.getColumnNumber(m_skey);
m_tidx = edges.getColumnNumber(m_tkey);
m_scol = edges.getColumn(m_sidx);
m_tcol = edges.getColumn(m_tidx);
m_scol.addColumnListener(this);
m_tcol.addColumnListener(this);
}
}
public void tableChanged(Table t, int start, int end, int col, int type) {
if (!containsSet(t))
throw new IllegalStateException(
"Graph shouldn't be listening to an unrelated table");
if (type != EventConstants.UPDATE) {
if (t == getNode1Table()) {
// update the linkage structure table
if (col == EventConstants.ALL_COLUMNS) {
boolean added = type == EventConstants.INSERT;
for (int r = start; r <= end; ++r)
updateNodeData(m_links1, r, added);
}
} else if (t == getNode2Table()) {
// update the linkage structure table
if (col == EventConstants.ALL_COLUMNS) {
boolean added = type == EventConstants.INSERT;
for (int r = start; r <= end; ++r)
updateNodeData(m_links2, r, added);
}
} else {
// update the linkage structure table
if (col == EventConstants.ALL_COLUMNS) {
boolean added = type == EventConstants.INSERT;
for (int r = start; r <= end; ++r)
updateDegrees(start, added ? 1 : -1);
}
}
}
fireGraphEvent(t, start, end, col, type);
}
public void columnChanged(Column src, int idx, int prev) {
columnChanged(src, idx, (long) prev);
}
public void columnChanged(Column src, int idx, long prev) {
if (src == m_scol || src == m_tcol) {
boolean isSrc = src == m_scol;
int e = m_edges.getTableRow(idx, isSrc ? m_sidx : m_tidx);
if (e == -1)
return; // edge not in this graph
int s = getSourceNode(e);
int t = getTargetNode(e);
int p = isSrc ? getNode1Index(prev) : getNode2Index(prev);
if (p > -1 && ((isSrc && t > -1) || (!isSrc && s > -1)))
updateDegrees(e, isSrc ? p : s, isSrc ? t : p, -1);
if (s > -1 && t > -1)
updateDegrees(e, s, t, 1);
} else {
throw new IllegalStateException();
}
}
public void columnChanged(Column src, int type, int start, int end) {
// should never be called
throw new IllegalStateException();
}
public void columnChanged(Column src, int idx, float prev) {
// should never be called
throw new IllegalStateException();
}
public void columnChanged(Column src, int idx, double prev) {
// should never be called
throw new IllegalStateException();
}
public void columnChanged(Column src, int idx, boolean prev) {
// should never be called
throw new IllegalStateException();
}
public void columnChanged(Column src, int idx, Object prev) {
// should never be called
throw new IllegalStateException();
}
} // end of inner class Listener
// Graph Linkage Schema
/** In-degree data field for the links table */
protected static final String DEGREE = "_degree";
/** In-links adjacency list data field for the links table */
protected static final String LINKS = "_inlinks";
/** Schema used for the internal graph linkage table */
protected static final Schema LINKS_SCHEMA = new Schema();
static {
Integer defaultValue = new Integer(0);
LINKS_SCHEMA.addColumn(DEGREE, int.class, defaultValue);
LINKS_SCHEMA.addColumn(LINKS, int[].class);
LINKS_SCHEMA.lockSchema();
}
} // end of class Graph
|
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import javax.swing.*;
import gnu.io.*;
public class AvrdudeUploader extends Uploader {
public AvrdudeUploader() {
}
public boolean uploadUsingPreferences(String buildPath, String className)
throws RunnerException {
List commandDownloader = new ArrayList();
String programmer = Preferences.get("upload.programmer");
// avrdude wants "stk500v1" to distinguish it from stk500v2
if (programmer.equals("stk500"))
programmer = "stk500v1";
// avrdude doesn't want to read device signatures (it always gets
// 0x000000); force it to continue uploading anyway
commandDownloader.add("-F");
commandDownloader.add("-c" + programmer);
if (Preferences.get("upload.programmer").equals("dapa")) {
// avrdude doesn't need to be told the address of the parallel port
//commandDownloader.add("-dlpt=" + Preferences.get("parallel.port"));
} else {
commandDownloader.add(
"-P" + (Base.isWindows() ?
"/dev/" + Preferences.get("serial.port").toLowerCase() :
Preferences.get("serial.port")));
commandDownloader.add(
"-b" + Preferences.getInteger("serial.download_rate"));
}
if (Preferences.getBoolean("upload.erase"))
commandDownloader.add("-e");
else
commandDownloader.add("-D");
if (!Preferences.getBoolean("upload.verify"))
commandDownloader.add("-V");
commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex");
return uisp(commandDownloader);
}
public boolean burnBootloaderAVRISP() throws RunnerException {
List commandDownloader = new ArrayList();
commandDownloader.add("-dprog=" + Preferences.get("bootloader.programmer"));
commandDownloader.add(
"-dserial=" + (Base.isWindows() ?
"/dev/" + Preferences.get("serial.port").toLowerCase() :
Preferences.get("serial.port")));
commandDownloader.add("-dspeed=" + Preferences.get("serial.burn_rate"));
return burnBootloader(commandDownloader);
}
public boolean burnBootloaderParallel() throws RunnerException {
List commandDownloader = new ArrayList();
commandDownloader.add("-dprog=dapa");
commandDownloader.add("-dlpt=" + Preferences.get("parallel.port"));
return burnBootloader(commandDownloader);
}
protected boolean burnBootloader(Collection params) throws RunnerException {
// I know this is ugly; apologies - that's what happens when you try to
// write Lisp-style code in Java.
return
// unlock bootloader segment of flash memory
uisp(params, Arrays.asList(new String[] {
"--wr_lock=" + Preferences.get("bootloader.unlock_bits") })) &&
// write fuses:
// bootloader size of 512 words; from 0xE00-0xFFF
// clock speed of 16 MHz, external quartz
uisp(params, Arrays.asList(new String[] {
"--wr_fuse_l=" + Preferences.get("bootloader.low_fuses"),
"--wr_fuse_h=" + Preferences.get("bootloader.high_fuses") })) &&
// upload bootloader
uisp(params, Arrays.asList(new String[] {
"--erase", "--upload", "--verify",
"if=" + Preferences.get("bootloader.path") + File.separator +
Preferences.get("bootloader.file") })) &&
// lock bootloader segment
uisp(params, Arrays.asList(new String[] {
"--wr_lock=" + Preferences.get("bootloader.lock_bits") }));
}
public boolean uisp(Collection p1, Collection p2) throws RunnerException {
ArrayList p = new ArrayList(p1);
p.addAll(p2);
return uisp(p);
}
public boolean uisp(Collection params) throws RunnerException {
flushSerialBuffer();
List commandDownloader = new ArrayList();
commandDownloader.add("avrdude");
// On Windows and the Mac, we need to point avrdude at its config file
// since it's getting installed in an unexpected location (i.e. a
// sub-directory of wherever the user happens to stick Arduino). On Linux,
// avrdude will have been properly installed by the distribution's package
// manager and should be able to find its config file.
if(Base.isMacOS()) {
commandDownloader.add("-C" + "tools/avr/etc/avrdude.conf");
}
else if(Base.isWindows()) {
String userdir = System.getProperty("user.dir") + File.separator;
commandDownloader.add("-C" + userdir + "tools/avr/etc/avrdude.conf");
}
if (Preferences.getBoolean("upload.verbose")) {
commandDownloader.add("-v");
commandDownloader.add("-v");
commandDownloader.add("-v");
commandDownloader.add("-v");
} else {
commandDownloader.add("-q");
commandDownloader.add("-q");
}
// XXX: quick hack to chop the "atmega" off of "atmega8" and "atmega168",
// then shove an "m" at the beginning. won't work for attiny's, etc.
commandDownloader.add("-pm" + Preferences.get("build.mcu").substring(6));
commandDownloader.addAll(params);
return executeUploadCommand(commandDownloader);
}
}
|
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import javax.swing.*;
import gnu.io.*;
public class AvrdudeUploader extends Uploader {
public AvrdudeUploader() {
}
public boolean uploadUsingPreferences(String buildPath, String className)
throws RunnerException {
List commandDownloader = new ArrayList();
// avrdude doesn't want to read device signatures (it always gets
// 0x000000); force it to continue uploading anyway
commandDownloader.add("-F");
String programmer = Preferences.get("upload.programmer");
// avrdude wants "stk500v1" to distinguish it from stk500v2
if (programmer.equals("stk500"))
programmer = "stk500v1";
commandDownloader.add("-c" + programmer);
if (Preferences.get("upload.programmer").equals("dapa")) {
// avrdude doesn't need to be told the address of the parallel port
//commandDownloader.add("-dlpt=" + Preferences.get("parallel.port"));
} else {
commandDownloader.add("-P" + Preferences.get("serial.port"));
commandDownloader.add(
"-b" + Preferences.getInteger("serial.download_rate"));
}
if (Preferences.getBoolean("upload.erase"))
commandDownloader.add("-e");
else
commandDownloader.add("-D");
if (!Preferences.getBoolean("upload.verify"))
commandDownloader.add("-V");
commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i");
return uisp(commandDownloader);
}
public boolean burnBootloaderAVRISP(String target) throws RunnerException {
List commandDownloader = new ArrayList();
commandDownloader.add("-c" +
Preferences.get("bootloader." + target + ".programmer"));
if (Preferences.get("bootloader." + target + ".communication").equals("usb")) {
commandDownloader.add("-Pusb");
} else {
commandDownloader.add(
"-P" + (Base.isWindows() ?
"/dev/" + Preferences.get("serial.port").toLowerCase() :
Preferences.get("serial.port")));
}
commandDownloader.add("-b" + Preferences.get("serial.burn_rate"));
return burnBootloader(target, commandDownloader);
}
public boolean burnBootloaderParallel(String target) throws RunnerException {
List commandDownloader = new ArrayList();
commandDownloader.add("-dprog=dapa");
commandDownloader.add("-dlpt=" + Preferences.get("parallel.port"));
return burnBootloader(target, commandDownloader);
}
protected boolean burnBootloader(String target, Collection params)
throws RunnerException
{
return
// unlock bootloader segment of flash memory and write fuses
uisp(params, Arrays.asList(new String[] {
"-e",
"-Ulock:w:" + Preferences.get("bootloader." + target + ".unlock_bits") + ":m",
"-Uefuse:w:" + Preferences.get("bootloader." + target + ".extended_fuses") + ":m",
"-Uhfuse:w:" + Preferences.get("bootloader." + target + ".high_fuses") + ":m",
"-Ulfuse:w:" + Preferences.get("bootloader." + target + ".low_fuses") + ":m",
})) &&
// upload bootloader and lock bootloader segment
uisp(params, Arrays.asList(new String[] {
"-Uflash:w:" + Preferences.get("bootloader." + target + ".path") +
File.separator + Preferences.get("bootloader." + target + ".file") + ":i",
"-Ulock:w:" + Preferences.get("bootloader." + target + ".lock_bits") + ":m"
}));
}
public boolean uisp(Collection p1, Collection p2) throws RunnerException {
ArrayList p = new ArrayList(p1);
p.addAll(p2);
return uisp(p);
}
public boolean uisp(Collection params) throws RunnerException {
flushSerialBuffer();
List commandDownloader = new ArrayList();
commandDownloader.add("avrdude");
// On Windows and the Mac, we need to point avrdude at its config file
// since it's getting installed in an unexpected location (i.e. a
// sub-directory of wherever the user happens to stick Arduino). On Linux,
// avrdude will have been properly installed by the distribution's package
// manager and should be able to find its config file.
if(Base.isMacOS()) {
commandDownloader.add("-C" + "tools/avr/etc/avrdude.conf");
}
else if(Base.isWindows()) {
String userdir = System.getProperty("user.dir") + File.separator;
commandDownloader.add("-C" + userdir + "tools/avr/etc/avrdude.conf");
}
if (Preferences.getBoolean("upload.verbose")) {
commandDownloader.add("-v");
commandDownloader.add("-v");
commandDownloader.add("-v");
commandDownloader.add("-v");
} else {
commandDownloader.add("-q");
commandDownloader.add("-q");
}
// XXX: quick hack to chop the "atmega" off of "atmega8" and "atmega168",
// then shove an "m" at the beginning. won't work for attiny's, etc.
commandDownloader.add("-pm" + Preferences.get("build.mcu").substring(6));
commandDownloader.addAll(params);
return executeUploadCommand(commandDownloader);
}
}
|
package ibis.io;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SingleBufferArrayOutputStream extends DataOutputStream {
private static final Logger logger = LoggerFactory
.getLogger(BufferedArrayOutputStream.class);
private static final boolean DEBUG = IOProperties.DEBUG;
/** Size of the buffer in which output data is collected. */
private final int BUF_SIZE;
/** The buffer in which output data is collected. */
private byte[] buffer;
/** Size of the buffer in which output data is collected. */
private int index = 0;
private int offset = 0;
/** Object used for conversion of primitive types to bytes. */
private Conversion conversion;
/**
* Constructor.
*
* @param buffer
* the underlying byte buffer
*/
public SingleBufferArrayOutputStream(byte[] buffer) {
this.buffer = buffer;
BUF_SIZE = buffer.length;
conversion = Conversion.loadConversion(false);
}
public void reset() {
index = 0;
}
public long bytesWritten() {
return index - offset;
}
public void resetBytesWritten() {
offset = index;
}
/**
* Checks if there is space for <code>incr</code> more bytes and if not,
* the buffer is written to the underlying <code>OutputStream</code>.
*
* @param incr
* the space requested
* @exception IOException
* in case of trouble.
*/
private void checkFreeSpace(int bytes) throws IOException {
if (DEBUG && logger.isDebugEnabled()) {
logger.debug("checkFreeSpace(" + bytes + ") : " + " "
+ (index + bytes >= BUF_SIZE) + " " + (index) + ")");
}
if (index + bytes > BUF_SIZE) {
throw new IOException("End of buffer reached (" + index + "+"
+ bytes + " > " + BUF_SIZE + ")");
}
}
public void write(int b) throws IOException {
writeByte((byte) b);
}
public void writeBoolean(boolean value) throws IOException {
byte b = conversion.boolean2byte(value);
checkFreeSpace(1);
buffer[index++] = b;
}
public void writeByte(byte value) throws IOException {
checkFreeSpace(1);
buffer[index++] = value;
}
public void writeChar(char value) throws IOException {
checkFreeSpace(Constants.SIZEOF_CHAR);
conversion.char2byte(value, buffer, index);
index += Constants.SIZEOF_CHAR;
}
public void writeShort(short value) throws IOException {
checkFreeSpace(Constants.SIZEOF_SHORT);
conversion.short2byte(value, buffer, index);
index += Constants.SIZEOF_SHORT;
}
public void writeInt(int value) throws IOException {
checkFreeSpace(Constants.SIZEOF_INT);
conversion.int2byte(value, buffer, index);
index += Constants.SIZEOF_INT;
}
public void writeLong(long value) throws IOException {
checkFreeSpace(Constants.SIZEOF_LONG);
conversion.long2byte(value, buffer, index);
index += Constants.SIZEOF_LONG;
}
public void writeFloat(float value) throws IOException {
checkFreeSpace(Constants.SIZEOF_FLOAT);
conversion.float2byte(value, buffer, index);
index += Constants.SIZEOF_FLOAT;
}
public void writeDouble(double value) throws IOException {
checkFreeSpace(Constants.SIZEOF_DOUBLE);
conversion.double2byte(value, buffer, index);
index += Constants.SIZEOF_DOUBLE;
}
public void write(byte[] b) throws IOException {
writeArray(b);
}
public void write(byte[] b, int off, int len) throws IOException {
writeArray(b, off, len);
}
public void writeArray(boolean[] ref, int off, int len) throws IOException {
if (DEBUG && logger.isDebugEnabled()) {
logger.debug("writeArray(boolean[" + off + " ... " + (off + len)
+ "])");
}
final int toWrite = len * Constants.SIZEOF_BOOLEAN;
checkFreeSpace(toWrite);
conversion.boolean2byte(ref, off, len, buffer, index);
index += toWrite;
}
public void writeArray(byte[] ref, int off, int len) throws IOException {
if (DEBUG && logger.isDebugEnabled()) {
logger.debug("writeArray(byte[" + off + " ... " + (off + len)
+ "])");
}
checkFreeSpace(len);
System.arraycopy(ref, off, buffer, index, len);
index += len;
}
public void writeArray(char[] ref, int off, int len) throws IOException {
if (DEBUG && logger.isDebugEnabled()) {
logger.debug("writeArray(char[" + off + " ... " + (off + len)
+ "])");
}
final int toWrite = len * Constants.SIZEOF_CHAR;
checkFreeSpace(toWrite);
conversion.char2byte(ref, off, len, buffer, index);
index += toWrite;
}
public void writeArray(short[] ref, int off, int len) throws IOException {
if (DEBUG && logger.isDebugEnabled()) {
logger.debug("writeArray(short[" + off + " ... " + (off + len)
+ "])");
}
final int toWrite = len * Constants.SIZEOF_SHORT;
checkFreeSpace(toWrite);
conversion.short2byte(ref, off, len, buffer, index);
index += toWrite;
}
public void writeArray(int[] ref, int off, int len) throws IOException {
if (DEBUG && logger.isDebugEnabled()) {
logger
.debug("writeArray(int[" + off + " ... " + (off + len)
+ "])");
}
final int toWrite = len * Conversion.INT_SIZE;
checkFreeSpace(toWrite);
conversion.int2byte(ref, off, len, buffer, index);
index += toWrite;
}
public void writeArray(long[] ref, int off, int len) throws IOException {
if (DEBUG && logger.isDebugEnabled()) {
logger.debug("writeArray(long[" + off + " ... " + (off + len)
+ "])");
}
final int toWrite = len * Conversion.INT_SIZE;
checkFreeSpace(toWrite);
conversion.long2byte(ref, off, len, buffer, index);
index += toWrite;
}
public void writeArray(float[] ref, int off, int len) throws IOException {
if (DEBUG && logger.isDebugEnabled()) {
logger.debug("writeArray(float[" + off + " ... " + (off + len)
+ "])");
}
final int toWrite = len * Conversion.FLOAT_SIZE;
checkFreeSpace(toWrite);
conversion.float2byte(ref, off, len, buffer, index);
index += toWrite;
}
public void writeArray(double[] ref, int off, int len) throws IOException {
if (DEBUG && logger.isDebugEnabled()) {
logger.debug("writeArray(double[" + off + " ... " + (off + len)
+ "])");
}
final int toWrite = len * Conversion.FLOAT_SIZE;
checkFreeSpace(toWrite);
conversion.double2byte(ref, off, len, buffer, index);
index += toWrite;
}
public void flush() throws IOException {
// empty
}
public void finish() {
// empty
}
public boolean finished() {
return true;
}
public void close() throws IOException {
// empty
}
public int bufferSize() {
return BUF_SIZE;
}
}
|
package com.walmartlabs.logback;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.core.AppenderBase;
import com.aphyr.riemann.client.EventDSL;
import com.aphyr.riemann.client.RiemannClient;
import com.aphyr.riemann.client.SimpleUdpTransport;
import com.aphyr.riemann.client.SynchronousTransport;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
public class RiemannAppender<E> extends AppenderBase<E> {
private static final String DEFAULT_PORT = "5555";
private static final String DEFAULT_HOST = "localhost";
private final String className = getClass().getSimpleName();
private String serviceName = "*no-service-name*";
private Level riemannLogLevel = Level.ERROR;
private String riemannHostname = DEFAULT_HOST;
private String riemannPort = DEFAULT_PORT;
private String hostname = "*no-host-name*";
private Map<String, String> customAttributes = new HashMap<String, String>();
public static AtomicLong timesCalled = new AtomicLong(0);
private static boolean debug = false;
private RiemannClient riemannClient = null;
public void start() {
try {
if (debug) {
printError("%s.start()", this);
}
SynchronousTransport transport = new SimpleUdpTransport(riemannHostname, Integer.parseInt(riemannPort));
riemannClient = new RiemannClient(transport);
if (debug) {
printError("%s.start: connecting", className);
}
riemannClient.connect();
if (debug) {
printError("%s.start: connected", className);
}
} catch (IOException ex) {
if (debug) {
printError("%s: Error initializing: %s", className, ex);
}
throw new RuntimeException(ex);
}
super.start();
}
public void stop() {
if (debug) {
printError("%s.stop()", this);
}
if (riemannClient != null) {
try {
riemannClient.disconnect();
} catch (IOException ex) {
// do nothing, it's ok
}
}
super.stop();
}
public String toString() {
return String.format(
"RiemannAppender{hashCode=%s;serviceName=%s;riemannHostname=%s;riemannPort=%s;hostname=%s}",
hashCode(),
serviceName,
riemannHostname,
riemannPort,
hostname);
}
private String getStackTraceFromEvent(ILoggingEvent logEvent) {
String result = null;
IThrowableProxy throwable = logEvent.getThrowableProxy();
if (null != throwable) {
String firstLine = String.format("%s: %s\n", throwable.getClassName(), throwable.getMessage());
StringBuilder sb = new StringBuilder(firstLine);
if (null != throwable.getStackTraceElementProxyArray()) {
for (StackTraceElementProxy elt : throwable.getStackTraceElementProxyArray()) {
sb.append("\t")
.append(elt.toString())
.append("\n");
}
}
result = sb.toString();
}
return result;
}
public void forceAppend(E event) {
append(event);
}
boolean isMinimumLevel(ILoggingEvent logEvent) {
return logEvent.getLevel().isGreaterOrEqual(riemannLogLevel);
}
protected synchronized void append(E event) {
timesCalled.incrementAndGet();
ILoggingEvent logEvent = (ILoggingEvent) event;
if(debug) {
printError("Original log event: %s", asString(logEvent));
}
if (isMinimumLevel(logEvent)) {
EventDSL rEvent = createRiemannEvent(logEvent);
try {
try {
if (debug) {
printError("%s.append: sending riemann event: %s", className, rEvent);
}
rEvent.send();
if (debug) {
printError("%s.append(logEvent): sent to riemann %s:%s", className, riemannHostname, riemannPort);
}
} catch (Exception ex) {
if (debug) {
printError("%s: Error sending event %s", this, ex);
ex.printStackTrace(System.err);
}
riemannClient.reconnect();
rEvent.send();
}
} catch (Exception ex) {
// do nothing
if (debug) {
printError("%s.append: Error during append(): %s", className, ex);
ex.printStackTrace(System.err);
}
}
}
}
private String asString(ILoggingEvent logEvent) {
return String.format("LogEvent{level:%s, message:%s, logger:%s, thread:%s",
logEvent.getLevel().toString(),
logEvent.getMessage(),
logEvent.getLoggerName(),
logEvent.getThreadName());
}
private EventDSL createRiemannEvent(ILoggingEvent logEvent) {
EventDSL event = riemannClient.event()
.host(hostname)
// timestamp is expressed in millis,
// `time` is expressed in seconds
.time(logEvent.getTimeStamp() / 1000)
.description(logEvent.getMessage())
.attribute("log/level", logEvent.getLevel().levelStr)
.attribute("log/logger", logEvent.getLoggerName())
.attribute("log/thread", logEvent.getThreadName())
.attribute("log/message", logEvent.getMessage());
if (logEvent.getThrowableProxy() != null) {
event.attribute("log/stacktrace", getStackTraceFromEvent(logEvent));
}
if (logEvent.getMarker() != null) {
event.tag("log/" + logEvent.getMarker().getName());
}
copyAttributes(event, logEvent.getMDCPropertyMap());
copyAttributes(event, customAttributes);
return event;
}
/**
* Copy attributes out of the source and add them to `target`,
* making sure to prefix the keys with `log/` -- this puts the
* keywords in that namespace, preventing any collisions with the
* Riemann schema.
* @param target
* @param source
*/
private void copyAttributes(EventDSL target, Map<String, String> source) {
for (String key : source.keySet()) {
target.attribute("log/" + key, source.get(key));
}
}
private void printError(String format, Object... params) {
System.err.println(String.format(format, params));
}
public void setServiceName(String s) {
serviceName = s;
}
public void setRiemannHostname(String s) {
riemannHostname = s;
}
public void setRiemannPort(String s) {
riemannPort = s;
}
public void setHostname(String s) {
hostname = s;
}
public void setRiemannLogLevel(String s) {
riemannLogLevel = Level.toLevel(s);
}
public void setCustomAttributes(String s) {
customAttributes.putAll(parseCustomAttributes(s));
}
Map<String, String> parseCustomAttributes(String attributesString) {
HashMap<String, String> result = new HashMap<String, String>();
try {
for (String kvPair : attributesString.split(",")) {
String[] splitKvPair = kvPair.split(":");
result.put(splitKvPair[0], splitKvPair[1]);
}
} catch (Throwable t) {
printError("Encountered error while parsing attribute string: %s", attributesString);
}
return result;
}
public void setDebug(String s) {
debug = "true".equals(s);
}
}
|
import java.util.*;
/**
* Given an absolute path for a file (Unix-style), simplify it.
*
* For example,
* path = "/home/", => "/home"
* path = "/a/./b/../../c/", => "/c"
*
* Corner Cases:
* Did you consider the case where path = "/../"?
* In this case, you should return "/".
* Another corner case is the path might contain multiple slashes '/' together,
* such as "/home//foo/".
* In this case, you should ignore redundant slashes and return "/home/foo".
*
* Tags: Stack, String
*/
class SimplifyPath {
public static void main(String[] args) {
// System.out.println(simplifyPath("/home/"));
// System.out.println(simplifyPath("/a/./b/../../c/"));
// System.out.println(simplifyPath("/../"));
// System.out.println(simplifyPath("/home//foo/"));
System.out.println(simplifyPath("/a/./b///../c/../././../d/..//../e/./f/./g/././//.//h///././/..///"));
}
/**
* Split words with /, use a stack to save directories
* If ".", skip
* If "..", check stack. If stack empty, skip; If not, pop
* Else, push it to stack
* Initialize result as "/" if stack is empty, otherwise as empty string
* Go through stack and concatenate words
* Return result
*/
public static String simplifyPath(String path) {
if (path == null) return "";
Stack<String> s = new Stack<String>();
String[] words = path.split("/");
for (String str : words) {
if (str.length() == 0 || str.equals(".")) continue;
if (str.equals("..")) {
if (s.isEmpty()) continue;
else s.pop();
} else s.push(str); // is a word
}
String res = s.isEmpty() ? "/" : ""; // check whether stack is empty
// stack iterator traverse the stack in a opposite way. (FIFO)
for (String word : s) res += "/" + word;
return res;
}
}
|
package net.ohloh.ohcount4j.scan;
import org.testng.annotations.Test;
import static net.ohloh.ohcount4j.Entity.*;
import static net.ohloh.ohcount4j.Language.*;
public class AdaScannerTest extends BaseScannerTest {
@Test
public void basic() {
assertLine(new AdaScanner(), new Line(LANG_ADA, BLANK), "\n");
assertLine(new AdaScanner(), new Line(LANG_ADA, BLANK), " \n");
assertLine(new AdaScanner(), new Line(LANG_ADA, BLANK), "\t\n");
assertLine(new AdaScanner(), new Line(LANG_ADA, CODE), "Ada.Text_IO.Put_Line (\"Hello World\");\n");
assertLine(new AdaScanner(), new Line(LANG_ADA, COMMENT), "-- Line comment\n");
assertLine(new AdaScanner(), new Line(LANG_ADA, COMMENT), "
assertLine(new AdaScanner(), new Line(LANG_ADA, CODE), "Ada.Text_IO.Put_Line (\"Hello World\"); -- with comment\n");
}
@Test
public void eofHandling() {
// Note lack of trailing \n in all cases below
assertLine(new AdaScanner(), new Line(LANG_ADA, BLANK), " ");
assertLine(new AdaScanner(), new Line(LANG_ADA, BLANK), "\t");
assertLine(new AdaScanner(), new Line(LANG_ADA, CODE), "Ada.Text_IO.Put_Line (\"Hello World\");");
assertLine(new AdaScanner(), new Line(LANG_ADA, COMMENT), "-- Line comment");
assertLine(new AdaScanner(), new Line(LANG_ADA, COMMENT), "
assertLine(new AdaScanner(), new Line(LANG_ADA, CODE), "Ada.Text_IO.Put_Line (\"Hello World\"); -- with comment");
}
@Test
public void sampleTest() {
String code
= "-- Sample Test Program\n"
+ "
+ "\t\n"
+ "for i in 1 .. 10 loop\n"
+ " Ada.Text_IO.Put (\"Iteration: \");\n"
+ " Ada.Text_IO.Put (i); -- Print the current iteration\n"
+ " Ada.Text_IO.Put_Line;\n"
+ "end loop;\n";
Line[] expected = {
new Line(LANG_ADA, COMMENT),
new Line(LANG_ADA, COMMENT),
new Line(LANG_ADA, BLANK),
new Line(LANG_ADA, CODE),
new Line(LANG_ADA, CODE),
new Line(LANG_ADA, CODE),
new Line(LANG_ADA, CODE),
new Line(LANG_ADA, CODE)
};
assertLines(new AdaScanner(), expected, code);
}
@Test
public void unterminatedMultilineStringCrash() {
// This minimal case caused an Arrays.copyOfRange() crash
String code = "\"\nA\n\n";
Line[] expected = {
new Line(LANG_ADA, CODE),
new Line(LANG_ADA, CODE),
new Line(LANG_ADA, BLANK)
};
assertLines(new AdaScanner(), expected, code);
}
}
|
package org.myrobotlab.service;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.test.TestUtils;
// Grr.. TODO: disable this until we can figure out why travis is dying on it.
// @Ignore
public class InMoovScriptTest {
private static final String V_PORT_1 = "test_port_1";
private static final String V_PORT_2 = "test_port_2";
public Arduino ard1;
public Arduino ard2;
@Before
public void setup() throws Exception {
// setup the test environment , and create an arduino with a virtual backend for it.
// TestUtils.initEnvirionment();
// initialize 2 serial ports (virtual arduino)
VirtualArduino va1 = (VirtualArduino)Runtime.createAndStart("va1", "VirtualArduino");
VirtualArduino va2 = (VirtualArduino)Runtime.createAndStart("va2", "VirtualArduino");
// one for the left port
va1.connect(V_PORT_1);
// one for the right port.
va2.connect(V_PORT_2);
}
@Test
public void testInMoovMinimal() throws IOException {
// The script should reference V_PORT_1 or V_PORT_2
String inmoovScript = "test/resources/InMoov/InMoov3.minimal.py";
File f = new File(inmoovScript);
System.out.println("IN MOOV SCRIPT: " + f.getAbsolutePath());
//InputStream is = this.getClass().getResourceAsStream(inmoovScript);
String script = FileIO.toString(inmoovScript);
//String script = new String(FileIO.toByteArray(is));
Python python = (Python)Runtime.createAndStart("python", "Python");
python.createPythonInterpreter();
// python.execAndWait(script);
python.interp.exec(script);
// Assert something
assertNotNull(Runtime.getService("i01"));
}
}
|
package jodd.db.oom;
import jodd.db.DbQuery;
import jodd.db.DbSession;
import jodd.db.DbUtil;
import jodd.db.oom.mapper.ResultSetMapper;
import jodd.db.oom.sqlgen.ParameterValue;
import jodd.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.Map;
import static jodd.db.oom.DbOomUtil.initialCollectionSize;
/**
* A simple ORM extension for {@link DbQuery}.
* <p>
* OOM extension may map results to objects in two ways:
* <ul>
* <li><i>auto</i> mode - when result set is mapped to provided types, and</li>
* <li><i>mapped</i> mode - requires explicit mapping definitions.</li>
* </ul>
*/
public class DbOomQuery extends DbQuery {
private static final Logger log = LoggerFactory.getLogger(DbOomQuery.class);
public DbOomQuery(Connection conn, String sqlString) {
super(conn, sqlString);
}
public static DbOomQuery query(Connection conn, String sqlString) {
return new DbOomQuery(conn, sqlString);
}
public DbOomQuery(DbSession session, String sqlString) {
super(session, sqlString);
}
public static DbOomQuery query(DbSession session, String sqlString) {
return new DbOomQuery(session, sqlString);
}
public DbOomQuery(String sqlString) {
super(sqlString);
}
public static DbOomQuery query(String sqlString) {
return new DbOomQuery(sqlString);
}
protected DbSqlGenerator sqlgen;
public DbOomQuery(Connection conn, DbSqlGenerator sqlgen) {
super(conn, sqlgen.generateQuery());
this.sqlgen = sqlgen;
}
public static DbOomQuery query(Connection conn, DbSqlGenerator sqlgen) {
return new DbOomQuery(conn, sqlgen);
}
public DbOomQuery(DbSession session, DbSqlGenerator sqlgen) {
super(session, sqlgen.generateQuery());
this.sqlgen = sqlgen;
}
public static DbOomQuery query(DbSession session, DbSqlGenerator sqlgen) {
return new DbOomQuery(session, sqlgen);
}
public DbOomQuery(DbSqlGenerator sqlgen) {
super(sqlgen.generateQuery());
this.sqlgen = sqlgen;
}
public static DbOomQuery query(DbSqlGenerator sqlgen) {
return new DbOomQuery(sqlgen);
}
protected DbOomManager dbOomManager = DbOomManager.getInstance();
/**
* Returns used ORM manager.
*/
public DbOomManager getManager() {
return dbOomManager;
}
/**
* Prepares the query after initialization. Besides default work, it checks if sql generator
* is used, and if so, generator hints and query parameters will be used for this query.
* Note regarding hints: since hints can be added manually, generators hints will be ignored
* if there exists some manually set hints.
*/
@Override
protected void prepareQuery() {
super.prepareQuery();
if (sqlgen == null) {
return;
}
if (hints == null) {
String[] joinHints = sqlgen.getJoinHints();
if (joinHints != null) {
withHints(joinHints);
}
}
// insert parameters
Map<String, ParameterValue> parameters = sqlgen.getQueryParameters();
if (parameters == null) {
return;
}
for (Map.Entry<String, ParameterValue> entry : parameters.entrySet()) {
String paramName = entry.getKey();
ParameterValue param = entry.getValue();
DbEntityColumnDescriptor dec = param.getColumnDescriptor();
if (dec == null) {
setObject(paramName, param.getValue());
} else {
resolveColumnDbSqlType(connection, dec);
setObject(paramName, param.getValue(), dec.getSqlTypeClass(), dec.getDbSqlType());
}
}
}
/**
* Resolves column db sql type and populates it in column descriptor if missing.
*/
protected void resolveColumnDbSqlType(Connection connection, DbEntityColumnDescriptor dec) {
if (dec.dbSqlType != DbEntityColumnDescriptor.DB_SQLTYPE_UNKNOWN) {
return;
}
ResultSet rs = null;
DbEntityDescriptor ded = dec.getDbEntityDescriptor();
try {
DatabaseMetaData dmd = connection.getMetaData();
rs = dmd.getColumns(null, ded.getSchemaName(), ded.getTableName(), dec.getColumnName());
if (rs.next()) {
dec.dbSqlType = rs.getInt("DATA_TYPE");
} else {
dec.dbSqlType = DbEntityColumnDescriptor.DB_SQLTYPE_NOT_AVAILABLE;
if (log.isWarnEnabled()) {
log.warn("Column SQL type not available: " + ded.toString() + '.' + dec.getColumnName());
}
}
} catch (SQLException sex) {
dec.dbSqlType = DbEntityColumnDescriptor.DB_SQLTYPE_NOT_AVAILABLE;
if (log.isWarnEnabled()) {
log.warn("Column SQL type not resolved: " + ded.toString() + '.' + dec.getColumnName(), sex);
}
} finally {
DbUtil.close(rs);
}
}
protected String[] hints;
protected JoinHintResolver hintResolver = dbOomManager.getHintResolver();
/**
* Specifies hints for the query. Provided string is
* split on ',' separator.
*/
public DbOomQuery withHints(String hint) {
this.hints = StringUtil.splitc(hint, ',');
return this;
}
/**
* Specifies multiple hints for the query.
*/
public DbOomQuery withHints(String... hints) {
this.hints = hints;
return this;
}
/**
* Prepares a row (array of rows mapped object) using hints.
* Returns either single object or objects array.
*/
protected Object resolveRowHints(Object[] row) {
row = hintResolver.join(row, hints);
return row.length == 1 ? row[0] : row;
}
/**
* Executes the query and returns {@link #createResultSetMapper(java.sql.ResultSet) builded ResultSet mapper}.
*/
protected ResultSetMapper executeAndBuildResultSetMapper() {
return createResultSetMapper(execute());
}
/**
* Factory for result sets mapper.
*/
protected ResultSetMapper createResultSetMapper(ResultSet resultSet) {
return dbOomManager.createResultSetMapper(resultSet, sqlgen != null ? sqlgen.getColumnData() : null);
}
public <T> Iterator<T> iterateOne(Class<T> type) {
return iterateOne(type, false);
}
public <T> Iterator<T> iterateOneAndClose(Class<T> type) {
return iterateOne(type, true);
}
public <T> Iterator<T> iterateOne() {
return iterateOne(null, false);
}
public <T> Iterator<T> iterateOneAndClose() {
return iterateOne(null, true);
}
protected <T> Iterator<T> iterateOne(Class<T> type, boolean close) {
return new DbListOneIterator<T>(this, type, close);
}
public <T> Iterator<T> iterate(Class... types) {
return iterate(types, false);
}
public <T> Iterator<T> iterateAndClose(Class... types) {
return iterate(types, true);
}
public <T> Iterator<T> iterate() {
return iterate(null, false);
}
public <T> Iterator<T> iterateAndClose() {
return iterate(null, true);
}
protected <T> Iterator<T> iterate(Class[] types, boolean close) {
return new DbListIterator<T>(this, types, close);
}
public <T> List<T> listOne(Class<T> type) {
return listOne(type, 0, false);
}
public <T> List<T> listOneAndClose(Class<T> type) {
return listOne(type, 0, true);
}
public <T> List<T> listOne() {
return listOne(null, 0, false);
}
public <T> List<T> listOneAndClose() {
return listOne(null, 0, true);
}
public <T> List<T> listOne(int max, Class<T> type) {
return listOne(type, max, false);
}
public <T> List<T> listOneAndClose(int max, Class<T> type) {
return listOne(type, max, true);
}
public <T> List<T> listOne(int max) {
return listOne(null, max, false);
}
public <T> List<T> listOneAndClose(int max) {
return listOne(null, max, true);
}
/**
* Iterates results set, maps rows to just one class and populates the array list.
* @param type target type
* @param max max number of rows to collect, <code>0</code> for all
* @param close <code>true</code> if query is closed at the end, otherwise <code> false
* @return list of mapped entities
*/
@SuppressWarnings({"unchecked"})
protected <T> List<T> listOne(Class<T> type, int max, boolean close) {
List<T> result = new ArrayList<T>(initialCollectionSize(max));
ResultSetMapper rsm = executeAndBuildResultSetMapper();
Class[] types = (type == null ? rsm.resolveTables() : new Class[]{type});
while (rsm.next()) {
result.add((T) rsm.parseOneObject(types));
max
if (max == 0) {
break;
}
}
close(rsm, close);
return result;
}
public <T> List<T> list(Class... types) {
return list(types, 0, false);
}
public <T> List<T> listAndClose(Class... types) {
return list(types, 0, true);
}
public <T> List<T> list() {
return list(null, 0, false);
}
public <T> List<T> listAndClose() {
return list(null, 0, true);
}
public <T> List<T> list(int max, Class... types) {
return list(types, max, false);
}
public <T> List<T> listAndClose(int max, Class... types) {
return list(types, max, true);
}
public <T> List<T> list(int max) {
return list(null, max, false);
}
public <T> List<T> listAndClose(int max) {
return list(null, max, true);
}
/**
* Iterates result set, maps rows to classes and populates the array list.
* @param types mapping types
* @param max max number of rows to collect, <code>0</code> for all
* @param close <code>true</code> if query is closed at the end, otherwise <code> false
* @return list of mapped entities
*/
@SuppressWarnings({"unchecked"})
protected <T> List<T> list(Class[] types, int max, boolean close) {
List<T> result = new ArrayList<T>(initialCollectionSize(max));
ResultSetMapper rsm = executeAndBuildResultSetMapper();
if (types == null) {
types = rsm.resolveTables();
}
while (rsm.next()) {
Object[] objects = rsm.parseObjects(types);
Object row = resolveRowHints(objects);
result.add((T) row);
max
if (max == 0) {
break;
}
}
close(rsm, close);
return result;
}
public <T> Set<T> listSetOne(Class<T> type) {
return listSetOne(type, 0, false);
}
public <T> Set<T> listSetOneAndClose(Class<T> type) {
return listSetOne(type, 0, true);
}
public <T> Set<T> listSetOne() {
return listSetOne(null, 0, false);
}
public <T> Set<T> listSetOneAndClose() {
return listSetOne(null, 0, true);
}
public <T> Set<T> listSetOne(int max, Class<T> type) {
return listSetOne(type, max, false);
}
public <T> Set<T> listSetOneAndClose(int max, Class<T> type) {
return listSetOne(type, max, true);
}
public <T> Set<T> listSetOne(int max) {
return listSetOne(null, max, false);
}
public <T> Set<T> listSetOneAndClose(int max) {
return listSetOne(null, max, true);
}
@SuppressWarnings({"unchecked"})
protected <T> Set<T> listSetOne(Class<T> type, int max, boolean close) {
Set<T> result = new LinkedHashSet<T>(initialCollectionSize(max));
ResultSetMapper rsm = executeAndBuildResultSetMapper();
Class[] types = (type == null ? rsm.resolveTables() : new Class[]{type});
while (rsm.next()) {
result.add((T) rsm.parseOneObject(types));
max
if (max == 0) {
break;
}
}
close(rsm, close);
return result;
}
public <T> Set<T> listSet(Class... types) {
return listSet(types, 0, false);
}
public <T> Set<T> listSetAndClose(Class... types) {
return listSet(types, 0, true);
}
public <T> Set<T> listSet() {
return listSet(null, 0, false);
}
public <T> Set<T> listSetAndClose() {
return listSet(null, 0, true);
}
public <T> Set<T> listSet(int max, Class... types) {
return listSet(types, max, false);
}
public <T> Set<T> listSetAndClose(int max, Class... types) {
return listSet(types, max, true);
}
public <T> Set<T> listSet(int max) {
return listSet(null, max, false);
}
public <T> Set<T> listSetAndClose(int max) {
return listSet(null, max, true);
}
@SuppressWarnings({"unchecked"})
protected <T> Set<T> listSet(Class[] types, int max, boolean close) {
Set<T> result = new LinkedHashSet<T>(initialCollectionSize(max));
ResultSetMapper rsm = executeAndBuildResultSetMapper();
if (types == null) {
types = rsm.resolveTables();
}
while (rsm.next()) {
Object[] objects = rsm.parseObjects(types);
Object row = resolveRowHints(objects);
result.add((T) row);
max
if (max == 0) {
break;
}
}
close(rsm, close);
return result;
}
@SuppressWarnings({"unchecked"})
public <T> T findOne(Class<T> type) {
return findOne(type, false, null);
}
public <T> T findOneAndClose(Class<T> type) {
return findOne(type, true, null);
}
public Object findOne() {
return findOne(null, false, null);
}
public Object findOneAndClose() {
return findOne(null, true, null);
}
@SuppressWarnings({"unchecked"})
protected <T> T findOne(Class<T> type, boolean close, ResultSet resultSet) {
if (resultSet == null) {
resultSet = execute();
}
ResultSetMapper rsm = createResultSetMapper(resultSet);
if (rsm.next() == false) {
return null;
}
Class[] types = (type == null ? rsm.resolveTables() : new Class[]{type});
Object result = rsm.parseOneObject(types);
close(rsm, close);
return (T) result;
}
public Object find(Class... types) {
return find(types, false, null);
}
public Object findAndClose(Class... types) {
return find(types, true, null);
}
public Object find() {
return find(null, false, null);
}
public Object findAndClose() {
return find(null, true, null);
}
protected Object find(Class[] types, boolean close, ResultSet resultSet) {
if (resultSet == null) {
resultSet = execute();
}
ResultSetMapper rsm = createResultSetMapper(resultSet);
if (rsm.next() == false) {
return null;
}
if (types == null) {
types = rsm.resolveTables();
}
Object[] objects = rsm.parseObjects(types);
Object result = resolveRowHints(objects);
close(rsm, close);
return result;
}
public <T> T findGeneratedKey(Class<T> type) {
return findOne(type, false, getGeneratedColumns());
}
public Object findGeneratedColumns(Class... types) {
return find(types, false, getGeneratedColumns());
}
/**
* Closes results set or whole query.
*/
protected void close(ResultSetMapper rsm, boolean closeQuery) {
if (closeQuery == true) {
close();
} else {
closeResultSet(rsm.getResultSet());
}
}
}
|
package org.jpos.core;
import org.jpos.iso.ISOUtil;
import org.jpos.util.Caller;
import org.jpos.util.Loggeable;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.scanner.ScannerException;
import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Environment implements Loggeable {
private static final String DEFAULT_ENVDIR = "cfg"; // default dir for the env file (relative to cwd), overridable with sys prop "jpos.envdir"
private static final String CFG_PREFIX = "cfg";
private static final String SYSTEM_PREFIX = "sys";
private static final String ENVIRONMENT_PREFIX = "env";
private static Pattern valuePattern = Pattern.compile("^(.*)(\\$)([\\w]*)\\{([-\\w.]+)(:(.*))?\\}(.*)$");
// make groups easier to read :-) 11112222233333333 44444444445566665 7777
private static Pattern verbPattern = Pattern.compile("^\\$verb\\{([\\w\\W]+)\\}$");
private static Environment INSTANCE;
private String name;
private String envDir;
private AtomicReference<Properties> propRef = new AtomicReference<>(new Properties());
private static String SP_PREFIX = "system.property.";
private static int SP_PREFIX_LENGTH = SP_PREFIX.length();
private String errorString;
private ServiceLoader<EnvironmentProvider> serviceLoader;
static {
try {
INSTANCE = new Environment();
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private Environment() throws IOException {
name = System.getProperty ("jpos.env");
name = name == null ? "default" : name;
envDir = System.getProperty("jpos.envdir", DEFAULT_ENVDIR);
readConfig ();
serviceLoader = ServiceLoader.load(EnvironmentProvider.class);
}
public String getName() {
return name;
}
public String getEnvDir() {
return envDir;
}
public static Environment reload() throws IOException {
return (INSTANCE = new Environment());
}
public static Environment getEnvironment() {
return INSTANCE;
}
public static String get (String p) {
return getEnvironment().getProperty(p, p);
}
public static String get (String p, String def) {
return getEnvironment().getProperty(p, def);
}
public String getProperty (String p, String def) {
String s = getProperty (p);
return s != null ? s : def;
}
public String getErrorString() {
return errorString;
}
/**
* If property name has the pattern <code>${propname}</code>, this method will
*
* <ul>
* <li>Attempt to get it from an operating system environment variable called 'propname'</li>
* <li>If not present, it will try to pick it from the Java system.property</li>
* <li>If not present either, it will try the target environment (either <code>.yml</code> or <code>.cfg</code></li>
* <li>Otherwise it returns null</li>
* </ul>
*
* The special pattern <code>$env{propname}</code> would just try to pick it from the OS environment.
* <code>$sys{propname}</code> will just try to get it from a System.property and
* <code>$verb{propname}</code> will return a verbatim copy of the value.
*
* @param s property name
* @return property value
*/
public String getProperty (String s) {
String r = s;
if (s != null) {
Matcher m = verbPattern.matcher(s);
if (m.matches()) { // matches $verb{...}
return m.group(1); // return internal value, verbatim
}
m = valuePattern.matcher(s);
if (!m.matches()) // doesn't match $xxx{...} at all
return s; // return the whole thing
while (m != null && m.matches()) {
String gPrefix = m.group(3);
String gValue = m.group(4);
gPrefix = gPrefix != null ? gPrefix : "";
switch (gPrefix) {
case CFG_PREFIX:
r = propRef.get().getProperty(gValue, null);
break;
case SYSTEM_PREFIX:
r = System.getProperty(gValue);
break;
case ENVIRONMENT_PREFIX:
r = System.getenv(gValue);
break;
default:
if (gPrefix.length() == 0) {
r = System.getenv(gValue); // ENV has priority
r = r == null ? System.getenv(gValue.replace('.', '_').toUpperCase()) : r;
r = r == null ? System.getProperty(gValue) : r; // then System.property
r = r == null ? propRef.get().getProperty(gValue) : r; // then jPOS --environment
} else {
return s; // do nothing - unknown prefix
}
}
if (r == null) {
String defValue = m.group(6);
if (defValue != null)
r = defValue;
}
if (r != null) {
for (EnvironmentProvider p : serviceLoader) {
int l = p.prefix().length();
if (r != null && r.length() > l && r.startsWith(p.prefix())) {
r = p.get(r.substring(l));
}
}
if (m.group(1) != null) {
r = m.group(1) + r;
}
if (m.group(7) != null)
r = r + m.group(7);
m = valuePattern.matcher(r);
}
else
m = null;
}
}
return r;
}
@SuppressWarnings("unchecked")
private void readConfig () throws IOException {
if (name != null) {
if (!readYAML())
readCfg();
extractSystemProperties();
propRef.get().put ("jpos.env", name);
propRef.get().put ("jpos.envdir", envDir);
}
}
private void extractSystemProperties() {
Properties properties = propRef.get();
properties
.stringPropertyNames()
.stream()
.filter(e -> e.startsWith(SP_PREFIX))
.forEach(prop -> System.setProperty(prop.substring(SP_PREFIX_LENGTH), (String) properties.get(prop)));
}
private boolean readYAML () throws IOException {
errorString = null;
boolean configRead = false;
String[] names = ISOUtil.commaDecode(name);
for (String n : names) {
File f = new File(envDir + "/" + n + ".yml");
if (f.exists() && f.canRead()) {
Properties properties = new Properties();
try (InputStream fis = new FileInputStream(f)) {
Yaml yaml = new Yaml();
Iterable<Object> document = yaml.loadAll(fis);
document.forEach(d -> {
flat(properties, null, (Map<String, Object>) d, false);
});
propRef.set(properties);
configRead = true;
} catch (ScannerException e) {
errorString = "Environment (" + getName() + ") error " + e.getMessage();
}
}
}
return configRead;
}
private boolean readCfg () throws IOException {
String[] names = ISOUtil.commaDecode(name);
boolean configRead = false;
Properties properties = new Properties();
for (String n : names) {
File f = new File(envDir + "/" + n + ".cfg");
if (f.exists() && f.canRead()) {
try (InputStream fis = new FileInputStream(f)) {
properties.load(new BufferedInputStream(fis));
propRef.set(properties);
configRead = true;
}
}
}
return configRead;
}
@SuppressWarnings("unchecked")
public static void flat (Properties properties, String prefix, Map<String,Object> c, boolean dereference) {
for (Object o : c.entrySet()) {
Map.Entry<String,Object> entry = (Map.Entry<String,Object>) o;
String p = prefix == null ? entry.getKey() : (prefix + "." + entry.getKey());
if (entry.getValue() instanceof Map) {
flat(properties, p, (Map) entry.getValue(), dereference);
} else {
Object obj = entry.getValue();
properties.put (p, "" + (dereference && obj instanceof String ? Environment.get((String) obj) : entry.getValue()));
}
}
}
@Override
public void dump(final PrintStream p, String indent) {
p.printf ("%s<environment name='%s' envdir='%s'>%n", indent, name, envDir);
Properties properties = propRef.get();
properties.stringPropertyNames().stream().
forEachOrdered(prop -> p.printf ("%s %s=%s%n", indent, prop, properties.getProperty(prop)) );
p.printf ("%s</environment>%n", indent);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (name != null) {
sb.append(String.format("[%s]%n", name));
Properties properties = propRef.get();
properties.stringPropertyNames().stream().
forEachOrdered(prop -> {
String s = properties.getProperty(prop);
String ds = Environment.get(String.format("${%s}", prop)); // de-referenced string
boolean differ = !s.equals(ds);
sb.append(String.format (" %s=%s%s%n",
prop,
s,
differ ? " (*)" : ""
)
);
});
if (serviceLoader.iterator().hasNext()) {
sb.append (" providers:");
sb.append (System.lineSeparator());
for (EnvironmentProvider provider : serviceLoader) {
sb.append(String.format(" %s%n", provider.getClass().getCanonicalName()));
}
}
}
return sb.toString();
}
}
|
package com.example.testgit;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package natlab.utils;
import java.util.Iterator;
import java.util.Stack;
import ast.ASTNode;
import com.google.common.base.Preconditions;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.AbstractSequentialIterator;
import com.google.common.collect.FluentIterable;
/**
* A utility that finds nodes of a certain type in the AST, and returns them as a lazy iterable.
* This class is intended to be used together with Guava's Iterable utilities; see also
* AstPredicates and AstFunctions for utilities related to this. For example, the
* following snippet searches <tt>tree</tt> for all functions that aren't nested, returns
* a list of their names:
*
* <pre>
* FluentIterable.from(NodeFinder.find(ast.Function.class, tree))
* .filter(Predicates.not(AstPredicates.nestedFunction()))
* .transform(AstFunctions.functionToName())
* .toImmutableList();
* </pre>
*/
public class NodeFinder {
/**
* Returns an iterable of all the descendents of <tt>tree</tt>. This corresponds to a
* depth-first traversal of the subtree rooted at <tt>tree</tt>.
*/
public static Iterable<ASTNode<?>> allDescendentsOf(final ASTNode<?> tree) {
Preconditions.checkNotNull(tree);
return new Iterable<ASTNode<?>>() {
@Override public Iterator<ASTNode<?>> iterator() {
final Stack<ASTNode<?>> toVisit = new Stack<ASTNode<?>>();
toVisit.push(tree);
return new AbstractIterator<ASTNode<?>>() {
@Override protected ASTNode<?> computeNext() {
while (!toVisit.empty()) {
ASTNode<?> next = toVisit.pop();
for (int i = 0; i < next.getNumChild(); i++) {
toVisit.push(next.getChild(i));
}
return next;
}
return endOfData();
}
};
}
};
}
/**
* Returns an iterable of the ancestors of <tt>tree</tt>.
*/
public static Iterable<ASTNode<?>> allAncestorsOf(final ASTNode<?> tree) {
Preconditions.checkNotNull(tree);
return new Iterable<ASTNode<?>>() {
@Override public Iterator<ASTNode<?>> iterator() {
return new AbstractSequentialIterator<ASTNode<?>>(tree.getParent()) {
@Override protected ASTNode<?> computeNext(ASTNode<?> previous) {
return previous.getParent();
}
};
}
};
}
/**
* Returns a lazy iterable of the nodes of this finder's type in <tt>tree</tt>.
*/
public static <T> Iterable<T> find(final Class<T> clazz, final ASTNode<?> tree) {
return FluentIterable.from(allDescendentsOf(tree)).filter(clazz);
}
/**
* Walks up the tree to find a parent of the specified type.
* Returns null if no such parent exists.
*/
public static <T> T findParent(Class<T> clazz, ASTNode<?> node) {
return FluentIterable.from(allAncestorsOf(node)).filter(clazz).first().orNull();
}
/**
* Applies <tt>func</tt> to each node of type <tt>type</tt> in <tt>n</tt>.
*/
public static <T> void apply(final Class<T> type, final ASTNode<?> n,
final AbstractNodeFunction<T> func) {
for (T node : NodeFinder.find(type, n)) {
func.apply(node);
}
}
}
|
// Using recursion: O(3^m), where m = word1.length() => Time Limit Exceeded
public class MinDistance {
public static int minDistance(String word1, String word2) {
return minDistance(word1, word2, word1.length(), word2.length());
}
public static int minDistance(String s1, String s2, int n1, int n2) {
// if 1st string s1 is empty, the only option is to insert all characters of s2 into s1
if (n1 == 0) return n2;
// if s2 is empty, the only option is to remove all characters of s1
if (n2 == 0) return n1;
// if the last 2 chars are the same, we skip last chars and recurse for remaining strings
if (s1.charAt(n1-1) == s2.charAt(n2-1)) {
return minDistance(s1, s2, n1-1, n2-1);
}
// if last 2 chars are not the same, we consider all 3 possibilities
// (insert, delete, and replace) and take the min of all 3
int insert = minDistance(s1, s2, n1, n2-1); // recurse for n1 and n2-1
int delete = minDistance(s1, s2, n1-1, n2); // recurse for n1-1 and n2
int replace = minDistance(s1, s2, n1-1, n2-1); // recurse for n1-1 and n2-1
return 1 + min(insert, delete, replace);
}
// Dynamic programming solution: O(n1 * n2) runtime and O(n1 * n2) space complexities
public static int minDistance2(String word1, String word2) {
int n1 = word1.length(), n2 = word2.length();
int[][] dp = new int[n1+1][n2+1];
for (int i = 0; i <= n1; i++) {
for (int j = 0; j <= n2; j++) {
// if 1st string s1 is empty, the only option is to insert all characters of s2 into s1
if (i == 0) dp[i][j] = j;
// if s2 is empty, the only option is to remove all characters of s1
else if (j == 0) dp[i][j] = i;
// if last 2 characters are the same, no operation is needed; we just take the previous result
else if (word1.charAt(i-1) == word2.charAt(j-1)) dp[i][j] = dp[i-1][j-1];
// if last 2 chars are not the same, we consider all 3 possibilities (insert, delete, and replace)
// and take the minimuk of all 3
else {
dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]);
}
}
}
return dp[n1][n2];
}
public static int min(int a, int b, int c) {
return Math.min(a, Math.min(b, c));
}
public static void main(String[] args) {
System.out.println("Using recursion:");
System.out.println("minDistance(\"sunday\", \"saturday\") = " + minDistance("sunday", "saturday"));
System.out.println("minDistance(\"horse\", \"ros\") = " + minDistance("horse", "ros"));
System.out.println("minDistance(\"intention\", \"execution\") = " + minDistance("intention", "execution"));
System.out.println("\nUsing Dynamic Programming:");
System.out.println("minDistance2(\"sunday\", \"saturday\") = " + minDistance2("sunday", "saturday"));
System.out.println("minDistance2(\"horse\", \"ros\") = " + minDistance2("horse", "ros"));
System.out.println("minDistance2(\"intention\", \"execution\") = " + minDistance2("intention", "execution"));
}
}
|
package org.leores.demo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.leores.plot.JGnuplot;
import org.leores.plot.JGnuplot.Plot;
import org.leores.util.U;
import org.leores.util.able.Processable2;
import org.leores.util.data.DataTable;
import org.leores.util.data.DataTableSet;
public class JGnuplotDemo extends Demo {
Plot plot1, plot2;
public JGnuplotDemo() {
prepPlot();
}
public void plot2d() {
JGnuplot jg = new JGnuplot() {
{
terminal = "pngcairo enhanced dashed";
output = "plot2d.png";
}
};
Plot plot = new Plot("") {
{
xlabel = "x";
ylabel = "y";
}
};
double[] x = { 1, 2, 3, 4, 5 }, y1 = { 2, 4, 6, 8, 10 }, y2 = { 3, 6, 9, 12, 15 };
DataTableSet dts = plot.addNewDataTableSet("2D Plot");
dts.addNewDataTable("y=2x", x, y1);
dts.addNewDataTable("y=3x", x, y2);
jg.execute(plot, jg.plot2d);
}
public void plot2dBar() {
JGnuplot jg = new JGnuplot() {
{
terminal = "pngcairo enhanced dashed";
output = "plot2dBar.png";
}
};
Plot plot = new Plot("") {
{
xlabel = "x";
ylabel = "y";
yrange = "[0:15]";
extra2 = "set key top left";
}
};
double[] x = { 1, 2, 3, 4, 5 }, y1 = { 2, 4, 6, 8, 10 }, y2 = { 3, 6, 9, 12, 15 };
DataTableSet dts = plot.addNewDataTableSet("2D Bar");
DataTable dt = dts.addNewDataTable("", x, y1, y2);
dt.insert(0, new String[] { "", "y1=2x", "y2=3x" });
jg.execute(plot, jg.plot2dBar);
}
public void plot3d() {
JGnuplot jg = new JGnuplot() {
{
terminal = "pngcairo enhanced dashed";
output = "plot3d.png";
}
};
Plot plot = new Plot("") {
{
xlabel = "x";
ylabel = "y";
zlabel = "z";
}
};
double[] x = { 1, 2, 3, 4, 5 }, y = { 2, 4, 6, 8, 10 }, z = { 3, 6, 9, 12, 15 }, z2 = { 2, 8, 18, 32, 50 };
DataTableSet dts = plot.addNewDataTableSet("3D Plot");
dts.addNewDataTable("z=x+y", x, y, z);
dts.addNewDataTable("z=x*y", x, y, z2);
jg.execute(plot, jg.plot3d);
}
public void plotDensity() {
JGnuplot jg = new JGnuplot() {
{
terminal = "pngcairo enhanced dashed";
output = "plotDensity.png";
}
};
Plot plot = new Plot("") {
{
xlabel = "x";
ylabel = "y";
zlabel = "z=x^2+y^2";
}
};
DataTableSet dts = plot.addNewDataTableSet("Density Plot");
//prepare data
List x = new ArrayList(), y = new ArrayList(), z = new ArrayList();
for (double i = -2; i <= 2; i += 0.5) {
for (double j = -2; j <= 2; j += 0.5) {
x.add(i);
y.add(j);
z.add(i * i + j * j);
}
}
dts.addNewDataTable("z=x^2+y^2", x, y, z);
jg.execute(plot, jg.plotDensity);
}
public void plotImage() {
JGnuplot jg = new JGnuplot() {
{
terminal = "pngcairo enhanced dashed";
output = "plotImage.png";
}
};
Plot plot = new Plot("") {
{
xlabel = "x";
ylabel = "y";
zlabel = "z=x^2+y^2";
}
};
DataTableSet dts = plot.addNewDataTableSet("Image Plot");
//prepare data
List x = new ArrayList(), y = new ArrayList(), z = new ArrayList();
for (double i = -2; i <= 2; i += 0.5) {
for (double j = -2; j <= 2; j += 0.5) {
x.add(i);
y.add(j);
z.add(i * i + j * j);
}
}
dts.addNewDataTable("z=x^2+y^2", x, y, z);
jg.execute(plot, jg.plotImage);
}
public void simple() {
plot2d();
plot2dBar();
plot3d();
plotDensity();
plotImage();
}
public void prepPlot() {
plot1 = new Plot("plot1") {
{
xlabel = "x axis";
ylabel = "y axis";
extra2 = "set key top left";
}
};
//DataTableSet 1 2d add data one by one
DataTableSet dts1 = plot1.addNewDataTableSet("DataTableSet 2d");//use null to avoid the output of figure title for this dataset.
DataTable dt1 = dts1.addNewDataTable("x", 2);
DataTable dt2 = dts1.addNewDataTable("2x", 2);
DataTable dt3 = dts1.addNewDataTable("3x", 2);
DataTable dt4 = dts1.addNewDataTable("4x", 2);
DataTable dt5 = dts1.addNewDataTable("5x", 2);
DataTable dt6 = dts1.addNewDataTable("6x", 2);
DataTable dt7 = dts1.addNewDataTable("7x", 2);
DataTable dt8 = dts1.addNewDataTable("8x", 2);
DataTable dt9 = dts1.addNewDataTable("9x", 2);
DataTable dt10 = dts1.addNewDataTable("10x", 2);
for (int i = 0; i < 5; i++) {
dt1.add(i, i);
dt2.add(i, 2 * i);
dt3.add(i, 3 * i);
dt4.add(i, 4 * i);
dt5.add(i, 5 * i);
dt6.add(i, 6 * i);
dt7.add(i, 7 * i);
dt8.add(i, 8 * i);
dt9.add(i, 9 * i);
dt10.add(i, 10 * i);
}
//DataTableSet 2 3d add data using prepared lists
DataTableSet dts2 = plot1.addNewDataTableSet("DataTableSet 3d");
List x = new ArrayList(), y = new ArrayList(), z1 = new ArrayList(), z2 = new ArrayList();
for (double i = -2; i <= 2; i += 0.5) {
for (double j = -2; j <= 2; j += 0.5) {
x.add(i);
y.add(j);
z1.add(i * i + j * j);
z2.add(4 + i * i + j * j);
}
}
Processable2 pa2 = new Processable2.SampleListByIndex(3);
dts2.addNewDataTable("x^2+y^2", pa2, x, y, z1);
dts2.addNewDataTable("4+x^2+y^2", x, y, z2);
DataTableSet dts3 = dts1;
plot1.add(dts3);
plot2 = new Plot("plot2");
plot2.load("xlabel=x axis;ylabel=y axis;zlabel=z axis");
plot2.add(dts2);
}
/**
* Output the generated gnuplot script file without executing it.
*/
public void compile() {
JGnuplot jg = new JGnuplot();
jg.compile(plot1, jg.plot2d);//if file name is omitted it will use plot.info+".plt" as the file name.
jg.compile(plot2, jg.plot3d);
jg.compile(plot2, jg.plotDensity, "plot2density.plt");
jg.compile(plot1, jg.multiplot, "jgnuplot3.plt");
}
/**
* Shows how to use both synchronized and asynchronized running of Gnuplot.
* (Synchronized: your java program will wait until you close the popped
* Gnuplot window; Asynchronized: you java program will not wait.)
*/
public void execute() {
JGnuplot jg = new JGnuplot();
jg.terminal = "wxt enhanced";
jg.execute(plot1, jg.plot2d, jg.JG_InNewThread | jg.JG_Pause);
jg.execute(plot2, jg.plot3d);
jg.beforeStyleVar = "ls1=10;ls10=1;ls2=9;ls9=2;";
jg.executeA(plot1, jg.plot2d);//Asynchronous plot in a new thread
jg.beforeStyleVar = null;
jg.extra = "set label \"Dynamically add extra code using the extra field.\" at graph 0.5,0.5 center";
//jg.extra = "set style line 1 lc rgbcolor 'greenyellow' lt 1 lw 2 pt 1";
jg.execute(plot1, jg.plot2d);
jg.execute(plot2, jg.plot3d);
jg.terminal = "wxt enhanced size 800,600;";
jg.execute(plot1, jg.multiplot);//show gnuplot warning in the java console. warning can be easily solved by extending the canvas size
}
/**
* Show different available terminals to plot. Please refer to the Gnuplot
* website for the complete list of terminals.
*/
public void terminals() {
JGnuplot jg = new JGnuplot();
jg.execute(plot1, jg.plot2d);//Using the default terminal
//windows terminal is only available to windows. You might get error output from gnuplot if you are not using windows.
jg.terminal = "windows enhanced dashed title 'id=100 hello there' size 600,600";
jg.beforeStyle = "linewidth=4";
jg.execute(plot1, jg.plot2d, ~jg.JG_DeleteTempFile);
jg.terminal = null;//Set the terminal to the default terminal
jg.execute(plot1, jg.plot2d);//wxt terminal default size 640,384
jg.terminal = "dumb";//ascii art terminal for anything that prints text
jg.execute(plot1, jg.plot2d);
jg.terminal = "jpeg enhanced size 600,600";
jg.output = "plot1.jpg";
jg.execute(plot1, jg.plot2d);
jg.terminal = "pngcairo enhanced dashed size 600,600";
jg.output = "plot1.png";
jg.execute(plot1, jg.plot2d);
jg.output = "plot2.png";
jg.execute(plot2, jg.plot3d);
//the size unit for pdf is Inch. It is different from other terminals. The default pdf size is 5,3.
jg.terminal = "pdfcairo enhanced dashed size 6,6";
jg.output = "plot1.pdf";
jg.execute(plot1, jg.plot2d);
jg.output = "plot2.pdf";
jg.execute(plot2, jg.plot3d);
jg.output = "plot3.pdf";
jg.execute(plot1, jg.multiplot);
}
/**
* Customised plot functions.
*/
public void plotx() {
//way1: through the JGunplot.plotx field.
JGnuplot jg = new JGnuplot();
jg.plotx = "$header$\n plot for [i=1:$size(1)$] '-' title info2(1,i).' plotx' w lp ls i\n $data(1,2d)$";
jg.execute(plot1, jg.plotx);
//way2: through a sub class extending JGunplot
class JGnuplot2 extends JGnuplot {
String myplot, rawcode;//No need to declare public/protected/private for these fields.
public void initialize() {
String sFLoad2 = "jgnuplot2.xml";
//U.copyFileFromClassPath(this, sFLoad2, sFLoad2, false);//this also works in a jar file
U.loadFromXML(this, sFLoad2, false);
}
}
JGnuplot2 jg2 = new JGnuplot2();
jg2.execute(plot1, jg2.myplot);
jg2.execute(new Plot(null), jg2.rawcode);
}
public static void demo() {
JGnuplotDemo jgd = new JGnuplotDemo();
jgd.simple();
//jgd.compile();
//jgd.execute();
//jgd.terminals();
//jgd.plotx();
}
}
|
package com.squareup.spoon.sample.tests;
import android.test.ActivityInstrumentationTestCase2;
import com.squareup.spoon.Screenshot;
import com.squareup.spoon.sample.LoginActivity;
public class FailTest extends ActivityInstrumentationTestCase2<LoginActivity> {
public FailTest() {
super(LoginActivity.class);
}
public void testThisIsAVeryLongNameJustBecauseIWantToSeeThePageWordWrapAndAlwaysBeFailingForFun() {
Screenshot.snap(getActivity(), "initial_state");
fail("Explicitly testing Stack Traces!");
}
}
|
package hu.advancedweb.scott.instrumentation;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import hu.advancedweb.scott.instrumentation.transformation.ScottClassTransformer;
public class ScottAgent {
private ScottAgent() {
// Intended to be used as an agent and not to be instantiated directly.
}
public static void premain(String agentArgument, Instrumentation instrumentation) {
instrumentation.addTransformer(new ClassFileTransformer() {
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
if (loader == null) {
/*
* Leave the class alone, if it is being loaded by the Bootstrap classloader,
* as we don't want to do anything with JDK libs. See Issue #22.
*/
return classfileBuffer;
} else {
try {
return new ScottClassTransformer().transform(classfileBuffer, ScottConfigurer.getConfiguration());
} catch (Exception e) {
System.err.println("Scott: test instrumentation failed for " + className + "!");
e.printStackTrace();
throw e;
}
}
}
});
}
}
|
package com.smartdevicelink.SdlConnection;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.CopyOnWriteArrayList;
import android.util.Log;
import com.smartdevicelink.exception.SdlException;
import com.smartdevicelink.protocol.AbstractProtocol;
import com.smartdevicelink.protocol.IProtocolListener;
import com.smartdevicelink.protocol.ProtocolMessage;
import com.smartdevicelink.protocol.WiProProtocol;
import com.smartdevicelink.protocol.enums.SessionType;
import com.smartdevicelink.proxy.RPCRequest;
import com.smartdevicelink.streaming.AbstractPacketizer;
import com.smartdevicelink.streaming.IStreamListener;
import com.smartdevicelink.streaming.StreamPacketizer;
import com.smartdevicelink.streaming.StreamRPCPacketizer;
import com.smartdevicelink.transport.*;
public class SdlConnection implements IProtocolListener, ITransportListener, IStreamListener {
SdlTransport _transport = null;
AbstractProtocol _protocol = null;
ISdlConnectionListener _connectionListener = null;
AbstractPacketizer mPacketizer = null;
// Thread safety locks
Object TRANSPORT_REFERENCE_LOCK = new Object();
Object PROTOCOL_REFERENCE_LOCK = new Object();
private Object SESSION_LOCK = new Object();
private CopyOnWriteArrayList<SdlSession> listenerList = new CopyOnWriteArrayList<SdlSession>();
/**
* Constructor.
*
* @param listener Sdl connection listener.
* @param transportConfig Transport configuration for this connection.
*/
public SdlConnection(BaseTransportConfig transportConfig) {
_connectionListener = new InternalMsgDispatcher();
// Initialize the transport
synchronized(TRANSPORT_REFERENCE_LOCK) {
// Ensure transport is null
if (_transport != null) {
if (_transport.getIsConnected()) {
_transport.disconnect();
}
_transport = null;
}
if (transportConfig.getTransportType() == TransportType.BLUETOOTH)
{
BTTransportConfig myConfig = (BTTransportConfig) transportConfig;
_transport = new BTTransport(this, myConfig.getKeepSocketActive());
}
else if (transportConfig.getTransportType() == TransportType.TCP)
{
_transport = new TCPTransport((TCPTransportConfig) transportConfig, this);
} else if (transportConfig.getTransportType() == TransportType.USB) {
_transport = new USBTransport((USBTransportConfig) transportConfig, this);
}
}
// Initialize the protocol
synchronized(PROTOCOL_REFERENCE_LOCK) {
// Ensure protocol is null
if (_protocol != null) {
_protocol = null;
}
_protocol = new WiProProtocol(this);
}
}
public AbstractProtocol getWiProProtocol(){
return _protocol;
}
private void closeConnection(boolean willRecycle, byte rpcSessionID) {
synchronized(PROTOCOL_REFERENCE_LOCK) {
if (_protocol != null) {
// If transport is still connected, sent EndProtocolSessionMessage
if (_transport != null && _transport.getIsConnected()) {
_protocol.EndProtocolSession(SessionType.RPC, rpcSessionID);
}
if (willRecycle) {
_protocol = null;
}
} // end-if
}
synchronized (TRANSPORT_REFERENCE_LOCK) {
if (willRecycle) {
if (_transport != null) {
_transport.disconnect();
}
_transport = null;
}
}
}
public void startTransport() throws SdlException {
_transport.openConnection();
}
public Boolean getIsConnected() {
// If _transport is null, then it can't be connected
if (_transport == null) {
return false;
}
return _transport.getIsConnected();
}
public String getBroadcastComment() {
if (_transport == null) {
return "";
}
return _transport.getBroadcastComment();
}
public void sendMessage(ProtocolMessage msg) {
if(_protocol != null)
_protocol.SendMessage(msg);
}
void startHandShake() {
synchronized(PROTOCOL_REFERENCE_LOCK){
if(_protocol != null){
_protocol.StartProtocolSession(SessionType.RPC);
}
}
}
@Override
public void onTransportBytesReceived(byte[] receivedBytes,
int receivedBytesLength) {
// Send bytes to protocol to be interpreted
synchronized(PROTOCOL_REFERENCE_LOCK) {
if (_protocol != null) {
_protocol.HandleReceivedBytes(receivedBytes, receivedBytesLength);
}
}
}
@Override
public void onTransportConnected() {
synchronized(PROTOCOL_REFERENCE_LOCK){
if(_protocol != null){
for (SdlSession s : listenerList) {
if (s.getSessionId() == 0) {
startHandShake();
}
}
}
}
}
@Override
public void onTransportDisconnected(String info) {
// Pass directly to connection listener
_connectionListener.onTransportDisconnected(info);
}
@Override
public void onTransportError(String info, Exception e) {
// Pass directly to connection listener
_connectionListener.onTransportError(info, e);
}
@Override
public void onProtocolMessageBytesToSend(byte[] msgBytes, int offset,
int length) {
// Protocol has packaged bytes to send, pass to transport for transmission
synchronized(TRANSPORT_REFERENCE_LOCK) {
if (_transport != null) {
_transport.sendBytes(msgBytes, offset, length);
}
}
}
@Override
public void onProtocolMessageReceived(ProtocolMessage msg) {
_connectionListener.onProtocolMessageReceived(msg);
}
@Override
public void onProtocolSessionStarted(SessionType sessionType,
byte sessionID, byte version, String correlationID) {
_connectionListener.onProtocolSessionStarted(sessionType, sessionID, version, correlationID);
}
@Override
public void onProtocolSessionNACKed(SessionType sessionType,
byte sessionID, byte version, String correlationID) {
_connectionListener.onProtocolSessionNACKed(sessionType, sessionID, version, correlationID);
}
@Override
public void onProtocolSessionEnded(SessionType sessionType, byte sessionID,
String correlationID) {
_connectionListener.onProtocolSessionEnded(sessionType, sessionID, correlationID);
}
@Override
public void onProtocolError(String info, Exception e) {
_connectionListener.onProtocolError(info, e);
}
/**
* Gets type of transport currently used by this connection.
*
* @return One of TransportType enumeration values.
*
* @see TransportType
*/
public TransportType getCurrentTransportType() {
return _transport.getTransportType();
}
public void startStream(InputStream is, SessionType sType, byte rpcSessionID) {
try {
mPacketizer = new StreamPacketizer(this, is, sType, rpcSessionID);
mPacketizer.start();
} catch (Exception e) {
Log.e("SdlConnection", "Unable to start streaming:" + e.toString());
}
}
public OutputStream startStream(SessionType sType, byte rpcSessionID) {
try {
OutputStream os = new PipedOutputStream();
InputStream is = new PipedInputStream((PipedOutputStream) os);
mPacketizer = new StreamPacketizer(this, is, sType, rpcSessionID);
mPacketizer.start();
return os;
} catch (Exception e) {
Log.e("SdlConnection", "Unable to start streaming:" + e.toString());
}
return null;
}
public void startRPCStream(InputStream is, RPCRequest request, SessionType sType, byte rpcSessionID, byte wiproVersion) {
try {
mPacketizer = new StreamRPCPacketizer(this, is, request, sType, rpcSessionID, wiproVersion);
mPacketizer.start();
} catch (Exception e) {
Log.e("SdlConnection", "Unable to start streaming:" + e.toString());
}
}
public OutputStream startRPCStream(RPCRequest request, SessionType sType, byte rpcSessionID, byte wiproVersion) {
try {
OutputStream os = new PipedOutputStream();
InputStream is = new PipedInputStream((PipedOutputStream) os);
mPacketizer = new StreamRPCPacketizer(this, is, request, sType, rpcSessionID, wiproVersion);
mPacketizer.start();
return os;
} catch (Exception e) {
Log.e("SdlConnection", "Unable to start streaming:" + e.toString());
}
return null;
}
public void stopStream()
{
if (mPacketizer != null)
{
mPacketizer.stop();
}
}
@Override
public void sendStreamPacket(ProtocolMessage pm) {
sendMessage(pm);
}
public void startService (SessionType sessionType, byte sessionID) {
synchronized(PROTOCOL_REFERENCE_LOCK){
if(_protocol != null){
_protocol.StartProtocolService(sessionType, sessionID);
}
}
}
public void endService (SessionType sessionType, byte sessionID) {
synchronized(PROTOCOL_REFERENCE_LOCK){
if(_protocol != null){
_protocol.EndProtocolSession(sessionType, sessionID);
}
}
}
void registerSession(SdlSession registerListener) throws SdlException {
synchronized (SESSION_LOCK) {
if (!listenerList.contains(registerListener)) {
listenerList.add(registerListener); //TODO: check if we need to sort the list.
}
}
if (!this.getIsConnected()) {
this.startTransport();
} else {
this.startHandShake();
}
}
public void sendHeartbeat(SdlSession mySession) {
if(_protocol != null && mySession != null)
_protocol.SendHeartBeat(mySession.getSessionId());
}
public void unregisterSession(SdlSession registerListener) {
synchronized (SESSION_LOCK) {
listenerList.remove(registerListener);
closeConnection(listenerList.size() == 0, registerListener.getSessionId());
}
}
private SdlSession findSessionById(byte id) {
for (SdlSession listener : listenerList) {
if (listener.getSessionId() == id) {
return listener;
}
}
return null;
}
private class InternalMsgDispatcher implements ISdlConnectionListener {
@Override
public void onTransportDisconnected(String info) {
for (SdlSession session : listenerList) {
session.onTransportDisconnected(info);
}
}
@Override
public void onTransportError(String info, Exception e) {
for (SdlSession session : listenerList) {
session.onTransportError(info, e);
}
}
@Override
public void onProtocolMessageReceived(ProtocolMessage msg) {
SdlSession session = findSessionById(msg.getSessionID());
if (session != null) {
session.onProtocolMessageReceived(msg);
}
}
@Override
public void onProtocolSessionStarted(SessionType sessionType,
byte sessionID, byte version, String correlationID) {
for (SdlSession session : listenerList) {
if (session.getSessionId() == 0 || sessionType == SessionType.NAV) {
session.onProtocolSessionStarted(sessionType, sessionID, version, correlationID);
break; //FIXME: need changes on SDL side, as the sessionID is devided by SDL.
}
}
}
@Override
public void onProtocolSessionEnded(SessionType sessionType,
byte sessionID, String correlationID) {
SdlSession session = findSessionById(sessionID);
if (session != null) {
session.onProtocolSessionEnded(sessionType, sessionID, correlationID);
}
}
@Override
public void onProtocolError(String info, Exception e) {
for (SdlSession session : listenerList) {
session.onProtocolError(info, e);
}
}
@Override
public void onProtocolSessionNACKed(SessionType sessionType,
byte sessionID, byte version, String correlationID) {
for (SdlSession session : listenerList) {
session.onProtocolSessionNACKed(sessionType, sessionID, version, correlationID);
}
}
@Override
public void onHeartbeatTimedOut(byte sessionID) {
for (SdlSession session : listenerList) {
session.onHeartbeatTimedOut(sessionID);
}
}
}
public int getRegisterCount() {
return listenerList.size();
}
@Override
public void onProtocolHeartbeatACK(SessionType sessionType, byte sessionID) {
SdlSession mySession = findSessionById(sessionID);
if (mySession == null) return;
if (mySession._heartbeatMonitor != null) {
mySession._heartbeatMonitor.heartbeatACKReceived();
}
}
@Override
public void onResetHeartbeat(SessionType sessionType, byte sessionID){
SdlSession mySession = findSessionById(sessionID);
if (mySession == null) return;
if (mySession._heartbeatMonitor != null) {
mySession._heartbeatMonitor.notifyTransportActivity();
}
}
}
|
package com.krillsson.sysapi.resources;
import com.krillsson.sysapi.provider.InfoProvider;
import io.dropwizard.auth.Auth;
import com.krillsson.sysapi.UserConfiguration;
import com.krillsson.sysapi.auth.BasicAuthorizer;
import com.krillsson.sysapi.domain.network.NetworkInfo;
import com.krillsson.sysapi.domain.network.NetworkInterfaceConfig;
import com.krillsson.sysapi.domain.network.NetworkInterfaceSpeed;
import com.krillsson.sysapi.sigar.NetworkSigar;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("networks")
@Produces(MediaType.APPLICATION_JSON)
public class NetworkResource extends Resource {
private InfoProvider provider;
public NetworkResource(InfoProvider provider) {
this.provider = provider;
}
@GET
@Override
@RolesAllowed(BasicAuthorizer.AUTHENTICATED_ROLE)
public NetworkInfo getRoot(@Auth UserConfiguration user) {
return provider.networkInfo();
}
@Path("{id}")
@GET
@RolesAllowed(BasicAuthorizer.AUTHENTICATED_ROLE)
public NetworkInterfaceConfig getConfigById(@Auth UserConfiguration user, @PathParam("name") String name) {
try {
return provider.getConfigById(name);
} catch (IllegalArgumentException e) {
throw buildWebException(Response.Status.NOT_FOUND, e.getMessage());
}
}
@Path("{id}/speed")
@GET
@RolesAllowed(BasicAuthorizer.AUTHENTICATED_ROLE)
public NetworkInterfaceSpeed getNetworkInterfaceSpeedById(@Auth UserConfiguration user, @PathParam("id") String id) {
try {
return provider.networkSpeedById(id);
} catch (IllegalArgumentException e) {
throw buildWebException(Response.Status.NOT_FOUND, e.getMessage());
}
}
}
|
package io.spine.server.entity;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Message;
import com.google.protobuf.Message.Builder;
import io.spine.annotation.Internal;
import io.spine.core.EventEnvelope;
import io.spine.core.Version;
import io.spine.server.event.EventDispatch;
import io.spine.server.model.Nothing;
import io.spine.validate.ValidatingBuilder;
/**
* A transaction that supports event {@linkplain EventPlayer playing}.
*
* @param <I>
* the type of entity IDs
* @param <E>
* the type of entity
* @param <S>
* the type of entity state
* @param <B>
* the type of a {@code ValidatingBuilder} for the entity state
*/
@Internal
public abstract class EventPlayingTransaction<I,
E extends TransactionalEntity<I, S, B>,
S extends Message,
B extends ValidatingBuilder<S, ? extends Builder>>
extends Transaction<I, E, S, B> {
protected EventPlayingTransaction(E entity) {
super(entity);
}
protected EventPlayingTransaction(E entity, S state, Version version) {
super(entity, state, version);
}
/**
* Applies the given event to the entity in transaction.
*/
@VisibleForTesting
public void play(EventEnvelope event) {
VersionIncrement increment = createVersionIncrement(event);
Phase<I, Nothing> phase = new EventDispatchingPhase<>(
new EventDispatch<>(this::dispatch, getEntity(), event),
increment
);
propagate(phase);
}
private Nothing dispatch(E entity, EventEnvelope event) {
doDispatch(entity, event);
return Nothing.getDefaultInstance();
}
/**
* Dispatches the event message and its context to the given entity.
*
* <p>This operation is always performed in scope of an active transaction.
*
* @param entity
* the entity to which the envelope is dispatched
* @param event
* the event to dispatch
*/
protected abstract void doDispatch(E entity, EventEnvelope event);
/**
* Creates a version increment for the entity based on the currently processed event.
*
* @param event
* the currently processed event
* @return the {@code VersionIncrement} to apply to the entity in transaction
*/
protected abstract VersionIncrement createVersionIncrement(EventEnvelope event);
}
|
package io.spine.server.event.enrich;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMultimap;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import io.spine.Resources;
import io.spine.option.OptionsProto;
import io.spine.type.KnownTypes;
import io.spine.type.TypeName;
import io.spine.type.TypeUrl;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.google.common.collect.Sets.newHashSet;
import static io.spine.io.PropertyFiles.loadAllProperties;
import static io.spine.util.Preconditions2.checkNotEmptyOrBlank;
import static java.util.stream.Collectors.toList;
/**
* Loads enrichment information from resource files named
* {@link Resources#ENRICHMENTS enrichments.properties}.
*/
final class EnrichmentFileSet {
private static final char PROTO_PACKAGE_SEPARATOR = '.';
private static final Pattern pipeSeparatorPattern = Pattern.compile("\\|");
private static final String PACKAGE_WILDCARD_INDICATOR = ".*";
/** A separator between event types in the `.properties` file. */
private static final String EVENT_TYPE_SEPARATOR = ",";
private static final Splitter eventTypeSplitter = Splitter.on(EVENT_TYPE_SEPARATOR);
private final Iterable<Properties> properties;
private final ImmutableMultimap.Builder<String, String> builder;
/**
* Loads the enrichment map from all resource files.
*/
static ImmutableMultimap<String, String> loadFromResources() {
Set<Properties> files = loadAllProperties(Resources.ENRICHMENTS);
EnrichmentFileSet builder = new EnrichmentFileSet(files);
ImmutableMultimap<String, String> result = builder.build();
return result;
}
private EnrichmentFileSet(Iterable<Properties> properties) {
this.properties = properties;
this.builder = ImmutableMultimap.builder();
}
private ImmutableMultimap<String, String> build() {
for (Properties props : this.properties) {
parse(props);
}
return builder.build();
}
private void parse(Properties props) {
Set<String> enrichmentTypes = props.stringPropertyNames();
for (String enrichmentType : enrichmentTypes) {
String eventTypesStr = props.getProperty(enrichmentType);
Iterable<String> eventTypes = eventTypeSplitter.split(eventTypesStr);
put(enrichmentType, eventTypes);
}
}
private void put(String enrichmentType, Iterable<String> eventQualifiers) {
for (String eventQualifier : eventQualifiers) {
if (isPackage(eventQualifier)) {
putAllTypesFromPackage(enrichmentType, eventQualifier);
} else {
builder.put(enrichmentType, eventQualifier);
}
}
}
/**
* Puts all the events from the given package into the map to match the
* given enrichment type.
*
* @param enrichmentType type of the enrichment for the given events
* @param eventsPackage package qualifier representing the protobuf package containing
* the event to enrich
*/
private void putAllTypesFromPackage(String enrichmentType, String eventsPackage) {
int lastSignificantCharPos = eventsPackage.length() -
PACKAGE_WILDCARD_INDICATOR.length();
String packageName = eventsPackage.substring(0, lastSignificantCharPos);
Set<String> boundFields = getBoundFields(enrichmentType);
Collection<TypeUrl> eventTypes = KnownTypes.instance()
.getAllFromPackage(packageName);
for (TypeUrl type : eventTypes) {
if (hasOneOfTargetFields(type.toName(), boundFields)) {
String typeQualifier = type.getTypeName();
builder.put(enrichmentType, typeQualifier);
}
}
}
private static Set<String> getBoundFields(String enrichmentType) {
Descriptor enrichmentDescriptor = TypeName.of(enrichmentType)
.getMessageDescriptor();
Set<String> result = newHashSet();
for (FieldDescriptor field : enrichmentDescriptor.getFields()) {
String extension = field.getOptions()
.getExtension(OptionsProto.by);
Collection<String> fieldNames = parseFieldNames(extension);
result.addAll(fieldNames);
}
return result;
}
private static Collection<String> parseFieldNames(String qualifiers) {
Collection<String> result =
pipeSeparatorPattern.splitAsStream(qualifiers)
.map(String::trim)
.filter(fieldName -> !fieldName.isEmpty())
.map(EnrichmentFileSet::getSimpleFieldName)
.collect(toList());
return result;
}
@SuppressWarnings("ConstantConditions")
private static String getSimpleFieldName(String qualifier) {
int startIndex = qualifier.lastIndexOf(PROTO_PACKAGE_SEPARATOR) + 1;
startIndex = startIndex > 0 // 0 is an invalid value, see line above
? startIndex
: 0;
String fieldName = qualifier.substring(startIndex);
return fieldName;
}
private static
boolean hasOneOfTargetFields(TypeName eventType, Collection<String> targetFields) {
Descriptor eventDescriptor = eventType.getMessageDescriptor();
List<FieldDescriptor> fields = eventDescriptor.getFields();
Set<String> fieldNames =
fields.stream()
.map(FieldDescriptor::getName)
.collect(Collectors.toSet());
Optional<String> found =
targetFields.stream()
.filter(fieldNames::contains)
.findAny();
return found.isPresent();
}
/**
* Returns {@code true} if the given qualifier is a package according to the contract
* of {@code "enrichment_for") option notation.
*/
private static boolean isPackage(String qualifier) {
checkNotEmptyOrBlank(qualifier);
int indexOfWildcardChar = qualifier.indexOf(PACKAGE_WILDCARD_INDICATOR);
int qualifierLength = qualifier.length();
boolean result =
indexOfWildcardChar == (qualifierLength - PACKAGE_WILDCARD_INDICATOR.length());
return result;
}
}
|
package io.spine.server.integration;
import com.google.protobuf.Message;
import io.spine.base.Error;
import io.spine.core.Ack;
import io.spine.core.BoundedContextName;
import io.spine.core.Event;
import io.spine.core.Rejection;
import io.spine.grpc.MemoizingObserver;
import io.spine.grpc.StreamObservers;
import io.spine.protobuf.AnyPacker;
import io.spine.server.BoundedContext;
import io.spine.server.event.EventBus;
import io.spine.server.integration.given.IntegrationBusTestEnv.ContextAwareProjectDetails;
import io.spine.server.integration.given.IntegrationBusTestEnv.ExternalMismatchSubscriber;
import io.spine.server.integration.given.IntegrationBusTestEnv.ProjectCountAggregate;
import io.spine.server.integration.given.IntegrationBusTestEnv.ProjectDetails;
import io.spine.server.integration.given.IntegrationBusTestEnv.ProjectEventsSubscriber;
import io.spine.server.integration.given.IntegrationBusTestEnv.ProjectRejectionsExtSubscriber;
import io.spine.server.integration.given.IntegrationBusTestEnv.ProjectStartedExtSubscriber;
import io.spine.server.integration.given.IntegrationBusTestEnv.ProjectWizard;
import io.spine.server.rejection.RejectionBus;
import io.spine.server.rejection.RejectionSubscriber;
import io.spine.server.transport.memory.InMemoryTransportFactory;
import io.spine.validate.Validate;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static io.spine.server.integration.ExternalMessageValidationError.UNSUPPORTED_EXTERNAL_MESSAGE;
import static io.spine.server.integration.given.IntegrationBusTestEnv.cannotStartArchivedProject;
import static io.spine.server.integration.given.IntegrationBusTestEnv.contextWithContextAwareEntitySubscriber;
import static io.spine.server.integration.given.IntegrationBusTestEnv.contextWithExtEntitySubscribers;
import static io.spine.server.integration.given.IntegrationBusTestEnv.contextWithExternalSubscribers;
import static io.spine.server.integration.given.IntegrationBusTestEnv.contextWithProjectCreatedNeeds;
import static io.spine.server.integration.given.IntegrationBusTestEnv.contextWithProjectStartedNeeds;
import static io.spine.server.integration.given.IntegrationBusTestEnv.contextWithTransport;
import static io.spine.server.integration.given.IntegrationBusTestEnv.projectCreated;
import static io.spine.server.integration.given.IntegrationBusTestEnv.projectStarted;
import static io.spine.test.Verify.assertContains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Alex Tymchenko
*/
@DisplayName("IntegrationBus should")
class IntegrationBusTest {
@BeforeEach
void setUp() {
ProjectDetails.clear();
ProjectWizard.clear();
ProjectCountAggregate.clear();
ContextAwareProjectDetails.clear();
ProjectEventsSubscriber.clear();
ProjectStartedExtSubscriber.clear();
ProjectRejectionsExtSubscriber.clear();
}
@Nested
@DisplayName("dispatch events from one BC")
class DispatchEvents {
@Test
@DisplayName("to entities with external subscribers of another BC")
void toEntitiesOfBc() {
final InMemoryTransportFactory transportFactory =
InMemoryTransportFactory.newInstance();
final BoundedContext sourceContext = contextWithTransport(transportFactory);
contextWithExtEntitySubscribers(transportFactory);
assertNull(ProjectDetails.getExternalEvent());
assertNull(ProjectWizard.getExternalEvent());
assertNull(ProjectCountAggregate.getExternalEvent());
final Event event = projectCreated();
sourceContext.getEventBus()
.post(event);
final Message expectedMessage = AnyPacker.unpack(event.getMessage());
assertEquals(expectedMessage, ProjectDetails.getExternalEvent());
assertEquals(expectedMessage, ProjectWizard.getExternalEvent());
assertEquals(expectedMessage, ProjectCountAggregate.getExternalEvent());
}
@Test
@DisplayName("to external subscribers of another BC")
void toBcSubscribers() {
final InMemoryTransportFactory transportFactory =
InMemoryTransportFactory.newInstance();
final BoundedContext sourceContext = contextWithTransport(transportFactory);
contextWithExternalSubscribers(transportFactory);
assertNull(ProjectEventsSubscriber.getExternalEvent());
final Event event = projectCreated();
sourceContext.getEventBus()
.post(event);
assertEquals(AnyPacker.unpack(event.getMessage()),
ProjectEventsSubscriber.getExternalEvent());
}
@Test
@DisplayName("to entities with external subscribers of multiple BCs")
void toEntitiesOfMultipleBcs() {
final InMemoryTransportFactory transportFactory =
InMemoryTransportFactory.newInstance();
final Set<BoundedContextName> destinationNames = newHashSet();
final BoundedContext sourceContext = contextWithTransport(transportFactory);
for (int i = 0; i < 42; i++) {
final BoundedContext destinationCtx =
contextWithContextAwareEntitySubscriber(transportFactory);
final BoundedContextName name = destinationCtx.getName();
destinationNames.add(name);
}
assertTrue(ContextAwareProjectDetails.getExternalContexts()
.isEmpty());
final Event event = projectCreated();
sourceContext.getEventBus()
.post(event);
assertEquals(destinationNames.size(),
ContextAwareProjectDetails.getExternalContexts()
.size());
assertEquals(destinationNames.size(),
ContextAwareProjectDetails.getExternalEvents()
.size());
}
@SuppressWarnings("unused") // Variables declared for readability.
@Test
@DisplayName("to two BCs with different needs")
void toTwoBcSubscribers() {
final InMemoryTransportFactory transportFactory =
InMemoryTransportFactory.newInstance();
final BoundedContext sourceContext = contextWithTransport(transportFactory);
final BoundedContext destA = contextWithProjectCreatedNeeds(transportFactory);
final BoundedContext destB = contextWithProjectStartedNeeds(transportFactory);
assertNull(ProjectStartedExtSubscriber.getExternalEvent());
assertNull(ProjectEventsSubscriber.getExternalEvent());
final EventBus sourceEventBus = sourceContext.getEventBus();
final Event eventA = projectCreated();
sourceEventBus.post(eventA);
final Event eventB = projectStarted();
sourceEventBus.post(eventB);
assertEquals(AnyPacker.unpack(eventA.getMessage()),
ProjectEventsSubscriber.getExternalEvent());
assertEquals(AnyPacker.unpack(eventB.getMessage()),
ProjectStartedExtSubscriber.getExternalEvent());
}
}
@Test
@DisplayName("dispatch rejections from one BC to external subscribers of another BC")
void dispatchRejectionsToOtherBc() {
final InMemoryTransportFactory transportFactory = InMemoryTransportFactory.newInstance();
final BoundedContext sourceContext = contextWithTransport(transportFactory);
contextWithExternalSubscribers(transportFactory);
assertNull(ProjectRejectionsExtSubscriber.getExternalRejection());
assertNull(ProjectCountAggregate.getExternalRejection());
assertNull(ProjectWizard.getExternalRejection());
final Rejection rejection = cannotStartArchivedProject();
sourceContext.getRejectionBus()
.post(rejection);
final Message rejectionMessage = AnyPacker.unpack(rejection.getMessage());
assertEquals(rejectionMessage, ProjectRejectionsExtSubscriber.getExternalRejection());
assertEquals(rejectionMessage, ProjectCountAggregate.getExternalRejection());
assertEquals(rejectionMessage, ProjectWizard.getExternalRejection());
}
@Nested
@DisplayName("avoid dispatching events from one BC")
class AvoidDispatching {
@Test
@DisplayName("to domestic entity subscribers of another BC")
void toDomesticEntitySubscribers() {
final InMemoryTransportFactory transportFactory =
InMemoryTransportFactory.newInstance();
final BoundedContext sourceContext = contextWithTransport(transportFactory);
final BoundedContext destContext = contextWithExtEntitySubscribers(transportFactory);
assertNull(ProjectDetails.getDomesticEvent());
final Event event = projectStarted();
sourceContext.getEventBus()
.post(event);
assertNotEquals(AnyPacker.unpack(event.getMessage()),
ProjectDetails.getDomesticEvent());
assertNull(ProjectDetails.getDomesticEvent());
destContext.getEventBus()
.post(event);
assertEquals(AnyPacker.unpack(event.getMessage()), ProjectDetails.getDomesticEvent());
}
@Test
@DisplayName("to domestic standalone subscribers of another BC")
void toDomesticStandaloneSubscribers() {
final InMemoryTransportFactory transportFactory =
InMemoryTransportFactory.newInstance();
final BoundedContext sourceContext = contextWithTransport(transportFactory);
final BoundedContext destContext = contextWithExternalSubscribers(transportFactory);
assertNull(ProjectEventsSubscriber.getDomesticEvent());
final Event event = projectStarted();
sourceContext.getEventBus()
.post(event);
assertNotEquals(AnyPacker.unpack(event.getMessage()),
ProjectEventsSubscriber.getDomesticEvent());
assertNull(ProjectEventsSubscriber.getDomesticEvent());
destContext.getEventBus()
.post(event);
assertEquals(AnyPacker.unpack(event.getMessage()),
ProjectEventsSubscriber.getDomesticEvent());
}
}
@Test
@DisplayName("update local subscriptions upon repeated RequestedMessageTypes")
void updateLocalSubscriptions() {
final InMemoryTransportFactory transportFactory = InMemoryTransportFactory.newInstance();
final BoundedContext sourceContext = contextWithTransport(transportFactory);
final BoundedContext destinationCtx = contextWithTransport(transportFactory);
// Prepare two external subscribers for the different events in the the `destinationCtx`.
final ProjectEventsSubscriber projectCreatedSubscriber
= new ProjectEventsSubscriber();
final ProjectStartedExtSubscriber projectStartedSubscriber
= new ProjectStartedExtSubscriber();
// Before anything happens, there were no events received by those.
assertNull(ProjectEventsSubscriber.getExternalEvent());
assertNull(ProjectStartedExtSubscriber.getExternalEvent());
// Both events are prepared along with the `EventBus` of the source bounded context.
final EventBus sourceEventBus = sourceContext.getEventBus();
final Event eventA = projectCreated();
final Event eventB = projectStarted();
// Both events are emitted, `ProjectCreated` subscriber only is present.
destinationCtx.getIntegrationBus()
.register(projectCreatedSubscriber);
sourceEventBus.post(eventA);
sourceEventBus.post(eventB);
// Only `ProjectCreated` should have been dispatched.
assertEquals(AnyPacker.unpack(eventA.getMessage()),
ProjectEventsSubscriber.getExternalEvent());
assertNull(ProjectStartedExtSubscriber.getExternalEvent());
// Clear before the next round starts.
ProjectStartedExtSubscriber.clear();
ProjectEventsSubscriber.clear();
// Both events are emitted, No external subscribers at all.
destinationCtx.getIntegrationBus()
.unregister(projectCreatedSubscriber);
sourceEventBus.post(eventA);
sourceEventBus.post(eventB);
// No events should have been dispatched.
assertNull(ProjectEventsSubscriber.getExternalEvent());
assertNull(ProjectStartedExtSubscriber.getExternalEvent());
// Both events are emitted, `ProjectStarted` subscriber only is present
destinationCtx.getIntegrationBus()
.register(projectStartedSubscriber);
sourceEventBus.post(eventA);
sourceEventBus.post(eventB);
// This time `ProjectStarted` event should only have been dispatched.
assertNull(ProjectEventsSubscriber.getExternalEvent());
assertEquals(AnyPacker.unpack(eventB.getMessage()),
ProjectStartedExtSubscriber.getExternalEvent());
}
@Test
@DisplayName("throw exception on mismatch of external attribute during dispatching")
void throwOnExtAttributeMismatch() {
final InMemoryTransportFactory transportFactory = InMemoryTransportFactory.newInstance();
final BoundedContext sourceContext = contextWithTransport(transportFactory);
final RejectionSubscriber rejectionSubscriber = new ExternalMismatchSubscriber();
sourceContext.getRejectionBus()
.register(rejectionSubscriber);
sourceContext.getIntegrationBus()
.register(rejectionSubscriber);
final Rejection rejection = cannotStartArchivedProject();
try {
sourceContext.getRejectionBus()
.post(rejection);
fail("An exception is expected.");
} catch (Exception e) {
final String exceptionMsg = e.getMessage();
assertContains("external", exceptionMsg);
}
}
@Nested
@DisplayName("not dispatch to domestic subscribers if they requested external")
class NotDispatchToDomestic {
@Test
@DisplayName("events")
void eventsIfNeedExternal() {
final InMemoryTransportFactory transportFactory =
InMemoryTransportFactory.newInstance();
final BoundedContext context = contextWithExtEntitySubscribers(transportFactory);
final ProjectEventsSubscriber eventSubscriber = new ProjectEventsSubscriber();
final EventBus eventBus = context.getEventBus();
eventBus.register(eventSubscriber);
assertNull(ProjectEventsSubscriber.getExternalEvent());
assertNull(ProjectDetails.getExternalEvent());
assertNull(ProjectWizard.getExternalEvent());
assertNull(ProjectCountAggregate.getExternalEvent());
final Event projectCreated = projectCreated();
eventBus.post(projectCreated);
assertNull(ProjectEventsSubscriber.getExternalEvent());
assertNull(ProjectDetails.getExternalEvent());
assertNull(ProjectWizard.getExternalEvent());
assertNull(ProjectCountAggregate.getExternalEvent());
}
@Test
@DisplayName("rejections")
void rejectionsIfNeedExternal() {
final InMemoryTransportFactory transportFactory =
InMemoryTransportFactory.newInstance();
final BoundedContext sourceContext = contextWithExtEntitySubscribers(transportFactory);
final ProjectRejectionsExtSubscriber standaloneSubscriber =
new ProjectRejectionsExtSubscriber();
final RejectionBus rejectionBus = sourceContext.getRejectionBus();
rejectionBus.register(standaloneSubscriber);
assertNull(ProjectRejectionsExtSubscriber.getExternalRejection());
assertNull(ProjectWizard.getExternalRejection());
assertNull(ProjectCountAggregate.getExternalRejection());
final Rejection rejection = cannotStartArchivedProject();
rejectionBus.post(rejection);
assertNull(ProjectRejectionsExtSubscriber.getExternalRejection());
assertNull(ProjectWizard.getExternalRejection());
assertNull(ProjectCountAggregate.getExternalRejection());
}
}
@Test
@DisplayName("emit unsupported external message exception if message type is unknown")
void throwOnUnknownMessage() {
final InMemoryTransportFactory transportFactory = InMemoryTransportFactory.newInstance();
final BoundedContext boundedContext = contextWithTransport(transportFactory);
final Event event = projectCreated();
final BoundedContextName boundedContextName = BoundedContext.newName("External context ID");
final ExternalMessage externalMessage = ExternalMessages.of(event,
boundedContextName);
final MemoizingObserver<Ack> observer = StreamObservers.memoizingObserver();
boundedContext.getIntegrationBus()
.post(externalMessage, observer);
final Error error = observer.firstResponse()
.getStatus()
.getError();
assertFalse(Validate.isDefault(error));
assertEquals(ExternalMessageValidationError.getDescriptor()
.getFullName(),
error.getType());
assertTrue(UNSUPPORTED_EXTERNAL_MESSAGE.getNumber() == error.getCode());
}
}
|
package kcl.teamIndexZero.traffic.simulator.data;
import kcl.teamIndexZero.traffic.log.Logger;
import kcl.teamIndexZero.traffic.log.Logger_Interface;
/**
* ID class for simulation entities
*/
public class ID {
private static Logger_Interface LOG = Logger.getLoggerInstance(ID.class.getSimpleName());
private String id;
/**
* Constructor
*
* @param id ID tag to copy
* @param discriminant Discriminant to append at the end of the copied tag
*/
public ID(ID id, String discriminant) {
this.id = id.getId() + ":" + discriminant;
}
/**
* Constructor
*
* @param id ID tag to copy
* @param discriminant Discriminant to add in from of the copied tag
*/
public ID(String discriminant, ID id) {
this.id = discriminant + ":" + id.getId();
}
/**
* Constructor
*
* @param id Identification tag
*/
public ID(String id) {
this.id = id;
}
/**
* Gets the identification tag
*
* @return ID tag
*/
public String getId() {
return this.id;
}
/**
* Gets the String of the ID tag
*
* @return ID tag as a String
*/
public String toString() {
return this.id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ID id1 = (ID) o;
return id != null ? id.equals(id1.id) : id1.id == null;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
|
package com.intellij.ide.fileTemplates.impl;
import com.intellij.codeInsight.template.impl.TemplateColors;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.lexer.CompositeLexer;
import com.intellij.lexer.FlexAdapter;
import com.intellij.lexer.Lexer;
import com.intellij.lexer.MergingLexerAdapter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.undo.DocumentReference;
import com.intellij.openapi.command.undo.DocumentReferenceByDocument;
import com.intellij.openapi.command.undo.NonUndoableAction;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.EditorSettings;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.util.LexerEditorHighlighter;
import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class FileTemplateConfigurable implements Configurable {
private static final Logger LOG = Logger.getInstance("#com.intellij.ide.fileTemplates.impl.FileTemplateConfigurable");
private JPanel myMainPanel;
private FileTemplate myTemplate;
private Editor myTemplateEditor;
private JTextField myNameField;
private JTextField myExtensionField;
private JCheckBox myAdjustBox;
private JPanel myTopPanel;
private JEditorPane myDescriptionComponent;
private boolean myModified = false;
private ArrayList<ChangeListener> myChangeListeners = new ArrayList<ChangeListener>();
private VirtualFile myDefaultDescription;
@NonNls private static final String CONTENT_TYPE_HTML = "text/html";
@NonNls private static final String EMPTY_HTML = "<html></html>";
@NonNls private static final String CONTENT_TYPE_PLAIN = "text/plain";
public FileTemplate getTemplate() {
return myTemplate;
}
public void setTemplate(FileTemplate template, VirtualFile defaultDescription) {
myDefaultDescription = defaultDescription;
myTemplate = template;
reset();
myNameField.selectAll();
myExtensionField.selectAll();
}
public void setShowInternalMessage(String message) {
if (message == null) {
myTopPanel.removeAll();
myTopPanel.add(new JLabel(IdeBundle.message("label.name")),
new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
new Insets(0, 0, 0, 2), 0, 0));
myTopPanel.add(myNameField,
new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(0, 2, 0, 2), 0, 0));
myTopPanel.add(new JLabel(IdeBundle.message("label.extension")),
new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
new Insets(0, 2, 0, 2), 0, 0));
myTopPanel.add(myExtensionField,
new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(0, 2, 0, 0), 0, 0));
myExtensionField.setColumns(7);
}
else {
myTopPanel.removeAll();
myTopPanel.add(new JLabel(message),
new GridBagConstraints(0, 0, 4, 1, 1.0, 0.0, GridBagConstraints.WEST,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
myTopPanel.add(Box.createVerticalStrut(myNameField.getPreferredSize().height),
new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
}
myMainPanel.revalidate();
myTopPanel.repaint();
}
public void setShowAdjustCheckBox(boolean show) {
myAdjustBox.setEnabled(show);
}
public String getDisplayName() {
return IdeBundle.message("title.file.templates");
}
public Icon getIcon() {
return null;
}
public String getHelpTopic() {
return null;
}
public JComponent createComponent() {
myMainPanel = new JPanel(new GridBagLayout());
myTemplateEditor = createEditor();
myNameField = new JTextField();
myExtensionField = new JTextField();
final Splitter splitter = new Splitter(true, 0.66f);
myDescriptionComponent = new JEditorPane(CONTENT_TYPE_HTML, EMPTY_HTML);
myDescriptionComponent.setEditable(false);
// myDescriptionComponent.setMargin(new Insets(2, 2, 2, 2));
// myDescriptionComponent = new JLabel();
// myDescriptionComponent.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
// myDescriptionComponent.setVerticalAlignment(SwingConstants.TOP);
myAdjustBox = new JCheckBox(IdeBundle.message("checkbox.reformat.according.to.style"));
myTopPanel = new JPanel(new GridBagLayout());
JPanel secondPanel = new JPanel(new GridBagLayout());
secondPanel.add(new JLabel(IdeBundle.message("label.description")),
new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 2, 0), 0, 0));
secondPanel.add(new JScrollPane(myDescriptionComponent),
new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(2, 0, 0, 0), 0, 0));
myMainPanel.add(myTopPanel,
new GridBagConstraints(0, 0, 4, 1, 1.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 2, 0), 0, 0));
myMainPanel.add(myAdjustBox,
new GridBagConstraints(0, 1, 4, 1, 0.0, 0.0, GridBagConstraints.WEST,
GridBagConstraints.HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0));
myMainPanel.add(splitter,
new GridBagConstraints(0, 2, 4, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(2, 0, 0, 0), 0, 0));
splitter.setFirstComponent(myTemplateEditor.getComponent());
splitter.setSecondComponent(secondPanel);
setShowInternalMessage(null);
myTemplateEditor.getDocument().addDocumentListener(new DocumentAdapter() {
public void documentChanged(DocumentEvent e) {
onTextChanged();
}
});
myNameField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
onNameChanged();
}
});
myExtensionField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
onNameChanged();
}
});
myMainPanel.setPreferredSize(new Dimension(400, 300));
return myMainPanel;
}
private static Editor createEditor() {
EditorFactory editorFactory = EditorFactory.getInstance();
Document doc = editorFactory.createDocument("");
Editor editor = editorFactory.createEditor(doc);
EditorSettings editorSettings = editor.getSettings();
editorSettings.setVirtualSpace(false);
editorSettings.setLineMarkerAreaShown(false);
editorSettings.setLineNumbersShown(false);
editorSettings.setFoldingOutlineShown(false);
editorSettings.setAdditionalColumnsCount(3);
editorSettings.setAdditionalLinesCount(3);
EditorColorsScheme scheme = editor.getColorsScheme();
scheme.setColor(EditorColors.CARET_ROW_COLOR, null);
return editor;
}
private void onTextChanged() {
myModified = true;
}
public String getNameValue() {
return myNameField.getText();
}
public String getExtensionValue() {
return myExtensionField.getText();
}
private void onNameChanged() {
ChangeEvent event = new ChangeEvent(this);
for (ChangeListener changeListener : myChangeListeners) {
changeListener.stateChanged(event);
}
}
public void addChangeListener(ChangeListener listener) {
if (!myChangeListeners.contains(listener)) {
myChangeListeners.add(listener);
}
}
public void removeChangeListener(ChangeListener listener) {
myChangeListeners.remove(listener);
}
public boolean isModified() {
if (myModified) {
return true;
}
String name = (myTemplate == null) ? "" : myTemplate.getName();
String extension = (myTemplate == null) ? "" : myTemplate.getExtension();
if (!Comparing.equal(name, myNameField.getText())) {
return true;
}
if (!Comparing.equal(extension, myExtensionField.getText())) {
return true;
}
if (myTemplate != null) {
if (myTemplate.isAdjust() != myAdjustBox.isSelected()) {
return true;
}
}
return false;
}
public void apply() throws ConfigurationException {
if (myTemplate != null) {
myTemplate.setText(myTemplateEditor.getDocument().getText());
String name = myNameField.getText();
String extension = myExtensionField.getText();
int lastDotIndex = extension.lastIndexOf(".");
if (lastDotIndex >= 0) {
name += extension.substring(0, lastDotIndex + 1);
extension = extension.substring(lastDotIndex + 1);
}
if (name.length() == 0 || !isValidFilename(name + "." + extension)) {
throw new ConfigurationException(IdeBundle.message("error.invalid.template.file.name.or.extension"));
}
myTemplate.setName(name);
myTemplate.setExtension(extension);
myTemplate.setAdjust(myAdjustBox.isSelected());
}
myModified = false;
}
// TODO: needs to be generalized someday for other profiles
private static boolean isValidFilename(final String filename) {
if ( filename.contains("/") || filename.contains("\\")) {
return false;
}
final File tempFile = new File (FileUtil.getTempDirectory() + File.separator + filename);
if (!tempFile.exists ()) {
try {
if (!tempFile.createNewFile()) {
return false;
}
FileUtil.delete(tempFile);
}
catch (IOException e) {
return false;
}
}
return true;
}
public void reset() {
final String text = (myTemplate == null) ? "" : myTemplate.getText();
String name = (myTemplate == null) ? "" : myTemplate.getName();
String extension = (myTemplate == null) ? "" : myTemplate.getExtension();
String description = (myTemplate == null) ? "" : myTemplate.getDescription();
if (description == null) {
description = "";
}
if ((description.length() == 0) && (myDefaultDescription != null)) {
try {
description = VfsUtil.loadText(myDefaultDescription);
}
catch (IOException e) {
LOG.error(e);
}
}
boolean adjust = (myTemplate != null) && myTemplate.isAdjust();
setHighlighter();
myNameField.setText(name);
myExtensionField.setText(extension);
myAdjustBox.setSelected(adjust);
String desc = description.length() > 0 ? description : EMPTY_HTML;
// [myakovlev] do not delete these stupid lines! Or you get Exception!
myDescriptionComponent.setContentType(CONTENT_TYPE_PLAIN);
myDescriptionComponent.setEditable(true);
myDescriptionComponent.setText(desc);
myDescriptionComponent.setContentType(CONTENT_TYPE_HTML);
myDescriptionComponent.setText(desc);
myDescriptionComponent.setCaretPosition(0);
myDescriptionComponent.setEditable(false);
CommandProcessor.getInstance().executeCommand(null, new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
final Document document = myTemplateEditor.getDocument();
document.replaceString(0, document.getTextLength(), text);
UndoManager.getGlobalInstance().undoableActionPerformed(new NonUndoableAction() {
public DocumentReference[] getAffectedDocuments() {
return new DocumentReference[] {DocumentReferenceByDocument.createDocumentReference(document)};
}
public boolean isComplex() {
return false;
}
});
}
});
}
}, "", null);
myNameField.setEditable((myTemplate != null) && (!myTemplate.isDefault()));
myExtensionField.setEditable((myTemplate != null) && (!myTemplate.isDefault()));
myModified = false;
}
public void disposeUIResources() {
myMainPanel = null;
if (myTemplateEditor != null) {
EditorFactory.getInstance().releaseEditor(myTemplateEditor);
myTemplateEditor = null;
}
}
private void setHighlighter() {
FileType fileType;
if (myTemplate != null) {
String extension = myTemplate.getExtension();
fileType = FileTypeManager.getInstance().getFileTypeByExtension(extension);
}
else {
fileType = StdFileTypes.PLAIN_TEXT;
}
SyntaxHighlighter originalHighlighter = fileType.getHighlighter(null, null);
if (originalHighlighter == null) originalHighlighter = new PlainSyntaxHighlighter();
LexerEditorHighlighter highlighter = new LexerEditorHighlighter(new TemplateHighlighter(originalHighlighter), EditorColorsManager.getInstance().getGlobalScheme());
((EditorEx)myTemplateEditor).setHighlighter(highlighter);
((EditorEx)myTemplateEditor).repaint(0, myTemplateEditor.getDocument().getTextLength());
}
private final static TokenSet TOKENS_TO_MERGE = TokenSet.create(FileTemplateTokenType.TEXT);
private static class TemplateHighlighter extends SyntaxHighlighterBase {
private Lexer myLexer;
private SyntaxHighlighter myOriginalHighlighter;
public TemplateHighlighter(SyntaxHighlighter original) {
myOriginalHighlighter = original;
Lexer originalLexer = original.getHighlightingLexer();
Lexer templateLexer = new FlexAdapter(new FileTemplateTextLexer());
templateLexer = new MergingLexerAdapter(templateLexer, TOKENS_TO_MERGE);
myLexer = new CompositeLexer(originalLexer, templateLexer) {
protected IElementType getCompositeTokenType(IElementType type1, IElementType type2) {
if (type2 == FileTemplateTokenType.MACRO || type2 == FileTemplateTokenType.DIRECTIVE) {
return type2;
}
else {
return type1;
}
}
};
}
@NotNull
public Lexer getHighlightingLexer() {
return myLexer;
}
@NotNull
public TextAttributesKey[] getTokenHighlights(IElementType tokenType) {
if (tokenType == FileTemplateTokenType.MACRO) {
return pack(myOriginalHighlighter.getTokenHighlights(tokenType), TemplateColors.TEMPLATE_VARIABLE_ATTRIBUTES);
}
else if (tokenType == FileTemplateTokenType.DIRECTIVE) {
return pack(myOriginalHighlighter.getTokenHighlights(tokenType), TemplateColors.TEMPLATE_VARIABLE_ATTRIBUTES);
}
return myOriginalHighlighter.getTokenHighlights(tokenType);
}
}
public void focusToNameField() {
myNameField.selectAll();
myNameField.requestFocus();
}
public void focusToExtensionField() {
myExtensionField.selectAll();
myExtensionField.requestFocus();
}
}
|
package com.intellij.moduleDependencies;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataConstants;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.impl.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.peer.PeerFactory;
import com.intellij.psi.PsiElement;
import com.intellij.ui.content.Content;
import javax.swing.*;
import java.awt.*;
public class ShowModuleDependenciesAction extends AnAction{
public void actionPerformed(AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
final Project project = (Project)dataContext.getData(DataConstants.PROJECT);
if (project == null){
return;
}
ModulesDependenciesPanel panel;
final Module[] modules = (Module[])dataContext.getData(DataConstants.MODULE_CONTEXT_ARRAY);
if (modules != null){
panel = new ModulesDependenciesPanel(project, modules);
} else {
final PsiElement element = (PsiElement)dataContext.getData(DataConstants.PSI_FILE);
final Module module = element != null ? ModuleUtil.findModuleForPsiElement(element) : null;
if (module != null && ModuleManager.getInstance(project).getModules().length > 1){
MyModuleOrProjectScope dlg = new MyModuleOrProjectScope(module.getName());
dlg.show();
if (dlg.isOK()){
if (!dlg.useProjectScope()){
panel = new ModulesDependenciesPanel(project, new Module[]{module});
} else {
panel = new ModulesDependenciesPanel(project);
}
} else {
return;
}
} else {
panel = new ModulesDependenciesPanel(project);
}
}
Content content = PeerFactory.getInstance().getContentFactory().createContent(panel,
"Module Dependencies of " + project.getName(),
false);
panel.setContent(content);
DependenciesAnalyzeManager.getInstance(project).addContent(content);
}
public void update(AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
final Project project = (Project)dataContext.getData(DataConstants.PROJECT);
e.getPresentation().setEnabled(project != null);
}
private static class MyModuleOrProjectScope extends DialogWrapper{
private JRadioButton myProjectScope;
private JRadioButton myModuleScope;
protected MyModuleOrProjectScope(String moduleName) {
super(false);
setTitle("Specify Analysis Scope");
ButtonGroup group = new ButtonGroup();
myProjectScope = new JRadioButton("Inspect the whole project");
myProjectScope.setMnemonic('p');
myModuleScope = new JRadioButton("Inspect module \'" + moduleName + "\'");
myModuleScope.setMnemonic('m');
group.add(myProjectScope);
group.add(myModuleScope);
myProjectScope.setSelected(true);
init();
}
protected JComponent createCenterPanel() {
JPanel panel = new JPanel(new GridLayout(2, 1));
panel.add(myProjectScope);
panel.add(myModuleScope);
return panel;
}
public boolean useProjectScope(){
return myProjectScope.isSelected();
}
}
}
|
import java.net.*;
import java.io.*;
import java.util.*;
import org.xbill.DNS.*;
import org.xbill.DNS.utils.*;
/** @author Brian Wellington <bwelling@xbill.org> */
public class update {
Message query, response;
Resolver res;
String server = null;
Name origin, zone;
int defaultTTL;
short defaultClass = DClass.IN;
PrintStream log = null;
void
print(Object o) {
System.out.println(o);
if (log != null)
log.println(o);
}
public
update(InputStream in) throws IOException {
Vector inputs = new Vector();
Vector istreams = new Vector();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
inputs.addElement(br);
istreams.addElement(in);
while (true) {
try {
String line = null;
do {
InputStream is;
is = (InputStream) istreams.lastElement();
br = (BufferedReader)inputs.lastElement();
if (is == System.in)
System.out.print("> ");
line = Master.readExtendedLine(br);
if (line == null) {
br.close();
inputs.removeElement(br);
istreams.removeElement(is);
if (inputs.isEmpty())
return;
}
} while (line == null);
if (log != null)
log.println("> " + line);
if (line.length() == 0 || line.charAt(0) == '
continue;
/* Allows cut and paste from other update sessions */
if (line.charAt(0) == '>')
line = line.substring(1);
MyStringTokenizer st = new MyStringTokenizer(line);
if (!st.hasMoreTokens())
continue;
String operation = st.nextToken();
if (operation.equals("server")) {
server = st.nextToken();
res = new SimpleResolver(server);
}
else if (operation.equals("key")) {
String keyname = st.nextToken();
String keydata = st.nextToken();
if (res == null)
res = new SimpleResolver(server);
res.setTSIGKey(keyname, keydata);
}
else if (operation.equals("port")) {
if (res == null)
res = new SimpleResolver(server);
res.setPort(Short.parseShort(st.nextToken()));
}
else if (operation.equals("tcp")) {
if (res == null)
res = new SimpleResolver(server);
res.setTCP(true);
}
else if (operation.equals("class")) {
String s = st.nextToken();
short newClass = DClass.value(s);
if (newClass > 0)
defaultClass = newClass;
else
print("Invalid class " + newClass);
}
else if (operation.equals("ttl"))
defaultTTL = TTL.parseTTL(st.nextToken());
else if (operation.equals("origin"))
origin = new Name(st.nextToken());
else if (operation.equals("zone"))
zone = new Name(st.nextToken());
else if (operation.equals("require"))
doRequire(st);
else if (operation.equals("prohibit"))
doProhibit(st);
else if (operation.equals("add"))
doAdd(st);
else if (operation.equals("delete"))
doDelete(st);
else if (operation.equals("glue"))
doGlue(st);
else if (operation.equals("help")) {
if (st.hasMoreTokens())
help(st.nextToken());
else
help(null);
}
else if (operation.equals("echo"))
print(line.substring(4).trim());
else if (operation.equals("send")) {
if (res == null)
res = new SimpleResolver(server);
sendUpdate();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("query"))
doQuery(st);
else if (operation.equals("quit") ||
operation.equals("q"))
{
if (log != null)
log.close();
Enumeration e = inputs.elements();
while (e.hasMoreElements()) {
BufferedReader tbr;
tbr = (BufferedReader) e.nextElement();
tbr.close();
}
System.exit(0);
}
else if (operation.equals("file"))
doFile(st, inputs, istreams);
else if (operation.equals("log"))
doLog(st);
else if (operation.equals("assert")) {
if (doAssert(st) == false)
return;
}
else
print("invalid keyword: " + operation);
}
catch (NullPointerException npe) {
System.out.println("Parse error");
}
catch (InterruptedIOException iioe) {
System.out.println("Operation timed out");
}
}
}
void
sendUpdate() throws IOException {
if (query.getHeader().getCount(Section.ZONE) == 0) {
Name updzone;
if (zone != null)
updzone = zone;
else
updzone = origin;
short dclass = defaultClass;
if (updzone == null) {
Enumeration updates = query.getSection(Section.UPDATE);
if (updates == null) {
print("Invalid update");
return;
}
Record r = (Record) updates.nextElement();
updzone = new Name(r.getName(), 1);
dclass = r.getDClass();
}
Record soa = Record.newRecord(updzone, Type.SOA, dclass);
query.addRecord(soa, Section.ZONE);
}
response = res.send(query);
if (response == null)
return;
print(response);
}
/*
* <name> [ttl] [class] <type> <data>
* Ignore the class, if present.
*/
Record
parseRR(MyStringTokenizer st, short classValue, int TTLValue)
throws IOException
{
Name name = new Name(st.nextToken(), origin);
int ttl;
short type;
String s = st.nextToken();
try {
ttl = TTL.parseTTL(s);
s = st.nextToken();
}
catch (NumberFormatException e) {
ttl = TTLValue;
}
if (DClass.value(s) >= 0)
s = st.nextToken();
if ((type = Type.value(s)) < 0)
/* Close enough... */
throw new NullPointerException("Parse error");
return Record.fromString(name, type, classValue, ttl, st, origin);
}
/*
* <name> <type>
*/
Record
parseSet(MyStringTokenizer st, short classValue) throws IOException {
Name name = new Name(st.nextToken(), origin);
short type;
if ((type = Type.value(st.nextToken())) < 0)
throw new IOException("Parse error");
return Record.newRecord(name, type, classValue, 0);
}
/*
* <name>
*/
Record
parseName(MyStringTokenizer st, short classValue) throws IOException {
Name name = new Name(st.nextToken(), origin);
return Record.newRecord(name, Type.ANY, classValue, 0);
}
void
doRequire(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (qualifier.equals("-r"))
rec = parseRR(st, defaultClass, 0);
else if (qualifier.equals("-s"))
rec = parseSet(st, DClass.ANY);
else if (qualifier.equals("-n"))
rec = parseName(st, DClass.ANY);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(rec, Section.PREREQ);
print(rec);
}
}
void
doProhibit(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (qualifier.equals("-r"))
rec = parseRR(st, defaultClass, 0);
else if (qualifier.equals("-s"))
rec = parseSet(st, DClass.NONE);
else if (qualifier.equals("-n"))
rec = parseName(st, DClass.NONE);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(rec, Section.PREREQ);
print(rec);
}
}
void
doAdd(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (!qualifier.startsWith("-")) {
st.putBackToken(qualifier);
qualifier = "-r";
}
if (qualifier.equals("-r"))
rec = parseRR(st, defaultClass, defaultTTL);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(rec, Section.UPDATE);
print(rec);
}
}
void
doDelete(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (qualifier.equals("-r"))
rec = parseRR(st, DClass.NONE, 0);
else if (qualifier.equals("-s"))
rec = parseSet(st, DClass.ANY);
else if (qualifier.equals("-n"))
rec = parseName(st, DClass.ANY);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(rec, Section.UPDATE);
print(rec);
}
}
void
doGlue(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (!qualifier.startsWith("-")) {
st.putBackToken(qualifier);
qualifier = "-r";
}
if (qualifier.equals("-r"))
rec = parseRR(st, defaultClass, defaultTTL);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(rec, Section.ADDITIONAL);
print(rec);
}
}
void
doQuery(MyStringTokenizer st) throws IOException {
Record rec;
Name name = null;
short type = Type.A, dclass = defaultClass;
name = new Name(st.nextToken(), origin);
if (st.hasMoreTokens()) {
type = Type.value(st.nextToken());
if (type < 0)
throw new IOException("Invalid type");
if (st.hasMoreTokens()) {
dclass = DClass.value(st.nextToken());
if (dclass < 0)
throw new IOException("Invalid class");
}
}
rec = Record.newRecord(name, type, dclass);
Message newQuery = Message.newQuery(rec);
if (res == null)
res = new SimpleResolver(server);
if (rec.getType() == Type.AXFR)
response = res.sendAXFR(newQuery);
else
response = res.send(newQuery);
print(response);
}
void
doFile(MyStringTokenizer st, Vector inputs, Vector istreams) {
String s = st.nextToken();
try {
InputStreamReader isr2;
if (!s.equals("-")) {
FileInputStream fis = new FileInputStream(s);
isr2 = new InputStreamReader(fis);
istreams.addElement(fis);
}
else {
isr2 = new InputStreamReader(System.in);
istreams.addElement(System.in);
}
BufferedReader br2 = new BufferedReader(isr2);
inputs.addElement(br2);
}
catch (FileNotFoundException e) {
print(s + "not found");
}
}
void
doLog(MyStringTokenizer st) {
String s = st.nextToken();
try {
FileOutputStream fos = new FileOutputStream(s);
log = new PrintStream(fos);
}
catch (Exception e) {
print("Error opening " + s);
}
}
boolean
doAssert(MyStringTokenizer st) {
String field = st.nextToken();
String expected = st.nextToken();
String value = null;
boolean flag = true;
int section;
if (response == null) {
print("No response has been received");
return true;
}
if (field.equalsIgnoreCase("rcode")) {
short rcode = response.getHeader().getRcode();
if (rcode != Rcode.value(expected)) {
value = Rcode.string(rcode);
flag = false;
}
}
else if (field.equalsIgnoreCase("serial")) {
Record [] answers = response.getSectionArray(Section.ANSWER);
if (answers.length < 1 || !(answers[0] instanceof SOARecord))
print("Invalid response (no SOA)");
else {
SOARecord soa = (SOARecord) answers[0];
int serial = soa.getSerial();
if (serial != Integer.parseInt(expected)) {
value = new Integer(serial).toString();
flag = false;
}
}
}
else if ((section = Section.value(field)) >= 0) {
int count = response.getHeader().getCount(section);
if (count != Integer.parseInt(expected)) {
value = new Integer(count).toString();
flag = false;
}
}
else
print("Invalid assertion keyword: " + field);
if (flag == false) {
print("Expected " + field + " " + expected +
", received " + value);
if (st.hasMoreTokens())
print(st.nextToken());
}
return flag;
}
static void
help(String topic) {
System.out.println();
if (topic == null)
System.out.println("The following are supported commands:\n" +
"add assert class delete echo file\n" +
"glue help log key origin port\n" +
"prohibit q query quit require send\n" +
"server tcp ttl zone
else if (topic.equalsIgnoreCase("add"))
System.out.println(
"add [-r] <name> [ttl] [class] <type> <data>\n\n" +
"specify a record to be added\n");
else if (topic.equalsIgnoreCase("assert"))
System.out.println(
"assert <field> <value> [msg]\n\n" +
"asserts that the value of the field in the last\n" +
"response matches the value specified. If not,\n" +
"the message is printed (if present) and the\n" +
"program exits. The field may be any of <rcode>,\n" +
"<serial>, <qu>, <an>, <au>, or <ad>.\n");
else if (topic.equalsIgnoreCase("class"))
System.out.println(
"class <class>\n\n" +
"class of the zone to be updated (default: IN)\n");
else if (topic.equalsIgnoreCase("delete"))
System.out.println(
"delete -r <name> [ttl] [class] <type> <data> \n" +
"delete -s <name> <type> \n" +
"delete -n <name>\n\n" +
"specify a record or set to be deleted, or that\n" +
"all records at a name should be deleted\n");
else if (topic.equalsIgnoreCase("echo"))
System.out.println(
"echo <text>\n\n" +
"prints the text\n");
else if (topic.equalsIgnoreCase("file"))
System.out.println(
"file <file>\n\n" +
"opens the specified file as the new input source\n" +
"(- represents stdin)\n");
else if (topic.equalsIgnoreCase("glue"))
System.out.println(
"glue [-r] <name> [ttl] [class] <type> <data>\n\n" +
"specify an additional record\n");
else if (topic.equalsIgnoreCase("help"))
System.out.println(
"help\n" +
"help [topic]\n\n" +
"prints a list of commands or help about a specific\n" +
"command\n");
else if (topic.equalsIgnoreCase("log"))
System.out.println(
"log <file>\n\n" +
"opens the specified file and uses it to log output\n");
else if (topic.equalsIgnoreCase("key"))
System.out.println(
"key <name> <data>\n\n" +
"TSIG key used to sign messages\n");
else if (topic.equalsIgnoreCase("origin"))
System.out.println(
"origin <origin>\n\n" +
"default origin of unqualified names (default: .)\n");
else if (topic.equalsIgnoreCase("port"))
System.out.println(
"port <port>\n\n" +
"UDP/TCP port messages are sent to (default: 53)\n");
else if (topic.equalsIgnoreCase("prohibit"))
System.out.println(
"prohibit -r <name> [ttl] [class] <type> <data> \n" +
"prohibit -s <name> <type> \n" +
"prohibit -n <name>\n\n" +
"require that a record, set, or name is not present\n");
else if (topic.equalsIgnoreCase("query"))
System.out.println(
"query <name> [type [class]] \n\n" +
"issues a query\n");
else if (topic.equalsIgnoreCase("q") ||
topic.equalsIgnoreCase("quit"))
System.out.println(
"q/quit\n\n" +
"quits the program\n");
else if (topic.equalsIgnoreCase("require"))
System.out.println(
"require -r <name> [ttl] [class] <type> <data> \n" +
"require -s <name> <type> \n" +
"require -n <name>\n\n" +
"require that a record, set, or name is present\n");
else if (topic.equalsIgnoreCase("send"))
System.out.println(
"send\n\n" +
"sends and resets the current update packet\n");
else if (topic.equalsIgnoreCase("server"))
System.out.println(
"server <name>\n\n" +
"server that receives send updates/queries\n");
else if (topic.equalsIgnoreCase("tcp"))
System.out.println(
"tcp\n\n" +
"TCP should be used to send all messages\n");
else if (topic.equalsIgnoreCase("ttl"))
System.out.println(
"ttl <ttl>\n\n" +
"default ttl of added records (default: 0)\n");
else if (topic.equalsIgnoreCase("zone"))
System.out.println(
"zone <zone>\n\n" +
"zone to update (default: value of <origin>\n");
else if (topic.equalsIgnoreCase("
System.out.println(
"# <text>\n\n" +
"a comment\n");
else
System.out.println ("Topic " + topic + " unrecognized\n");
}
public static void
main(String args[]) throws IOException {
InputStream in = null;
if (args.length == 1) {
try {
in = new FileInputStream(args[0]);
}
catch (FileNotFoundException e) {
System.out.println(args[0] + " not found.");
System.exit(-1);
}
}
else
in = System.in;
update u = new update(in);
}
}
|
import java.net.*;
import java.io.*;
import java.util.*;
import org.xbill.DNS.*;
/** @author Brian Wellington <bwelling@xbill.org> */
public class update {
Message query, response;
Resolver res;
String server = null;
Name zone = Name.root;
long defaultTTL;
int defaultClass = DClass.IN;
PrintStream log = null;
void
print(Object o) {
System.out.println(o);
if (log != null)
log.println(o);
}
public Message
newMessage() {
Message msg = new Message();
msg.getHeader().setOpcode(Opcode.UPDATE);
return msg;
}
public
update(InputStream in) throws IOException {
List inputs = new LinkedList();
List istreams = new LinkedList();
query = newMessage();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
inputs.add(br);
istreams.add(in);
while (true) {
try {
String line = null;
do {
InputStream is;
is = (InputStream)istreams.get(0);
br = (BufferedReader)inputs.get(0);
if (is == System.in)
System.out.print("> ");
line = br.readLine();
if (line == null) {
br.close();
inputs.remove(0);
istreams.remove(0);
if (inputs.isEmpty())
return;
}
} while (line == null);
if (log != null)
log.println("> " + line);
if (line.length() == 0 || line.charAt(0) == '
continue;
/* Allows cut and paste from other update sessions */
if (line.charAt(0) == '>')
line = line.substring(1);
Tokenizer st = new Tokenizer(line);
Tokenizer.Token token = st.get();
if (token.isEOL())
continue;
String operation = token.value;
if (operation.equals("server")) {
server = st.getString();
res = new SimpleResolver(server);
token = st.get();
if (token.isString()) {
String portstr = token.value;
res.setPort(Short.parseShort(portstr));
}
}
else if (operation.equals("key")) {
String keyname = st.getString();
String keydata = st.getString();
if (res == null)
res = new SimpleResolver(server);
res.setTSIGKey(new TSIG(keyname, keydata));
}
else if (operation.equals("edns")) {
if (res == null)
res = new SimpleResolver(server);
res.setEDNS(st.getUInt16());
}
else if (operation.equals("port")) {
if (res == null)
res = new SimpleResolver(server);
res.setPort(st.getUInt16());
}
else if (operation.equals("tcp")) {
if (res == null)
res = new SimpleResolver(server);
res.setTCP(true);
}
else if (operation.equals("class")) {
String classStr = st.getString();
int newClass = DClass.value(classStr);
if (newClass > 0)
defaultClass = newClass;
else
print("Invalid class " + classStr);
}
else if (operation.equals("ttl"))
defaultTTL = st.getTTL();
else if (operation.equals("origin") ||
operation.equals("zone"))
{
zone = st.getName(Name.root);
}
else if (operation.equals("require"))
doRequire(st);
else if (operation.equals("prohibit"))
doProhibit(st);
else if (operation.equals("add"))
doAdd(st);
else if (operation.equals("delete"))
doDelete(st);
else if (operation.equals("glue"))
doGlue(st);
else if (operation.equals("help") ||
operation.equals("?"))
{
token = st.get();
if (token.isString())
help(token.value);
else
help(null);
}
else if (operation.equals("echo"))
print(line.substring(4).trim());
else if (operation.equals("send")) {
sendUpdate();
query = newMessage();
}
else if (operation.equals("show")) {
print(query);
}
else if (operation.equals("clear"))
query = newMessage();
else if (operation.equals("query"))
doQuery(st);
else if (operation.equals("quit") ||
operation.equals("q"))
{
if (log != null)
log.close();
Iterator it = inputs.iterator();
while (it.hasNext()) {
BufferedReader tbr;
tbr = (BufferedReader) it.next();
tbr.close();
}
System.exit(0);
}
else if (operation.equals("file"))
doFile(st, inputs, istreams);
else if (operation.equals("log"))
doLog(st);
else if (operation.equals("assert")) {
if (doAssert(st) == false)
return;
}
else if (operation.equals("sleep")) {
long interval = st.getUInt32();
try {
Thread.sleep(interval);
}
catch (InterruptedException e) {
}
}
else if (operation.equals("date")) {
Date now = new Date();
token = st.get();
if (token.isString() &&
token.value.equals("-ms"))
print(Long.toString(now.getTime()));
else
print(now);
}
else
print("invalid keyword: " + operation);
}
catch (TextParseException tpe) {
System.out.println(tpe.getMessage());
}
catch (InterruptedIOException iioe) {
System.out.println("Operation timed out");
}
catch (SocketException se) {
System.out.println("Socket error");
}
catch (IOException ioe) {
System.out.println(ioe);
}
}
}
void
sendUpdate() throws IOException {
if (query.getHeader().getCount(Section.UPDATE) == 0) {
print("Empty update message. Ignoring.");
return;
}
if (query.getHeader().getCount(Section.ZONE) == 0) {
Name updzone;
updzone = zone;
int dclass = defaultClass;
if (updzone == null) {
Record [] recs = query.getSectionArray(Section.UPDATE);
for (int i = 0; i < recs.length; i++) {
if (updzone == null)
updzone = new Name(recs[i].getName(),
1);
if (recs[i].getDClass() != DClass.NONE &&
recs[i].getDClass() != DClass.ANY)
{
dclass = recs[i].getDClass();
break;
}
}
}
Record soa = Record.newRecord(updzone, Type.SOA, dclass);
query.addRecord(soa, Section.ZONE);
}
if (res == null)
res = new SimpleResolver(server);
response = res.send(query);
print(response);
}
/*
* <name> [ttl] [class] <type> <data>
* Ignore the class, if present.
*/
Record
parseRR(Tokenizer st, int classValue, long TTLValue)
throws IOException
{
Name name = st.getName(zone);
long ttl;
int type;
Record record;
String s = st.getString();
try {
ttl = TTL.parseTTL(s);
s = st.getString();
}
catch (NumberFormatException e) {
ttl = TTLValue;
}
if (DClass.value(s) >= 0) {
classValue = DClass.value(s);
s = st.getString();
}
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
record = Record.fromString(name, type, classValue, ttl, st, zone);
if (record != null)
return (record);
else
throw new IOException("Parse error");
}
void
doRequire(Tokenizer st) throws IOException {
Tokenizer.Token token;
Name name;
Record record;
int type;
name = st.getName(zone);
token = st.get();
if (token.isString()) {
if ((type = Type.value(token.value)) < 0)
throw new IOException("Invalid type: " + token.value);
token = st.get();
boolean iseol = token.isEOL();
st.unget();
if (!iseol) {
record = Record.fromString(name, type, defaultClass,
0, st, zone);
} else
record = Record.newRecord(name, type,
DClass.ANY, 0);
} else
record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
query.addRecord(record, Section.PREREQ);
print(record);
}
void
doProhibit(Tokenizer st) throws IOException {
Tokenizer.Token token;
String s;
Name name;
Record record;
int type;
name = st.getName(zone);
token = st.get();
if (token.isString()) {
if ((type = Type.value(token.value)) < 0)
throw new IOException("Invalid type: " + token.value);
} else
type = Type.ANY;
record = Record.newRecord(name, type, DClass.NONE, 0);
query.addRecord(record, Section.PREREQ);
print(record);
}
void
doAdd(Tokenizer st) throws IOException {
Record record = parseRR(st, defaultClass, defaultTTL);
query.addRecord(record, Section.UPDATE);
print(record);
}
void
doDelete(Tokenizer st) throws IOException {
Tokenizer.Token token;
String s;
Name name;
Record record;
int type;
int dclass;
name = st.getName(zone);
token = st.get();
if (token.isString()) {
s = token.value;
if ((dclass = DClass.value(s)) >= 0) {
s = st.getString();
}
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
token = st.get();
boolean iseol = token.isEOL();
st.unget();
if (!iseol) {
record = Record.fromString(name, type, DClass.NONE,
0, st, zone);
} else
record = Record.newRecord(name, type, DClass.ANY, 0);
}
else
record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
query.addRecord(record, Section.UPDATE);
print(record);
}
void
doGlue(Tokenizer st) throws IOException {
Record record = parseRR(st, defaultClass, defaultTTL);
query.addRecord(record, Section.ADDITIONAL);
print(record);
}
void
doQuery(Tokenizer st) throws IOException {
Record rec;
Tokenizer.Token token;
Name name = null;
int type = Type.A;
int dclass = defaultClass;
name = st.getName(zone);
token = st.get();
if (token.isString()) {
type = Type.value(token.value);
if (type < 0)
throw new IOException("Invalid type");
token = st.get();
if (token.isString()) {
dclass = DClass.value(token.value);
if (dclass < 0)
throw new IOException("Invalid class");
}
}
rec = Record.newRecord(name, type, dclass);
Message newQuery = Message.newQuery(rec);
if (res == null)
res = new SimpleResolver(server);
response = res.send(newQuery);
print(response);
}
void
doFile(Tokenizer st, List inputs, List istreams) throws IOException {
String s = st.getString();
InputStream is;
try {
if (s.equals("-"))
is = System.in;
else
is = new FileInputStream(s);
istreams.add(0, is);
inputs.add(new BufferedReader(new InputStreamReader(is)));
}
catch (FileNotFoundException e) {
print(s + " not found");
}
}
void
doLog(Tokenizer st) throws IOException {
String s = st.getString();
try {
FileOutputStream fos = new FileOutputStream(s);
log = new PrintStream(fos);
}
catch (Exception e) {
print("Error opening " + s);
}
}
boolean
doAssert(Tokenizer st) throws IOException {
String field = st.getString();
String expected = st.getString();
String value = null;
boolean flag = true;
int section;
if (response == null) {
print("No response has been received");
return true;
}
if (field.equalsIgnoreCase("rcode")) {
int rcode = response.getHeader().getRcode();
if (rcode != Rcode.value(expected)) {
value = Rcode.string(rcode);
flag = false;
}
}
else if (field.equalsIgnoreCase("serial")) {
Record [] answers = response.getSectionArray(Section.ANSWER);
if (answers.length < 1 || !(answers[0] instanceof SOARecord))
print("Invalid response (no SOA)");
else {
SOARecord soa = (SOARecord) answers[0];
long serial = soa.getSerial();
if (serial != Long.parseLong(expected)) {
value = Long.toString(serial);
flag = false;
}
}
}
else if (field.equalsIgnoreCase("tsig")) {
if (response.isSigned()) {
if (response.isVerified())
value = "ok";
else
value = "failed";
}
else
value = "unsigned";
if (!value.equalsIgnoreCase(expected))
flag = false;
}
else if ((section = Section.value(field)) >= 0) {
int count = response.getHeader().getCount(section);
if (count != Integer.parseInt(expected)) {
value = new Integer(count).toString();
flag = false;
}
}
else
print("Invalid assertion keyword: " + field);
if (flag == false) {
print("Expected " + field + " " + expected +
", received " + value);
while (true) {
Tokenizer.Token token = st.get();
if (!token.isString())
break;
print(token.value);
}
st.unget();
}
return flag;
}
static void
help(String topic) {
System.out.println();
if (topic == null) {
System.out.println("The following are supported commands:\n" +
"add assert class clear date delete\n" +
"echo edns file glue help key\n" +
"log port prohibit query quit require\n" +
"send server show sleep tcp ttl\n" +
"zone
return;
}
topic = topic.toLowerCase();
if (topic.equals("add"))
System.out.println(
"add <name> [ttl] [class] <type> <data>\n\n" +
"specify a record to be added\n");
else if (topic.equals("assert"))
System.out.println(
"assert <field> <value> [msg]\n\n" +
"asserts that the value of the field in the last\n" +
"response matches the value specified. If not,\n" +
"the message is printed (if present) and the\n" +
"program exits. The field may be any of <rcode>,\n" +
"<serial>, <tsig>, <qu>, <an>, <au>, or <ad>.\n");
else if (topic.equals("class"))
System.out.println(
"class <class>\n\n" +
"class of the zone to be updated (default: IN)\n");
else if (topic.equals("clear"))
System.out.println(
"clear\n\n" +
"clears the current update packet\n");
else if (topic.equals("date"))
System.out.println(
"date [-ms]\n\n" +
"prints the current date and time in human readable\n" +
"format or as the number of milliseconds since the\n" +
"epoch");
else if (topic.equals("delete"))
System.out.println(
"delete <name> [ttl] [class] <type> <data> \n" +
"delete <name> <type> \n" +
"delete <name>\n\n" +
"specify a record or set to be deleted, or that\n" +
"all records at a name should be deleted\n");
else if (topic.equals("echo"))
System.out.println(
"echo <text>\n\n" +
"prints the text\n");
else if (topic.equals("edns"))
System.out.println(
"edns <level>\n\n" +
"EDNS level specified when sending messages\n");
else if (topic.equals("file"))
System.out.println(
"file <file>\n\n" +
"opens the specified file as the new input source\n" +
"(- represents stdin)\n");
else if (topic.equals("glue"))
System.out.println(
"glue <name> [ttl] [class] <type> <data>\n\n" +
"specify an additional record\n");
else if (topic.equals("help"))
System.out.println(
"help\n" +
"help [topic]\n\n" +
"prints a list of commands or help about a specific\n" +
"command\n");
else if (topic.equals("key"))
System.out.println(
"key <name> <data>\n\n" +
"TSIG key used to sign messages\n");
else if (topic.equals("log"))
System.out.println(
"log <file>\n\n" +
"opens the specified file and uses it to log output\n");
else if (topic.equals("port"))
System.out.println(
"port <port>\n\n" +
"UDP/TCP port messages are sent to (default: 53)\n");
else if (topic.equals("prohibit"))
System.out.println(
"prohibit <name> <type> \n" +
"prohibit <name>\n\n" +
"require that a set or name is not present\n");
else if (topic.equals("query"))
System.out.println(
"query <name> [type [class]] \n\n" +
"issues a query\n");
else if (topic.equals("q") || topic.equals("quit"))
System.out.println(
"quit\n\n" +
"quits the program\n");
else if (topic.equals("require"))
System.out.println(
"require <name> [ttl] [class] <type> <data> \n" +
"require <name> <type> \n" +
"require <name>\n\n" +
"require that a record, set, or name is present\n");
else if (topic.equals("send"))
System.out.println(
"send\n\n" +
"sends and resets the current update packet\n");
else if (topic.equals("server"))
System.out.println(
"server <name> [port]\n\n" +
"server that receives send updates/queries\n");
else if (topic.equals("show"))
System.out.println(
"show\n\n" +
"shows the current update packet\n");
else if (topic.equals("sleep"))
System.out.println(
"sleep <milliseconds>\n\n" +
"pause for interval before next command\n");
else if (topic.equals("tcp"))
System.out.println(
"tcp\n\n" +
"TCP should be used to send all messages\n");
else if (topic.equals("ttl"))
System.out.println(
"ttl <ttl>\n\n" +
"default ttl of added records (default: 0)\n");
else if (topic.equals("zone") || topic.equals("origin"))
System.out.println(
"zone <zone>\n\n" +
"zone to update (default: .\n");
else if (topic.equals("
System.out.println(
"# <text>\n\n" +
"a comment\n");
else
System.out.println ("Topic '" + topic + "' unrecognized\n");
}
public static void
main(String args[]) throws IOException {
InputStream in = null;
if (args.length >= 1) {
try {
in = new FileInputStream(args[0]);
}
catch (FileNotFoundException e) {
System.out.println(args[0] + " not found.");
System.exit(1);
}
}
else
in = System.in;
update u = new update(in);
}
}
|
import java.net.*;
import java.io.*;
import java.util.*;
import org.xbill.DNS.*;
import org.xbill.DNS.utils.*;
/** @author Brian Wellington <bwelling@xbill.org> */
public class update {
Message query, response;
Resolver res;
String server = null;
Name origin, zone;
int defaultTTL;
short defaultClass = DClass.IN;
PrintStream log = null;
void
print(Object o) {
System.out.println(o);
if (log != null)
log.println(o);
}
public
update(InputStream in) throws IOException {
Vector inputs = new Vector();
Vector istreams = new Vector();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
inputs.addElement(br);
istreams.addElement(in);
while (true) {
try {
String line = null;
do {
InputStream is;
is = (InputStream) istreams.lastElement();
br = (BufferedReader)inputs.lastElement();
if (is == System.in)
System.out.print("> ");
line = Master.readExtendedLine(br);
if (line == null) {
br.close();
inputs.removeElement(br);
istreams.removeElement(is);
if (inputs.isEmpty())
return;
}
} while (line == null);
if (log != null)
log.println("> " + line);
if (line.length() == 0 || line.charAt(0) == '
continue;
MyStringTokenizer st = new MyStringTokenizer(line);
if (!st.hasMoreTokens())
continue;
String operation = st.nextToken();
if (operation.equals("server")) {
server = st.nextToken();
res = new SimpleResolver(server);
}
else if (operation.equals("key")) {
String keyname = st.nextToken();
String keydata = st.nextToken();
if (res == null)
res = new SimpleResolver(server);
res.setTSIGKey(keyname, keydata);
}
else if (operation.equals("port")) {
if (res == null)
res = new SimpleResolver(server);
res.setPort(Short.parseShort(st.nextToken()));
}
else if (operation.equals("tcp")) {
if (res == null)
res = new SimpleResolver(server);
res.setTCP(true);
}
else if (operation.equals("class")) {
String s = st.nextToken();
short newClass = DClass.value(s);
if (newClass > 0)
defaultClass = newClass;
else
print("Invalid class " + newClass);
}
else if (operation.equals("ttl"))
defaultTTL = TTL.parseTTL(st.nextToken());
else if (operation.equals("origin"))
origin = new Name(st.nextToken());
else if (operation.equals("zone"))
zone = new Name(st.nextToken());
else if (operation.equals("require"))
doRequire(st);
else if (operation.equals("prohibit"))
doProhibit(st);
else if (operation.equals("add"))
doAdd(st);
else if (operation.equals("delete"))
doDelete(st);
else if (operation.equals("glue"))
doGlue(st);
else if (operation.equals("help")) {
if (st.hasMoreTokens())
help(st.nextToken());
else
help(null);
}
else if (operation.equals("echo"))
print(line.substring(4).trim());
else if (operation.equals("send")) {
if (res == null)
res = new SimpleResolver(server);
sendUpdate();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("query"))
doQuery(st);
else if (operation.equals("quit") ||
operation.equals("q"))
{
if (log != null)
log.close();
Enumeration e = inputs.elements();
while (e.hasMoreElements()) {
BufferedReader tbr;
tbr = (BufferedReader) e.nextElement();
tbr.close();
}
System.exit(0);
}
else if (operation.equals("file"))
doFile(st, inputs, istreams);
else if (operation.equals("log"))
doLog(st);
else if (operation.equals("assert")) {
if (doAssert(st) == false)
return;
}
else
print("invalid keyword: " + operation);
}
catch (NullPointerException npe) {
System.out.println("Parse error");
}
catch (InterruptedIOException iioe) {
System.out.println("Operation timed out");
}
}
}
void
sendUpdate() throws IOException {
if (query.getHeader().getCount(Section.ZONE) == 0) {
Name updzone;
if (zone != null)
updzone = zone;
else
updzone = origin;
short dclass = defaultClass;
if (updzone == null) {
Enumeration updates = query.getSection(Section.UPDATE);
if (updates == null) {
print("Invalid update");
return;
}
Record r = (Record) updates.nextElement();
updzone = new Name(r.getName(), 1);
dclass = r.getDClass();
}
Record soa = Record.newRecord(updzone, Type.SOA, dclass);
query.addRecord(soa, Section.ZONE);
}
response = res.send(query);
if (response == null)
return;
print(response);
}
/*
* <name> [ttl] [class] <type> <data>
* Ignore the class, if present.
*/
Record
parseRR(MyStringTokenizer st, short classValue, int TTLValue)
throws IOException
{
Name name = new Name(st.nextToken(), origin);
int ttl;
short type;
String s = st.nextToken();
try {
ttl = TTL.parseTTL(s);
s = st.nextToken();
}
catch (NumberFormatException e) {
ttl = TTLValue;
}
if (DClass.value(s) >= 0)
s = st.nextToken();
if ((type = Type.value(s)) < 0)
/* Close enough... */
throw new NullPointerException("Parse error");
return Record.fromString(name, type, classValue, ttl, st, origin);
}
/*
* <name> <type>
*/
Record
parseSet(MyStringTokenizer st, short classValue) throws IOException {
Name name = new Name(st.nextToken(), origin);
short type;
if ((type = Type.value(st.nextToken())) < 0)
throw new IOException("Parse error");
return Record.newRecord(name, type, classValue, 0);
}
/*
* <name>
*/
Record
parseName(MyStringTokenizer st, short classValue) throws IOException {
Name name = new Name(st.nextToken(), origin);
return Record.newRecord(name, Type.ANY, classValue, 0);
}
void
doRequire(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (qualifier.equals("-r"))
rec = parseRR(st, defaultClass, 0);
else if (qualifier.equals("-s"))
rec = parseSet(st, DClass.ANY);
else if (qualifier.equals("-n"))
rec = parseName(st, DClass.ANY);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(rec, Section.PREREQ);
print(rec);
}
}
void
doProhibit(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (qualifier.equals("-r"))
rec = parseRR(st, defaultClass, 0);
else if (qualifier.equals("-s"))
rec = parseSet(st, DClass.NONE);
else if (qualifier.equals("-n"))
rec = parseName(st, DClass.NONE);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(rec, Section.PREREQ);
print(rec);
}
}
void
doAdd(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (!qualifier.startsWith("-")) {
st.putBackToken(qualifier);
qualifier = "-r";
}
if (qualifier.equals("-r"))
rec = parseRR(st, defaultClass, defaultTTL);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(rec, Section.UPDATE);
print(rec);
}
}
void
doDelete(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (qualifier.equals("-r"))
rec = parseRR(st, DClass.NONE, 0);
else if (qualifier.equals("-s"))
rec = parseSet(st, DClass.ANY);
else if (qualifier.equals("-n"))
rec = parseName(st, DClass.ANY);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(rec, Section.UPDATE);
print(rec);
}
}
void
doGlue(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (!qualifier.startsWith("-")) {
st.putBackToken(qualifier);
qualifier = "-r";
}
if (qualifier.equals("-r"))
rec = parseRR(st, defaultClass, defaultTTL);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(rec, Section.ADDITIONAL);
print(rec);
}
}
void
doQuery(MyStringTokenizer st) throws IOException {
Record rec;
Name name = null;
short type = Type.A, dclass = defaultClass;
name = new Name(st.nextToken(), origin);
if (st.hasMoreTokens()) {
type = Type.value(st.nextToken());
if (type < 0)
throw new IOException("Invalid type");
if (st.hasMoreTokens()) {
dclass = DClass.value(st.nextToken());
if (dclass < 0)
throw new IOException("Invalid class");
}
}
rec = Record.newRecord(name, type, dclass);
Message newQuery = Message.newQuery(rec);
if (res == null)
res = new SimpleResolver(server);
if (rec.getType() == Type.AXFR)
response = res.sendAXFR(newQuery);
else
response = res.send(newQuery);
print(response);
}
void
doFile(MyStringTokenizer st, Vector inputs, Vector istreams) {
String s = st.nextToken();
try {
InputStreamReader isr2;
if (!s.equals("-")) {
FileInputStream fis = new FileInputStream(s);
isr2 = new InputStreamReader(fis);
istreams.addElement(fis);
}
else {
isr2 = new InputStreamReader(System.in);
istreams.addElement(System.in);
}
BufferedReader br2 = new BufferedReader(isr2);
inputs.addElement(br2);
}
catch (FileNotFoundException e) {
print(s + "not found");
}
}
void
doLog(MyStringTokenizer st) {
String s = st.nextToken();
try {
FileOutputStream fos = new FileOutputStream(s);
log = new PrintStream(fos);
}
catch (Exception e) {
print("Error opening " + s);
}
}
boolean
doAssert(MyStringTokenizer st) {
String field = st.nextToken();
String expected = st.nextToken();
String value = null;
boolean flag = true;
int section;
if (response == null) {
print("No response has been received");
return true;
}
if (field.equalsIgnoreCase("rcode")) {
short rcode = response.getHeader().getRcode();
if (rcode != Rcode.value(expected)) {
value = Rcode.string(rcode);
flag = false;
}
}
else if (field.equalsIgnoreCase("serial")) {
Record [] answers = response.getSectionArray(Section.ANSWER);
if (answers.length < 1 || !(answers[0] instanceof SOARecord))
print("Invalid response (no SOA)");
else {
SOARecord soa = (SOARecord) answers[0];
int serial = soa.getSerial();
if (serial != new Integer(expected).intValue()) {
value = new Integer(serial).toString();
flag = false;
}
}
}
else if ((section = Section.value(field)) >= 0) {
short count = response.getHeader().getCount(section);
if (count != Short.parseShort(expected)) {
value = new Short(count).toString();
flag = false;
}
}
else
print("Invalid assertion keyword: " + field);
if (flag == false) {
print("Expected " + field + " " + expected +
", received " + value);
if (st.hasMoreTokens())
print(st.nextToken());
}
return flag;
}
static void
helpResolver() {
System.out.println("Resolver options:\n" +
" server <name>" +
"\tserver that receives the updates\n" +
" key <name> <data>" +
"\tTSIG key used to sign the messages\n" +
" port <port>" +
"\t\tUDP/TCP port the message is sent to (default: 53)\n" +
" tcp" +
"\t\t\tTCP should be used to send messages (default: unset)\n"
);
}
static void
helpAttributes() {
System.out.println("Attributes:\n" +
" class <class>\t" +
"class of the zone to be updated (default: IN)\n" +
" ttl <ttl>\t\t" +
"ttl of an added record, if unspecified (default: 0)\n" +
" origin <origin>\t" +
"default origin of each record name (default: .)\n" +
" zone <zone>\t" +
"zone to update (default: value of <origin>)\n"
);
};
static void
helpData() {
System.out.println("Data:\n" +
" require/prohibit\t" +
"require that a record, set, or name is/is not present\n" +
"\t-r <name> [ttl] [class] <type> <data ...> \n" +
"\t-s <name> <type> \n" +
"\t-n <name> \n\n" +
" add\t\t" +
"specify a record to be added\n" +
"\t[-r] <name> [ttl] [class] <type> <data ...> \n\n" +
" delete\t" +
"specify a record, set, or all records at a name to be deleted\n" +
"\t-r <name> [ttl] [class] <type> <data ...> \n" +
"\t-s <name> <type> \n" +
"\t-n <name> \n\n" +
" glue\t" +
"specify an additional record\n" +
"\t[-r] <name> [ttl] [class] <type> <data ...> \n\n" +
" (notes: @ represents the origin " +
"and @me@ represents the local IP address)\n"
);
}
static void
helpOperations() {
System.out.println("Operations:\n" +
" help [topic]\t" +
"this information\n" +
" echo <text>\t\t" +
"echoes the line\n" +
" send\t\t" +
"sends the update and resets the current query\n" +
" query <name> <type> <class> \t" +
"issues a query for this name, type, and class\n" +
" quit\t\t" +
"quits the program\n" +
" file <file>\t\t" +
"opens the specified file as the new input source\n" +
" log <file>\t\t" +
"opens the specified file and uses it to log output\n" +
" assert <field> <value> [msg]\n" +
"\t\t\tasserts that the value of the field in the last response\n" +
"\t\t\tmatches the value specified. If not, the message is\n" +
"\t\t\tprinted (if present) and the program exits.\n"
);
}
static void
help(String topic) {
if (topic != null) {
if (topic.equalsIgnoreCase("resolver"))
helpResolver();
else if (topic.equalsIgnoreCase("attributes"))
helpAttributes();
else if (topic.equalsIgnoreCase("data"))
helpData();
else if (topic.equalsIgnoreCase("operations"))
helpOperations();
else
System.out.println ("Topic " + topic + " unrecognized");
return;
}
System.out.println("The help topics are:\n" +
" Resolver\t" +
"Properties of the resolver and DNS\n" +
" Attributes\t" +
"Properties of some/all records\n" +
" Data\t" +
"Prerequisites, updates, and additional records\n" +
" Operations\t" +
"Actions to be taken\n"
);
}
public static void
main(String args[]) throws IOException {
InputStream in = null;
if (args.length == 1) {
try {
in = new FileInputStream(args[0]);
}
catch (FileNotFoundException e) {
System.out.println(args[0] + " not found.");
System.exit(-1);
}
}
else
in = System.in;
update u = new update(in);
}
}
|
package org.processwarp.android;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import junit.framework.Assert;
public class RouterService extends Service implements Router.Delegate {
private Router router = null;
private ServerConnector server = null;
private static ControllerInterface controller = null;
/**
* When create service, setup Router and Server Connector instances.
*/
@Override
public void onCreate() {
router = new Router();
server = new ServerConnector();
router.initialize(this, server);
server.initialize(router);
}
/**
* When service is created explicit, connect with server by Socket.IO if needed.
* @param intent Not used.
* @param flags Not used.
* @param startId Not used.
* @return START_STICKY value.
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
server.connect();
return START_STICKY;
}
/**
* When service is bundled by another process, pass binder.
* @param intent Not used.
* @return Binder.
*/
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
private RouterInterface.Stub binder = new RouterInterface.Stub() {
/**
* When method is called by frontend, save passed controller callback.
* @param controller Controller callback instance.
*/
@Override
public void registerController(ControllerInterface controller) {
Assert.assertNull(RouterService.controller);
RouterService.controller = controller;
}
/**
* When method is called by frontend, pass it to router.
* @param account Account string.
* @param password Password string.
* @throws RemoteException
*/
@Override
public void connectServer(String account, String password) throws RemoteException {
router.connectServer(account, password);
}
/**
* When send command is called by another activity or services,
* make packet and relay to router.
* @param pid Process-id bundled to packet.
* @param dstNid Destination node-id.
* @param module Target module.
* @param content JSON string contain command and parameter.
* @throws RemoteException
*/
@Override
public void sendCommand(String pid, String dstNid, int module, String content)
throws RemoteException {
CommandPacket packet = new CommandPacket();
packet.pid = pid;
packet.dstNid = dstNid;
packet.srcNid = SpecialNid.NONE;
packet.module = module;
packet.content = content;
router.relayCommand(packet);
}
};
/**
* When relay controller is required, relay packet to controller by AIDL.
* @param packet Command packet.
*/
@Override
public void relayControllerPacket(CommandPacket packet) {
if (controller == null) return;
try {
controller.recvCommand(
packet.pid, packet.dstNid, packet.srcNid,
packet.module, packet.content);
} catch (RemoteException e) {
Assert.fail();
}
}
static {
System.loadLibrary("processwarp_jni");
}
}
|
package com.whatistics.backend;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.whatistics.backend.dal.DataAccessLayerModule;
import com.whatistics.backend.mail.MailModule;
import com.whatistics.backend.parser.ParserModule;
import com.whatistics.backend.statistics.StatisticsModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Random;
/**
* Main Whatistics class
*/
public class WhatisticsBackend {
private static Injector injector;
public static Random rand = new Random();
public static void main(String[] args) {
// System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "DEBUG");
final Logger logger = LoggerFactory.getLogger(WhatisticsBackend.class);
injector = Guice.createInjector(new MailModule(),
new ParserModule(),
new DataAccessLayerModule(),
new WhatisticsModule(),
new StatisticsModule());
// start the restheart server as a process
// todo: make RESTHeart use configuration file from resources
// todo: redirect stdout or call lib directly
// todo: movo into seperate model so
try {
Process restProc = Runtime.getRuntime().exec("java -server -jar build/libs/lib/restheart-1.1.7.jar");
} catch (IOException e) {
logger.error("Failed starting RESTHeart Server", e);
e.printStackTrace();
}
WhatisticsService whatisticsService = injector.getInstance(WhatisticsService.class);
whatisticsService.start();
}
public static Injector getInjector() {
return injector;
}
}
|
package burai.app.project.editor.result.movie;
import java.io.File;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import burai.app.QEFXMain;
import burai.app.project.QEFXProjectController;
import burai.app.project.editor.result.QEFXResultEditorController;
import burai.app.project.viewer.result.movie.QEFXMovieViewerController;
import burai.atoms.model.Atom;
import burai.atoms.model.Cell;
import burai.atoms.model.exception.ZeroVolumCellException;
import burai.com.consts.Constants;
import burai.com.env.Environments;
import burai.com.graphic.svg.SVGLibrary;
import burai.com.graphic.svg.SVGLibrary.SVGData;
import burai.com.math.Matrix3D;
import burai.project.Project;
import burai.project.property.ProjectGeometry;
public class QEFXMovieEditorController extends QEFXResultEditorController<QEFXMovieViewerController> {
private static final double GRAPHIC_SIZE = 20.0;
private static final String GRAPHIC_CLASS = "piclight-button";
private Project project;
@FXML
private Button movieButton;
@FXML
private TextField numberField;
private String numberText;
@FXML
private Label totalLabel;
@FXML
private Label timeLabel;
@FXML
private Button exportButton;
@FXML
private TextArea atomArea;
public QEFXMovieEditorController(
QEFXProjectController projectController, QEFXMovieViewerController viewerController, Project project) {
super(projectController, viewerController);
if (project == null) {
throw new IllegalArgumentException("project is null.");
}
this.project = project;
this.numberText = null;
}
@Override
protected void setupFXComponents() {
this.setupMovieButton();
this.setupNumberField();
this.setupExportButton();
this.setupAtomArea();
}
private void setupMovieButton() {
if (this.movieButton == null) {
return;
}
this.movieButton.setText("");
this.movieButton.setGraphic(SVGLibrary.getGraphic(SVGData.MOVIE, GRAPHIC_SIZE, null, GRAPHIC_CLASS));
this.movieButton.setOnAction(event -> {
// TODO
});
}
private void setupNumberField() {
if (this.numberField == null) {
return;
}
this.numberField.focusedProperty().addListener(o -> {
if (this.numberField.isFocused()) {
this.numberText = this.numberField.getText();
} else {
if (this.numberText != null) {
this.numberField.setText(this.numberText);
}
}
});
this.numberField.setOnAction(event -> {
String value = this.numberField.getText();
value = value == null ? null : value.trim();
if (value == null || value.isEmpty()) {
return;
}
int index = -1;
try {
index = Integer.parseInt(value);
} catch (NumberFormatException e) {
index = -1;
}
boolean status = false;
if (this.viewerController != null && index > 0) {
status = this.viewerController.showGeometry(index - 1);
}
if (!status) {
Alert alert = new Alert(AlertType.ERROR);
QEFXMain.initializeDialogOwner(alert);
alert.setHeaderText("Incorrect number of atomic configuration.");
alert.showAndWait();
return;
}
this.numberText = Integer.toString(index);
});
}
private void setupExportButton() {
if (this.exportButton == null) {
return;
}
this.exportButton.getStyleClass().add(GRAPHIC_CLASS);
this.exportButton.setGraphic(SVGLibrary.getGraphic(SVGData.EXPORT, GRAPHIC_SIZE, null, GRAPHIC_CLASS));
this.exportButton.setOnAction(event -> {
Project project = this.saveNewProject();
if (project == null) {
return;
}
boolean status = this.editProject(project);
if (!status) {
System.err.println("cannot edit project.");
return;
}
if (this.mainController != null) {
this.mainController.showProject(project);
}
});
}
public Project saveNewProject() {
File directory = null;
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("New project");
String projPath = this.project == null ? null : this.project.getDirectoryPath();
projPath = projPath == null ? null : projPath.trim();
File projDir = null;
if (projPath != null && !(projPath.isEmpty())) {
projDir = new File(projPath);
}
File initDir = projDir == null ? null : projDir.getParentFile();
String initPath = initDir == null ? null : initDir.getPath();
if (initDir == null || initPath == null || initPath.trim().isEmpty()) {
initPath = Environments.getProjectsPath();
initDir = new File(initPath);
}
if (initDir != null) {
try {
if (initDir.isDirectory()) {
fileChooser.setInitialDirectory(initDir);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Stage stage = this.getStage();
if (stage != null) {
directory = fileChooser.showSaveDialog(stage);
}
if (directory == null) {
return null;
}
try {
if (directory.exists()) {
Alert alert = new Alert(AlertType.ERROR);
QEFXMain.initializeDialogOwner(alert);
alert.setHeaderText(directory.getName() + " already exists.");
alert.showAndWait();
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Project project = null;
if (this.project != null) {
project = this.project.cloneProject(directory);
}
if (project == null) {
Alert alert = new Alert(AlertType.ERROR);
QEFXMain.initializeDialogOwner(alert);
alert.setHeaderText("Cannot create project: " + directory.getPath());
alert.showAndWait();
return null;
}
return project;
}
private boolean editProject(Project project) {
Cell cell = project == null ? null : project.getCell();
if (cell == null) {
return false;
}
ProjectGeometry geometry = null;
if (this.viewerController != null) {
geometry = this.viewerController.getGeometry();
}
if (geometry == null) {
return false;
}
double[][] lattice = geometry.getCell();
lattice = Matrix3D.mult(Constants.BOHR_RADIUS_ANGS, lattice);
if (lattice == null || lattice.length < 3) {
return false;
}
if (lattice[0] == null || lattice[0].length < 3) {
return false;
}
if (lattice[1] == null || lattice[1].length < 3) {
return false;
}
if (lattice[2] == null || lattice[2].length < 3) {
return false;
}
try {
cell.moveLattice(lattice);
} catch (ZeroVolumCellException e) {
e.printStackTrace();
return false;
}
int natom = geometry.numAtoms();
int natom_ = cell.numAtoms(true);
Atom[] refAtoms = null;
if (natom == natom_) {
refAtoms = cell.listAtoms(true);
}
if (refAtoms != null && refAtoms.length >= natom) {
for (int i = 0; i < natom; i++) {
String name = geometry.getName(i);
if (name == null || name.trim().isEmpty()) {
continue;
}
double x = geometry.getX(i) * Constants.BOHR_RADIUS_ANGS;
double y = geometry.getY(i) * Constants.BOHR_RADIUS_ANGS;
double z = geometry.getZ(i) * Constants.BOHR_RADIUS_ANGS;
Atom atom = refAtoms[i];
if (atom == null) {
cell.addAtom(new Atom(name, x, y, z));
} else {
atom.setName(name);
atom.moveTo(x, y, z);
}
}
} else {
cell.removeAllAtoms();
for (int i = 0; i < natom; i++) {
String name = geometry.getName(i);
if (name == null || name.trim().isEmpty()) {
continue;
}
double x = geometry.getX(i) * Constants.BOHR_RADIUS_ANGS;
double y = geometry.getY(i) * Constants.BOHR_RADIUS_ANGS;
double z = geometry.getZ(i) * Constants.BOHR_RADIUS_ANGS;
cell.addAtom(new Atom(name, x, y, z));
}
}
project.saveQEInputs();
return true;
}
private void setupAtomArea() {
if (this.atomArea == null) {
return;
}
if (this.viewerController == null) {
return;
}
this.viewerController.setOnGeometryShown((i, n, geometry) -> {
if (0 <= i && i < n) {
if (this.numberField != null) {
this.numberField.setText(Integer.toString(i + 1));
}
} else {
if (this.numberField != null) {
this.numberField.setText("
}
return;
}
if (n > 0) {
if (this.totalLabel != null) {
this.totalLabel.setText(Integer.toString(n));
}
} else {
if (this.totalLabel != null) {
this.totalLabel.setText("
}
return;
}
double time = geometry == null ? -1.0 : geometry.getTime();
if (time >= 0.0) {
if (this.timeLabel != null) {
this.timeLabel.setText("( t = " + String.format("%10.4f", time).trim() + "ps )");
}
} else {
if (this.timeLabel != null) {
this.timeLabel.setText("");
}
}
String strGeometry = this.geometryToString(geometry);
if (strGeometry != null && !(strGeometry.isEmpty())) {
if (this.atomArea != null) {
this.atomArea.setText(strGeometry);
}
} else {
if (this.atomArea != null) {
this.atomArea.setText("");
}
return;
}
});
}
private String geometryToString(ProjectGeometry geometry) {
if (geometry == null) {
return null;
}
String str = "";
// cell
double[][] lattice = geometry.getCell();
lattice = Matrix3D.mult(Constants.BOHR_RADIUS_ANGS, lattice);
if (lattice == null || lattice.length < 3) {
return null;
}
if (lattice[0] == null || lattice[0].length < 3) {
return null;
}
if (lattice[1] == null || lattice[1].length < 3) {
return null;
}
if (lattice[2] == null || lattice[2].length < 3) {
return null;
}
String strFormat = "%10.6f %10.6f %10.6f%n";
str = str + "CELL_PARAMETERS {angstrom}" + System.lineSeparator();
str = str + String.format(strFormat, lattice[0][0], lattice[0][1], lattice[0][2]);
str = str + String.format(strFormat, lattice[1][0], lattice[1][1], lattice[1][2]);
str = str + String.format(strFormat, lattice[2][0], lattice[2][1], lattice[2][2]);
// atoms
int natom = geometry.numAtoms();
if (natom > 0) {
str = str + System.lineSeparator();
str = str + "ATOMIC_POSITIONS {angstrom}" + System.lineSeparator();
}
for (int i = 0; i < natom; i++) {
String name = geometry.getName(i);
if (name == null || name.isEmpty()) {
continue;
}
double x = geometry.getX(i) * Constants.BOHR_RADIUS_ANGS;
double y = geometry.getY(i) * Constants.BOHR_RADIUS_ANGS;
double z = geometry.getZ(i) * Constants.BOHR_RADIUS_ANGS;
str = str + String.format("%-5s %10.6f %10.6f %10.6f%n", name, x, y, z);
}
return str;
}
}
|
package ca.ualberta.CMPUT301F13T02.chooseyouradventure;
import java.util.ArrayList;
import java.util.UUID;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
/**
* The Activity in the application that is responsible for viewing and editing
* a page within a story. <br />
* <br />
* In this activity a reader can:
* <ol>
* <li> Read the page </li>
* <li> Follow decisions at the bottom </li>
* <li> Comment on the page </li>
* </ol>
* In this activity an author can:
* <ol>
* <li> Edit the tiles on this page (add, edit, reorder, delete) </li>
* </ol>
*
* The ViewPageActivity is a view of the application.
*
* TODO This activity will need to be able to display and edit Audio-, Video-, and Photo- Tiles
*/
public class ViewPageActivity extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
private final int TAKE_PHOTO = 2;
private final int GRAB_PHOTO = 3;
private final int ADD_PHOTO = 4;
private final int EDIT_INDEX = 0;
private final int SAVE_INDEX = 1;
private final int HELP_INDEX = 2;
private LinearLayout tilesLayout;
private LinearLayout decisionsLayout;
private LinearLayout commentsLayout;
private LinearLayout fightingLayout;
private FightingView fightView = new FightingView();
private StoryController storyController;
private PageController pageController;
private ControllerApp app;
private Menu menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_page_activity);
}
/**
* Called when the Activity resumes
*/
@Override
public void onResume() {
super.onResume();
app = (ControllerApp) this.getApplication();
storyController = app.getStoryController();
pageController = app.getPageController();
fightingLayout = (LinearLayout) findViewById(R.id.fightingLayout);
tilesLayout = (LinearLayout) findViewById(R.id.tilesLayout);
decisionsLayout = (LinearLayout) findViewById(R.id.decisionsLayout);
commentsLayout = (LinearLayout) findViewById(R.id.commentsLayout);
pageController.setActivity(this);
update(pageController.getPage());
/* Set up onClick listeners for buttons on screen, even if some aren't
* shown at the time.
*/
Button addTileButton = (Button) findViewById(R.id.addTile);
addTileButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
addTileMenu();
}
});
Button addDecisionButton = (Button) findViewById(R.id.addDecision);
addDecisionButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
pageController.addDecision();
}
});
TextView addComment = (TextView) findViewById(R.id.addComment);
addComment.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
onCallComment();
}
});
TextView pageEnding = (TextView) findViewById(R.id.pageEnding);
pageEnding.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
onEditPageEnding(view);
}
});
}
@Override
public void onPause() {
super.onPause();
pageController.deleteActivity();
}
/**
* Create an options menu.
*
* @param menu The menu to create
* @return Success
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
super.onCreateOptionsMenu(menu);
makeMenu(menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
app = (ControllerApp) getApplication();
changeActionBarButtons();
return true;
}
/**
* Puts button for changing to edit mode in the action bar.
* @param menu The Menu to make
*/
public void makeMenu(Menu menu) {
MenuItem editPage = menu.add(0, EDIT_INDEX, EDIT_INDEX, getString(R.string.edit));
MenuItem savePage = menu.add(0, SAVE_INDEX, SAVE_INDEX, getString(R.string.done));
MenuItem help = menu.add(0, HELP_INDEX, HELP_INDEX, getString(R.string.help));
editPage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
savePage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
help.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
/**
* Callback for clicking an item in the menu.
*
* @param item The item that was clicked
* @return Success
*/
public boolean onOptionsItemSelected(MenuItem item)
{
try {
return menuItemClicked(item);
} catch (HandlerException e) {
e.printStackTrace();
}
return true;
}
/**
* Handles what to do when an item of the action bar is pressed.
* @param item The clicked item
* @return
*/
private boolean menuItemClicked(MenuItem item) throws HandlerException {
switch (item.getItemId()) {
case EDIT_INDEX:
final String myId = Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID);
final String storyID = storyController.getStory().getAuthor();
if(myId.equals(storyID)){
app.setEditing(true);
pageController.reloadPage();
changeActionBarButtons();
setButtonVisibility();
}
break;
case SAVE_INDEX:
app.setEditing(false);
storyController.saveStory();
pageController.reloadPage();
changeActionBarButtons();
setButtonVisibility();
break;
case HELP_INDEX:
AlertDialog dialog = null;
if (app.getEditing())
dialog = HelpDialogFactory.create(R.string.edit_page_help, this);
else
dialog = HelpDialogFactory.create(R.string.read_page_help, this);
dialog.show();
break;
}
return true;
}
/**
* Sets which buttons are visible in the action bar.
*/
public void changeActionBarButtons() {
MenuItem editButton = menu.findItem(EDIT_INDEX);
MenuItem saveButton = menu.findItem(SAVE_INDEX);
final String myId = Secure.getString(
getBaseContext().getContentResolver(), Secure.ANDROID_ID);
Story story = storyController.getStory();
final String storyID = story.getAuthor();
if(myId.equals(storyID)){
if (app.getEditing()) {
saveButton.setVisible(true);
editButton.setVisible(false);
} else {
saveButton.setVisible(false);
editButton.setVisible(true);
}
} else {
saveButton.setVisible(false);
editButton.setVisible(false);
}
}
/**
* Show the dialog that allows users to pick which type of tile they would
* like to add.
*/
public void addTileMenu(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog.Builder photoSelector =
new AlertDialog.Builder(this);
final String[] titles = { getString(R.string.textTile), getString(R.string.photoTile),
getString(R.string.videoTile), getString(R.string.audioTile), getString(R.string.cancel) };
final String[] titlesPhoto = { getString(R.string.fromFile), getString(R.string.takePhoto), getString(R.string.cancel) };
builder.setItems(titles, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case(0):
//TODO fix this to be MVC and observer pattern
TextTile tile = new TextTile();
pageController.getPage().addTile(tile);
addTile(pageController.getPage().getTiles().size() - 1, tile);
break;
case(1):
photoSelector.setItems(titlesPhoto,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
switch(item){
case(0):
getPhoto();
break;
case(1):
takePhoto();
break;
}
}});
photoSelector.show();
break;
case(2):
break;
case(3):
break;
}
}});
builder.show();
}
/**
* Updates a page to show any changes that have been made. These
* changes can also include whether the page is in view mode or
* edit mode.
* @param page The current page
*/
public void grabPhoto(){
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, GRAB_PHOTO);
}
public void getPhoto(){
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
public void update(Page page) {
setButtonVisibility();
if (storyController.getStory().isUsesCombat() == true) {
fightView.updateCounters(fightingLayout, app);
}
if (pageController.haveTilesChanged()) {
updateTiles(page);
}
if (pageController.haveDecisionsChanged()) {
updateDecisions(page);
}
if (pageController.haveCommentsChanged()) {
updateComments(page);
}
if (pageController.hasEndingChanged()) {
updateEnding(page);
}
pageController.finishedUpdating();
}
/**
* Handles removing or showing the proper buttons in both the action bar
* and the in the page.
*/
private void setButtonVisibility() {
Button addTileButton = (Button) findViewById(R.id.addTile);
Button addDecisionButton = (Button) findViewById(R.id.addDecision);
final String myId = Secure.getString(
getBaseContext().getContentResolver(), Secure.ANDROID_ID);
final String storyID = storyController.getStory().getAuthor();
if(myId.equals(storyID)){
int visibility = 0;
if (app.getEditing()) {
visibility = View.VISIBLE;
} else {
visibility = View.GONE;
}
addTileButton.setVisibility(visibility);
addDecisionButton.setVisibility(visibility);
} else {
addTileButton.setVisibility(View.GONE);
addDecisionButton.setVisibility(View.GONE);
}
}
/**
* Removes all the tiles from the tilesLayout and repopulates it with
* the current state of the tiles.
* @param page
*/
private void updateTiles(Page page) {
tilesLayout.removeAllViews();
//For each tile in the page, add the tile to tilesLayout
ArrayList<Tile> tiles = page.getTiles();
for (int i = 0; i < tiles.size(); i++) {
addTile(i, tiles.get(i));
}
}
/**
* Removes all the decisions from the decisionsLayout and repopulates it
* with the current state of the decisions.
* @param page
*/
private void updateDecisions(Page page) {
decisionsLayout.removeAllViews();
//For each decision in the page, add it to decisionsLayout
ArrayList<Decision> decisions = page.getDecisions();
for (int i = 0; i < decisions.size(); i++) {
addDecision(i, decisions.get(i));
}
}
private boolean passThreshold(Decision decision) {
int type = decision.getChoiceModifiers().getThresholdType();
int sign = decision.getChoiceModifiers().getThresholdSign();
int value = decision.getChoiceModifiers().getThresholdValue();
Counters counter = storyController.getStory().getPlayerStats();
boolean outcome = false;
int[] typeBase = {counter.getPlayerHpStat(),counter.getEnemyHpStat(),counter.getTreasureStat()};
switch(sign){
case(0):
if(typeBase[type] < value){outcome = true;};
break;
case(1):
if(typeBase[type] > value){outcome = true;};
break;
case(2):
if(typeBase[type] == value){outcome = true;};
break;
}
return outcome;
}
/**
* Removes the comments from commentsLayout and repopulates it with the
* current comments.
* @param page
*/
private void updateComments(Page page) {
commentsLayout.removeAllViews();
//For each comment in the page, add it to commentsLayout
ArrayList<Comment> comments = page.getComments();
for (int i = 0; i < comments.size(); i++) {
addComment(comments.get(i));
}
}
/**
* Updates the pageEnding from the passed page object.
* @param page
*/
private void updateEnding(Page page) {
TextView pageEnding = (TextView) findViewById(R.id.pageEnding);
pageEnding.setText(page.getPageEnding());
}
/**
* Called to display a new tile at position i. If we are in editing mode,
* add a click listener to allow user to edit the tile
* @param i
* @param tile
*/
public void addTile(int i, Tile tile) {
if (tile.getType() == "text") {
View view = makeTileView("text");
TextTile textTile = (TextTile) tile;
TextView textView = (TextView) view;
textView.setText(textTile.getText());
tilesLayout.addView(view, i);
if (app.getEditing()) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
editTileMenu(v);
}
});
view.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
v.startDrag(data, shadowBuilder, v, 0);
return true;
}
});
}
} else if (tile.getType() == "photo") {
View view = makeTileView("photo");
PhotoTile photoTile = (PhotoTile) tile;
ImageView imageView = (ImageView) view;
imageView.setImageBitmap(photoTile.getImage());
tilesLayout.addView(imageView, i);
} else if (tile.getType() == "video") {
// TODO Implement for part 4
} else if (tile.getType() == "audio") {
// TODO Implement for part 4
} else {
Log.d("no such tile", "no tile of type " + tile.getType());
}
}
/**
* Create a view that has the proper padding, and if we are in editing
* mode, adds a small margin to the bottom so we can see a little of
* the layout background which makes a line separating the tile views.
* @return
*/
private View makeTileView(String type) {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
View view;
if (type == "text") {
view = new TextView(this);
} else {
view = new ImageView(this);
}
// Set what the tiles look like
view.setPadding(0, 5, 0, 6);
if (app.getEditing()) {
/* Background to the layout is grey, so adding margins adds
* separators.
*/
lp.setMargins(0, 0, 0, 3);
} else {
view.setPadding(0, 5, 0, 9);
}
view.setBackgroundColor(0xFFFFFFFF);
view.setLayoutParams(lp);
return view;
}
/**
* Brings up a menu with options of what to do to the decision.
* @param view
*/
public void editTileMenu(final View view){
final String[] titles = { getString(R.string.edit), getString(R.string.delete) };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.story_options);
builder.setItems(titles, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
int whichTile = tilesLayout.indexOfChild(view);
switch(item){
case(0):
onEditTile(view);
break;
case(1):
pageController.deleteTile(whichTile);
break;
}
}
});
builder.show();
}
private void takePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PHOTO);
}
private void addPhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, ADD_PHOTO);
}
/**
* Displays a dialog for editing a tile.
* @param view
*/
private void onEditTile(View view) {
final TextView textView = (TextView) view;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText alertEdit = new EditText(this);
alertEdit.setText(textView.getText().toString());
builder.setView(alertEdit);
builder.setPositiveButton(getString(R.string.done), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int whichTile = tilesLayout.indexOfChild(textView);
pageController.updateTile(alertEdit.getText().toString(), whichTile);
}
})
.setNegativeButton(getString(R.string.done), null);
builder.show();
}
/**
* Adds a decision to the page. If we are in editing mode, give the view a
* onClickListener to allow you to edit the decision. If we are in
* viewing mode add an onClickListener to go to the next page.
*
* @param i
* @param decision
*/
private void addDecision(int i, Decision decision) {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
TextView view = new TextView(this);
lp.setMargins(0, 0, 0, 3);
view.setPadding(20, 5, 0, 5);
view.setBackgroundColor(0xFFFFFFFF);
view.setLayoutParams(lp);
view.setText(decision.getText());
decisionsLayout.addView(view, i);
if(pageController.getPage().isFightingFrag() == false){
view.setVisibility(View.VISIBLE);
}
else if(app.getEditing() == true){
view.setVisibility(View.VISIBLE);
}
else{
boolean outcome = passThreshold(decision);
if(outcome == false){
view.setVisibility(View.GONE);
}
}
if (app.getEditing()) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
decisionMenu(v);
}
});
} else {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
decisionClicked(v);
}
});
}
}
/**
* Brings up a menu with options of what to do to the decision.
* @param view
*/
public void decisionMenu(final View view){
final String[] titles;
final String[] titlesBasic = { getString(R.string.editProperties), getString(R.string.delete), getString(R.string.cancel) };
final String[] titlesCounter = { getString(R.string.editProperties), getString(R.string.delete),
getString(R.string.transitionMessages), getString(R.string.cancel) };
final String[] titlesFight = { getString(R.string.editProperties), getString(R.string.delete), getString(R.string.transitionMessages),
getString(R.string.setConditionals), getString(R.string.cancel) };
final boolean fighting = pageController.getPage().isFightingFrag();
final boolean combat = storyController.getStory().isUsesCombat();
if(fighting == true){
titles = titlesFight;
}
else if(combat == true){
titles = titlesCounter;
}
else{
titles = titlesBasic;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.story_options);
builder.setItems(titles, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
int whichDecision = decisionsLayout.indexOfChild(view);
switch(item){
case(0):
onEditDecision(view);
break;
case(1):
pageController.deleteDecision(whichDecision);
break;
case(2):
if(combat == true){
onEditMessages(view);
}
break;
case(3):
if(fighting == true){
onEditConditionals(view);
}
break;
}
}
});
builder.show();
}
protected void onEditMessages(View view) {
final int whichDecision = decisionsLayout.indexOfChild(view);
final Decision decision = pageController.findDecisionByIndex(whichDecision);
ArrayList<Page> pages = storyController.getPages();
int toPagePosition = pageController.findArrayPosition(decision, pages);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.counterMessage));
final LinearLayout layout = (LinearLayout) View.inflate(this, R.layout.edit_messages_dialog, null);
final EditText decisionTitle = (EditText) layout.findViewById(R.id.edit_messages_dialog_decision_edittext);
final EditText dMessage = (EditText) layout.findViewById(R.id.edit_messages_dialog_takeDamage_edittext);
final EditText hMessage = (EditText) layout.findViewById(R.id.edit_messages_dialog_giveDamage_edittext);
final EditText tMessage = (EditText) layout.findViewById(R.id.edit_messages_dialog_coin_edittext);
final Spinner pageSpinner = (Spinner) layout.findViewById(R.id.edit_messages_dialog_page_spinner);
ArrayList<String> pageStrings = app.getPageStrings(pages);
ArrayAdapter<String> pagesAdapter = new ArrayAdapter<String>(this, R.layout.list_item_base, pageStrings);
pageSpinner.setAdapter(pagesAdapter);
pageSpinner.setSelection(toPagePosition);
decisionTitle.setText(decision.getText());
dMessage.setText("" + decision.getChoiceModifiers().getDamageMessage());
hMessage.setText("" + decision.getChoiceModifiers().getHitMessage());
tMessage.setText("" + decision.getChoiceModifiers().getTreasureMessage());
builder.setView(layout);
builder.setPositiveButton(getString(R.string.done), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Counters counter = decision.getChoiceModifiers();
counter.setMessages(dMessage.getText().toString(), tMessage.getText().toString(), hMessage.getText().toString());
app.updateDecisionFight(decisionTitle.getText().toString(), pageSpinner.getSelectedItemPosition(),whichDecision, counter);
}
})
.setNegativeButton(getString(R.string.cancel), null);
builder.show();
}
protected void onEditConditionals(View view) {
final int whichDecision = decisionsLayout.indexOfChild(view);
final Decision decision = pageController.findDecisionByIndex(whichDecision);
ArrayList<Page> pages = storyController.getPages();
int toPagePosition = pageController.findArrayPosition(decision, pages);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.setDecisionConditions));
final LinearLayout layout = (LinearLayout) View.inflate(this, R.layout.edit_conditionals_dialog, null);
final EditText decisionText = (EditText) layout.findViewById(R.id.edit_conditionals_dialog_decision_edittext);
final EditText conditionText = (EditText) layout.findViewById(R.id.edit_conditionals_dialog_threshold_edittext);
final Spinner pageSpinner = (Spinner) layout.findViewById(R.id.edit_conditionals_dialog_page_spinner);
final Spinner condSpinner = (Spinner) layout.findViewById(R.id.edit_conditionals_dialog_type_spinner);
final Spinner signSpinner = (Spinner) layout.findViewById(R.id.edit_conditionals_dialog_op_spinner);
conditionText.setText("" + decision.getChoiceModifiers().getThresholdValue());
decisionText.setText(decision.getText());
ArrayList<String> pageStrings = app.getPageStrings(pages);
ArrayAdapter<String> pagesAdapter = new ArrayAdapter<String>(this, R.layout.list_item_base, pageStrings);
pageSpinner.setAdapter(pagesAdapter);
pageSpinner.setSelection(toPagePosition);
condSpinner.setSelection(decision.getChoiceModifiers().getThresholdType());
signSpinner.setSelection(decision.getChoiceModifiers().getThresholdSign());
builder.setView(layout);
builder.setPositiveButton(getString(R.string.done), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Counters counter = decision.getChoiceModifiers();
counter.setThresholds(signSpinner.getSelectedItemPosition(), condSpinner.getSelectedItemPosition(), conditionText.getText().toString());
app.updateDecisionFight(decisionText.getText().toString(), pageSpinner.getSelectedItemPosition(), whichDecision, counter);
}
})
.setNegativeButton(getString(R.string.cancel), null);
builder.show();
}
/**
* Changes the view so that the next page is showing.
* @param view
*/
private void decisionClicked(View view) {
Story story = storyController.getStory();
Page page = pageController.getPage();
int whichDecision = decisionsLayout.indexOfChild(view);
if(story.isUsesCombat() == true){
Decision decision = page.getDecisions().get(whichDecision);
if(page.isFightingFrag() == true){
story.getPlayerStats().invokeUpdateComplex(decision.getChoiceModifiers());
}
else{
story.getPlayerStats().invokeUpdateSimple(decision.getChoiceModifiers());
}
}
app.followDecision(whichDecision);
}
/**
* Brings up a dialog for editing the decision clicked.
* @param view
*/
private void onEditDecision(View view) {
int whichDecision = decisionsLayout.indexOfChild(view);
final Decision decision = pageController.getPage().getDecisions().get(whichDecision);
final Story story = storyController.getStory();
final Page page = pageController.getPage();
UUID toPageId = decision.getPageID();
ArrayList<Page> pages = story.getPages();
int toPagePosition = -1;
for (int i = 0; i < pages.size(); i++) {
UUID comparePage = pages.get(i).getId();
System.out.println("toPageID: " + toPageId + "\ncomparePage: " + comparePage + "\nPage: " + page + "\nDecision: " + decision.getPageID() + decision.getText());
if (toPageId.equals(comparePage)) {
toPagePosition = i;
break;
}
}
final TextView decisionView = (TextView) view;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.setTextandPage));
final LinearLayout layout = (LinearLayout) View.inflate(this, R.layout.edit_decision_dialog, null);
final LinearLayout combatOptions = (LinearLayout) layout.findViewById(R.id.edit_decision_dialog_page_combatoptions);
final LinearLayout fightOptions = (LinearLayout) layout.findViewById(R.id.edit_decision_dialog_page_fightoptions);
final Spinner pageSpinner = (Spinner) layout.findViewById(R.id.edit_decision_dialog_page_spinner);
final EditText decisionText = (EditText) layout.findViewById(R.id.edit_decision_dialog_decision_edittext);
final EditText alertTreasure = (EditText) layout.findViewById(R.id.edit_decision_dialog_coin_edittext);
final EditText playerDamage = (EditText) layout.findViewById(R.id.edit_decision_dialog_playerDamage_edittext);
final EditText enemyDamage = (EditText) layout.findViewById(R.id.edit_decision_dialog_enemyDamage_edittext);
final SeekBar seekPlayer = (SeekBar) layout.findViewById(R.id.edit_decision_dialog_playerPerc);
final SeekBar seekEnemy = (SeekBar) layout.findViewById(R.id.edit_decision_dialog_enemyPerc);
decisionText.setText(decision.getText());
ArrayList<String> pageStrings = app.getPageStrings(pages);
ArrayAdapter<String> pagesAdapter = new ArrayAdapter<String>(this, R.layout.list_item_base, pageStrings);
if(page.getDecisions().size() > 2){
pageStrings.add(getString(R.string.randomChoice));
}
pageSpinner.setAdapter(pagesAdapter);
pageSpinner.setSelection(toPagePosition);
if(!story.isUsesCombat()) {
combatOptions.setVisibility(View.GONE);
}
else {
alertTreasure.setText("" + decision.getChoiceModifiers().getTreasureStat());
playerDamage.setText("" + decision.getChoiceModifiers().getPlayerHpStat());
if(!page.isFightingFrag()) {
fightOptions.setVisibility(View.GONE);
}
else {
seekPlayer.setProgress(decision.getChoiceModifiers().getPlayerHitPercent());
enemyDamage.setText("" + decision.getChoiceModifiers().getEnemyHpStat());
seekEnemy.setProgress(decision.getChoiceModifiers().getEnemyHitPercent());
}
}
builder.setView(layout);
builder.setPositiveButton(getString(R.string.done), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Counters counter = decision.getChoiceModifiers();
int decisionNumber = decisionsLayout.indexOfChild(decisionView);
if(story.isUsesCombat() == true){
String treasure = alertTreasure.getText().toString();
String hp = playerDamage.getText().toString();
if(page.isFightingFrag() == false){
counter.setBasic(treasure, hp);
app.updateDecisionFight(decisionText.getText().toString(),
pageSpinner.getSelectedItemPosition(), decisionNumber, counter);
}
else{
String ehp = enemyDamage.getText().toString();
String hitP = "" + seekPlayer.getProgress();
String hitE = "" + seekEnemy.getProgress();
counter.setStats(treasure, hp, ehp, hitE, hitP);
app.updateDecisionFight(decisionText.getText().toString(),
pageSpinner.getSelectedItemPosition(), decisionNumber, counter);
}
}
else{
app.updateDecision(decisionText.getText().toString(),
pageSpinner.getSelectedItemPosition(), decisionNumber);
}
}
})
.setNegativeButton(getString(R.string.cancel), null);
builder.show();
}
/**
* Called to display a new comment at position i.
* @param comment
*/
public void addComment(Comment comment) {
final LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 5, 0, 0);
TextView view = new TextView(this);
view.setBackgroundColor(0xFFFFFFFF);
view.setPadding(10, 5, 10, 5);
view.setLayoutParams(lp);
view.setText(comment.getTimestamp() + " - '" + comment.getText() + "'");
layout.addView(view);
if(comment.getAnnotation() != null){
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(comment.getAnnotation().getImage());
imageView.setBackgroundColor(0xFFFFFFFF);
layout.addView(imageView);
}
commentsLayout.addView(layout);
}
/**
* Called when the add comment button is clicked. It creates a dialog that
* allows the user to input text and then save the comment.
* @param view
*/
private void onCallComment(){
final String[] titlesPhoto = { getString(R.string.noImage), getString(R.string.fromFile),
getString(R.string.takePhoto) };
final AlertDialog.Builder photoSelector =
new AlertDialog.Builder(this);
photoSelector.setTitle(getString(R.string.usePhotoComment));
photoSelector.setItems(titlesPhoto,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
switch(item){
case(0):
onEditComment();
break;
case(1):
grabPhoto();
break;
case(2):
addPhoto();
break;
}
}
}
);
photoSelector.show();
}
private void onEditComment() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.whatToSay));
final LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
final EditText alertEdit = new EditText(this);
layout.addView(alertEdit);
final ImageView alertImage = new ImageView(this);
final PhotoTile photoAdd = (PhotoTile) app.getTempSpace();
app.setTempSpace(null);
if(photoAdd != null)
alertImage.setImageBitmap(photoAdd.getImage());
layout.addView(alertImage);
builder.setView(layout);
builder.setPositiveButton(getString(R.string.save), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
app.addComment(alertEdit.getText().toString(),photoAdd );
}
})
.setNegativeButton(getString(R.string.cancel), null);
builder.show();
}
/**
* Opens a dialog that allows the user to edit the pageEnding.
* @param view
*/
private void onEditPageEnding(View view) {
if (app.getEditing()) {
TextView textView = (TextView) view;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText alertEdit = new EditText(this);
alertEdit.setText(textView.getText().toString());
builder.setView(alertEdit);
builder.setPositiveButton(getString(R.string.done), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
pageController.setEnding(alertEdit.getText().toString());
}
})
.setNegativeButton(getString(R.string.cancel), null);
builder.show();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
AlertDialog.Builder successChecker = new AlertDialog.Builder(this);
if (resultCode == RESULT_OK && null != data) {
switch(requestCode) {
case (RESULT_LOAD_IMAGE):
pageController.addTile(loadImage(data));
break;
case (GRAB_PHOTO):
app.setTempSpace(loadImage(data));
onEditComment();
break;
case(TAKE_PHOTO):
final Bitmap image = retrievePhoto(data);
successChecker.setView(makeViewByPhoto(image));
successChecker.setTitle(getString(R.string.retakeQuestion));
successChecker.setPositiveButton(getString(R.string.save),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PhotoTile tile = new PhotoTile();
tile.setContent(image);
pageController.addTile(tile);
}
})
.setNegativeButton(getString(R.string.retake), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
takePhoto();
}
});
successChecker.show();
break;
case(ADD_PHOTO):
final Bitmap image2 = retrievePhoto(data);
successChecker.setView(makeViewByPhoto(image2));
successChecker.setTitle(getString(R.string.retakeQuestion));
successChecker.setPositiveButton(getString(R.string.save),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PhotoTile tile = new PhotoTile();
tile.setContent(image2);
app.setTempSpace(tile);
onEditComment();
}
})
.setNegativeButton(getString(R.string.retake), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
addPhoto();
}
});
successChecker.show();
break;
}}
}
public PhotoTile loadImage(Intent data){
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap pickedPhoto = BitmapFactory.decodeFile(picturePath);
PhotoTile newPhoto = new PhotoTile();
newPhoto.setImageFile(pickedPhoto);
return newPhoto;
}
public Bitmap retrievePhoto(Intent data){
Bundle bundle = data.getExtras();
return (Bitmap) bundle.get("data");
}
public ImageView makeViewByPhoto(Bitmap image){
ImageView pictureTaken = new ImageView(this);
pictureTaken.setImageBitmap(image);
return pictureTaken;
}
}
|
package com.ianhanniballake.contractiontimer.ui;
import android.content.AsyncQueryHandler;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.TextView;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.ianhanniballake.contractiontimer.R;
import com.ianhanniballake.contractiontimer.provider.ContractionContract;
/**
* Fragment to list contractions entered by the user
*/
public class ContractionListFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor>
{
/**
* Cursor Adapter for creating and binding contraction list view items
*/
private class ContractionListCursorAdapter extends CursorAdapter
{
/**
* Local reference to the layout inflater service
*/
private final LayoutInflater inflater;
/**
* @param context
* The context where the ListView associated with this
* SimpleListItemFactory is running
* @param c
* The database cursor. Can be null if the cursor is not
* available yet.
* @param flags
* Flags used to determine the behavior of the adapter, as
* per
* {@link CursorAdapter#CursorAdapter(Context, Cursor, int)}.
*/
public ContractionListCursorAdapter(final Context context,
final Cursor c, final int flags)
{
super(context, c, flags);
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public void bindView(final View view, final Context context,
final Cursor cursor)
{
final TextView startTimeView = (TextView) view
.findViewById(R.id.start_time);
final TextView endTimeView = (TextView) view
.findViewById(R.id.end_time);
final TextView durationView = (TextView) view
.findViewById(R.id.duration);
final TextView frequencyView = (TextView) view
.findViewById(R.id.frequency);
final TextView noteView = (TextView) view.findViewById(R.id.note);
String timeFormat = "hh:mm:ssaa";
if (DateFormat.is24HourFormat(context))
timeFormat = "kk:mm:ss";
final int startTimeColumnIndex = cursor
.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_START_TIME);
final long startTime = cursor.getLong(startTimeColumnIndex);
startTimeView.setText(DateFormat.format(timeFormat, startTime));
final int endTimeColumnIndex = cursor
.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_END_TIME);
if (cursor.isNull(endTimeColumnIndex))
{
endTimeView.setText(" ");
durationView.setText("");
currentContractionStartTime = startTime;
durationView.setTag("durationView");
liveDurationHandler.removeCallbacks(liveDurationUpdate);
liveDurationHandler.post(liveDurationUpdate);
}
else
{
final long endTime = cursor.getLong(endTimeColumnIndex);
endTimeView.setText(DateFormat.format(timeFormat, endTime));
durationView.setTag("");
final long durationInSeconds = (endTime - startTime) / 1000;
durationView.setText(DateUtils
.formatElapsedTime(durationInSeconds));
}
// If we aren't the last entry, move to the next (previous in time)
// contraction to get its start time to compute the frequency
if (!cursor.isLast() && cursor.moveToNext())
{
final int prevContractionStartTimeColumnIndex = cursor
.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_START_TIME);
final long prevContractionStartTime = cursor
.getLong(prevContractionStartTimeColumnIndex);
final long frequencyInSeconds = (startTime - prevContractionStartTime) / 1000;
frequencyView.setText(DateUtils
.formatElapsedTime(frequencyInSeconds));
// Go back to the previous spot
cursor.moveToPrevious();
}
else
frequencyView.setText("");
final int noteColumnIndex = cursor
.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_NOTE);
final String note = cursor.getString(noteColumnIndex);
noteView.setText(note);
if (note.equals(""))
noteView.setVisibility(View.GONE);
else
noteView.setVisibility(View.VISIBLE);
}
@Override
public View newView(final Context context, final Cursor cursor,
final ViewGroup parent)
{
return inflater.inflate(R.layout.list_item_contraction, parent,
false);
}
}
/**
* Adapter to display the list's data
*/
private CursorAdapter adapter;
/**
* Handler for asynchronous deletes of contractions
*/
private AsyncQueryHandler contractionQueryHandler;
/**
* Start time of the current contraction
*/
private long currentContractionStartTime = 0;
/**
* Handler of live duration updates
*/
private final Handler liveDurationHandler = new Handler();
/**
* Reference to the Runnable live duration updater
*/
private final Runnable liveDurationUpdate = new Runnable()
{
/**
* Updates the appropriate duration view to the current elapsed time and
* schedules this to rerun in 1 second
*/
@Override
public void run()
{
final long durationInSeconds = (System.currentTimeMillis() - currentContractionStartTime) / 1000;
final View rootView = getView();
if (rootView != null)
{
final TextView currentContractionDurationView = (TextView) rootView
.findViewWithTag("durationView");
if (currentContractionDurationView != null)
currentContractionDurationView.setText(DateUtils
.formatElapsedTime(durationInSeconds));
}
liveDurationHandler.postDelayed(this, 1000);
}
};
@Override
public void onActivityCreated(final Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setEmptyText(getText(R.string.list_loading));
adapter = new ContractionListCursorAdapter(getActivity(), null, 0);
setListAdapter(adapter);
getListView().setChoiceMode(AbsListView.CHOICE_MODE_NONE);
registerForContextMenu(getListView());
getLoaderManager().initLoader(0, null, this);
}
@Override
public boolean onContextItemSelected(
final android.support.v4.view.MenuItem item)
{
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId())
{
case R.id.menu_context_note:
final TextView noteView = (TextView) info.targetView
.findViewById(R.id.note);
final String existingNote = noteView.getText().toString();
Log.d(getClass().getSimpleName(), "Context Menu selected "
+ (existingNote.equals("") ? "Add Note" : "Edit Note"));
GoogleAnalyticsTracker.getInstance().trackEvent("ContextMenu",
"Note",
existingNote.equals("") ? "Add Note" : "Edit Note",
info.position);
final NoteDialogFragment noteDialogFragment = new NoteDialogFragment(
info.id, existingNote);
noteDialogFragment.show(getFragmentManager(), "note");
return true;
case R.id.menu_context_delete:
Log.d(getClass().getSimpleName(),
"Context Menu selected delete");
GoogleAnalyticsTracker.getInstance().trackEvent("ContextMenu",
"Delete", "", info.position);
final Uri deleteUri = ContentUris.withAppendedId(
ContractionContract.Contractions.CONTENT_ID_URI_BASE,
info.id);
contractionQueryHandler
.startDelete(0, 0, deleteUri, null, null);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
contractionQueryHandler = new AsyncQueryHandler(getActivity()
.getContentResolver())
{
};
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View v,
final ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
final MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.list_context, menu);
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
final TextView noteView = (TextView) info.targetView
.findViewById(R.id.note);
final CharSequence note = noteView.getText();
final MenuItem noteItem = menu.findItem(R.id.menu_context_note);
if (note.equals(""))
noteItem.setTitle(R.string.note_dialog_title_add);
else
noteItem.setTitle(R.string.note_dialog_title_edit);
Log.d(getClass().getSimpleName(), "Context Menu Opened");
GoogleAnalyticsTracker.getInstance().trackEvent("ContextMenu", "Open",
note.equals("") ? "Add Note" : "Edit Note", 0);
}
@Override
public Loader<Cursor> onCreateLoader(final int id, final Bundle args)
{
return new CursorLoader(getActivity(),
ContractionContract.Contractions.CONTENT_ID_URI_BASE, null,
null, null, null);
}
@Override
public View onCreateView(final LayoutInflater inflater,
final ViewGroup container, final Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_contraction_list, container,
false);
}
@Override
public void onLoaderReset(final Loader<Cursor> loader)
{
liveDurationHandler.removeCallbacks(liveDurationUpdate);
adapter.swapCursor(null);
}
@Override
public void onLoadFinished(final Loader<Cursor> loader, final Cursor data)
{
liveDurationHandler.removeCallbacks(liveDurationUpdate);
adapter.swapCursor(data);
if (data.getCount() == 0)
setEmptyText(getText(R.string.list_empty));
else
getListView().setSelection(0);
}
@Override
public void onPause()
{
super.onPause();
liveDurationHandler.removeCallbacks(liveDurationUpdate);
}
@Override
public void setEmptyText(final CharSequence text)
{
final TextView emptyText = (TextView) getListView().getEmptyView();
emptyText.setText(text);
}
}
|
package org.rstudio.studio.client.workbench.views.source;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.logical.shared.*;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.rstudio.core.client.*;
import org.rstudio.core.client.command.AppCommand;
import org.rstudio.core.client.command.Handler;
import org.rstudio.core.client.command.KeyboardShortcut;
import org.rstudio.core.client.command.ShortcutManager;
import org.rstudio.core.client.events.*;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.js.JsObject;
import org.rstudio.core.client.widget.Operation;
import org.rstudio.core.client.widget.OperationWithInput;
import org.rstudio.core.client.widget.ProgressIndicator;
import org.rstudio.core.client.widget.ProgressOperationWithInput;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.Desktop;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.FileDialogs;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.GlobalProgressDelayer;
import org.rstudio.studio.client.common.SimpleRequestCallback;
import org.rstudio.studio.client.common.filetypes.EditableFileType;
import org.rstudio.studio.client.common.filetypes.FileTypeRegistry;
import org.rstudio.studio.client.common.filetypes.TextFileType;
import org.rstudio.studio.client.common.filetypes.events.OpenPresentationSourceFileEvent;
import org.rstudio.studio.client.common.filetypes.events.OpenSourceFileEvent;
import org.rstudio.studio.client.common.filetypes.events.OpenSourceFileEvent.NavigationMethod;
import org.rstudio.studio.client.common.filetypes.events.OpenSourceFileHandler;
import org.rstudio.studio.client.common.rnw.RnwWeave;
import org.rstudio.studio.client.common.rnw.RnwWeaveRegistry;
import org.rstudio.studio.client.common.synctex.Synctex;
import org.rstudio.studio.client.common.synctex.events.SynctexStatusChangedEvent;
import org.rstudio.studio.client.rmarkdown.model.RMarkdownContext;
import org.rstudio.studio.client.rmarkdown.model.RmdChosenTemplate;
import org.rstudio.studio.client.rmarkdown.model.RmdFrontMatter;
import org.rstudio.studio.client.rmarkdown.model.RmdOutputFormat;
import org.rstudio.studio.client.rmarkdown.model.RmdTemplateData;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.VoidServerRequestCallback;
import org.rstudio.studio.client.workbench.FileMRUList;
import org.rstudio.studio.client.workbench.WorkbenchContext;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.model.ClientState;
import org.rstudio.studio.client.workbench.model.RemoteFileSystemContext;
import org.rstudio.studio.client.workbench.model.Session;
import org.rstudio.studio.client.workbench.model.SessionInfo;
import org.rstudio.studio.client.workbench.model.SessionUtils;
import org.rstudio.studio.client.workbench.model.UnsavedChangesTarget;
import org.rstudio.studio.client.workbench.model.helper.IntStateValue;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.snippets.SnippetHelper;
import org.rstudio.studio.client.workbench.snippets.model.SnippetsChangedEvent;
import org.rstudio.studio.client.workbench.ui.unsaved.UnsavedChangesDialog;
import org.rstudio.studio.client.workbench.views.data.events.ViewDataEvent;
import org.rstudio.studio.client.workbench.views.data.events.ViewDataHandler;
import org.rstudio.studio.client.workbench.views.output.find.events.FindInFilesEvent;
import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.EditingTargetSource;
import org.rstudio.studio.client.workbench.views.source.editors.codebrowser.CodeBrowserEditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.data.DataEditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.profiler.ProfilerEditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.profiler.model.ProfilerContents;
import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor;
import org.rstudio.studio.client.workbench.views.source.editors.text.ChunkIconsManager;
import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetPresentationHelper;
import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetRMarkdownHelper;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceEditorNative;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.DisplayChunkOptionsEvent;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.ExecuteChunkEvent;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.FileTypeChangedEvent;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.FileTypeChangedHandler;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.SourceOnSaveChangedEvent;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.SourceOnSaveChangedHandler;
import org.rstudio.studio.client.workbench.views.source.editors.text.ui.NewRMarkdownDialog;
import org.rstudio.studio.client.workbench.views.source.editors.text.ui.NewRdDialog;
import org.rstudio.studio.client.workbench.views.source.events.*;
import org.rstudio.studio.client.workbench.views.source.model.ContentItem;
import org.rstudio.studio.client.workbench.views.source.model.DataItem;
import org.rstudio.studio.client.workbench.views.source.model.RdShellResult;
import org.rstudio.studio.client.workbench.views.source.model.SourceDocument;
import org.rstudio.studio.client.workbench.views.source.model.SourceNavigation;
import org.rstudio.studio.client.workbench.views.source.model.SourceNavigationHistory;
import org.rstudio.studio.client.workbench.views.source.model.SourcePosition;
import org.rstudio.studio.client.workbench.views.source.model.SourceServerOperations;
import java.util.ArrayList;
import java.util.HashSet;
public class Source implements InsertSourceHandler,
IsWidget,
OpenSourceFileHandler,
TabClosingHandler,
TabCloseHandler,
TabReorderHandler,
SelectionHandler<Integer>,
TabClosedHandler,
FileEditHandler,
ShowContentHandler,
ShowDataHandler,
CodeBrowserNavigationHandler,
CodeBrowserFinishedHandler,
CodeBrowserHighlightEvent.Handler,
SourceExtendedTypeDetectedEvent.Handler,
BeforeShowHandler,
SnippetsChangedEvent.Handler
{
public interface Display extends IsWidget,
HasTabClosingHandlers,
HasTabCloseHandlers,
HasTabClosedHandlers,
HasTabReorderHandlers,
HasBeforeSelectionHandlers<Integer>,
HasSelectionHandlers<Integer>
{
void addTab(Widget widget,
ImageResource icon,
String name,
String tooltip,
boolean switchToTab);
void selectTab(int tabIndex);
void selectTab(Widget widget);
int getTabCount();
int getActiveTabIndex();
void closeTab(Widget widget, boolean interactive);
void closeTab(Widget widget, boolean interactive, Command onClosed);
void closeTab(int index, boolean interactive);
void closeTab(int index, boolean interactive, Command onClosed);
void setDirty(Widget widget, boolean dirty);
void manageChevronVisibility();
void showOverflowPopup();
void showUnsavedChangesDialog(
String title,
ArrayList<UnsavedChangesTarget> dirtyTargets,
OperationWithInput<UnsavedChangesDialog.Result> saveOperation,
Command onCancelled);
void ensureVisible();
void renameTab(Widget child,
ImageResource icon,
String value,
String tooltip);
HandlerRegistration addBeforeShowHandler(BeforeShowHandler handler);
}
public interface CPSEditingTargetCommand
{
void execute(EditingTarget editingTarget, Command continuation);
}
@Inject
public Source(Commands commands,
Display view,
SourceServerOperations server,
EditingTargetSource editingTargetSource,
FileTypeRegistry fileTypeRegistry,
GlobalDisplay globalDisplay,
FileDialogs fileDialogs,
RemoteFileSystemContext fileContext,
EventBus events,
final Session session,
Synctex synctex,
WorkbenchContext workbenchContext,
Provider<FileMRUList> pMruList,
UIPrefs uiPrefs,
RnwWeaveRegistry rnwWeaveRegistry,
ChunkIconsManager chunkIconsManager)
{
commands_ = commands;
view_ = view;
server_ = server;
editingTargetSource_ = editingTargetSource;
fileTypeRegistry_ = fileTypeRegistry;
globalDisplay_ = globalDisplay;
fileDialogs_ = fileDialogs;
fileContext_ = fileContext;
rmarkdown_ = new TextEditingTargetRMarkdownHelper();
events_ = events;
session_ = session;
synctex_ = synctex;
workbenchContext_ = workbenchContext;
pMruList_ = pMruList;
uiPrefs_ = uiPrefs;
rnwWeaveRegistry_ = rnwWeaveRegistry;
chunkIconsManager_ = chunkIconsManager;
vimCommands_ = new SourceVimCommands();
view_.addTabClosingHandler(this);
view_.addTabCloseHandler(this);
view_.addTabClosedHandler(this);
view_.addTabReorderHandler(this);
view_.addSelectionHandler(this);
view_.addBeforeShowHandler(this);
dynamicCommands_ = new HashSet<AppCommand>();
dynamicCommands_.add(commands.saveSourceDoc());
dynamicCommands_.add(commands.reopenSourceDocWithEncoding());
dynamicCommands_.add(commands.saveSourceDocAs());
dynamicCommands_.add(commands.saveSourceDocWithEncoding());
dynamicCommands_.add(commands.printSourceDoc());
dynamicCommands_.add(commands.vcsFileLog());
dynamicCommands_.add(commands.vcsFileDiff());
dynamicCommands_.add(commands.vcsFileRevert());
dynamicCommands_.add(commands.executeCode());
dynamicCommands_.add(commands.executeCodeWithoutFocus());
dynamicCommands_.add(commands.executeAllCode());
dynamicCommands_.add(commands.executeToCurrentLine());
dynamicCommands_.add(commands.executeFromCurrentLine());
dynamicCommands_.add(commands.executeCurrentFunction());
dynamicCommands_.add(commands.executeCurrentSection());
dynamicCommands_.add(commands.executeLastCode());
dynamicCommands_.add(commands.insertChunk());
dynamicCommands_.add(commands.insertSection());
dynamicCommands_.add(commands.executePreviousChunks());
dynamicCommands_.add(commands.executeCurrentChunk());
dynamicCommands_.add(commands.executeNextChunk());
dynamicCommands_.add(commands.sourceActiveDocument());
dynamicCommands_.add(commands.sourceActiveDocumentWithEcho());
dynamicCommands_.add(commands.usingRMarkdownHelp());
dynamicCommands_.add(commands.authoringRPresentationsHelp());
dynamicCommands_.add(commands.knitDocument());
dynamicCommands_.add(commands.previewHTML());
dynamicCommands_.add(commands.compilePDF());
dynamicCommands_.add(commands.compileNotebook());
dynamicCommands_.add(commands.synctexSearch());
dynamicCommands_.add(commands.popoutDoc());
dynamicCommands_.add(commands.findReplace());
dynamicCommands_.add(commands.findNext());
dynamicCommands_.add(commands.findPrevious());
dynamicCommands_.add(commands.findFromSelection());
dynamicCommands_.add(commands.replaceAndFind());
dynamicCommands_.add(commands.extractFunction());
dynamicCommands_.add(commands.extractLocalVariable());
dynamicCommands_.add(commands.commentUncomment());
dynamicCommands_.add(commands.reindent());
dynamicCommands_.add(commands.reflowComment());
dynamicCommands_.add(commands.jumpTo());
dynamicCommands_.add(commands.jumpToMatching());
dynamicCommands_.add(commands.goToHelp());
dynamicCommands_.add(commands.goToFunctionDefinition());
dynamicCommands_.add(commands.setWorkingDirToActiveDoc());
dynamicCommands_.add(commands.debugDumpContents());
dynamicCommands_.add(commands.debugImportDump());
dynamicCommands_.add(commands.goToLine());
dynamicCommands_.add(commands.checkSpelling());
dynamicCommands_.add(commands.codeCompletion());
dynamicCommands_.add(commands.findUsages());
dynamicCommands_.add(commands.rcppHelp());
dynamicCommands_.add(commands.debugBreakpoint());
dynamicCommands_.add(commands.vcsViewOnGitHub());
dynamicCommands_.add(commands.vcsBlameOnGitHub());
dynamicCommands_.add(commands.editRmdFormatOptions());
dynamicCommands_.add(commands.reformatCode());
dynamicCommands_.add(commands.showDiagnosticsActiveDocument());
dynamicCommands_.add(commands.insertRoxygenSkeleton());
for (AppCommand command : dynamicCommands_)
{
command.setVisible(false);
command.setEnabled(false);
}
// fake shortcuts for commands which we handle at a lower level
commands.goToHelp().setShortcut(new KeyboardShortcut(112));
commands.goToFunctionDefinition().setShortcut(new KeyboardShortcut(113));
commands.codeCompletion().setShortcut(
new KeyboardShortcut(KeyCodes.KEY_TAB));
if (BrowseCap.isMacintosh())
{
ShortcutManager.INSTANCE.register(
KeyboardShortcut.META | KeyboardShortcut.ALT,
192,
commands.executeNextChunk(),
"Execute",
commands.executeNextChunk().getMenuLabel(false),
"");
}
events.addHandler(ShowContentEvent.TYPE, this);
events.addHandler(ShowDataEvent.TYPE, this);
events.addHandler(ViewDataEvent.TYPE, new ViewDataHandler()
{
public void onViewData(ViewDataEvent event)
{
server_.newDocument(
FileTypeRegistry.DATAFRAME.getTypeId(),
null,
JsObject.createJsObject(),
new SimpleRequestCallback<SourceDocument>("Edit Data Frame") {
public void onResponseReceived(SourceDocument response)
{
addTab(response);
}
});
}
});
events.addHandler(CodeBrowserNavigationEvent.TYPE, this);
events.addHandler(CodeBrowserFinishedEvent.TYPE, this);
events.addHandler(CodeBrowserHighlightEvent.TYPE, this);
events.addHandler(FileTypeChangedEvent.TYPE, new FileTypeChangedHandler()
{
public void onFileTypeChanged(FileTypeChangedEvent event)
{
manageCommands();
}
});
events.addHandler(SourceOnSaveChangedEvent.TYPE,
new SourceOnSaveChangedHandler() {
@Override
public void onSourceOnSaveChanged(SourceOnSaveChangedEvent event)
{
manageSaveCommands();
}
});
events.addHandler(SwitchToDocEvent.TYPE, new SwitchToDocHandler()
{
public void onSwitchToDoc(SwitchToDocEvent event)
{
ensureVisible(false);
setPhysicalTabIndex(event.getSelectedIndex());
}
});
events.addHandler(SourceFileSavedEvent.TYPE, new SourceFileSavedHandler()
{
public void onSourceFileSaved(SourceFileSavedEvent event)
{
pMruList_.get().add(event.getPath());
}
});
events.addHandler(SourceNavigationEvent.TYPE,
new SourceNavigationHandler() {
@Override
public void onSourceNavigation(SourceNavigationEvent event)
{
if (!suspendSourceNavigationAdding_)
{
sourceNavigationHistory_.add(event.getNavigation());
}
}
});
events.addHandler(SourceExtendedTypeDetectedEvent.TYPE, this);
sourceNavigationHistory_.addChangeHandler(new ChangeHandler()
{
@Override
public void onChange(ChangeEvent event)
{
manageSourceNavigationCommands();
}
});
events.addHandler(SynctexStatusChangedEvent.TYPE,
new SynctexStatusChangedEvent.Handler()
{
@Override
public void onSynctexStatusChanged(SynctexStatusChangedEvent event)
{
manageSynctexCommands();
}
});
events.addHandler(ExecuteChunkEvent.TYPE, new ExecuteChunkEvent.Handler()
{
@Override
public void onExecuteChunk(ExecuteChunkEvent event)
{
if (activeEditor_ == null)
return;
if (!(activeEditor_ instanceof TextEditingTarget))
return;
TextEditingTarget target = (TextEditingTarget) activeEditor_;
Position position =
target.screenCoordinatesToDocumentPosition(
event.getPageX(), event.getPageY());
target.executeChunk(position);
target.focus();
}
});
// Suppress 'CTRL + ALT + SHIFT + click' to work around #2483 in Ace
Event.addNativePreviewHandler(new NativePreviewHandler()
{
@Override
public void onPreviewNativeEvent(NativePreviewEvent event)
{
int type = event.getTypeInt();
if (type == Event.ONMOUSEDOWN || type == Event.ONMOUSEUP)
{
int modifier = KeyboardShortcut.getModifierValue(event.getNativeEvent());
if (modifier == (KeyboardShortcut.ALT | KeyboardShortcut.CTRL | KeyboardShortcut.SHIFT))
{
event.cancel();
return;
}
}
}
});
restoreDocuments(session);
new IntStateValue(MODULE_SOURCE, KEY_ACTIVETAB, ClientState.PROJECT_PERSISTENT,
session.getSessionInfo().getClientState())
{
@Override
protected void onInit(Integer value)
{
if (value == null)
return;
if (value >= 0 && view_.getTabCount() > value)
view_.selectTab(value);
if (view_.getTabCount() > 0 && view_.getActiveTabIndex() >= 0)
{
editors_.get(view_.getActiveTabIndex()).onInitiallyLoaded();
}
// clear the history manager
sourceNavigationHistory_.clear();
}
@Override
protected Integer getValue()
{
return getPhysicalTabIndex();
}
};
uiPrefs_.verticallyAlignArgumentIndent().bind(new CommandWithArg<Boolean>()
{
@Override
public void execute(Boolean arg)
{
AceEditorNative.setVerticallyAlignFunctionArgs(arg);
}
});
// adjust shortcuts when vim mode changes
uiPrefs_.useVimMode().bind(new CommandWithArg<Boolean>()
{
@Override
public void execute(Boolean arg)
{
ShortcutManager.INSTANCE.setEditorMode(arg ?
KeyboardShortcut.MODE_VIM :
KeyboardShortcut.MODE_NONE);
}
});
initialized_ = true;
// As tabs were added before, manageCommands() was suppressed due to
// initialized_ being false, so we need to run it explicitly
manageCommands();
// Same with this event
fireDocTabsChanged();
// open project docs
openProjectDocs(session);
// add vim commands
initVimCommands();
// handle chunk options event
handleChunkOptionsEvent();
}
private void initVimCommands()
{
vimCommands_.save(this);
vimCommands_.selectNextTab(this);
vimCommands_.selectPreviousTab(this);
vimCommands_.closeActiveTab(this);
vimCommands_.closeAllTabs(this);
vimCommands_.createNewDocument(this);
vimCommands_.saveAndCloseActiveTab(this);
vimCommands_.readFile(this, uiPrefs_.defaultEncoding().getValue());
vimCommands_.runRScript(this);
vimCommands_.reflowText(this);
vimCommands_.showVimHelp(
RStudioGinjector.INSTANCE.getShortcutViewer());
vimCommands_.showHelpAtCursor(this);
vimCommands_.reindent(this);
}
private void closeAllTabs(boolean interactive)
{
if (interactive)
{
// call into the interactive tab closer
onCloseAllSourceDocs();
}
else
{
// revert unsaved targets and close tabs
revertUnsavedTargets(new Command()
{
@Override
public void execute()
{
// documents have been reverted; we can close
cpsExecuteForEachEditor(editors_,
new CPSEditingTargetCommand()
{
@Override
public void execute(EditingTarget editingTarget,
Command continuation)
{
view_.closeTab(
editingTarget.asWidget(),
false,
continuation);
}
});
}
});
}
}
private void saveActiveSourceDoc()
{
if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget)
{
TextEditingTarget target = (TextEditingTarget) activeEditor_;
target.save();
}
}
private void saveAndCloseActiveSourceDoc()
{
if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget)
{
TextEditingTarget target = (TextEditingTarget) activeEditor_;
target.save(new Command()
{
@Override
public void execute()
{
onCloseSourceDoc();
}
});
}
}
/**
* @param isNewTabPending True if a new tab is about to be created. (If
* false and there are no tabs already, then a new source doc might
* be created to make sure we don't end up with a source pane showing
* with no tabs in it.)
*/
private void ensureVisible(boolean isNewTabPending)
{
newTabPending_++;
try
{
view_.ensureVisible();
}
finally
{
newTabPending_
}
}
public Widget asWidget()
{
return view_.asWidget();
}
private void restoreDocuments(final Session session)
{
final JsArray<SourceDocument> docs =
session.getSessionInfo().getSourceDocuments();
for (int i = 0; i < docs.length(); i++)
{
addTab(docs.get(i));
}
}
private void openProjectDocs(final Session session)
{
JsArrayString openDocs = session.getSessionInfo().getProjectOpenDocs();
if (openDocs.length() > 0)
{
// set new tab pending for the duration of the continuation
newTabPending_++;
// create a continuation for opening the source docs
SerializedCommandQueue openCommands = new SerializedCommandQueue();
for (int i=0; i<openDocs.length(); i++)
{
String doc = openDocs.get(i);
final FileSystemItem fsi = FileSystemItem.createFile(doc);
openCommands.addCommand(new SerializedCommand() {
@Override
public void onExecute(final Command continuation)
{
openFile(fsi,
fileTypeRegistry_.getTextTypeForFile(fsi),
new CommandWithArg<EditingTarget>() {
@Override
public void execute(EditingTarget arg)
{
continuation.execute();
}
});
}
});
}
// decrement newTabPending and select first tab when done
openCommands.addCommand(new SerializedCommand() {
@Override
public void onExecute(Command continuation)
{
newTabPending_
onFirstTab();
continuation.execute();
}
});
// execute the continuation
openCommands.run();
}
}
public void onShowContent(ShowContentEvent event)
{
ensureVisible(true);
ContentItem content = event.getContent();
server_.newDocument(
FileTypeRegistry.URLCONTENT.getTypeId(),
null,
(JsObject) content.cast(),
new SimpleRequestCallback<SourceDocument>("Show")
{
@Override
public void onResponseReceived(SourceDocument response)
{
addTab(response);
}
});
}
public void onShowData(ShowDataEvent event)
{
DataItem data = event.getData();
for (int i = 0; i < editors_.size(); i++)
{
String path = editors_.get(i).getPath();
if (path != null && path.equals(data.getURI()))
{
((DataEditingTarget)editors_.get(i)).updateData(data);
ensureVisible(false);
view_.selectTab(i);
return;
}
}
ensureVisible(true);
server_.newDocument(
FileTypeRegistry.DATAFRAME.getTypeId(),
null,
(JsObject) data.cast(),
new SimpleRequestCallback<SourceDocument>("Show Data Frame")
{
@Override
public void onResponseReceived(SourceDocument response)
{
addTab(response);
}
});
}
@Handler
public void onShowProfiler()
{
// first try to activate existing
for (int idx = 0; idx < editors_.size(); idx++)
{
String path = editors_.get(idx).getPath();
if (ProfilerEditingTarget.PATH.equals(path))
{
ensureVisible(false);
view_.selectTab(idx);
return;
}
}
// create new profiler
ensureVisible(true);
server_.newDocument(
FileTypeRegistry.PROFILER.getTypeId(),
null,
(JsObject) ProfilerContents.createDefault().cast(),
new SimpleRequestCallback<SourceDocument>("Show Profiler")
{
@Override
public void onResponseReceived(SourceDocument response)
{
addTab(response);
}
});
}
@Handler
public void onNewSourceDoc()
{
newDoc(FileTypeRegistry.R, null);
}
@Handler
public void onNewTextDoc()
{
newDoc(FileTypeRegistry.TEXT, null);
}
@Handler
public void onNewCppDoc()
{
if (uiPrefs_.useRcppTemplate().getValue())
{
newSourceDocWithTemplate(
FileTypeRegistry.CPP,
"",
"rcpp.cpp",
Position.create(0, 0),
new CommandWithArg<EditingTarget> () {
@Override
public void execute(EditingTarget target)
{
target.verifyCppPrerequisites();
}
}
);
}
else
{
newDoc(FileTypeRegistry.CPP,
new ResultCallback<EditingTarget, ServerError> () {
@Override
public void onSuccess(EditingTarget target)
{
target.verifyCppPrerequisites();
}
});
}
}
@Handler
public void onNewSweaveDoc()
{
// set concordance value if we need to
String concordance = new String();
if (uiPrefs_.alwaysEnableRnwConcordance().getValue())
{
RnwWeave activeWeave = rnwWeaveRegistry_.findTypeIgnoreCase(
uiPrefs_.defaultSweaveEngine().getValue());
if (activeWeave.getInjectConcordance())
concordance = "\\SweaveOpts{concordance=TRUE}\n";
}
final String concordanceValue = concordance;
// show progress
final ProgressIndicator indicator = new GlobalProgressDelayer(
globalDisplay_, 500, "Creating new document...").getIndicator();
// get the template
server_.getSourceTemplate("",
"sweave.Rnw",
new ServerRequestCallback<String>() {
@Override
public void onResponseReceived(String templateContents)
{
indicator.onCompleted();
// add in concordance if necessary
final boolean hasConcordance = concordanceValue.length() > 0;
if (hasConcordance)
{
String beginDoc = "\\begin{document}\n";
templateContents = templateContents.replace(
beginDoc,
beginDoc + concordanceValue);
}
newDoc(FileTypeRegistry.SWEAVE,
templateContents,
new ResultCallback<EditingTarget, ServerError> () {
@Override
public void onSuccess(EditingTarget target)
{
int startRow = 4 + (hasConcordance ? 1 : 0);
target.setCursorPosition(Position.create(startRow, 0));
}
});
}
@Override
public void onError(ServerError error)
{
indicator.onError(error.getUserMessage());
}
});
}
@Handler
public void onNewRMarkdownDoc()
{
SessionInfo sessionInfo = session_.getSessionInfo();
boolean useRMarkdownV2 = sessionInfo.getRMarkdownPackageAvailable();
if (useRMarkdownV2)
newRMarkdownV2Doc();
else
newRMarkdownV1Doc();
}
@Handler
public void onNewRHTMLDoc()
{
newSourceDocWithTemplate(FileTypeRegistry.RHTML,
"",
"r_html.Rhtml");
}
@Handler
public void onNewRDocumentationDoc()
{
new NewRdDialog(
new OperationWithInput<NewRdDialog.Result>() {
@Override
public void execute(final NewRdDialog.Result result)
{
final Command createEmptyDoc = new Command() {
@Override
public void execute()
{
newSourceDocWithTemplate(FileTypeRegistry.RD,
result.name,
"r_documentation_empty.Rd",
Position.create(3, 7));
}
};
if (!result.type.equals(NewRdDialog.Result.TYPE_NONE))
{
server_.createRdShell(
result.name,
result.type,
new SimpleRequestCallback<RdShellResult>() {
@Override
public void onResponseReceived(RdShellResult result)
{
if (result.getPath() != null)
{
fileTypeRegistry_.openFile(
FileSystemItem.createFile(result.getPath()));
}
else if (result.getContents() != null)
{
newDoc(FileTypeRegistry.RD,
result.getContents(),
null);
}
else
{
createEmptyDoc.execute();
}
}
});
}
else
{
createEmptyDoc.execute();
}
}
}).showModal();
}
@Handler
public void onNewRPresentationDoc()
{
fileDialogs_.saveFile(
"New R Presentation",
fileContext_,
workbenchContext_.getDefaultFileDialogDir(),
".Rpres",
true,
new ProgressOperationWithInput<FileSystemItem>() {
@Override
public void execute(final FileSystemItem input,
final ProgressIndicator indicator)
{
if (input == null)
{
indicator.onCompleted();
return;
}
indicator.onProgress("Creating Presentation...");
server_.createNewPresentation(
input.getPath(),
new VoidServerRequestCallback(indicator) {
@Override
public void onSuccess()
{
openFile(input,
FileTypeRegistry.RPRESENTATION,
new CommandWithArg<EditingTarget>() {
@Override
public void execute(EditingTarget arg)
{
server_.showPresentationPane(
input.getPath(),
new VoidServerRequestCallback());
}
});
}
});
}
});
}
private void newRMarkdownV1Doc()
{
newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN,
"",
"r_markdown.Rmd",
Position.create(3, 0));
}
private void newRMarkdownV2Doc()
{
rmarkdown_.withRMarkdownPackage(
"Creating R Markdown documents",
false,
new CommandWithArg<RMarkdownContext>(){
@Override
public void execute(RMarkdownContext context)
{
new NewRMarkdownDialog(
context,
workbenchContext_,
uiPrefs_.documentAuthor().getGlobalValue(),
new OperationWithInput<NewRMarkdownDialog.Result>()
{
@Override
public void execute(final NewRMarkdownDialog.Result result)
{
if (result.isNewDocument())
{
NewRMarkdownDialog.RmdNewDocument doc =
result.getNewDocument();
String author = doc.getAuthor();
if (author.length() > 0)
{
uiPrefs_.documentAuthor().setGlobalValue(author);
uiPrefs_.writeUIPrefs();
}
newRMarkdownV2Doc(doc);
}
else
{
newDocFromRmdTemplate(result);
}
}
}
).showModal();
}
}
);
}
private void newDocFromRmdTemplate(final NewRMarkdownDialog.Result result)
{
final RmdChosenTemplate template = result.getFromTemplate();
if (template.createDir())
{
rmarkdown_.createDraftFromTemplate(template);
return;
}
rmarkdown_.getTemplateContent(template,
new OperationWithInput<String>() {
@Override
public void execute(final String content)
{
if (content.length() == 0)
globalDisplay_.showErrorMessage("Template Content Missing",
"The template at " + template.getTemplatePath() +
" is missing.");
newDoc(FileTypeRegistry.RMARKDOWN, content, null);
}
});
}
private void newRMarkdownV2Doc(
final NewRMarkdownDialog.RmdNewDocument doc)
{
rmarkdown_.frontMatterToYAML((RmdFrontMatter)doc.getJSOResult().cast(),
null,
new CommandWithArg<String>()
{
@Override
public void execute(final String yaml)
{
String template = "";
// select a template appropriate to the document type we're creating
if (doc.getTemplate().equals(RmdTemplateData.PRESENTATION_TEMPLATE))
template = "r_markdown_v2_presentation.Rmd";
else if (doc.isShiny())
{
if (doc.getFormat().endsWith(
RmdOutputFormat.OUTPUT_PRESENTATION_SUFFIX))
template = "r_markdown_presentation_shiny.Rmd";
else
template = "r_markdown_shiny.Rmd";
}
else
template = "r_markdown_v2.Rmd";
newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN,
"",
template,
Position.create(1, 0),
null,
new TransformerCommand<String>()
{
@Override
public String transform(String input)
{
return RmdFrontMatter.FRONTMATTER_SEPARATOR +
yaml +
RmdFrontMatter.FRONTMATTER_SEPARATOR + "\n" +
input;
}
});
}
});
}
private void newSourceDocWithTemplate(final TextFileType fileType,
String name,
String template)
{
newSourceDocWithTemplate(fileType, name, template, null);
}
private void newSourceDocWithTemplate(final TextFileType fileType,
String name,
String template,
final Position cursorPosition)
{
newSourceDocWithTemplate(fileType, name, template, cursorPosition, null);
}
private void newSourceDocWithTemplate(
final TextFileType fileType,
String name,
String template,
final Position cursorPosition,
final CommandWithArg<EditingTarget> onSuccess)
{
newSourceDocWithTemplate(fileType, name, template, cursorPosition, onSuccess, null);
}
private void newSourceDocWithTemplate(
final TextFileType fileType,
String name,
String template,
final Position cursorPosition,
final CommandWithArg<EditingTarget> onSuccess,
final TransformerCommand<String> contentTransformer)
{
final ProgressIndicator indicator = new GlobalProgressDelayer(
globalDisplay_, 500, "Creating new document...").getIndicator();
server_.getSourceTemplate(name,
template,
new ServerRequestCallback<String>() {
@Override
public void onResponseReceived(String templateContents)
{
indicator.onCompleted();
if (contentTransformer != null)
templateContents = contentTransformer.transform(templateContents);
newDoc(fileType,
templateContents,
new ResultCallback<EditingTarget, ServerError> () {
@Override
public void onSuccess(EditingTarget target)
{
if (cursorPosition != null)
target.setCursorPosition(cursorPosition);
if (onSuccess != null)
onSuccess.execute(target);
}
});
}
@Override
public void onError(ServerError error)
{
indicator.onError(error.getUserMessage());
}
});
}
private void newDoc(EditableFileType fileType,
ResultCallback<EditingTarget, ServerError> callback)
{
newDoc(fileType, null, callback);
}
private void newDoc(EditableFileType fileType,
final String contents,
final ResultCallback<EditingTarget, ServerError> resultCallback)
{
ensureVisible(true);
server_.newDocument(
fileType.getTypeId(),
contents,
JsObject.createJsObject(),
new SimpleRequestCallback<SourceDocument>(
"Error Creating New Document")
{
@Override
public void onResponseReceived(SourceDocument newDoc)
{
EditingTarget target = addTab(newDoc);
if (contents != null)
{
target.forceSaveCommandActive();
manageSaveCommands();
}
if (resultCallback != null)
resultCallback.onSuccess(target);
}
@Override
public void onError(ServerError error)
{
if (resultCallback != null)
resultCallback.onFailure(error);
}
});
}
@Handler
public void onFindInFiles()
{
String searchPattern = "";
if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget)
{
TextEditingTarget textEditor = (TextEditingTarget) activeEditor_;
String selection = textEditor.getSelectedText();
boolean multiLineSelection = selection.indexOf('\n') != -1;
if ((selection.length() != 0) && !multiLineSelection)
searchPattern = selection;
}
events_.fireEvent(new FindInFilesEvent(searchPattern));
}
@Handler
public void onActivateSource()
{
if (activeEditor_ == null)
{
newDoc(FileTypeRegistry.R, new ResultCallback<EditingTarget, ServerError>()
{
@Override
public void onSuccess(EditingTarget target)
{
activeEditor_ = target;
doActivateSource();
}
});
}
else
{
doActivateSource();
}
}
private void doActivateSource()
{
ensureVisible(false);
if (activeEditor_ != null)
{
activeEditor_.focus();
activeEditor_.ensureCursorVisible();
}
}
@Handler
public void onSwitchToTab()
{
if (view_.getTabCount() == 0)
return;
ensureVisible(false);
view_.showOverflowPopup();
}
@Handler
public void onFirstTab()
{
if (view_.getTabCount() == 0)
return;
ensureVisible(false);
if (view_.getTabCount() > 0)
setPhysicalTabIndex(0);
}
@Handler
public void onPreviousTab()
{
if (view_.getTabCount() == 0)
return;
ensureVisible(false);
int index = getPhysicalTabIndex();
if (index >= 1)
setPhysicalTabIndex(index - 1);
}
@Handler
public void onNextTab()
{
if (view_.getTabCount() == 0)
return;
ensureVisible(false);
int index = getPhysicalTabIndex();
if (index < view_.getTabCount() - 1)
setPhysicalTabIndex(index + 1);
}
@Handler
public void onLastTab()
{
if (view_.getTabCount() == 0)
return;
ensureVisible(false);
if (view_.getTabCount() > 0)
setPhysicalTabIndex(view_.getTabCount() - 1);
}
@Handler
public void onCloseSourceDoc()
{
closeSourceDoc(true);
}
void closeSourceDoc(boolean interactive)
{
if (view_.getTabCount() == 0)
return;
view_.closeTab(view_.getActiveTabIndex(), interactive);
}
/**
* Execute the given command for each editor, using continuation-passing
* style. When executed, the CPSEditingTargetCommand needs to execute its
* own Command parameter to continue the iteration.
* @param command The command to run on each EditingTarget
*/
private void cpsExecuteForEachEditor(ArrayList<EditingTarget> editors,
final CPSEditingTargetCommand command,
final Command completedCommand)
{
SerializedCommandQueue queue = new SerializedCommandQueue();
// Clone editors_, since the original may be mutated during iteration
for (final EditingTarget editor : new ArrayList<EditingTarget>(editors))
{
queue.addCommand(new SerializedCommand()
{
@Override
public void onExecute(Command continuation)
{
command.execute(editor, continuation);
}
});
}
if (completedCommand != null)
{
queue.addCommand(new SerializedCommand() {
public void onExecute(Command continuation)
{
completedCommand.execute();
continuation.execute();
}
});
}
}
private void cpsExecuteForEachEditor(ArrayList<EditingTarget> editors,
final CPSEditingTargetCommand command)
{
cpsExecuteForEachEditor(editors, command, null);
}
@Handler
public void onSaveAllSourceDocs()
{
cpsExecuteForEachEditor(editors_, new CPSEditingTargetCommand()
{
@Override
public void execute(EditingTarget target, Command continuation)
{
if (target.dirtyState().getValue())
{
target.save(continuation);
}
else
{
continuation.execute();
}
}
});
}
private void saveEditingTargetsWithPrompt(
String title,
ArrayList<EditingTarget> editingTargets,
final Command onCompleted,
final Command onCancelled)
{
// execute on completed right away if the list is empty
if (editingTargets.size() == 0)
{
onCompleted.execute();
}
// if there is just one thing dirty then go straight to the save dialog
else if (editingTargets.size() == 1)
{
editingTargets.get(0).saveWithPrompt(onCompleted, onCancelled);
}
// otherwise use the multi save changes dialog
else
{
// convert to UnsavedChangesTarget collection
ArrayList<UnsavedChangesTarget> unsavedTargets =
new ArrayList<UnsavedChangesTarget>();
unsavedTargets.addAll(editingTargets);
// show dialog
view_.showUnsavedChangesDialog(
title,
unsavedTargets,
new OperationWithInput<UnsavedChangesDialog.Result>()
{
@Override
public void execute(UnsavedChangesDialog.Result result)
{
saveChanges(result.getSaveTargets(), onCompleted);
}
},
onCancelled);
}
}
private void saveChanges(ArrayList<UnsavedChangesTarget> targets,
Command onCompleted)
{
// convert back to editing targets
ArrayList<EditingTarget> saveTargets =
new ArrayList<EditingTarget>();
for (UnsavedChangesTarget target: targets)
{
EditingTarget saveTarget =
getEditingTargetForId(target.getId());
if (saveTarget != null)
saveTargets.add(saveTarget);
}
// execute the save
cpsExecuteForEachEditor(
// targets the user chose to save
saveTargets,
// save each editor
new CPSEditingTargetCommand()
{
@Override
public void execute(EditingTarget saveTarget,
Command continuation)
{
saveTarget.save(continuation);
}
},
// onCompleted at the end
onCompleted
);
}
private EditingTarget getEditingTargetForId(String id)
{
for (EditingTarget target : editors_)
if (id.equals(target.getId()))
return target;
return null;
}
@Handler
public void onCloseAllSourceDocs()
{
closeAllSourceDocs("Close All", null);
}
public void closeAllSourceDocs(String caption, Command onCompleted)
{
// collect up a list of dirty documents
ArrayList<EditingTarget> dirtyTargets = new ArrayList<EditingTarget>();
for (EditingTarget target : editors_)
if (target.dirtyState().getValue())
dirtyTargets.add(target);
// create a command used to close all tabs
final Command closeAllTabsCommand = new Command()
{
@Override
public void execute()
{
cpsExecuteForEachEditor(editors_, new CPSEditingTargetCommand()
{
@Override
public void execute(EditingTarget target, Command continuation)
{
view_.closeTab(target.asWidget(), false, continuation);
}
});
}
};
// save targets
saveEditingTargetsWithPrompt(caption,
dirtyTargets,
CommandUtil.join(closeAllTabsCommand,
onCompleted),
null);
}
private boolean isUnsavedFileBackedTarget(EditingTarget target)
{
return target.dirtyState().getValue() && (target.getPath() != null);
}
public ArrayList<UnsavedChangesTarget> getUnsavedChanges()
{
ArrayList<UnsavedChangesTarget> targets =
new ArrayList<UnsavedChangesTarget>();
for (EditingTarget target : editors_)
if (isUnsavedFileBackedTarget(target))
targets.add(target);
return targets;
}
public void saveAllUnsaved(Command onCompleted)
{
saveChanges(getUnsavedChanges(), onCompleted);
}
public void saveWithPrompt(UnsavedChangesTarget target,
Command onCompleted,
Command onCancelled)
{
EditingTarget editingTarget = getEditingTargetForId(target.getId());
if (editingTarget != null)
editingTarget.saveWithPrompt(onCompleted, onCancelled);
}
public void handleUnsavedChangesBeforeExit(
ArrayList<UnsavedChangesTarget> saveTargets,
final Command onCompleted)
{
// first handle saves, then revert unsaved, then callback on completed
saveChanges(saveTargets, new Command() {
@Override
public void execute()
{
// revert unsaved
revertUnsavedTargets(onCompleted);
}
});
}
private void revertActiveDocument()
{
if (activeEditor_ == null)
return;
if (activeEditor_.getPath() != null)
activeEditor_.revertChanges(null);
// Ensure that the document is in view
activeEditor_.ensureCursorVisible();
}
private void revertUnsavedTargets(Command onCompleted)
{
// collect up unsaved targets
ArrayList<EditingTarget> unsavedTargets = new ArrayList<EditingTarget>();
for (EditingTarget target : editors_)
if (isUnsavedFileBackedTarget(target))
unsavedTargets.add(target);
// revert all of them
cpsExecuteForEachEditor(
// targets the user chose not to save
unsavedTargets,
// save each editor
new CPSEditingTargetCommand()
{
@Override
public void execute(EditingTarget saveTarget,
Command continuation)
{
if (saveTarget.getPath() != null)
{
// file backed document -- revert it
saveTarget.revertChanges(continuation);
}
else
{
// untitled document -- just close the tab non-interactively
view_.closeTab(saveTarget.asWidget(), false, continuation);
}
}
},
// onCompleted at the end
onCompleted
);
}
@Handler
public void onOpenSourceDoc()
{
fileDialogs_.openFile(
"Open File",
fileContext_,
workbenchContext_.getDefaultFileDialogDir(),
new ProgressOperationWithInput<FileSystemItem>()
{
public void execute(final FileSystemItem input,
ProgressIndicator indicator)
{
if (input == null)
return;
workbenchContext_.setDefaultFileDialogDir(
input.getParentPath());
indicator.onCompleted();
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
public void execute()
{
fileTypeRegistry_.openFile(input);
}
});
}
});
}
public void onOpenSourceFile(OpenSourceFileEvent event)
{
doOpenSourceFile(event.getFile(),
event.getFileType(),
event.getPosition(),
null,
event.getNavigationMethod(),
false);
}
public void onOpenPresentationSourceFile(OpenPresentationSourceFileEvent event)
{
// don't do the navigation if the active document is a source
// file from this presentation module
doOpenSourceFile(event.getFile(),
event.getFileType(),
event.getPosition(),
event.getPattern(),
NavigationMethod.HighlightLine,
true);
}
public void onEditPresentationSource(final EditPresentationSourceEvent event)
{
openFile(
event.getSourceFile(),
FileTypeRegistry.RPRESENTATION,
new CommandWithArg<EditingTarget>() {
@Override
public void execute(final EditingTarget editor)
{
TextEditingTargetPresentationHelper.navigateToSlide(
editor,
event.getSlideIndex());
}
});
}
private void doOpenSourceFile(final FileSystemItem file,
final TextFileType fileType,
final FilePosition position,
final String pattern,
final NavigationMethod navMethod,
final boolean forceHighlightMode)
{
final boolean isDebugNavigation =
navMethod == NavigationMethod.DebugStep ||
navMethod == NavigationMethod.DebugEnd;
final CommandWithArg<EditingTarget> editingTargetAction =
new CommandWithArg<EditingTarget>()
{
@Override
public void execute(EditingTarget target)
{
if (position != null)
{
SourcePosition endPosition = null;
if (isDebugNavigation)
{
DebugFilePosition filePos =
(DebugFilePosition) position.cast();
endPosition = SourcePosition.create(
filePos.getEndLine() - 1,
filePos.getEndColumn() + 1);
if (Desktop.isDesktop() &&
navMethod != NavigationMethod.DebugEnd)
Desktop.getFrame().bringMainFrameToFront();
}
navigate(target,
SourcePosition.create(position.getLine() - 1,
position.getColumn() - 1),
endPosition);
}
else if (pattern != null)
{
Position pos = target.search(pattern);
if (pos != null)
{
navigate(target,
SourcePosition.create(pos.getRow(), 0),
null);
}
}
}
private void navigate(final EditingTarget target,
final SourcePosition srcPosition,
final SourcePosition srcEndPosition)
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
if (navMethod == NavigationMethod.DebugStep)
{
target.highlightDebugLocation(
srcPosition,
srcEndPosition,
true);
}
else if (navMethod == NavigationMethod.DebugEnd)
{
target.endDebugHighlighting();
}
else
{
// force highlight mode if requested
if (forceHighlightMode)
target.forceLineHighlighting();
// now navigate to the new position
boolean highlight =
navMethod == NavigationMethod.HighlightLine &&
!uiPrefs_.highlightSelectedLine().getValue();
target.navigateToPosition(srcPosition,
false,
highlight);
}
}
});
}
};
final CommandWithArg<FileSystemItem> action = new CommandWithArg<FileSystemItem>()
{
@Override
public void execute(FileSystemItem file)
{
openFile(file,
fileType,
editingTargetAction);
}
};
// If this is a debug navigation, we only want to treat this as a full
// file open if the file isn't already open; otherwise, we can just
// highlight in place.
if (isDebugNavigation)
{
setPendingDebugSelection();
for (int i = 0; i < editors_.size(); i++)
{
EditingTarget target = editors_.get(i);
String path = target.getPath();
if (path != null && path.equalsIgnoreCase(file.getPath()))
{
// the file's open; just update its highlighting
if (navMethod == NavigationMethod.DebugEnd)
{
target.endDebugHighlighting();
}
else
{
view_.selectTab(i);
editingTargetAction.execute(target);
}
return;
}
}
// If we're here, the target file wasn't open in an editor. Don't
// open a file just to turn off debug highlighting in the file!
if (navMethod == NavigationMethod.DebugEnd)
return;
}
// Warning: event.getFile() can be null (e.g. new Sweave document)
if (file != null && file.getLength() < 0)
{
// If the file has no size info, stat the file from the server. This
// is to prevent us from opening large files accidentally.
server_.stat(file.getPath(), new ServerRequestCallback<FileSystemItem>()
{
@Override
public void onResponseReceived(FileSystemItem response)
{
action.execute(response);
}
@Override
public void onError(ServerError error)
{
// Couldn't stat the file? Proceed anyway. If the file doesn't
// exist, we'll let the downstream code be the one to show the
// error.
action.execute(file);
}
});
}
else
{
action.execute(file);
}
}
private void openFile(FileSystemItem file)
{
openFile(file, fileTypeRegistry_.getTextTypeForFile(file));
}
private void openFile(FileSystemItem file, TextFileType fileType)
{
openFile(file,
fileType,
new CommandWithArg<EditingTarget>() {
@Override
public void execute(EditingTarget arg)
{
}
});
}
private void openFile(final FileSystemItem file,
final TextFileType fileType,
final CommandWithArg<EditingTarget> executeOnSuccess)
{
openFile(file,
fileType,
new ResultCallback<EditingTarget, ServerError>() {
@Override
public void onSuccess(EditingTarget target)
{
if (executeOnSuccess != null)
executeOnSuccess.execute(target);
}
@Override
public void onFailure(ServerError error)
{
String message = error.getUserMessage();
// see if a special message was provided
JSONValue errValue = error.getClientInfo();
if (errValue != null)
{
JSONString errMsg = errValue.isString();
if (errMsg != null)
message = errMsg.stringValue();
}
globalDisplay_.showMessage(GlobalDisplay.MSG_ERROR,
"Error while opening file",
message);
}
});
}
// top-level wrapper for opening files. takes care of:
// - making sure the view is visible
// - checking whether it is already open and re-selecting its tab
// - prohibit opening very large files (>500KB)
// - confirmation of opening large files (>100KB)
// - finally, actually opening the file from the server
// via the call to the lower level openFile method
private void openFile(final FileSystemItem file,
final TextFileType fileType,
final ResultCallback<EditingTarget, ServerError> resultCallback)
{
ensureVisible(true);
if (file == null)
{
newDoc(fileType, resultCallback);
return;
}
for (int i = 0; i < editors_.size(); i++)
{
EditingTarget target = editors_.get(i);
String thisPath = target.getPath();
if (thisPath != null
&& thisPath.equalsIgnoreCase(file.getPath()))
{
view_.selectTab(i);
pMruList_.get().add(thisPath);
if (resultCallback != null)
resultCallback.onSuccess(target);
return;
}
}
EditingTarget target = editingTargetSource_.getEditingTarget(fileType);
if (file.getLength() > target.getFileSizeLimit())
{
if (resultCallback != null)
resultCallback.onCancelled();
showFileTooLargeWarning(file, target.getFileSizeLimit());
}
else if (file.getLength() > target.getLargeFileSize())
{
confirmOpenLargeFile(file, new Operation() {
public void execute()
{
openFileFromServer(file, fileType, resultCallback);
}
}, new Operation() {
public void execute()
{
// user (wisely) cancelled
if (resultCallback != null)
resultCallback.onCancelled();
}
});
}
else
{
openFileFromServer(file, fileType, resultCallback);
}
}
private void showFileTooLargeWarning(FileSystemItem file,
long sizeLimit)
{
StringBuilder msg = new StringBuilder();
msg.append("The file '" + file.getName() + "' is too ");
msg.append("large to open in the source editor (the file is ");
msg.append(StringUtil.formatFileSize(file.getLength()) + " and the ");
msg.append("maximum file size is ");
msg.append(StringUtil.formatFileSize(sizeLimit) + ")");
globalDisplay_.showMessage(GlobalDisplay.MSG_WARNING,
"Selected File Too Large",
msg.toString());
}
private void confirmOpenLargeFile(FileSystemItem file,
Operation openOperation,
Operation cancelOperation)
{
StringBuilder msg = new StringBuilder();
msg.append("The source file '" + file.getName() + "' is large (");
msg.append(StringUtil.formatFileSize(file.getLength()) + ") ");
msg.append("and may take some time to open. ");
msg.append("Are you sure you want to continue opening it?");
globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_WARNING,
"Confirm Open",
msg.toString(),
openOperation,
false); // 'No' is default
}
private void openFileFromServer(
final FileSystemItem file,
final TextFileType fileType,
final ResultCallback<EditingTarget, ServerError> resultCallback)
{
final Command dismissProgress = globalDisplay_.showProgress(
"Opening file...");
server_.openDocument(
file.getPath(),
fileType.getTypeId(),
uiPrefs_.defaultEncoding().getValue(),
new ServerRequestCallback<SourceDocument>()
{
@Override
public void onError(ServerError error)
{
dismissProgress.execute();
pMruList_.get().remove(file.getPath());
Debug.logError(error);
if (resultCallback != null)
resultCallback.onFailure(error);
}
@Override
public void onResponseReceived(SourceDocument document)
{
dismissProgress.execute();
pMruList_.get().add(document.getPath());
EditingTarget target = addTab(document);
if (resultCallback != null)
resultCallback.onSuccess(target);
}
});
}
Widget createWidgetWithOutline(TextEditingTarget target)
{
final DockLayoutPanel panel = new DockLayoutPanel(Unit.PX);
final DocumentOutlineWidget outline = new DocumentOutlineWidget(target);
outline.getElement().getStyle().setBackgroundColor("#DEDEDE");
MouseDragHandler.addHandler(
outline,
new MouseDragHandler()
{
@Override
public void onDrag(MouseDragEvent event)
{
int delta = event.getMouseDelta().getMouseX();
double oldWidth = panel.getWidgetSize(outline);
double newWidth = Math.max(0, oldWidth + delta);
panel.setWidgetSize(outline, newWidth);
}
});
panel.addEast(outline, 200);
panel.add(target.asWidget());
return panel.asWidget();
}
Widget createWidget(EditingTarget target)
{
if (target instanceof TextEditingTarget && ((TextEditingTarget) target).getDocDisplay().hasScopeTree())
return createWidgetWithOutline((TextEditingTarget) target);
return target.asWidget();
}
private EditingTarget addTab(SourceDocument doc)
{
final EditingTarget target = editingTargetSource_.getEditingTarget(
doc, fileContext_, new Provider<String>()
{
public String get()
{
return getNextDefaultName();
}
});
final Widget widget = createWidget(target);
editors_.add(target);
view_.addTab(widget,
target.getIcon(),
target.getName().getValue(),
target.getTabTooltip(), // used as tooltip, if non-null
true);
fireDocTabsChanged();
target.getName().addValueChangeHandler(new ValueChangeHandler<String>()
{
public void onValueChange(ValueChangeEvent<String> event)
{
view_.renameTab(widget,
target.getIcon(),
event.getValue(),
target.getPath());
fireDocTabsChanged();
}
});
view_.setDirty(widget, target.dirtyState().getValue());
target.dirtyState().addValueChangeHandler(new ValueChangeHandler<Boolean>()
{
public void onValueChange(ValueChangeEvent<Boolean> event)
{
view_.setDirty(widget, event.getValue());
manageCommands();
}
});
target.addEnsureVisibleHandler(new EnsureVisibleHandler()
{
public void onEnsureVisible(EnsureVisibleEvent event)
{
view_.selectTab(widget);
}
});
target.addCloseHandler(new CloseHandler<Void>()
{
public void onClose(CloseEvent<Void> voidCloseEvent)
{
view_.closeTab(widget, false);
}
});
return target;
}
private String getNextDefaultName()
{
int max = 0;
for (EditingTarget target : editors_)
{
String name = target.getName().getValue();
max = Math.max(max, getUntitledNum(name));
}
return "Untitled" + (max + 1);
}
private native final int getUntitledNum(String name) /*-{
var match = /^Untitled([0-9]{1,5})$/.exec(name);
if (!match)
return 0;
return parseInt(match[1]);
}-*/;
public void onInsertSource(final InsertSourceEvent event)
{
if (activeEditor_ != null
&& activeEditor_ instanceof TextEditingTarget
&& commands_.executeCode().isEnabled())
{
TextEditingTarget textEditor = (TextEditingTarget) activeEditor_;
textEditor.insertCode(event.getCode(), event.isBlock());
}
else
{
newDoc(FileTypeRegistry.R,
new ResultCallback<EditingTarget, ServerError>()
{
public void onSuccess(EditingTarget arg)
{
((TextEditingTarget)arg).insertCode(event.getCode(),
event.isBlock());
}
});
}
}
public void onTabClosing(final TabClosingEvent event)
{
EditingTarget target = editors_.get(event.getTabIndex());
if (!target.onBeforeDismiss())
event.cancel();
}
@Override
public void onTabClose(TabCloseEvent event)
{
// can't proceed if there is no active editor
if (activeEditor_ == null)
return;
if (event.getTabIndex() >= editors_.size())
return; // Seems like this should never happen...?
final String activeEditorId = activeEditor_.getId();
if (editors_.get(event.getTabIndex()).getId().equals(activeEditorId))
{
// scan the source navigation history for an entry that can
// be used as the next active tab (anything that doesn't have
// the same document id as the currently active tab)
SourceNavigation srcNav = sourceNavigationHistory_.scanBack(
new SourceNavigationHistory.Filter()
{
public boolean includeEntry(SourceNavigation navigation)
{
return !navigation.getDocumentId().equals(activeEditorId);
}
});
// see if the source navigation we found corresponds to an active
// tab -- if it does then set this on the event
if (srcNav != null)
{
for (int i=0; i<editors_.size(); i++)
{
if (srcNav.getDocumentId().equals(editors_.get(i).getId()))
{
view_.selectTab(i);
break;
}
}
}
}
}
public void onTabClosed(TabClosedEvent event)
{
EditingTarget target = editors_.remove(event.getTabIndex());
tabOrder_.remove(new Integer(event.getTabIndex()));
for (int i = 0; i < tabOrder_.size(); i++)
{
if (tabOrder_.get(i) > event.getTabIndex())
{
tabOrder_.set(i, tabOrder_.get(i) - 1);
}
}
target.onDismiss();
if (activeEditor_ == target)
{
activeEditor_.onDeactivate();
activeEditor_ = null;
}
server_.closeDocument(target.getId(),
new VoidServerRequestCallback());
manageCommands();
fireDocTabsChanged();
if (view_.getTabCount() == 0)
{
sourceNavigationHistory_.clear();
events_.fireEvent(new LastSourceDocClosedEvent());
}
}
@Override
public void onTabReorder(TabReorderEvent event)
{
syncTabOrder();
// sanity check: make sure we're moving from a valid location and to a
// valid location
if (event.getOldPos() < 0 || event.getOldPos() >= tabOrder_.size() ||
event.getNewPos() < 0 || event.getNewPos() >= tabOrder_.size())
{
return;
}
// remove the tab from its old position
int idx = tabOrder_.get(event.getOldPos());
tabOrder_.remove(new Integer(idx)); // force type box
// add it to its new position
tabOrder_.add(event.getNewPos(), idx);
// sort the document IDs and send to the server
ArrayList<String> ids = new ArrayList<String>();
for (int i = 0; i < tabOrder_.size(); i++)
{
ids.add(editors_.get(tabOrder_.get(i)).getId());
}
server_.setDocOrder(ids, new VoidServerRequestCallback());
fireDocTabsChanged();
}
private void syncTabOrder()
{
// ensure the tab order is synced to the list of editors
for (int i = tabOrder_.size(); i < editors_.size(); i++)
{
tabOrder_.add(i);
}
for (int i = editors_.size(); i < tabOrder_.size(); i++)
{
tabOrder_.remove(i);
}
}
private void fireDocTabsChanged()
{
if (!initialized_)
return;
// ensure we have a tab order (we want the popup list to match the order
// of the tabs)
syncTabOrder();
String[] ids = new String[editors_.size()];
ImageResource[] icons = new ImageResource[editors_.size()];
String[] names = new String[editors_.size()];
String[] paths = new String[editors_.size()];
for (int i = 0; i < ids.length; i++)
{
EditingTarget target = editors_.get(tabOrder_.get(i));
ids[i] = target.getId();
icons[i] = target.getIcon();
names[i] = target.getName().getValue();
paths[i] = target.getPath();
}
events_.fireEvent(new DocTabsChangedEvent(ids, icons, names, paths));
view_.manageChevronVisibility();
}
public void onSelection(SelectionEvent<Integer> event)
{
if (activeEditor_ != null)
activeEditor_.onDeactivate();
activeEditor_ = null;
if (event.getSelectedItem() >= 0)
{
activeEditor_ = editors_.get(event.getSelectedItem());
activeEditor_.onActivate();
// don't send focus to the tab if we're expecting a debug selection
// event
if (initialized_ && !isDebugSelectionPending())
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
public void execute()
{
if (activeEditor_ != null)
activeEditor_.focus();
}
});
}
else if (isDebugSelectionPending())
{
clearPendingDebugSelection();
}
}
if (initialized_)
manageCommands();
}
private void manageCommands()
{
boolean hasDocs = editors_.size() > 0;
commands_.closeSourceDoc().setEnabled(hasDocs);
commands_.closeAllSourceDocs().setEnabled(hasDocs);
commands_.nextTab().setEnabled(hasDocs);
commands_.previousTab().setEnabled(hasDocs);
commands_.firstTab().setEnabled(hasDocs);
commands_.lastTab().setEnabled(hasDocs);
commands_.switchToTab().setEnabled(hasDocs);
commands_.setWorkingDirToActiveDoc().setEnabled(hasDocs);
HashSet<AppCommand> newCommands =
activeEditor_ != null ? activeEditor_.getSupportedCommands()
: new HashSet<AppCommand>();
HashSet<AppCommand> commandsToEnable = new HashSet<AppCommand>(newCommands);
commandsToEnable.removeAll(activeCommands_);
HashSet<AppCommand> commandsToDisable = new HashSet<AppCommand>(activeCommands_);
commandsToDisable.removeAll(newCommands);
for (AppCommand command : commandsToEnable)
{
command.setEnabled(true);
command.setVisible(true);
}
for (AppCommand command : commandsToDisable)
{
command.setEnabled(false);
command.setVisible(false);
}
// commands which should always be visible even when disabled
commands_.saveSourceDoc().setVisible(true);
commands_.saveSourceDocAs().setVisible(true);
commands_.printSourceDoc().setVisible(true);
commands_.setWorkingDirToActiveDoc().setVisible(true);
commands_.debugBreakpoint().setVisible(true);
// manage synctex commands
manageSynctexCommands();
// manage vcs commands
manageVcsCommands();
// manage save and save all
manageSaveCommands();
// manage source navigation
manageSourceNavigationCommands();
// manage RSConnect commands
manageRSConnectCommands();
// manage R Markdown commands
manageRMarkdownCommands();
activeCommands_ = newCommands;
assert verifyNoUnsupportedCommands(newCommands)
: "Unsupported commands detected (please add to Source.dynamicCommands_)";
}
private void manageSynctexCommands()
{
// synctex commands are enabled if we have synctex for the active editor
boolean synctexAvailable = synctex_.isSynctexAvailable();
if (synctexAvailable)
{
if ((activeEditor_ != null) &&
(activeEditor_.getPath() != null) &&
activeEditor_.canCompilePdf())
{
synctexAvailable = synctex_.isSynctexAvailable();
}
else
{
synctexAvailable = false;
}
}
synctex_.enableCommands(synctexAvailable);
}
private void manageVcsCommands()
{
// manage availablity of vcs commands
boolean vcsCommandsEnabled =
session_.getSessionInfo().isVcsEnabled() &&
(activeEditor_ != null) &&
(activeEditor_.getPath() != null) &&
activeEditor_.getPath().startsWith(
session_.getSessionInfo().getActiveProjectDir().getPath());
commands_.vcsFileLog().setVisible(vcsCommandsEnabled);
commands_.vcsFileLog().setEnabled(vcsCommandsEnabled);
commands_.vcsFileDiff().setVisible(vcsCommandsEnabled);
commands_.vcsFileDiff().setEnabled(vcsCommandsEnabled);
commands_.vcsFileRevert().setVisible(vcsCommandsEnabled);
commands_.vcsFileRevert().setEnabled(vcsCommandsEnabled);
if (vcsCommandsEnabled)
{
String name = FileSystemItem.getNameFromPath(activeEditor_.getPath());
commands_.vcsFileDiff().setMenuLabel("_Diff \"" + name + "\"");
commands_.vcsFileLog().setMenuLabel("_Log of \"" + name +"\"");
commands_.vcsFileRevert().setMenuLabel("_Revert \"" + name + "\"...");
}
boolean isGithubRepo = session_.getSessionInfo().isGithubRepository();
if (vcsCommandsEnabled && isGithubRepo)
{
String name = FileSystemItem.getNameFromPath(activeEditor_.getPath());
commands_.vcsViewOnGitHub().setVisible(true);
commands_.vcsViewOnGitHub().setEnabled(true);
commands_.vcsViewOnGitHub().setMenuLabel(
"_View \"" + name + "\" on GitHub");
commands_.vcsBlameOnGitHub().setVisible(true);
commands_.vcsBlameOnGitHub().setEnabled(true);
commands_.vcsBlameOnGitHub().setMenuLabel(
"_Blame \"" + name + "\" on GitHub");
}
else
{
commands_.vcsViewOnGitHub().setVisible(false);
commands_.vcsViewOnGitHub().setEnabled(false);
commands_.vcsBlameOnGitHub().setVisible(false);
commands_.vcsBlameOnGitHub().setEnabled(false);
}
}
private void manageRSConnectCommands()
{
boolean rsCommandsAvailable =
SessionUtils.showPublishUi(session_, uiPrefs_) &&
(activeEditor_ != null) &&
(activeEditor_.getPath() != null) &&
((activeEditor_.getExtendedFileType() == "shiny") ||
(activeEditor_.getExtendedFileType() == "rmarkdown"));
commands_.rsconnectDeploy().setVisible(rsCommandsAvailable);
if (activeEditor_ != null)
commands_.rsconnectDeploy().setLabel(
activeEditor_.getExtendedFileType() == "shiny" ?
"Publish Application..." : "Publish Document...");
commands_.rsconnectConfigure().setVisible(rsCommandsAvailable);
}
private void manageRMarkdownCommands()
{
boolean rmdCommandsAvailable =
session_.getSessionInfo().getRMarkdownPackageAvailable() &&
(activeEditor_ != null) &&
activeEditor_.getExtendedFileType() == "rmarkdown";
commands_.editRmdFormatOptions().setVisible(rmdCommandsAvailable);
commands_.editRmdFormatOptions().setEnabled(rmdCommandsAvailable);
}
private void manageSaveCommands()
{
boolean saveEnabled = (activeEditor_ != null) &&
activeEditor_.isSaveCommandActive();
commands_.saveSourceDoc().setEnabled(saveEnabled);
manageSaveAllCommand();
}
private void manageSaveAllCommand()
{
// if one document is dirty then we are enabled
for (EditingTarget target : editors_)
{
if (target.isSaveCommandActive())
{
commands_.saveAllSourceDocs().setEnabled(true);
return;
}
}
// not one was dirty, disabled
commands_.saveAllSourceDocs().setEnabled(false);
}
private boolean verifyNoUnsupportedCommands(HashSet<AppCommand> commands)
{
HashSet<AppCommand> temp = new HashSet<AppCommand>(commands);
temp.removeAll(dynamicCommands_);
return temp.size() == 0;
}
private void pasteFileContentsAtCursor(final String path, final String encoding)
{
if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget)
{
final TextEditingTarget target = (TextEditingTarget) activeEditor_;
server_.getFileContents(path, encoding, new ServerRequestCallback<String>()
{
@Override
public void onResponseReceived(String content)
{
target.insertCode(content, false);
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
}
});
}
}
private void pasteRCodeExecutionResult(final String code)
{
server_.executeRCode(code, new ServerRequestCallback<String>()
{
@Override
public void onResponseReceived(String output)
{
if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget)
{
TextEditingTarget editor = (TextEditingTarget) activeEditor_;
editor.insertCode(output, false);
}
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
}
});
}
private void reflowText()
{
if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget)
{
TextEditingTarget editor = (TextEditingTarget) activeEditor_;
editor.reflowText();
}
}
private void reindent()
{
if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget)
{
TextEditingTarget editor = (TextEditingTarget) activeEditor_;
editor.getDocDisplay().reindent();
}
}
private void editFile(final String path)
{
server_.ensureFileExists(
path,
new ServerRequestCallback<Boolean>()
{
@Override
public void onResponseReceived(Boolean success)
{
if (success)
{
FileSystemItem file = FileSystemItem.createFile(path);
openFile(file);
}
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
}
});
}
private void showHelpAtCursor()
{
if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget)
{
TextEditingTarget editor = (TextEditingTarget) activeEditor_;
editor.showHelpAtCursor();
}
}
public void onFileEdit(FileEditEvent event)
{
fileTypeRegistry_.editFile(event.getFile());
}
public void onBeforeShow(BeforeShowEvent event)
{
if (view_.getTabCount() == 0 && newTabPending_ == 0)
{
// Avoid scenarios where the Source tab comes up but no tabs are
// in it. (But also avoid creating an extra source tab when there
// were already new tabs about to be created!)
onNewSourceDoc();
}
}
@Handler
public void onSourceNavigateBack()
{
if (!sourceNavigationHistory_.isForwardEnabled())
{
if (activeEditor_ != null)
activeEditor_.recordCurrentNavigationPosition();
}
SourceNavigation navigation = sourceNavigationHistory_.goBack();
if (navigation != null)
attemptSourceNavigation(navigation, commands_.sourceNavigateBack());
}
@Handler
public void onSourceNavigateForward()
{
SourceNavigation navigation = sourceNavigationHistory_.goForward();
if (navigation != null)
attemptSourceNavigation(navigation, commands_.sourceNavigateForward());
}
private void attemptSourceNavigation(final SourceNavigation navigation,
final AppCommand retryCommand)
{
// see if we can navigate by id
String docId = navigation.getDocumentId();
final EditingTarget target = getEditingTargetForId(docId);
if (target != null)
{
// check for navigation to the current position -- in this
// case execute the retry command
if ( (target == activeEditor_) &&
target.isAtSourceRow(navigation.getPosition()))
{
if (retryCommand.isEnabled())
retryCommand.execute();
}
else
{
suspendSourceNavigationAdding_ = true;
try
{
view_.selectTab(target.asWidget());
target.restorePosition(navigation.getPosition());
}
finally
{
suspendSourceNavigationAdding_ = false;
}
}
}
// check for code browser navigation
else if ((navigation.getPath() != null) &&
navigation.getPath().equals(CodeBrowserEditingTarget.PATH))
{
activateCodeBrowser(
new SourceNavigationResultCallback<CodeBrowserEditingTarget>(
navigation.getPosition(),
retryCommand));
}
// check for file path navigation
else if ((navigation.getPath() != null) &&
!navigation.getPath().startsWith(DataItem.URI_PREFIX))
{
FileSystemItem file = FileSystemItem.createFile(navigation.getPath());
TextFileType fileType = fileTypeRegistry_.getTextTypeForFile(file);
// open the file and restore the position
openFile(file,
fileType,
new SourceNavigationResultCallback<EditingTarget>(
navigation.getPosition(),
retryCommand));
}
else
{
// couldn't navigate to this item, retry
if (retryCommand.isEnabled())
retryCommand.execute();
}
}
private void manageSourceNavigationCommands()
{
commands_.sourceNavigateBack().setEnabled(
sourceNavigationHistory_.isBackEnabled());
commands_.sourceNavigateForward().setEnabled(
sourceNavigationHistory_.isForwardEnabled());
}
@Override
public void onCodeBrowserNavigation(final CodeBrowserNavigationEvent event)
{
if (event.getDebugPosition() != null)
{
setPendingDebugSelection();
}
activateCodeBrowser(new ResultCallback<CodeBrowserEditingTarget,ServerError>() {
@Override
public void onSuccess(CodeBrowserEditingTarget target)
{
target.showFunction(event.getFunction());
if (event.getDebugPosition() != null)
{
highlightDebugBrowserPosition(target, event.getDebugPosition(),
event.getExecuting());
}
}
});
}
@Override
public void onCodeBrowserFinished(final CodeBrowserFinishedEvent event)
{
int codeBrowserTabIndex = indexOfCodeBrowserTab();
if (codeBrowserTabIndex >= 0)
{
view_.closeTab(codeBrowserTabIndex, false);
return;
}
}
@Override
public void onCodeBrowserHighlight(final CodeBrowserHighlightEvent event)
{
// no need to highlight if we don't have a code browser tab to highlight
if (indexOfCodeBrowserTab() < 0)
return;
setPendingDebugSelection();
activateCodeBrowser(new ResultCallback<CodeBrowserEditingTarget,ServerError>() {
@Override
public void onSuccess(CodeBrowserEditingTarget target)
{
highlightDebugBrowserPosition(target, event.getDebugPosition(), true);
}
});
}
private void highlightDebugBrowserPosition(CodeBrowserEditingTarget target,
DebugFilePosition pos,
boolean executing)
{
target.highlightDebugLocation(SourcePosition.create(
pos.getLine(),
pos.getColumn() - 1),
SourcePosition.create(
pos.getEndLine(),
pos.getEndColumn() + 1),
executing);
}
// returns the index of the tab currently containing the code browser, or
// -1 if the code browser tab isn't currently open;
private int indexOfCodeBrowserTab()
{
// see if there is an existing target to use
for (int idx = 0; idx < editors_.size(); idx++)
{
String path = editors_.get(idx).getPath();
if (CodeBrowserEditingTarget.PATH.equals(path))
{
return idx;
}
}
return -1;
}
private void activateCodeBrowser(
final ResultCallback<CodeBrowserEditingTarget,ServerError> callback)
{
int codeBrowserTabIndex = indexOfCodeBrowserTab();
if (codeBrowserTabIndex >= 0)
{
ensureVisible(false);
view_.selectTab(codeBrowserTabIndex);
// callback
callback.onSuccess( (CodeBrowserEditingTarget)
editors_.get(codeBrowserTabIndex));
// satisfied request
return;
}
// create a new one
newDoc(FileTypeRegistry.CODEBROWSER,
new ResultCallback<EditingTarget, ServerError>()
{
@Override
public void onSuccess(EditingTarget arg)
{
callback.onSuccess( (CodeBrowserEditingTarget)arg);
}
@Override
public void onFailure(ServerError error)
{
callback.onFailure(error);
}
@Override
public void onCancelled()
{
callback.onCancelled();
}
});
}
private boolean isDebugSelectionPending()
{
return debugSelectionTimer_ != null;
}
private void clearPendingDebugSelection()
{
if (debugSelectionTimer_ != null)
{
debugSelectionTimer_.cancel();
debugSelectionTimer_ = null;
}
}
private void setPendingDebugSelection()
{
if (!isDebugSelectionPending())
{
debugSelectionTimer_ = new Timer()
{
public void run()
{
debugSelectionTimer_ = null;
}
};
debugSelectionTimer_.schedule(250);
}
}
private class SourceNavigationResultCallback<T extends EditingTarget>
extends ResultCallback<T,ServerError>
{
public SourceNavigationResultCallback(SourcePosition restorePosition,
AppCommand retryCommand)
{
suspendSourceNavigationAdding_ = true;
restorePosition_ = restorePosition;
retryCommand_ = retryCommand;
}
@Override
public void onSuccess(final T target)
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
try
{
target.restorePosition(restorePosition_);
}
finally
{
suspendSourceNavigationAdding_ = false;
}
}
});
}
@Override
public void onFailure(ServerError info)
{
suspendSourceNavigationAdding_ = false;
if (retryCommand_.isEnabled())
retryCommand_.execute();
}
@Override
public void onCancelled()
{
suspendSourceNavigationAdding_ = false;
}
private final SourcePosition restorePosition_;
private final AppCommand retryCommand_;
}
@Override
public void onSourceExtendedTypeDetected(SourceExtendedTypeDetectedEvent e)
{
// set the extended type of the specified source file
for (EditingTarget editor : editors_)
{
if (editor.getId().equals(e.getDocId()))
{
editor.adaptToExtendedFileType(e.getExtendedType());
break;
}
}
}
@Override
public void onSnippetsChanged(SnippetsChangedEvent event)
{
SnippetHelper.onSnippetsChanged(event);
}
// when tabs have been reordered in the session, the physical layout of the
// tabs doesn't match the logical order of editors_. it's occasionally
// necessary to get or set the tabs by their physical order.
public int getPhysicalTabIndex()
{
int idx = view_.getActiveTabIndex();
if (idx < tabOrder_.size())
{
idx = tabOrder_.indexOf(idx);
}
return idx;
}
public void setPhysicalTabIndex(int idx)
{
if (idx < tabOrder_.size())
{
idx = tabOrder_.get(idx);
}
view_.selectTab(idx);
}
public EditingTarget getActiveEditor()
{
return activeEditor_;
}
public void handleChunkOptionsEvent()
{
events_.addHandler(
DisplayChunkOptionsEvent.TYPE,
new DisplayChunkOptionsEvent.Handler()
{
@Override
public void onDisplayChunkOptions(DisplayChunkOptionsEvent event)
{
// Ensure the source pane (not the console) is activated
if (activeEditor_ == null)
return;
// Ensure we have an Ace Editor
if (!(activeEditor_ instanceof TextEditingTarget))
return;
TextEditingTarget target = (TextEditingTarget) activeEditor_;
AceEditor editor = (AceEditor) target.getDocDisplay();
if (editor == null)
return;
NativeEvent nativeEvent = event.getNativeEvent();
chunkIconsManager_.displayChunkOptions(
editor,
nativeEvent);
}
});
}
ArrayList<EditingTarget> editors_ = new ArrayList<EditingTarget>();
ArrayList<Integer> tabOrder_ = new ArrayList<Integer>();
private EditingTarget activeEditor_;
private final Commands commands_;
private final Display view_;
private final SourceServerOperations server_;
private final EditingTargetSource editingTargetSource_;
private final FileTypeRegistry fileTypeRegistry_;
private final GlobalDisplay globalDisplay_;
private final WorkbenchContext workbenchContext_;
private final FileDialogs fileDialogs_;
private final RemoteFileSystemContext fileContext_;
private final TextEditingTargetRMarkdownHelper rmarkdown_;
private final EventBus events_;
private final Session session_;
private final Synctex synctex_;
private final Provider<FileMRUList> pMruList_;
private final UIPrefs uiPrefs_;
private final RnwWeaveRegistry rnwWeaveRegistry_;
private HashSet<AppCommand> activeCommands_ = new HashSet<AppCommand>();
private final HashSet<AppCommand> dynamicCommands_;
private final SourceNavigationHistory sourceNavigationHistory_ =
new SourceNavigationHistory(30);
private final SourceVimCommands vimCommands_;
private boolean suspendSourceNavigationAdding_;
private static final String MODULE_SOURCE = "source-pane";
private static final String KEY_ACTIVETAB = "activeTab";
private boolean initialized_;
private Timer debugSelectionTimer_ = null;
// If positive, a new tab is about to be created
private int newTabPending_;
private ChunkIconsManager chunkIconsManager_;
}
|
package org.xins.client;
import org.xins.util.MandatoryArgumentChecker;
import org.xins.util.text.FastStringBuffer;
/**
* Exception that indicates that an API call result was unsuccessful.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.36
*/
public final class UnsuccessfulCallException
extends CallException {
// Class fields
// Class functions
private static final String createMessage(CallResult result)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("result", result);
if (result.isSuccess()) {
throw new IllegalArgumentException("result.isSuccess() == true");
}
FastStringBuffer buffer = new FastStringBuffer(80);
buffer.append("Call was unsuccessful");
String code = result.getCode();
if (code != null && code.length() > 0) {
buffer.append(", result code was \"");
buffer.append(code);
buffer.append('"');
}
buffer.append('.');
return buffer.toString();
}
// Constructors
public UnsuccessfulCallException(CallResult result)
throws IllegalArgumentException {
super(createMessage(result), null);
_result = result;
}
// Fields
/**
* The call result. The value of this field cannot be <code>null</code>.
*/
private final CallResult _result;
// Methods
/**
* Returns the call result.
*
* @return
* the call result, cannot be <code>null</code>.
*/
public CallResult getCallResult() {
return _result;
}
}
|
package com.dstevens.web.config.controller;
import static com.dstevens.collections.Sets.set;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import com.dstevens.users.Role;
import com.dstevens.users.User;
import com.dstevens.users.UserDao;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
@Controller
public class CreateAccountController {
private UserDao userDao;
@Autowired
public CreateAccountController(UserDao userDao) {
this.userDao = userDao;
}
@RequestMapping(value = { "/createAccount"}, method = RequestMethod.GET)
public ModelAndView createAccountPage() {
return new ModelAndView("createAccount");
}
@RequestMapping(value = { "/createAccount"}, method = RequestMethod.POST)
public ModelAndView createAccount(@RequestParam(value = "email") String email,
@RequestParam(value = "username") String username,
@RequestParam(value = "password") String password) {
if(userDao.findWithEmail(email) != null) {
ModelAndView model = new ModelAndView("createAccount");
model.addObject("error", "An account already exists for user with email address " + email);
return model;
}
if(userDao.findWithName(username) != null) {
ModelAndView model = new ModelAndView("createAccount");
model.addObject("error", "An account already exists for user with name " + username);
return model;
}
User newUser = userDao.save(new User(username, email, password, set(Role.USER)));
sendConfirmatoryEmailTo(email);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(newUser, null, newUser.getAuthorities()));
return new ModelAndView(new RedirectView("/user/main"));
}
private void sendConfirmatoryEmailTo(String email) {
Properties properties = new Properties();
Session session = Session.getDefaultInstance(properties);
String msgBody = "Your Underground Theater User Account has been created";
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("database@undergroundtheater.org", "UT Database Admin"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(email));
msg.setSubject("Your Underground Theater User Account has been created");
msg.setText(msgBody);
Transport.send(msg);
} catch (MessagingException | UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to send message to " + email, e);
}
}
}
|
package au.com.agic.apptesting.steps;
import au.com.agic.apptesting.State;
import au.com.agic.apptesting.utils.AutoAliasUtils;
import cucumber.api.java.en.Then;
import javaslang.control.Try;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.swing.*;
import java.awt.*;
/**
* This class contains steps that can be used to display help information
* above the browser
*/
@Component
public class HelpPopupStepDefinitions {
private static final Logger LOGGER = LoggerFactory.getLogger(HelpPopupStepDefinitions.class);
private static final int MESSAGE_WIDTH = 800;
private static final int MESSAGE_HEIGHT = 600;
private static final int BORDER_THICKNESS = 5;
private static final Integer DEFAULT_TIME_TO_DISPLAY = 5;
private static final int MESSAGE_FONT_SIZE = 48;
private static final Color MESSAGE_BACKGROUND_COLOUR = new Color(255, 236, 179);
@Autowired
private AutoAliasUtils autoAliasUtils;
/**
* Displays a message in a window above the browser. Only works
* where Java is able to create a UI.
* @param message The message to display
* @param timeAlias indicates that the time value is aliased
* @param time The time to show the message for
* @param ignoreErrors Add this text to ignore any errors
*/
@Then("I display the help message \"(.*?)\"(?: for( alias)? \"(.*?)\" seconds)?( ignoring errors)?")
public void displayMessage(final String message,
final String timeAlias,
final String time,
final String ignoreErrors) {
try {
final String timeValue = StringUtils.isBlank(time)
? DEFAULT_TIME_TO_DISPLAY.toString()
: autoAliasUtils.getValue(
time,
StringUtils.isNotBlank(timeAlias),
State.getFeatureStateForThread());
final Integer fixedTime = NumberUtils.toInt(timeValue, DEFAULT_TIME_TO_DISPLAY);
final JFrame frame = new JFrame();
frame.setAlwaysOnTop(true);
frame.setUndecorated(true);
frame.setSize(MESSAGE_WIDTH, MESSAGE_HEIGHT);
/*
Center the window
*/
frame.setLocationRelativeTo(null);
/*
Create the message
*/
final JLabel label = new JLabel(message);
final Font labelFont = label.getFont();
label.setFont(new Font(labelFont.getName(), Font.PLAIN, MESSAGE_FONT_SIZE));
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
label.setOpaque(true);
label.setBackground(MESSAGE_BACKGROUND_COLOUR);
label.setBorder(BorderFactory.createLineBorder(Color.BLACK, BORDER_THICKNESS));
frame.getContentPane().add(label);
/*
Display the message
*/
frame.setVisible(true);
Try.run(() -> Thread.sleep(fixedTime * 1000));
/*
Close the window
*/
frame.setVisible(false);
frame.dispose();
} catch (final Exception ex) {
LOGGER.error("Could not display popup", ex);
if (!StringUtils.isEmpty(ignoreErrors)) {
throw ex;
}
}
}
}
|
package bftsmart.benchmark;
import controller.IBenchmarkStrategy;
import demo.Measurement;
import master.IProcessingResult;
import master.client.ClientsMaster;
import master.message.Message;
import master.server.ServersMaster;
import pod.ProcessInfo;
import pod.WorkerCommands;
import util.Configuration;
import util.Storage;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author robin
*/
public class ThroughputLatencyBenchmarkStrategy implements IBenchmarkStrategy {
private final Lock lock;
private final Condition sleepCondition;
private final int totalRounds;
private int round;
private final long sleepBetweenRounds;
private CountDownLatch serversReadyCounter;
private CountDownLatch clientsReadyCounter;
private CountDownLatch measurementDelivered;
private final String workingDirectory;
private final String serverCommand;
private final int numOfServers;
private final String clientCommand;
private final int numOfClients;
private final boolean isWrite;
private final int numRequests;
private final int dataSize;
private final int[] clients;
private final int maxClientsPerWorker;
private final int[] numMaxRealClients;
private final double[] avgLatency;
private final double[] latencyDev;
private final double[] avgThroughput;
private final double[] throughputDev;
private final double[] maxLatency;
private final double[] maxThroughput;
public ThroughputLatencyBenchmarkStrategy() {
Configuration configuration = Configuration.getInstance();
this.lock = new ReentrantLock(true);
this.sleepCondition = lock.newCondition();
this.totalRounds = configuration.getClientsPerRound().length;
this.numOfServers = configuration.getNumServerPods();
this.numOfClients = configuration.getNumClientPods();
this.numMaxRealClients = new int[totalRounds];
this.avgLatency = new double[totalRounds];
this.latencyDev = new double[totalRounds];
this.avgThroughput = new double[totalRounds];
this.throughputDev = new double[totalRounds];
this.maxLatency = new double[totalRounds];
this.maxThroughput = new double[totalRounds];
this.sleepBetweenRounds = 10;
this.isWrite = configuration.isWrite();
this.numRequests = 10_000_000;
this.dataSize = configuration.getDataSize();
this.clients = configuration.getClientsPerRound();
for (int i = 0; i < clients.length; i++) {
clients[i]
}
this.maxClientsPerWorker = configuration.getMaxClientsPerWorker();
this.workingDirectory = configuration.getWorkingDirectory();
String initialCommand = "java -Xmx28g -Djava.security.properties=./config/java" +
|
package com.akiban.server.t3expressions;
import com.akiban.server.error.AkibanInternalException;
import com.akiban.server.error.NoSuchFunctionException;
import com.akiban.server.error.ServiceStartupException;
import com.akiban.server.service.Service;
import com.akiban.server.service.jmx.JmxManageable;
import com.akiban.server.types3.TAggregator;
import com.akiban.server.types3.TCast;
import com.akiban.server.types3.TCastIdentifier;
import com.akiban.server.types3.TCastPath;
import com.akiban.server.types3.TClass;
import com.akiban.server.types3.TExecutionContext;
import com.akiban.server.types3.TInstance;
import com.akiban.server.types3.TOverload;
import com.akiban.server.types3.TStrongCasts;
import com.akiban.server.types3.mcompat.mtypes.MString;
import com.akiban.server.types3.pvalue.PValue;
import com.akiban.server.types3.pvalue.PValueSource;
import com.akiban.server.types3.pvalue.PValueTarget;
import com.akiban.server.types3.service.InstanceFinder;
import com.akiban.server.types3.service.ReflectiveInstanceFinder;
import com.akiban.server.types3.texpressions.Constantness;
import com.akiban.server.types3.texpressions.TValidatedOverload;
import com.akiban.util.DagChecker;
import com.akiban.util.HasId;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.Yaml;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
public final class T3RegistryServiceImpl implements T3RegistryService, Service, JmxManageable {
// T3RegistryService interface
@Override
public Iterable<? extends ScalarsGroup> getOverloads(String name) {
List<ScalarsGroup> result = overloadsByName.get(name.toLowerCase());
return result.isEmpty() ? null : result;
}
@Override
public TCast cast(TClass source, TClass target) {
return cast(castsBySource, source, target);
}
@Override
public Set<TClass> stronglyCastableFrom(TClass tClass) {
Map<TClass, TCast> castsFrom = strongCastsBySource.get(tClass);
return castsFrom.keySet();
}
@Override
public Collection<? extends TAggregator> getAggregates(String name) {
name = name.toLowerCase();
Collection<? extends TAggregator> aggrs = aggregatorsByName.get(name);
if (aggrs == null)
throw new NoSuchFunctionException(name);
return aggrs;
}
@Override
public boolean isStrong(TCast cast) {
TClass source = cast.sourceClass();
TClass target = cast.targetClass();
return stronglyCastableFrom(source).contains(target);
}
@Override
public boolean isIndexFriendly(TClass source, TClass target) {
return Objects.equal(
source.name().categoryName(),
target.name().categoryName()
);
}
// Service interface
@Override
public void start() {
InstanceFinder registry;
try {
registry = new ReflectiveInstanceFinder();
} catch (Exception e) {
logger.error("while creating registry", e);
throw new ServiceStartupException("T3Registry");
}
start(registry);
}
@Override
public void stop() {
castsBySource = null;
strongCastsBySource = null;
overloadsByName = null;
aggregatorsByName = null;
tClasses = null;
}
@Override
public void crash() {
stop();
}
// JmxManageable interface
@Override
public JmxObjectInfo getJmxObjectInfo() {
return new JmxObjectInfo("T3Registry", new Bean(), T3RegistryMXBean.class);
}
// private methods
private static TCast cast(Map<TClass, Map<TClass, TCast>> castsBySource, TClass source, TClass target) {
TCast result = null;
Map<TClass,TCast> castsByTarget = castsBySource.get(source);
if (castsByTarget != null)
result = castsByTarget.get(target);
return result;
}
void start(InstanceFinder finder) {
tClasses = new HashSet<TClass>(finder.find(TClass.class));
castsBySource = createCasts(tClasses, finder);
createDerivedCasts(castsBySource, finder);
deriveCastsFromVarchar();
strongCastsBySource = createStrongCastsMap(castsBySource, finder);
checkDag(strongCastsBySource);
overloadsByName = createScalars(finder);
aggregatorsByName = createAggregates(finder);
}
private static Map<String, Collection<TAggregator>> createAggregates(InstanceFinder finder) {
Collection<? extends TAggregator> aggrs = finder.find(TAggregator.class);
Map<String, Collection<TAggregator>> local = new HashMap<String, Collection<TAggregator>>(aggrs.size());
for (TAggregator aggr : aggrs) {
String name = aggr.name().toLowerCase();
Collection<TAggregator> values = local.get(name);
if (values == null) {
values = new ArrayList<TAggregator>(2); // most aggrs don't have many overloads
local.put(name, values);
}
values.add(aggr);
}
return local;
}
private static ListMultimap<String, ScalarsGroup> createScalars(InstanceFinder finder) {
Multimap<String, TValidatedOverload> overloadsByName = ArrayListMultimap.create();
int errors = 0;
for (TOverload scalar : finder.find(TOverload.class)) {
try {
TValidatedOverload validated = new TValidatedOverload(scalar);
for (String name : validated.registeredNames())
overloadsByName.put(name.toLowerCase(), validated);
} catch (RuntimeException e) {
rejectTOverload(scalar, e);
++errors;
} catch (AssertionError e) {
rejectTOverload(scalar, e);
++errors;
}
}
if (errors > 0) {
StringBuilder sb = new StringBuilder("Found ").append(errors).append(" error");
if (errors != 1)
sb.append('s');
sb.append(" while collecting scalar functions. Check logs for details.");
throw new AkibanInternalException(sb.toString());
}
ArrayListMultimap<String, ScalarsGroup> results = ArrayListMultimap.create();
for (Map.Entry<String, Collection<TValidatedOverload>> entry : overloadsByName.asMap().entrySet()) {
String overloadName = entry.getKey();
Collection<TValidatedOverload> allOverloads = entry.getValue();
for (Collection<TValidatedOverload> priorityGroup : scalarsByPriority(allOverloads)) {
ScalarsGroup scalarsGroup = new ScalarsGroupImpl(priorityGroup);
results.put(overloadName, scalarsGroup);
}
}
results.trimToSize();
return Multimaps.unmodifiableListMultimap(results);
}
private static List<Collection<TValidatedOverload>> scalarsByPriority(
Collection<TValidatedOverload> overloads)
{
// First, we'll put this into a SortedMap<Integer, Collection<TVO>> so that we have each subset of the
// overloads grouped by priority. Then we'll go over those collections; for each one, we'll wrap it in
// an unmodifiable Collection (so that users of the iterator() can't modify the Collections).
// Finally, we'll wrap the result in an unmodifiable Collection (so that users can't remove Collections
// from it via the Iterator).
SortedMap<Integer, ArrayList<TValidatedOverload>> byPriority
= new TreeMap<Integer, ArrayList<TValidatedOverload>>();
for (TValidatedOverload overload : overloads) {
for (int priority : overload.getPriorities()) {
ArrayList<TValidatedOverload> thisPriorityOverloads = byPriority.get(priority);
if (thisPriorityOverloads == null) {
thisPriorityOverloads = new ArrayList<TValidatedOverload>();
byPriority.put(priority, thisPriorityOverloads);
}
thisPriorityOverloads.add(overload);
}
}
List<Collection<TValidatedOverload>> results
= new ArrayList<Collection<TValidatedOverload>>(byPriority.size());
for (ArrayList<TValidatedOverload> priorityGroup : byPriority.values()) {
priorityGroup.trimToSize();
results.add(Collections.unmodifiableCollection(priorityGroup));
}
return results;
}
private static void rejectTOverload(TOverload overload, Throwable e) {
StringBuilder sb = new StringBuilder("rejecting overload ");
Class<?> overloadClass = overload == null ? null : overload.getClass();
try {
sb.append(overload).append(' ');
} catch (Exception e1) {
logger.error("couldn't toString overload: " + overload);
}
sb.append("from ").append(overloadClass);
logger.error(sb.toString(), e);
}
static Map<TClass, Map<TClass, TCast>> createCasts(Collection<? extends TClass> tClasses,
InstanceFinder finder) {
Map<TClass, Map<TClass, TCast>> localCastsMap = new HashMap<TClass, Map<TClass, TCast>>(tClasses.size());
// First, define the self casts
for (TClass tClass : tClasses) {
Map<TClass, TCast> map = new HashMap<TClass, TCast>();
map.put(tClass, new SelfCast(tClass));
localCastsMap.put(tClass, map);
}
Set<TCastIdentifier> duplicates = new TreeSet<TCastIdentifier>(tcastIdentifierComparator);
// Next, to/from varchar
for (TClass tClass : tClasses) {
putCast(localCastsMap, tClass.castToVarchar(), duplicates);
putCast(localCastsMap, tClass.castFromVarchar(), duplicates);
}
// Now the registered casts
for (TCast cast : finder.find(TCast.class)) {
putCast(localCastsMap, cast, duplicates);
}
if (!duplicates.isEmpty())
throw new AkibanInternalException("duplicate casts found for: " + duplicates);
return localCastsMap;
}
private static void putCast(Map<TClass, Map<TClass, TCast>> toMap, TCast cast, Set<TCastIdentifier> duplicates) {
if (cast == null)
return;
TClass source = cast.sourceClass();
TClass target = cast.targetClass();
Map<TClass,TCast> castsByTarget = toMap.get(source);
TCast old = castsByTarget.put(target, cast);
if (old != null) {
logger.error("CAST({} AS {}): {} replaced by {} ", new Object[]{
source, target, old.getClass(), cast.getClass()
});
if (duplicates == null)
throw new AkibanInternalException("multiple casts defined from " + source + " to " + target);
duplicates.add(new TCastIdentifier(source, target));
}
}
static void createDerivedCasts(Map<TClass,Map<TClass,TCast>> castsBySource, InstanceFinder finder) {
for (TCastPath castPath : finder.find(TCastPath.class)) {
List<? extends TClass> path = castPath.getPath();
// We need this loop to protect against "jumps." For instance, let's say the cast path is
// [ a, b, c, d, e ] and we have the following casts:
// "single step" casts: (a -> b), (b -> c), (c -> d), (d -> e)
// one "jump" cast: (a -> d),
// The first pass of this loop will create a derived cast (a -> d -> e), but we wouldn't have created
// (a -> c). This loop ensures that we will.
// We work from both ends, shrinking iteratively from the beginning and recursively (within deriveCast)
// from the end. A derived cast has to have at least three participants, so we can stop when we get
// to a path whose size is less than 3.
while (path.size() >= 3) {
for (int i = path.size() - 1; i > 0; --i) {
deriveCast(castsBySource, path, i);
}
path = path.subList(1, path.size());
}
}
}
/**
* Add derived casts for any pair of TClasses (A, B) s.t. there is not a cast from A to B, but there are casts
* from A to VARCHAR and from VARCHAR to B. This essentially uses VARCHAR as a base type. Not pretty, but effective.
* Uses the instance variable #castsBySource for its input and output; it must be initialized with at least
* the self-casts and declared casts.
*/
private void deriveCastsFromVarchar() {
final TClass COMMON = MString.VARCHAR;
Set<TClass> tClasses = castsBySource.keySet();
for (Map.Entry<TClass, Map<TClass, TCast>> entry : castsBySource.entrySet()) {
TClass source = entry.getKey();
Map<TClass, TCast> castsByTarget = entry.getValue();
for (TClass target : tClasses) {
if (target == source || castsByTarget.containsKey(target))
continue;
TCast sourceToVarchar = cast(source, COMMON);
if (sourceToVarchar == null)
continue;
TCast varcharToTarget = cast(COMMON, target);
if (varcharToTarget == null)
continue;
TCast derived = new ChainedCast(sourceToVarchar, varcharToTarget);
castsByTarget.put(target, derived);
}
}
}
private static TCast deriveCast(Map<TClass,Map<TClass,TCast>> castsBySource,
List<? extends TClass> path, int targetIndex) {
TClass source = path.get(0);
TClass target = path.get(targetIndex);
TCast alreadyThere = cast(castsBySource, source, target);
if (alreadyThere != null)
return alreadyThere;
int intermediateIndex = targetIndex - 1;
TClass intermediateClass = path.get(intermediateIndex);
TCast second = cast(castsBySource, intermediateClass, target);
if (second == null)
throw new AkibanInternalException("no explicit cast between " + intermediateClass + " and " + target
+ " while creating cast path: " + path);
TCast first = deriveCast(castsBySource, path, intermediateIndex);
if (first == null)
throw new AkibanInternalException("couldn't derive cast between " + source + " and " + intermediateClass
+ " while creating cast path: " + path);
TCast result = new ChainedCast(first, second);
putCast(castsBySource, result, null);
return result;
}
private static void checkDag(final Map<TClass, Map<TClass, TCast>> castsBySource) {
DagChecker<TClass> checker = new DagChecker<TClass>() {
@Override
protected Set<? extends TClass> initialNodes() {
return castsBySource.keySet();
}
@Override
protected Set<? extends TClass> nodesFrom(TClass starting) {
Set<TClass> result = new HashSet<TClass>(castsBySource.get(starting).keySet());
result.remove(starting);
return result;
}
};
if (!checker.isDag()) {
List<TClass> badPath = checker.getBadNodePath();
// create a List<String> where everything is lowercase except for the first and last instances
// of the offending node
List<String> names = new ArrayList<String>(badPath.size());
for (TClass tClass : badPath)
names.add(tClass.toString().toLowerCase());
String lastName = names.get(names.size() - 1);
String lastNameUpper = lastName.toUpperCase();
names.set(names.size() - 1, lastNameUpper);
names.set(names.indexOf(lastName), lastNameUpper);
throw new AkibanInternalException("non-DAG detected involving " + names);
}
}
// package-local; also used in testing
static Map<TClass, Map<TClass, TCast>> createStrongCastsMap(Map<TClass, Map<TClass, TCast>> castsBySource,
final Set<TCastIdentifier> strongCasts) {
Map<TClass,Map<TClass,TCast>> result = new HashMap<TClass, Map<TClass, TCast>>();
for (Map.Entry<TClass, Map<TClass,TCast>> origEntry : castsBySource.entrySet()) {
final TClass source = origEntry.getKey();
Map<TClass, TCast> filteredView = Maps.filterKeys(origEntry.getValue(), new Predicate<TClass>() {
@Override
public boolean apply(TClass target) {
return (source == target) || strongCasts.contains(new TCastIdentifier(source, target));
}
});
assert ! filteredView.isEmpty() : "no strong casts (including self casts) found for " + source;
result.put(source, new HashMap<TClass, TCast>(filteredView));
}
return result;
}
// private
private static Map<TClass,Map<TClass,TCast>> createStrongCastsMap(Map<TClass, Map<TClass, TCast>> castsBySource,
InstanceFinder finder)
{
Collection<? extends TStrongCasts> strongCastIds = finder.find(TStrongCasts.class);
Set<TCastIdentifier> strongCasts = new HashSet<TCastIdentifier>(strongCastIds.size()); // rough guess
for (TStrongCasts strongCastGenerator : strongCastIds) {
for (TCastIdentifier castId : strongCastGenerator.get(castsBySource.keySet())) {
TCast cast = cast(castsBySource, castId.getSource(), castId.getTarget());
if (cast == null)
throw new AkibanInternalException("no cast defined for " + castId +", which is marked as strong");
if (!strongCasts.add(castId)) {
logger.warn("multiple sources have listed cast {} as strong", castId);
}
}
}
return createStrongCastsMap(castsBySource, strongCasts);
}
// class state
private static final Logger logger = LoggerFactory.getLogger(T3RegistryServiceImpl.class);
// object state
private volatile Map<TClass,Map<TClass,TCast>> castsBySource;
private volatile Map<TClass,Map<TClass,TCast>> strongCastsBySource;
private volatile ListMultimap<String, ScalarsGroup> overloadsByName;
private volatile Map<String,Collection<TAggregator>> aggregatorsByName;
private volatile Collection<? extends TClass> tClasses;
private static final Comparator<TCastIdentifier> tcastIdentifierComparator = new Comparator<TCastIdentifier>() {
@Override
public int compare(TCastIdentifier o1, TCastIdentifier o2) {
String o1Str = o1.toString();
String o2Str = o2.toString();
return o1Str.compareTo(o2Str);
}
};
// inner classes
protected static class ScalarsGroupImpl implements ScalarsGroup {
@Override
public Collection<? extends TValidatedOverload> getOverloads() {
return overloads;
}
public ScalarsGroupImpl(Collection<TValidatedOverload> overloads) {
this.overloads = Collections.unmodifiableCollection(overloads);
boolean outRange[] = new boolean[1];
int argc[] = new int[1];
sameType = doFindSameType(overloads, argc, outRange);
outOfRangeVal = outRange[0];
nArgs = argc[0];
}
@Override
public boolean hasSameTypeAt(int pos)
{
return pos >= nArgs // if pos is out of range
? outOfRangeVal
: sameType.get(pos);
}
private static int nArgsOf(TValidatedOverload ovl)
{
return ovl.positionalInputs()
+ (ovl.varargInputSet() == null ? 0 : 1);
}
private static boolean hasVararg(TValidatedOverload ovl)
{
return ovl.varargInputSet() != null;
}
protected static BitSet doFindSameType(Collection<? extends TValidatedOverload> overloads, int range[], boolean outRange[])
{
ArrayList<Integer> nArgs = new ArrayList<Integer>();
// overload with the longest argument list
TValidatedOverload maxOvl = overloads.iterator().next();
int maxArgc = nArgsOf(maxOvl);
boolean hasVararg = hasVararg(maxOvl);
int n = 1;
// whether arg that's out of range should be 'same' or 'not same'
// false if all overloads in the group have fixed length
// true if all overloads with varargs in the group have the same targetType of vararg
// false otherwise
boolean outOfRange = false;
TClass firstVararg = null;
for (TValidatedOverload ovl : overloads)
{
int curArgc = nArgsOf(ovl);
nArgs.add(curArgc);
boolean curHasVar = hasVararg(ovl);
if (curHasVar)
{
if (firstVararg == null)
{
outOfRange = true;
firstVararg = ovl.varargInputSet().targetType();
}
else
outOfRange &= firstVararg.equals(ovl.varargInputSet().targetType());
}
if (curArgc > maxArgc
|| curArgc == maxArgc
&& hasVararg
&& !curHasVar)
{
hasVararg = hasVararg(ovl);
maxOvl = ovl;
maxArgc = curArgc;
}
++n;
}
outRange[0] = outOfRange;
range[0] = maxArgc;
// all the overloads in the group are vararg
if (hasVararg && maxArgc == 1)
{
BitSet ret = new BitSet(1);
ret.set(0, outOfRange);
return ret;
}
BitSet sameType = new BitSet(maxArgc);
Boolean same;
for (n = 0; n < maxArgc; ++n)
{
same = Boolean.TRUE;
TClass common = maxOvl.inputSetAt(n).targetType();
int index = 0;
for (TValidatedOverload ovl : overloads)
{
int curArgc = nArgs.get(index++);
TClass targetType;
// if the arg is absent
if (n >= curArgc)
{
if (!hasVararg(ovl))
continue;
else
targetType = ovl.varargInputSet().targetType();
}
else
targetType = ovl.inputSetAt(n).targetType();
if (targetType != null && !targetType.equals(common)
|| targetType == null && common != null)
{
same = Boolean.FALSE;
break;
}
}
sameType.set(n, same);
}
return sameType;
}
private final int nArgs;
private final boolean outOfRangeVal;
private final BitSet sameType;
private final Collection<? extends TValidatedOverload> overloads;
}
private static class SelfCast implements TCast {
@Override
public Constantness constness() {
return Constantness.UNKNOWN;
}
@Override
public TClass sourceClass() {
return tClass;
}
@Override
public TClass targetClass() {
return tClass;
}
@Override
public void evaluate(TExecutionContext context, PValueSource source, PValueTarget target) {
if (source.isNull()) {
target.putNull();
return;
}
TInstance srcInst = context.inputTInstanceAt(0);
TInstance dstInst = context.outputTInstance();
tClass.selfCast(context, srcInst, source, dstInst, target);
}
SelfCast(TClass tClass) {
this.tClass = tClass;
}
private final TClass tClass;
}
private static class ChainedCast implements TCast {
@Override
public Constantness constness() {
Constantness firstConst = first.constness();
return (firstConst == second.constness()) ? firstConst : Constantness.UNKNOWN;
}
@Override
public TClass sourceClass() {
return first.sourceClass();
}
@Override
public TClass targetClass() {
return second.targetClass();
}
@Override
public void evaluate(TExecutionContext context, PValueSource source, PValueTarget target) {
if (source.isNull()) {
target.putNull();
return;
}
PValue tmp = (PValue) context.exectimeObjectAt(TMP_PVALUE);
if (tmp == null) {
tmp = new PValue(first.targetClass().underlyingType());
context.putExectimeObject(TMP_PVALUE, tmp);
}
// TODO cache
TExecutionContext firstContext = context.deriveContext(
Collections.singletonList(context.inputTInstanceAt(0)),
intermediateType
);
TExecutionContext secondContext = context.deriveContext(
Collections.singletonList(intermediateType),
context.outputTInstance()
);
first.evaluate(firstContext, source, tmp);
second.evaluate(secondContext, tmp, target);
}
private ChainedCast(TCast first, TCast second) {
if (first.targetClass() != second.sourceClass()) {
throw new IllegalArgumentException("can't chain casts: " + first + " and " + second);
}
this.first = first;
this.second = second;
this.intermediateType = first.targetClass().instance();
}
private final TCast first;
private final TCast second;
private final TInstance intermediateType;
private static final int TMP_PVALUE = 0;
}
private class Bean implements T3RegistryMXBean {
@Override
public String describeTypes() {
return toYaml(typesDescriptors());
}
@Override
public String describeCasts() {
return toYaml(castsDescriptors());
}
@Override
public String describeScalars() {
return toYaml(scalarDescriptors());
}
@Override
public String describeAggregates() {
return toYaml(aggregateDescriptors());
}
@Override
public String describeAll() {
Map<String,Object> all = new LinkedHashMap<String, Object>(5);
all.put("types", typesDescriptors());
all.put("casts", castsDescriptors());
all.put("scalar_functions", scalarDescriptors());
all.put("aggregate_functions", aggregateDescriptors());
return toYaml(all);
}
private Object typesDescriptors() {
List<Map<String,Comparable<?>>> result = new ArrayList<Map<String,Comparable<?>>>(tClasses.size());
for (TClass tClass : tClasses) {
Map<String,Comparable<?>> map = new LinkedHashMap<String, Comparable<?>>();
buildTName("bundle", "name", tClass, map);
map.put("category", tClass.name().categoryName());
map.put("internalVersion", tClass.internalRepresentationVersion());
map.put("serializationVersion", tClass.serializationVersion());
map.put("fixedSize", tClass.hasFixedSerializationSize() ? tClass.fixedSerializationSize() : null);
result.add(map);
}
Collections.sort(result, new Comparator<Map<String, Comparable<?>>>() {
@Override
public int compare(Map<String, Comparable<?>> o1, Map<String, Comparable<?>> o2) {
return ComparisonChain.start()
.compare(o1.get("bundle"), o2.get("bundle"))
.compare(o1.get("category"), o2.get("category"))
.compare(o1.get("name"), o2.get("name"))
.result();
}
});
return result;
}
private Object castsDescriptors() {
// the starting size is just a guess
List<Map<String,Comparable<?>>> result = new ArrayList<Map<String,Comparable<?>>>(castsBySource.size() * 5);
for (Map<TClass,TCast> castsByTarget : castsBySource.values()) {
for (TCast tCast : castsByTarget.values()) {
Map<String,Comparable<?>> map = new LinkedHashMap<String, Comparable<?>>();
buildTName("source_bundle", "source_type", tCast.sourceClass(), map);
buildTName("target_bundle", "target_type", tCast.targetClass(), map);
map.put("strong", isStrong(tCast));
map.put("isDerived", tCast instanceof ChainedCast);
result.add(map);
}
}
Collections.sort(result, new Comparator<Map<String, Comparable<?>>>() {
@Override
public int compare(Map<String, Comparable<?>> o1, Map<String, Comparable<?>> o2) {
return ComparisonChain.start()
.compare(o1.get("source_bundle"), o2.get("source_bundle"))
.compare(o1.get("source_type"), o2.get("source_type"))
.compare(o1.get("target_bundle"), o2.get("target_bundle"))
.compare(o1.get("target_type"), o2.get("target_type"))
.result();
}
});
return result;
}
private Object scalarDescriptors() {
Multimap<String, TValidatedOverload> flattenedOverloads = HashMultimap.create();
for (Map.Entry<String, ScalarsGroup> entry : overloadsByName.entries()) {
String overloadName = entry.getKey();
ScalarsGroup scalarsGroup = entry.getValue();
flattenedOverloads.putAll(overloadName, scalarsGroup.getOverloads());
}
return describeOverloads(flattenedOverloads.asMap(), Functions.toStringFunction());
}
private Object aggregateDescriptors() {
return describeOverloads(aggregatorsByName, new Function<TAggregator, TClass>() {
@Override
public TClass apply(TAggregator aggr) {
return aggr.getTypeClass();
}
});
}
private <T extends HasId,S> Object describeOverloads(
Map<String, Collection<T>> elems, Function<? super T, S> format)
{
Map<String,Map<String,String>> result = new TreeMap<String, Map<String,String>>();
for (Map.Entry<String, ? extends Collection<T>> entry : elems.entrySet()) {
Collection<T> overloads = entry.getValue();
Map<String,String> overloadDescriptions = new TreeMap<String, String>();
int idSuffix = 1;
for (T overload : overloads) {
final String overloadId = overload.id();
final String origDescription = String.valueOf(format.apply(overload));
String overloadDescription = origDescription;
// We don't care about efficiency in this loop, so let's keep the code simple
while (overloadDescriptions.containsKey(overloadDescription)) {
overloadDescription = origDescription + " [" + Integer.toString(idSuffix++) + ']';
}
overloadDescriptions.put(overloadDescription, overloadId);
}
result.put(entry.getKey(), overloadDescriptions);
}
return result;
}
private void buildTName(String bundleTag, String nameTag, TClass tClass, Map<String, Comparable<?>> out) {
out.put(bundleTag, tClass.name().bundleId().name());
out.put(nameTag, tClass.name().unqualifiedName());
}
private String toYaml(Object obj) {
DumperOptions options = new DumperOptions();
options.setAllowReadOnlyProperties(true);
options.setDefaultFlowStyle(FlowStyle.BLOCK);
options.setIndent(4);
return new Yaml(options).dump(obj);
}
}
}
|
package com.cisco.trex.stateless;
import static org.pcap4j.util.ByteArrays.BYTE_SIZE_IN_BYTES;
import com.cisco.trex.stateless.exception.ServiceModeRequiredException;
import com.cisco.trex.stateless.model.Ipv6Node;
import com.cisco.trex.stateless.model.PortStatus;
import com.cisco.trex.stateless.model.StreamMode;
import com.cisco.trex.stateless.model.StreamModeRate;
import com.cisco.trex.stateless.model.StreamRxStats;
import com.cisco.trex.stateless.model.StreamVM;
import com.cisco.trex.stateless.model.TRexClientResult;
import com.cisco.trex.stateless.model.port.PortVlan;
import com.cisco.trex.stateless.model.vm.VMInstruction;
import com.google.common.collect.Lists;
import com.google.common.net.InetAddresses;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.pcap4j.packet.Dot1qVlanTagPacket;
import org.pcap4j.packet.EthernetPacket;
import org.pcap4j.packet.IcmpV6CommonPacket;
import org.pcap4j.packet.IcmpV6CommonPacket.IpV6NeighborDiscoveryOption;
import org.pcap4j.packet.IcmpV6EchoReplyPacket;
import org.pcap4j.packet.IcmpV6EchoRequestPacket;
import org.pcap4j.packet.IcmpV6NeighborAdvertisementPacket;
import org.pcap4j.packet.IcmpV6NeighborAdvertisementPacket.IcmpV6NeighborAdvertisementHeader;
import org.pcap4j.packet.IcmpV6NeighborSolicitationPacket;
import org.pcap4j.packet.IpV6NeighborDiscoverySourceLinkLayerAddressOption;
import org.pcap4j.packet.IpV6NeighborDiscoveryTargetLinkLayerAddressOption;
import org.pcap4j.packet.IpV6Packet;
import org.pcap4j.packet.IpV6SimpleFlowLabel;
import org.pcap4j.packet.IpV6SimpleTrafficClass;
import org.pcap4j.packet.Packet;
import org.pcap4j.packet.namednumber.EtherType;
import org.pcap4j.packet.namednumber.IcmpV6Code;
import org.pcap4j.packet.namednumber.IcmpV6Type;
import org.pcap4j.packet.namednumber.IpNumber;
import org.pcap4j.packet.namednumber.IpVersion;
import org.pcap4j.util.ByteArrays;
import org.pcap4j.util.MacAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IPv6NeighborDiscoveryService {
private static final EtherType QInQ =
new EtherType((short) 0x88a8, "802.1Q Provider Bridge (Q-in-Q)");
private static final Logger LOGGER = LoggerFactory.getLogger(IPv6NeighborDiscoveryService.class);
private TRexClient tRexClient;
public IPv6NeighborDiscoveryService(TRexClient tRexClient) {
this.tRexClient = tRexClient;
}
public Map<String, Ipv6Node> scan(int portIdx, int timeDuration, String dstIP, String srcIP)
throws ServiceModeRequiredException {
String broadcastIP = "ff02::1";
long endTimeSec = System.currentTimeMillis() + timeDuration / 2 * 1000;
TRexClientResult<PortStatus> portStatusResult = tRexClient.getPortStatus(portIdx);
PortStatus portStatus = portStatusResult.get();
if (!portStatus.getService()) {
throw new ServiceModeRequiredException();
}
String srcMac = portStatus.getAttr().getLayerConiguration().getL2Configuration().getSrc();
PortVlan vlan = portStatus.getAttr().getVlan();
Packet pingPkt =
buildICMPV6EchoReq(
srcIP,
srcMac,
multicastMacFromIPv6(broadcastIP).toString(),
expandIPv6Address(broadcastIP));
tRexClient.startStreamsIntermediate(portIdx, Collections.singletonList(buildStream(pingPkt)));
List<com.cisco.trex.stateless.model.Stream> nsNaStreams = new ArrayList<>();
Predicate<EthernetPacket> ipV6NSPktFilter =
etherPkt ->
etherPkt.contains(IcmpV6NeighborSolicitationPacket.class)
|| etherPkt.contains(IcmpV6NeighborAdvertisementPacket.class);
while (endTimeSec > System.currentTimeMillis()) {
tRexClient
.getRxQueue(portIdx, ipV6NSPktFilter)
.forEach(
pkt -> {
IpV6Packet ipV6Packet = pkt.get(IpV6Packet.class);
String nodeIp = ipV6Packet.getHeader().getSrcAddr().toString().substring(1);
String nodeMac = getLinkLayerAddress(ipV6Packet);
nsNaStreams.add(
buildStream(buildICMPV6NSPkt(vlan, srcMac, nodeMac, nodeIp, srcIP)));
nsNaStreams.add(
buildStream(buildICMPV6NAPkt(vlan, srcMac, nodeMac, nodeIp, srcIP)));
});
}
tRexClient.startStreamsIntermediate(portIdx, nsNaStreams);
List<EthernetPacket> icmpNAReplies = new ArrayList<>();
Predicate<EthernetPacket> ipV6NAPktFilter =
etherPkt -> etherPkt.contains(IcmpV6NeighborAdvertisementPacket.class);
endTimeSec = System.currentTimeMillis() + timeDuration / 2 * 1000;
while (endTimeSec > System.currentTimeMillis()) {
icmpNAReplies.addAll(tRexClient.getRxQueue(portIdx, ipV6NAPktFilter));
}
tRexClient.removeRxQueue(portIdx);
return icmpNAReplies
.stream()
.map(this::toIpv6Node)
.distinct()
.filter(
ipv6Node -> {
if (dstIP != null) {
return InetAddresses.forString(dstIP)
.equals(InetAddresses.forString(ipv6Node.getIp()));
}
return true;
})
.collect(Collectors.toMap(Ipv6Node::getIp, node -> node));
}
private Ipv6Node toIpv6Node(EthernetPacket ethernetPacket) {
IcmpV6NeighborAdvertisementHeader icmpV6NaHdr =
ethernetPacket.get(IcmpV6NeighborAdvertisementPacket.class).getHeader();
boolean isRouter = icmpV6NaHdr.getRouterFlag();
String nodeIp = icmpV6NaHdr.getTargetAddress().toString().substring(1);
String nodeMac = ethernetPacket.getHeader().getSrcAddr().toString();
return new Ipv6Node(nodeMac, nodeIp, isRouter);
}
public EthernetPacket sendIcmpV6Echo(
int portIdx, String dstIp, int icmpId, int icmpSeq, int timeOut)
throws ServiceModeRequiredException {
PortStatus portStatus = tRexClient.getPortStatus(portIdx).get();
if (!portStatus.getService()) {
throw new ServiceModeRequiredException();
}
String srcMac = portStatus.getAttr().getLayerConiguration().getL2Configuration().getSrc();
return sendIcmpV6Echo(portIdx, srcMac, dstIp, icmpId, icmpSeq, timeOut);
}
public EthernetPacket sendIcmpV6Echo(
int portIdx, String srcMac, String dstIp, int icmpId, int icmpSeq, int timeOut) {
Map<String, EthernetPacket> stringEthernetPacketMap =
sendNSandIcmpV6Req(portIdx, timeOut, srcMac, dstIp);
Optional<Map.Entry<String, EthernetPacket>> icmpMulticastResponse =
stringEthernetPacketMap.entrySet().stream().findFirst();
EthernetPacket icmpUnicastReply = null;
if (icmpMulticastResponse.isPresent()) {
EthernetPacket etherPkt = icmpMulticastResponse.get().getValue();
String nodeMac = etherPkt.getHeader().getSrcAddr().toString();
Packet pingPkt = buildICMPV6EchoReq(null, srcMac, nodeMac, dstIp, icmpId, icmpSeq);
tRexClient.startStreamsIntermediate(portIdx, Arrays.asList(buildStream(pingPkt)));
long endTimeSec = System.currentTimeMillis() + timeOut * 1000 / 2;
while (endTimeSec > System.currentTimeMillis()) {
List<EthernetPacket> rxQueue =
tRexClient.getRxQueue(portIdx, pkt -> pkt.contains(IcmpV6EchoReplyPacket.class));
if (!rxQueue.isEmpty()) {
icmpUnicastReply = rxQueue.get(0);
}
}
}
tRexClient.removeRxQueue(portIdx);
if (tRexClient.getPortStatus(portIdx).get().getState().equals("TX")) {
tRexClient.stopTraffic(portIdx);
}
tRexClient.removeAllStreams(portIdx);
return icmpUnicastReply;
}
public EthernetPacket sendNeighborSolicitation(int portIdx, int timeout, String dstIp)
throws ServiceModeRequiredException {
PortStatus portStatus = tRexClient.getPortStatus(portIdx).get();
if (!portStatus.getService()) {
throw new ServiceModeRequiredException();
}
String srcMac = portStatus.getAttr().getLayerConiguration().getL2Configuration().getSrc();
PortVlan vlan = portStatus.getAttr().getVlan();
return sendNeighborSolicitation(vlan, portIdx, timeout, srcMac, null, null, dstIp);
}
public EthernetPacket sendNeighborSolicitation(
PortVlan vlan,
int portIdx,
int timeout,
String srcMac,
String dstMac,
String srcIp,
String dstIp) {
long endTs = System.currentTimeMillis() + timeout * 1000;
final String multicastMac = dstMac != null ? dstMac : multicastMacFromIPv6(dstIp).toString();
Packet icmpv6NSPkt = buildICMPV6NSPkt(vlan, srcMac, multicastMac, dstIp, srcIp);
LOGGER.trace("Sending IPv6 Neighbor Solicitation packet:\n{}", icmpv6NSPkt);
tRexClient.startStreamsIntermediate(portIdx, Arrays.asList(buildStream(icmpv6NSPkt)));
Predicate<EthernetPacket> ipV6NAPktFilter =
etherPkt -> {
if (!etherPkt.contains(IcmpV6NeighborAdvertisementPacket.class)) {
return false;
}
IcmpV6NeighborAdvertisementHeader icmpV6NaHdr =
etherPkt.get(IcmpV6NeighborAdvertisementPacket.class).getHeader();
String nodeIp = icmpV6NaHdr.getTargetAddress().toString().substring(1);
IpV6Packet.IpV6Header ipV6Header = etherPkt.get(IpV6Packet.class).getHeader();
String dstAddr = ipV6Header.getDstAddr().toString().substring(1);
try {
Inet6Address dstIPv6Addr = (Inet6Address) InetAddress.getByName(dstAddr);
Inet6Address srcIPv6Addr =
(Inet6Address) InetAddress.getByName(generateIPv6AddrFromMAC(srcMac));
Inet6Address nodeIpv6 = (Inet6Address) InetAddress.getByName(nodeIp);
Inet6Address targetIpv6inNS = (Inet6Address) InetAddress.getByName(dstIp);
return icmpV6NaHdr.getSolicitedFlag()
&& nodeIpv6.equals(targetIpv6inNS)
&& dstIPv6Addr.equals(srcIPv6Addr);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Invalid address", e);
}
};
EthernetPacket na = null;
while (endTs > System.currentTimeMillis() && na == null) {
List<EthernetPacket> pkts = tRexClient.getRxQueue(portIdx, ipV6NAPktFilter);
if (!pkts.isEmpty()) {
na = pkts.get(0);
}
}
tRexClient.removeRxQueue(portIdx);
if (tRexClient.getPortStatus(portIdx).get().getState().equals("TX")) {
tRexClient.stopTraffic(portIdx);
}
tRexClient.removeAllStreams(portIdx);
return na;
}
private static AbstractMap.SimpleEntry<EtherType, Packet.Builder> buildVlan(
IpV6Packet.Builder ipv6Builder, PortVlan vlan) {
Queue<Integer> vlanTags = new LinkedList<>(Lists.reverse(vlan.getTags()));
Packet.Builder resultPayloadBuilder = ipv6Builder;
EtherType resultEtherType = EtherType.IPV6;
if (vlanTags.peek() != null) {
Dot1qVlanTagPacket.Builder vlanInsideBuilder = new Dot1qVlanTagPacket.Builder();
vlanInsideBuilder
.type(EtherType.IPV6)
.vid(vlanTags.poll().shortValue())
.payloadBuilder(ipv6Builder);
resultPayloadBuilder = vlanInsideBuilder;
resultEtherType = EtherType.DOT1Q_VLAN_TAGGED_FRAMES;
if (vlanTags.peek() != null) {
Dot1qVlanTagPacket.Builder vlanOutsideBuilder = new Dot1qVlanTagPacket.Builder();
vlanOutsideBuilder
.type(EtherType.DOT1Q_VLAN_TAGGED_FRAMES)
.vid(vlanTags.poll().shortValue())
.payloadBuilder(vlanInsideBuilder);
resultPayloadBuilder = vlanOutsideBuilder;
resultEtherType = QInQ;
}
}
return new AbstractMap.SimpleEntry<>(resultEtherType, resultPayloadBuilder);
}
private Map<String, EthernetPacket> sendNSandIcmpV6Req(
int portIdx, int timeDuration, String srcMac, String dstIp) {
long endTs = System.currentTimeMillis() + timeDuration * 1000;
TRexClientResult<PortStatus> portStatusResult = tRexClient.getPortStatus(portIdx);
PortVlan vlan = portStatusResult.get().getAttr().getVlan();
Packet pingPkt = buildICMPV6EchoReq(null, srcMac, null, dstIp);
Packet icmpv6NSPkt =
buildICMPV6NSPkt(vlan, srcMac, multicastMacFromIPv6(dstIp).toString(), dstIp, null);
List<com.cisco.trex.stateless.model.Stream> stlStreams =
Stream.of(buildStream(pingPkt), buildStream(icmpv6NSPkt)).collect(Collectors.toList());
tRexClient.startStreamsIntermediate(portIdx, stlStreams);
Map<String, EthernetPacket> naIncomingRequests = new HashMap<>();
Predicate<EthernetPacket> ipV6NAPktFilter =
etherPkt -> {
if (!etherPkt.contains(IcmpV6NeighborAdvertisementPacket.class)) {
return false;
}
IcmpV6NeighborAdvertisementHeader icmpV6NaHdr =
etherPkt.get(IcmpV6NeighborAdvertisementPacket.class).getHeader();
String nodeIp = icmpV6NaHdr.getTargetAddress().toString().substring(1);
IpV6Packet.IpV6Header ipV6Header = etherPkt.get(IpV6Packet.class).getHeader();
String dstAddr = ipV6Header.getDstAddr().toString().substring(1);
try {
Inet6Address dstIPv6Addr = (Inet6Address) InetAddress.getByName(dstAddr);
Inet6Address srcIPv6Addr =
(Inet6Address) InetAddress.getByName(generateIPv6AddrFromMAC(srcMac));
return !naIncomingRequests.containsKey(nodeIp) && dstIPv6Addr.equals(srcIPv6Addr);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Invalid address", e);
}
};
while (endTs > System.currentTimeMillis()) {
tRexClient
.getRxQueue(portIdx, ipV6NAPktFilter)
.forEach(
pkt -> {
IcmpV6NeighborAdvertisementHeader icmpV6NaHdr =
pkt.get(IcmpV6NeighborAdvertisementPacket.class).getHeader();
String nodeIp = icmpV6NaHdr.getTargetAddress().toString().substring(1);
naIncomingRequests.put(nodeIp, pkt);
});
}
tRexClient.removeRxQueue(portIdx);
return naIncomingRequests;
}
private static com.cisco.trex.stateless.model.Stream buildStream(Packet pkt) {
return buildStream(pkt, Collections.emptyList());
}
private static com.cisco.trex.stateless.model.Stream buildStream(
Packet pkt, List<VMInstruction> instructions) {
int streamId = (int) (Math.random() * 1000);
return new com.cisco.trex.stateless.model.Stream(
streamId,
true,
3,
0.0,
new StreamMode(
10,
10,
5,
1.0,
new StreamModeRate(StreamModeRate.Type.percentage, 100.0),
StreamMode.Type.single_burst),
-1,
pkt,
new StreamRxStats(false, false, true, streamId),
new StreamVM("", instructions),
true,
false,
null);
}
static Packet buildICMPV6NSPkt(
PortVlan vlan, String srcMac, String dstMac, String dstIp, String srcIp) {
EthernetPacket.Builder ethBuilder = new EthernetPacket.Builder();
try {
IpV6NeighborDiscoverySourceLinkLayerAddressOption sourceLLAddr =
new IpV6NeighborDiscoverySourceLinkLayerAddressOption.Builder()
.correctLengthAtBuild(true)
.linkLayerAddress(hexStringToByteArray(srcMac.replace(":", "")))
.build();
IcmpV6NeighborSolicitationPacket.Builder ipv6NSBuilder =
new IcmpV6NeighborSolicitationPacket.Builder();
ipv6NSBuilder
.options(Arrays.asList(sourceLLAddr))
.targetAddress((Inet6Address) InetAddress.getByName(dstIp));
final String specifiedSrcIP = srcIp != null ? srcIp : generateIPv6AddrFromMAC(srcMac);
// Calculate the Solicited-Node multicast address, RFC 4291 chapter 2.7.1
String[] destIpParts = dstIp.split(":");
String multicastIp =
String.format(
"FF02::1:FF%s:%s", destIpParts[6].substring(2, 4), destIpParts[7].substring(0, 4));
IcmpV6CommonPacket.Builder icmpCommonPktBuilder = new IcmpV6CommonPacket.Builder();
icmpCommonPktBuilder
.srcAddr((Inet6Address) InetAddress.getByName(specifiedSrcIP))
.dstAddr((Inet6Address) InetAddress.getByName(multicastIp))
.type(IcmpV6Type.NEIGHBOR_SOLICITATION)
.code(IcmpV6Code.NO_CODE)
.correctChecksumAtBuild(true)
.payloadBuilder(ipv6NSBuilder);
IpV6Packet.Builder ipV6Builder = new IpV6Packet.Builder();
ipV6Builder
.srcAddr((Inet6Address) InetAddress.getByName(specifiedSrcIP))
.dstAddr((Inet6Address) InetAddress.getByName(multicastIp))
.version(IpVersion.IPV6)
.hopLimit((byte) -1)
.trafficClass(IpV6SimpleTrafficClass.newInstance((byte) 0))
.flowLabel(IpV6SimpleFlowLabel.newInstance(0))
.nextHeader(IpNumber.ICMPV6)
.payloadBuilder(icmpCommonPktBuilder)
.correctLengthAtBuild(true);
AbstractMap.SimpleEntry<EtherType, Packet.Builder> payload =
new AbstractMap.SimpleEntry<>(EtherType.IPV6, ipV6Builder);
if (!vlan.getTags().isEmpty()) {
payload = buildVlan(ipV6Builder, vlan);
}
ethBuilder
.srcAddr(MacAddress.getByName(srcMac))
.dstAddr(MacAddress.getByName(dstMac))
.type(payload.getKey())
.payloadBuilder(payload.getValue())
.paddingAtBuild(true);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Invalid address", e);
}
return ethBuilder.build();
}
/**
* IPv6 Neighbor Discovery Source Link Layer Address header
*
* <p>0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | Link-Layer
* Address ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
private static String getLinkLayerAddress(IpV6Packet pkt) {
final int TYPE_OFFSET = 0;
final int TYPE_SIZE = BYTE_SIZE_IN_BYTES;
final int LENGTH_OFFSET = TYPE_OFFSET + TYPE_SIZE;
final int LENGTH_SIZE = BYTE_SIZE_IN_BYTES;
final int LINK_LAYER_ADDRESS_OFFSET = LENGTH_OFFSET + LENGTH_SIZE;
final int LINK_LAYER_ADDRESS_LENGTH = 6; // MAC address
IcmpV6NeighborSolicitationPacket nsPkt = pkt.get(IcmpV6NeighborSolicitationPacket.class);
IpV6NeighborDiscoveryOption linkLayerAddressOption = nsPkt.getHeader().getOptions().get(0);
byte[] linkLayerAddress =
ByteArrays.getSubArray(
linkLayerAddressOption.getRawData(),
LINK_LAYER_ADDRESS_OFFSET,
LINK_LAYER_ADDRESS_LENGTH);
return ByteArrays.toHexString(linkLayerAddress, ":");
}
private static Packet buildICMPV6NAPkt(
PortVlan vlan, String srcMac, String dstMac, String dstIp, String srcIP) {
final String specifiedSrcIP = srcIP != null ? srcIP : generateIPv6AddrFromMAC(srcMac);
EthernetPacket.Builder ethBuilder = new EthernetPacket.Builder();
try {
IpV6NeighborDiscoveryTargetLinkLayerAddressOption tLLAddr =
new IpV6NeighborDiscoveryTargetLinkLayerAddressOption.Builder()
.correctLengthAtBuild(true)
.linkLayerAddress(hexStringToByteArray(dstMac.replace(":", "")))
.build();
IcmpV6NeighborAdvertisementPacket.Builder ipv6NABuilder =
new IcmpV6NeighborAdvertisementPacket.Builder();
ipv6NABuilder
.routerFlag(false)
.options(Arrays.asList(tLLAddr))
.solicitedFlag(true)
.overrideFlag(true)
.targetAddress((Inet6Address) InetAddress.getByName(specifiedSrcIP));
IcmpV6CommonPacket.Builder icmpCommonPktBuilder = new IcmpV6CommonPacket.Builder();
icmpCommonPktBuilder
.srcAddr((Inet6Address) InetAddress.getByName(specifiedSrcIP))
.dstAddr((Inet6Address) InetAddress.getByName(dstIp))
.type(IcmpV6Type.NEIGHBOR_ADVERTISEMENT)
.code(IcmpV6Code.NO_CODE)
.correctChecksumAtBuild(true)
.payloadBuilder(ipv6NABuilder);
IpV6Packet.Builder ipV6Builder = new IpV6Packet.Builder();
ipV6Builder
.srcAddr((Inet6Address) InetAddress.getByName(specifiedSrcIP))
.dstAddr((Inet6Address) InetAddress.getByName(dstIp))
.version(IpVersion.IPV6)
.trafficClass(IpV6SimpleTrafficClass.newInstance((byte) 0))
.flowLabel(IpV6SimpleFlowLabel.newInstance(0))
.nextHeader(IpNumber.ICMPV6)
.hopLimit((byte) 1)
.payloadBuilder(icmpCommonPktBuilder)
.correctLengthAtBuild(true);
AbstractMap.SimpleEntry<EtherType, Packet.Builder> payload =
new AbstractMap.SimpleEntry<>(EtherType.IPV6, ipV6Builder);
if (!vlan.getTags().isEmpty()) {
payload = buildVlan(ipV6Builder, vlan);
}
ethBuilder
.srcAddr(MacAddress.getByName(srcMac))
.dstAddr(MacAddress.getByName("33:33:00:00:00:01"))
.type(payload.getKey())
.payloadBuilder(payload.getValue())
.paddingAtBuild(true);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Invalid address", e);
}
return ethBuilder.build();
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] =
(byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
}
return data;
}
public static EthernetPacket buildICMPV6EchoReq(
String srcIp,
String srcMacString,
String dstMacString,
String dstIp,
int icmpId,
int icmpSeq) {
PortVlan vlan = new PortVlan();
vlan.setTags(new ArrayList<Integer>());
return buildICMPV6EchoReq(vlan, srcIp, srcMacString, dstMacString, dstIp, icmpId, icmpSeq);
}
public static EthernetPacket buildICMPV6EchoReq(
PortVlan vlan,
String srcIp,
String srcMacString,
String dstMacString,
String dstIp,
int icmpId,
int icmpSeq) {
/*
*
* mld_pkt = (Ether(src = self.src_mac, dst = self.dst_mld_mac) / IPv6(src = self.src_ip, dst =
* self.dst_mld_ip, hlim = 1) / IPv6ExtHdrHopByHop(options = [RouterAlert(), PadN()]) /
* ICMPv6MLReportV2() / MLDv2Addr(type = 4, len = 0, multicast_addr = 'ff02::2')) ping_pkt =
* (Ether(src = self.src_mac, dst = dst_mac) / IPv6(src = self.src_ip, dst = self.dst_ip, hlim =
* 1) / ICMPv6EchoRequest()) return [self.vlan.embed(mld_pkt), self.vlan.embed(ping_pkt)]
*/
final String specifiedSrcIP = srcIp != null ? srcIp : generateIPv6AddrFromMAC(srcMacString);
IcmpV6EchoRequestPacket.Builder icmpV6ERBuilder = new IcmpV6EchoRequestPacket.Builder();
icmpV6ERBuilder.identifier((short) icmpId).sequenceNumber((short) icmpSeq);
IcmpV6CommonPacket.Builder icmpCommonPktBuilder = new IcmpV6CommonPacket.Builder();
try {
icmpCommonPktBuilder
.srcAddr((Inet6Address) InetAddress.getByName(specifiedSrcIP))
.dstAddr(
(Inet6Address) InetAddress.getByName(dstIp != null ? dstIp : "ff02:0:0:0:0:0:0:1"))
.type(IcmpV6Type.ECHO_REQUEST)
.code(IcmpV6Code.NO_CODE)
.correctChecksumAtBuild(true)
.payloadBuilder(icmpV6ERBuilder);
IpV6Packet.Builder ipV6Builder = new IpV6Packet.Builder();
ipV6Builder
.srcAddr((Inet6Address) InetAddress.getByName(specifiedSrcIP))
.dstAddr(
(Inet6Address) InetAddress.getByName(dstIp != null ? dstIp : "ff02:0:0:0:0:0:0:1"))
.version(IpVersion.IPV6)
.trafficClass(IpV6SimpleTrafficClass.newInstance((byte) 0))
.flowLabel(IpV6SimpleFlowLabel.newInstance(0))
.nextHeader(IpNumber.ICMPV6)
.hopLimit((byte) 64)
.payloadBuilder(icmpCommonPktBuilder)
.correctLengthAtBuild(true);
MacAddress dstMac;
if (dstMacString != null) {
dstMac = MacAddress.getByName(dstMacString);
} else {
dstMac =
dstIp == null ? MacAddress.getByName("33:33:00:00:00:01") : multicastMacFromIPv6(dstIp);
}
EthernetPacket.Builder ethBuilder = new EthernetPacket.Builder();
AbstractMap.SimpleEntry<EtherType, Packet.Builder> payload =
new AbstractMap.SimpleEntry<>(EtherType.IPV6, ipV6Builder);
if (!vlan.getTags().isEmpty()) {
payload = buildVlan(ipV6Builder, vlan);
}
ethBuilder
.srcAddr(MacAddress.getByName(srcMacString))
.dstAddr(dstMac)
.dstAddr(dstMac)
.type(payload.getKey())
.payloadBuilder(payload.getValue())
.paddingAtBuild(true);
return ethBuilder.build();
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Invalid address", e);
}
}
public static EthernetPacket buildICMPV6EchoReq(
String srcIp, String srcMacString, String dstMacString, String dstIp) {
return buildICMPV6EchoReq(srcIp, srcMacString, dstMacString, dstIp, 0, 0);
}
/**
* Convert to solicitated-node multicast described in RFC 2624 section 7
*
* @param ipV6
* @return
*/
static MacAddress multicastMacFromIPv6(String ipV6) {
String expandedIPv6 = expandIPv6Address(ipV6);
List<Long> ipv6Octets =
Arrays.stream(expandedIPv6.split(":"))
.map(octet -> Long.parseLong(octet, 16))
.collect(Collectors.toList());
int lastIdx = ipv6Octets.size() - 1;
int preLastIdx = ipv6Octets.size() - 2;
String macAddressStr =
String.format(
"33:33:ff:%02x:%02x:%02x",
divMod(ipv6Octets.get(preLastIdx), 256)[1],
divMod(ipv6Octets.get(lastIdx), 256)[0],
divMod(ipv6Octets.get(lastIdx), 256)[1]);
return MacAddress.getByName(macAddressStr);
}
private static long[] divMod(long a, long b) {
long[] result = new long[2];
result[1] = a % b;
result[0] = (a - result[1]) / b;
return result;
}
private static String expandIPv6Address(String shortAddress) {
String[] addressArray = shortAddress.split(":");
if (shortAddress.startsWith(":")) {
addressArray[0] = "0";
} else if (shortAddress.endsWith(":")) {
addressArray[addressArray.length - 1] = "0";
}
for (int i = 0; i < addressArray.length; i++) {
if (addressArray[i] == null || addressArray[i].isEmpty()) {
StringBuilder sb = new StringBuilder();
int leftSize = i + 1;
String[] left = new String[i + 1];
System.arraycopy(addressArray, 0, left, 0, leftSize);
sb.append(Arrays.stream(left).collect(Collectors.joining(":")));
String[] expanded =
Stream.generate(() -> "0").limit(9 - addressArray.length).toArray(String[]::new);
sb.append(Arrays.stream(expanded).collect(Collectors.joining(":")));
sb.append(":");
int rightSize = addressArray.length - i - 1;
String[] right = new String[rightSize];
System.arraycopy(addressArray, i + 1, right, 0, rightSize);
sb.append(Arrays.stream(right).collect(Collectors.joining(":")));
return sb.toString();
}
}
return Arrays.stream(addressArray).collect(Collectors.joining(":"));
}
static String generateIPv6AddrFromMAC(String mac) {
String prefix = "fe80";
List<Integer> macOctets =
Arrays.stream(mac.split(":"))
.map(octet -> Integer.parseInt(octet, 16))
.collect(Collectors.toList());
// insert ff fe in the middle
macOctets.add(3, 0xfe);
macOctets.add(3, 0xff);
// invert second bind
macOctets.set(0, macOctets.get(0) ^ 0b1 << 1);
List<String> strOctets = new ArrayList<>();
for (int i = 0; i < macOctets.size(); i += 2) {
strOctets.add(
String.format(
"%s%s",
StringUtils.leftPad(Integer.toHexString(macOctets.get(i)), 2, "0"),
StringUtils.leftPad(Integer.toHexString(macOctets.get(i + 1)), 2, "0")));
}
return String.format("%s::%s", prefix, String.join(":", strOctets));
}
}
|
package com.csfacturacion.csreporter.impl.util;
import com.csfacturacion.csreporter.Credenciales;
import com.csfacturacion.csreporter.Parametros;
import com.csfacturacion.csreporter.impl.http.Request;
import com.google.common.collect.Maps;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.UUID;
import org.apache.http.client.utils.URIBuilder;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
/**
*
* @author emerino
*/
public class RequestFactory {
private static final String HOST_DEFAULT = "www.csfacturacion.com";
private static final String PATH_DEFAULT = "/webservices/csdescargasat";
private static final String SCHEMA_DEFAULT = "https";
private static DateTimeFormatter dateFormatter;
private final String wsSchema;
private final String wsHost;
private final String wsPath;
public RequestFactory() {
this(SCHEMA_DEFAULT, HOST_DEFAULT, PATH_DEFAULT);
}
public RequestFactory(String wsSchema, String wsHost, String wsPath) {
this.wsHost = wsHost;
this.wsPath = wsPath;
this.wsSchema = wsSchema;
}
protected URIBuilder newBaseURIBuilder() {
return newBaseURIBuilder("");
}
protected URIBuilder newBaseURIBuilder(String path) {
return new URIBuilder()
.setScheme(wsSchema)
.setHost(wsHost)
.setPath(wsPath + path);
}
public Request newConsultaRequest(Credenciales csCredenciales,
Credenciales satCredenciales,
Parametros params) {
String tipo;
switch (params.getTipo()) {
case EMITIDAS:
tipo = "emitidas";
break;
case RECIBIDAS:
tipo = "recibidas";
break;
default:
tipo = "todos";
break;
}
try {
DateTimeFormatter df = getDateFormatter();
URIBuilder consultaUriBuilder = newBaseURIBuilder()
.setParameter("method", "ObtenerCfdisV2")
.setParameter("cRfcContrato", csCredenciales.getUsuario())
.setParameter("cpassContrato", csCredenciales.getPassword())
.setParameter("cRfc", satCredenciales.getUsuario())
.setParameter("cPassword", satCredenciales.getPassword())
.setParameter("cFchI",
df.print(params.getFechaInicio().getTime()))
.setParameter("cFchF",
df.print(params.getFechaFin().getTime()))
.setParameter("cConsulta", tipo)
.setParameter("cRfcSearch",
(params.getRfcBusqueda() != null)
? params.getRfcBusqueda().toString()
: "todos")
.setParameter("cServicio",
String.valueOf(params.getServicio().getNumero()));
String status;
switch (params.getStatus()) {
case VIGENTE:
status = "vigentes";
break;
case CANCELADO:
status = "cancelados";
break;
default:
status = "todos";
break;
}
consultaUriBuilder.setParameter("cEstatus", status);
return new Request(consultaUriBuilder.build(),
Request.HttpMethod.GET);
} catch (URISyntaxException e) {
throw new InvalidRequest(e);
}
}
public Request newRepetirConsultaRequest(UUID folio) {
try {
Map<String, String> entity = Maps.newHashMap();
entity.put("idConsulta", folio.toString());
return new Request(
newBaseURIBuilder("/repetir").build(),
Request.HttpMethod.POST,
entity);
} catch (URISyntaxException e) {
throw new InvalidRequest(e);
}
}
public Request newStatusRequest(UUID folio) {
try {
return new Request(
newResultadosURIBuilder(folio, "/progreso")
.build(),
Request.HttpMethod.POST);
} catch (URISyntaxException e) {
// log
throw new InvalidRequest(e);
}
}
protected URIBuilder newResultadosURIBuilder(UUID folio, String path) {
return newBaseURIBuilder("/resultados/" + folio + path);
}
public Request newResumenRequest(UUID folio) {
return newResultadosRequest(folio, "/resumen");
}
public Request newResultadosRequest(UUID folio, int pagina) {
return newResultadosRequest(folio, "/" + pagina);
}
private Request newResultadosRequest(UUID folio, String path) {
try {
return new Request(
newResultadosURIBuilder(folio, path)
.build(),
Request.HttpMethod.GET);
} catch (URISyntaxException e) {
// log
throw new InvalidRequest(e);
}
}
public Request newDescargaRequest(UUID folio, UUID folioCFDI) {
try {
return new Request(
newDescargaURIBuilder(folio, folioCFDI)
.build(),
Request.HttpMethod.GET)
.setAcceptMediaType(Request.MediaType.TEXT_XML);
} catch (URISyntaxException e) {
// log
throw new RuntimeException();
}
}
protected URIBuilder newDescargaURIBuilder(UUID folio, UUID folioCFDI) {
return newBaseURIBuilder("/descargas/" + folio + "/" + folioCFDI);
}
protected static DateTimeFormatter getDateFormatter() {
if (dateFormatter == null) {
dateFormatter = ISODateTimeFormat.dateHourMinuteSecond();
}
return dateFormatter;
}
}
|
package com.forgeessentials.protection;
import static cpw.mods.fml.common.eventhandler.Event.Result.ALLOW;
import static cpw.mods.fml.common.eventhandler.Event.Result.DENY;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MovingObjectPosition;
import net.minecraftforge.common.util.BlockSnapshot;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.event.entity.living.LivingSpawnEvent.CheckSpawn;
import net.minecraftforge.event.entity.living.LivingSpawnEvent.SpecialSpawn;
import net.minecraftforge.event.entity.player.AttackEntityEvent;
import net.minecraftforge.event.entity.player.EntityInteractEvent;
import net.minecraftforge.event.entity.player.EntityItemPickupEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.entity.player.PlayerOpenContainerEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.BlockEvent.BreakEvent;
import com.forgeessentials.api.APIRegistry;
import com.forgeessentials.util.FunctionHelper;
import com.forgeessentials.util.OutputHandler;
import com.forgeessentials.util.UserIdent;
import com.forgeessentials.util.events.PlayerChangedZone;
import com.forgeessentials.util.events.ServerEventHandler;
import com.forgeessentials.util.selections.WorldPoint;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.Event.Result;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.ServerTickEvent;
public class ProtectionEventHandler extends ServerEventHandler {
public static final List<EntityPlayer> playerTickList = new ArrayList<>();
@SubscribeEvent(priority = EventPriority.LOW)
public void attackEntityEvent(AttackEntityEvent e)
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
return;
if (e.target == null)
return;
EntityPlayer source = e.entityPlayer;
if (e.target instanceof EntityPlayer)
{
// player -> player
EntityPlayer target = (EntityPlayer) e.target;
if (!APIRegistry.perms.checkPermission(new UserIdent(target), ModuleProtection.PERM_PVP)
|| !APIRegistry.perms.checkPermission(new UserIdent(source), ModuleProtection.PERM_PVP)
|| !APIRegistry.perms.checkPermission(new UserIdent(source), new WorldPoint(target), ModuleProtection.PERM_PVP))
{
e.setCanceled(true);
}
}
else
{
// player -> entity
Entity target = e.target;
WorldPoint targetPos = new WorldPoint(e.target);
String permission = ModuleProtection.PERM_DAMAGE_TO + "." + target.getClass().getSimpleName();
if (ModuleProtection.isDebugMode(source))
OutputHandler.chatNotification(source, permission);
if (!APIRegistry.perms.checkPermission(new UserIdent(source), targetPos, permission))
{
e.setCanceled(true);
}
}
}
@SubscribeEvent(priority = EventPriority.LOW)
public void livingHurtEvent(LivingHurtEvent e)
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
return;
if (e.entityLiving == null)
return;
if (e.source.getEntity() instanceof EntityPlayer)
{
EntityPlayer source = (EntityPlayer) e.source.getEntity();
if (e.entityLiving instanceof EntityPlayer)
{
// player -> player
EntityPlayer target = (EntityPlayer) e.entityLiving;
if (!APIRegistry.perms.checkPermission(new UserIdent(target), ModuleProtection.PERM_PVP)
|| !APIRegistry.perms.checkPermission(new UserIdent(source), ModuleProtection.PERM_PVP)
|| !APIRegistry.perms.checkPermission(new UserIdent(source), new WorldPoint(target), ModuleProtection.PERM_PVP))
{
e.setCanceled(true);
return;
}
}
else
{
// player -> living
EntityLivingBase target = e.entityLiving;
String permission = ModuleProtection.PERM_DAMAGE_TO + "." + target.getClass().getSimpleName();
if (ModuleProtection.isDebugMode(source))
OutputHandler.chatNotification(source, permission);
if (!APIRegistry.perms.checkPermission(new UserIdent(source), new WorldPoint(target), ModuleProtection.PERM_INTERACT_ENTITY))
{
e.setCanceled(true);
return;
}
}
}
else
{
if (e.entityLiving instanceof EntityPlayer)
{
// non-player -> player (fall-damage, mob, dispenser, lava)
EntityPlayer target = (EntityPlayer) e.entityLiving;
String permission = ModuleProtection.PERM_DAMAGE_BY + "." + e.source.damageType;
if (ModuleProtection.isDebugMode(target))
OutputHandler.chatNotification(target, permission);
if (!APIRegistry.perms.checkPermission(new UserIdent(target), permission))
{
e.setCanceled(true);
return;
}
}
if (e.entityLiving instanceof EntityPlayer && e.source.getEntity() != null)
{
// non-player-entity -> player (mob)
EntityPlayer target = (EntityPlayer) e.entityLiving;
Entity source = e.source.getEntity();
String permission = ModuleProtection.PERM_DAMAGE_BY + "." + source.getClass().getSimpleName();
if (ModuleProtection.isDebugMode(target))
OutputHandler.chatNotification(target, permission);
if (!APIRegistry.perms.checkPermission(new UserIdent(target), permission))
{
e.setCanceled(true);
return;
}
}
}
}
@SubscribeEvent(priority = EventPriority.LOW)
public void breakEvent(BreakEvent e)
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
return;
Block block = e.world.getBlock(e.x, e.y, e.z);
String permission = ModuleProtection.PERM_BREAK + "." + block.getUnlocalizedName() + "." + block.getDamageValue(e.world, e.x, e.y, e.z);
if (ModuleProtection.isDebugMode(e.getPlayer()))
OutputHandler.chatNotification(e.getPlayer(), permission);
WorldPoint point = new WorldPoint(e.getPlayer().dimension, e.x, e.y, e.z);
if (!APIRegistry.perms.checkPermission(new UserIdent(e.getPlayer()), point, ModuleProtection.PERM_OVERRIDE_BREAK)
&& !APIRegistry.perms.checkPermission(new UserIdent(e.getPlayer()), point, permission))
{
e.setCanceled(true);
}
}
@SubscribeEvent(priority = EventPriority.LOW)
public void placeEvent(BlockEvent.PlaceEvent e)
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
return;
Block block = e.world.getBlock(e.x, e.y, e.z);
String permission = ModuleProtection.PERM_PLACE + "." + block.getUnlocalizedName() + "." + block.getDamageValue(e.world, e.x, e.y, e.z);
if (ModuleProtection.isDebugMode(e.player))
OutputHandler.chatNotification(e.player, permission);
WorldPoint point = new WorldPoint(e.player.dimension, e.x, e.y, e.z);
if (!APIRegistry.perms.checkPermission(new UserIdent(e.player), point, ModuleProtection.PERM_OVERRIDE_PLACE)
&& !APIRegistry.perms.checkPermission(new UserIdent(e.player), point, permission))
{
e.setCanceled(true);
}
}
@SubscribeEvent(priority = EventPriority.LOW)
public void multiPlaceEvent(BlockEvent.MultiPlaceEvent e)
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
return;
for (BlockSnapshot b : e.getReplacedBlockSnapshots())
{
Block block = e.world.getBlock(b.x, b.y, b.z);
String permission = ModuleProtection.PERM_PLACE + "." + block.getUnlocalizedName() + "." + block.getDamageValue(e.world, e.x, e.y, e.z);
if (ModuleProtection.isDebugMode(e.player))
OutputHandler.chatNotification(e.player, permission);
WorldPoint point = new WorldPoint(e.player.dimension, b.x, b.y, b.z);
if (!APIRegistry.perms.checkPermission(new UserIdent(e.player), point, ModuleProtection.PERM_OVERRIDE_PLACE)
&& !APIRegistry.perms.checkPermission(new UserIdent(e.player), point, permission))
{
e.setCanceled(true);
return;
}
}
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void playerInteractEvent(PlayerInteractEvent e)
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
return;
WorldPoint point;
if (e.action == PlayerInteractEvent.Action.RIGHT_CLICK_AIR)
{
MovingObjectPosition mop = FunctionHelper.getPlayerLookingSpot(e.entityPlayer, true);
point = new WorldPoint(e.entityPlayer.dimension, mop.blockX, mop.blockY, mop.blockZ);
}
else
point = new WorldPoint(e.entityPlayer.dimension, e.x, e.y, e.z);
// Check for block interaction
if (e.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK)
{
Block block = e.world.getBlock(e.x, e.y, e.z);
String permission = ModuleProtection.PERM_INTERACT + "." + block.getUnlocalizedName() + "." + block.getDamageValue(e.world, e.x, e.y, e.z);
if (ModuleProtection.isDebugMode(e.entityPlayer))
OutputHandler.chatNotification(e.entityPlayer, permission);
boolean allow = APIRegistry.perms.checkPermission(new UserIdent(e.entityPlayer), point, ModuleProtection.PERM_OVERRIDE_INTERACT)
|| APIRegistry.perms.checkPermission(new UserIdent(e.entityPlayer), point, permission);
e.useBlock = allow ? ALLOW : DENY;
}
// Check item (and block) usage
ItemStack stack = e.entityPlayer.getCurrentEquippedItem();
if (stack != null && !(stack.getItem() instanceof ItemBlock))
{
String permission = ModuleProtection.PERM_USE + "." + stack.getUnlocalizedName() + "." + stack.getItemDamage();
if (ModuleProtection.isDebugMode(e.entityPlayer))
OutputHandler.chatNotification(e.entityPlayer, permission);
boolean allow = APIRegistry.perms.checkPermission(new UserIdent(e.entityPlayer), point, ModuleProtection.PERM_OVERRIDE_USE)
|| APIRegistry.perms.checkPermission(new UserIdent(e.entityPlayer), point, permission);
e.useItem = allow ? ALLOW : DENY;
}
}
@SubscribeEvent(priority = EventPriority.LOW)
public void entityInteractEvent(EntityInteractEvent e)
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
return;
WorldPoint point = new WorldPoint(e.entityPlayer.dimension, (int) e.target.posX, (int) e.target.posY, (int) e.target.posZ);
String permission = ModuleProtection.PERM_INTERACT_ENTITY + "." + e.target.getClass().getSimpleName();
if (ModuleProtection.isDebugMode(e.entityPlayer))
OutputHandler.chatNotification(e.entityPlayer, permission);
boolean allow = APIRegistry.perms.checkPermission(new UserIdent(e.entityPlayer), point, ModuleProtection.PERM_OVERRIDE_INTERACT_ENTITY)
|| APIRegistry.perms.checkPermission(new UserIdent(e.entityPlayer), point, ModuleProtection.PERM_INTERACT_ENTITY);
if (!allow)
e.setCanceled(true);
}
@SubscribeEvent(priority = EventPriority.LOW)
public void checkSpawnEvent(CheckSpawn e)
{
if (e.entityLiving instanceof EntityPlayer)
return;
WorldPoint point = new WorldPoint(e.entityLiving);
String mobID = EntityList.getEntityString(e.entity);
if (!APIRegistry.perms.checkPermission(null, point, ModuleProtection.PERM_MOBSPAWN_NATURAL + "." + mobID))
{
e.setResult(Result.DENY);
OutputHandler.debug(mobID + " : DENIED");
}
else
{
OutputHandler.debug(mobID + " : ALLOWED");
}
}
@SubscribeEvent(priority = EventPriority.LOW)
public void specialSpawnEvent(SpecialSpawn e)
{
if (e.entityLiving instanceof EntityPlayer)
return;
WorldPoint point = new WorldPoint(e.entityLiving);
String mobID = EntityList.getEntityString(e.entity);
if (!APIRegistry.perms.checkPermission(null, point, ModuleProtection.PERM_MOBSPAWN_FORCED + "." + mobID))
{
e.setResult(Result.DENY);
}
}
@SubscribeEvent
public void itemPickupEvent(EntityItemPickupEvent e)
{
handleBannedInventoryItemEvent(e, e.item.getEntityItem());
}
@SubscribeEvent
public void playerOpenContainerEvent(PlayerOpenContainerEvent e)
{
// If it's the player's own inventory - ignore
if (e.entityPlayer.openContainer == e.entityPlayer.inventoryContainer)
return;
checkPlayerInventory(e.entityPlayer);
}
@SubscribeEvent
public void tickHandler(ServerTickEvent e)
{
for (EntityPlayer player : playerTickList)
checkPlayerInventory(player);
playerTickList.clear();
// handleBannedInventoryItemEvent(e, e.smelting);
}
@SubscribeEvent
public void playerChangedZoneEvent(PlayerChangedZone e)
{
checkPlayerInventory(e.entityPlayer);
// List<String> biList = bi.getBannedItems();
// for (ListIterator<String> iter = biList.listIterator(); iter.hasNext();)
// String element = iter.next();
// String[] split = element.split(":");
// int id = Integer.parseInt(split[0]);
// int meta = Integer.parseInt(split[1]);
// ItemStack is = new ItemStack(element, 0, meta);
// if (e.entityPlayer.inventory.hasItemStack(is))
// PlayerInfo.getPlayerInfo(e.entityPlayer).getHiddenItems().add(is);
// e.entityPlayer.setGameType(EnumGameType.getByID(Integer.parseInt(val)));
// System.out.println("yoohoo");
}
public boolean isInventoryItemBanned(EntityPlayer player, ItemStack stack)
{
String permission = ModuleProtection.PERM_INVENTORY + "." + stack.getUnlocalizedName() + "." + stack.getItemDamage();
if (ModuleProtection.isDebugMode(player))
OutputHandler.chatNotification(player, permission);
return !APIRegistry.perms.checkPermission(new UserIdent(player), permission);
}
public void handleBannedInventoryItemEvent(net.minecraftforge.event.entity.player.PlayerEvent e, ItemStack stack)
{
if (isInventoryItemBanned(e.entityPlayer, stack))
{
e.setCanceled(true);
}
}
public void checkPlayerInventory(EntityPlayer player)
{
for (int slotIdx = 0; slotIdx < player.inventory.getSizeInventory(); slotIdx++)
{
ItemStack stack = player.inventory.getStackInSlot(slotIdx);
if (stack != null)
{
if (isInventoryItemBanned(player, stack))
{
EntityItem droppedItem = player.func_146097_a(stack, true, false);
droppedItem.motionX = 0;
droppedItem.motionY = 0;
droppedItem.motionZ = 0;
player.inventory.setInventorySlotContents(slotIdx, null);
}
}
}
}
}
|
package com.github.davidcarboni.thetrain.storage;
import com.github.davidcarboni.restolino.json.Serialiser;
import com.github.davidcarboni.thetrain.helpers.Configuration;
import com.github.davidcarboni.thetrain.helpers.PathUtils;
import com.github.davidcarboni.thetrain.json.Transaction;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
/**
* Class for working with {@link Transaction} instances.
*/
public class Transactions {
static final String JSON = "transaction.json";
static final String CONTENT = "content";
static final String BACKUP = "backup";
static final Map<String, Transaction> transactionMap = new ConcurrentHashMap<>();
static final Map<String, ExecutorService> transactionExecutorMap = new ConcurrentHashMap<>();
static Path transactionStore;
/**
* Creates a new transaction.
*
* @param encryptionPassword If this is not blank, encryption will be enabled for the transaction.
* @return The details of the newly created transaction.
* @throws IOException If a filesystem error occurs in creating the transaction.
*/
public static Transaction create(String encryptionPassword) throws IOException {
Transaction transaction = new Transaction();
// Enable encryption if requested
transaction.enableEncryption(encryptionPassword);
// Generate the file structure
Path path = path(transaction.id());
Files.createDirectory(path);
Path json = path.resolve(JSON);
try (OutputStream output = Files.newOutputStream(json)) {
Serialiser.serialise(output, transaction);
Files.createDirectory(path.resolve(CONTENT));
Files.createDirectory(path.resolve(BACKUP));
transactionMap.put(transaction.id(), transaction);
if (!transactionExecutorMap.containsKey(transaction.id())) {
transactionExecutorMap.put(transaction.id(), Executors.newSingleThreadExecutor());
}
return transaction;
}
}
/**
* Cleanup any resources held by the transaction.
*
* @param transaction
*/
public static void end(Transaction transaction) {
if (transactionExecutorMap.containsKey(transaction.id())) {
transactionExecutorMap.get(transaction.id()).shutdown();
transactionExecutorMap.remove(transaction.id());
}
if (transactionMap.containsKey(transaction.id())) {
transactionMap.remove(transaction.id());
}
}
/**
* Reads the transaction Json specified by the given id.
*
* @param id The {@link Transaction} ID.
* @return The {@link Transaction} if it exists, otherwise null.
* @throws IOException If an error occurs in reading the transaction Json.
*/
public static Transaction get(String id, String encryptionPassword) throws IOException {
Transaction result = null;
if (StringUtils.isNotBlank(id)) {
if (!transactionMap.containsKey(id)) {
// Generate the file structure
Path transactionPath = path(id);
if (transactionPath != null && Files.exists(transactionPath)) {
final Path json = transactionPath.resolve(JSON);
try (InputStream input = Files.newInputStream(json)) {
result = Serialiser.deserialise(input, Transaction.class);
}
}
} else {
result = transactionMap.get(id);
if (result != null) {
result.enableEncryption(encryptionPassword);
}
}
}
return result;
}
public static void listFiles(Transaction transaction) throws IOException {
Map<String, List<String>> list = new HashMap<>();
Path content = content(transaction);
if (Files.isDirectory(content)) {
list.put("content", PathUtils.listUris(content));
}
Path backup = backup(transaction);
if (Files.isDirectory(backup)) {
list.put("backup", PathUtils.listUris(backup));
}
transaction.files = list;
}
/**
* Queue a task to update the transaction file. This task will only get run if the transaction
* is not already committed.
*
* @param transactionId
* @return
* @throws IOException
*/
public static Future<Boolean> tryUpdateAsync(final String transactionId) throws IOException {
Future<Boolean> future = null;
if (transactionExecutorMap.containsKey(transactionId)) {
ExecutorService transactionUpdateExecutor = transactionExecutorMap.get(transactionId);
future = transactionUpdateExecutor.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Boolean result = false;
try {
if (transactionExecutorMap.containsKey(transactionId)
&& transactionMap.containsKey(transactionId)) {
//System.out.print("X");
// The transaction passed in should always be an instance from the map
// otherwise there's potential to lose updates.
// NB the unit of synchronization is always a Transaction object.
Transaction read = transactionMap.get(transactionId);
synchronized (read) {
Path transactionPath = path(transactionId);
if (transactionPath != null && Files.exists(transactionPath)) {
final Path json = transactionPath.resolve(JSON);
try (OutputStream output = Files.newOutputStream(json)) {
Serialiser.serialise(output, read);
}
}
result = true;
}
} else {
//System.out.print("O");
}
} catch (IOException exception) {
System.out.println("Exception updating transaction: " + exception.getMessage());
ExceptionUtils.printRootCauseStackTrace(exception);
}
return result;
}
});
}
return future;
}
/**
* Reads the transaction Json specified by the given id.
*
* @param transaction The {@link Transaction}.
* @throws IOException If an error occurs in reading the transaction Json.
*/
public static void update(Transaction transaction) throws IOException {
if (transaction != null && transactionMap.containsKey(transaction.id())) {
// The transaction passed in should always be an instance from the map
// otherwise there's potential to lose updates.
// NB the unit of synchronization is always a Transaction object.
Transaction read = transactionMap.get(transaction.id());
synchronized (read) {
Path transactionPath = path(transaction.id());
if (transactionPath != null && Files.exists(transactionPath)) {
final Path json = transactionPath.resolve(JSON);
try (OutputStream output = Files.newOutputStream(json)) {
Serialiser.serialise(output, read);
}
}
}
}
}
/**
* Resolved the path under which content being published will be stored prior to being committed to the website content store.
*
* @param transaction The {@link Transaction} within which to determine the {@value #CONTENT} directory.
* @return The {@link Path} of the {@value #CONTENT} directory for the specified transaction.
* @throws IOException If an error occurs in determining the path.
*/
public static Path content(Transaction transaction) throws IOException {
Path result = null;
Path path = path(transaction.id());
if (path != null) {
path = path.resolve(CONTENT);
if (Files.exists(path)) {
result = path;
} else {
System.out.println("Content path for " + transaction.id() + " does not exist: " + path);
}
}
return result;
}
/**
* Resolved the path under which content being published will be stored prior to being committed to the website content store.
*
* @param transaction The {@link Transaction} within which to determine the {@value #CONTENT} directory.
* @return The {@link Path} of the {@value #CONTENT} directory for the specified transaction.
* @throws IOException If an error occurs in determining the path.
*/
public static Path backup(Transaction transaction) throws IOException {
Path result = null;
Path path = path(transaction.id());
if (path != null) {
path = path.resolve(BACKUP);
if (Files.exists(path)) result = path;
}
return result;
}
/**
* Determines the directory for a {@link Transaction}.
*
* @param id The {@link Transaction} ID.
* @return The {@link Path} for the specified transaction, or null if the ID is blank.
* @throws IOException If an error occurs in determining the path.
*/
static Path path(String id) throws IOException {
Path result = null;
if (StringUtils.isNotBlank(id)) {
result = store().resolve(id);
}
return result;
}
/**
* For development purposes, if no {@value Configuration#TRANSACTION_STORE} configuration value is set
* then a temponary folder is created.
*
* @return The {@link Path} to the storage directory for all transactions.
* @throws IOException If an error occurs.
*/
static Path store() throws IOException {
if (transactionStore == null) {
// Production configuration
String transactionStorePath = Configuration.get(Configuration.TRANSACTION_STORE);
if (StringUtils.isNotBlank(transactionStorePath)) {
Path path = Paths.get(transactionStorePath);
if (Files.isDirectory(path)) {
transactionStore = path;
System.out.println(Configuration.TRANSACTION_STORE + " configured as: " + path);
} else {
System.out.println("Not a valid transaction store directory: " + path);
}
}
// Development fallback
if (transactionStore == null) {
transactionStore = Files.createTempDirectory(Transactions.class.getSimpleName());
System.out.println("Temporary transaction store created at: " + transactionStore);
System.out.println("Please configure a " + Configuration.TRANSACTION_STORE + " variable to configure this directory in production.");
}
}
return transactionStore;
}
}
|
package com.jnape.palatable.lambda.functions.builtin.fn2;
import com.jnape.palatable.lambda.functions.Fn1;
import com.jnape.palatable.lambda.functions.Fn2;
import com.jnape.palatable.lambda.iterators.SnocIterator;
/**
* Opposite of {@link Cons}: lazily append an element to the end of the given {@link Iterable}.
* <p>
* Note that obtaining both laziness and stack-safety is particularly tricky here, and requires an initial eager
* deforestation of <code>O(k)</code> traversals where <code>k</code> is the number of contiguously nested
* {@link Snoc}s.
*
* @param <A> the Iterable element type
*/
public final class Snoc<A> implements Fn2<A, Iterable<A>, Iterable<A>> {
private static final Snoc INSTANCE = new Snoc();
private Snoc() {
}
@Override
public Iterable<A> apply(A a, Iterable<A> as) {
return () -> new SnocIterator<>(a, as);
}
@SuppressWarnings("unchecked")
public static <A> Snoc<A> snoc() {
return INSTANCE;
}
public static <A> Fn1<Iterable<A>, Iterable<A>> snoc(A a) {
return Snoc.<A>snoc().apply(a);
}
public static <A> Iterable<A> snoc(A a, Iterable<A> as) {
return snoc(a).apply(as);
}
}
|
package com.mashape.analytics.agent.connection.pool;
import static com.mashape.analytics.agent.common.AnalyticsConstants.AGENT_NAME;
import static com.mashape.analytics.agent.common.AnalyticsConstants.AGENT_VERSION;
import static com.mashape.analytics.agent.common.AnalyticsConstants.ANALYTICS_DATA;
import static com.mashape.analytics.agent.common.AnalyticsConstants.ANALYTICS_SERVER_PORT;
import static com.mashape.analytics.agent.common.AnalyticsConstants.ANALYTICS_SERVER_URL;
import static com.mashape.analytics.agent.common.AnalyticsConstants.ANALYTICS_TOKEN;
import static com.mashape.analytics.agent.common.AnalyticsConstants.HAR_VERSION;
import java.util.Map;
import org.apache.log4j.Logger;
import org.zeromq.ZMQ;
import com.google.gson.Gson;
import com.mashape.analytics.agent.modal.Creator;
import com.mashape.analytics.agent.modal.Entry;
import com.mashape.analytics.agent.modal.Har;
import com.mashape.analytics.agent.modal.Log;
import com.mashape.analytics.agent.modal.Message;
/*
* Opens a connection to Analytics server and sends data
*/
public class Messenger implements Work {
Logger logger = Logger.getLogger(Messenger.class);
private ZMQ.Context context;
private ZMQ.Socket socket;
public Messenger(){
context = ZMQ.context(1);
socket = context.socket(ZMQ.PUSH);
}
public void execute(Map<String, Object> analyticsData) {
Entry entry = (Entry) analyticsData.get(ANALYTICS_DATA);
String token = analyticsData.get(ANALYTICS_TOKEN).toString();
Message msg = getMessage(entry, token);
String data = new Gson().toJson(msg);
String analyticsServerUrl = analyticsData.get(ANALYTICS_SERVER_URL).toString();
String port = analyticsData.get(ANALYTICS_SERVER_PORT).toString();
socket.connect("tcp://" + analyticsServerUrl + ":" + port);
socket.send(data);
logger.debug("Message sent:" + data);
}
public void terminate() {
if (socket != null) {
logger.debug("Closing socket:" + socket.toString());
socket.close();
}
if (context != null) {
context.term();
}
}
public Message getMessage(Entry entry, String token) {
Message message = new Message();
message.setHar(setHar(entry));
message.setServiceToken(token);
return message;
}
private Har setHar(Entry entry) {
Har har = new Har();
har.setLog(setLog(entry));
return har;
}
private Log setLog(Entry entry) {
Log log = new Log();
log.setVersion(HAR_VERSION);
log.setCreator(setCreator());
log.getEntries().add(entry);
return log;
}
private Creator setCreator() {
Creator creator = new Creator();
creator.setName(AGENT_NAME);
creator.setVersion(AGENT_VERSION);
return creator;
}
}
|
package com.shankyank.maven.plugin.resgen;
import java.io.BufferedReader;
import java.io.BufferedWriter;
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.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Model;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
/**
* Templated Resource Generator Maven Plugin (template-resgen-maven-plugin:generate-resource).
* <p>
* The <code>generate-resource</code> goal of this plugin reads a provided resource template
* and writes it to a named location in the target project, replacing any Maven-style
* property references in the template (e.g. <code>${foo.bar}</code>) with the resolved
* property value.
*
* <h3>Configuration</h3>
*
* <table>
* <thead>
* <tr>
* <th>Configuration</th>
* <th>Property Key (-Dxxx)</th>
* <th>Description</th>
* <th>Required</th>
* <th>Default</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>template</td>
* <td>resgen.template</td>
* <td>The path to the resource template. See <a href="#templateResolution">Template Resolution</a>.</td>
* <td>true</td>
* <td></td>
* </tr>
* <tr>
* <td>templateEncoding</td>
* <td>resgen.encoding</td>
* <td>The encoding of the template file. (e.g. UTF-8)</td>
* <td>false</td>
* <td>Platform Default</td>
* </tr>
* <tr>
* <td>outputDir</td>
* <td></td>
* <td>The base output directory for the generated resource.</td>
* <td>false</td>
* <td><code>${project.build.outputDirectory}</code></td>
* </tr>
* <tr>
* <td>outputFile</td>
* <td>resgen.outputFile</td>
* <td>The relative path, from <code>outputDir</code>, for the generated resource.</td>
* <td>true</td>
* <td></td>
* </tr>
* <tr>
* <td>outputEncoding</td>
* <td>resgen.encoding</td>
* <td>The encoding of the output file. (e.g. UTF-8)</td>
* <td>false</td>
* <td>Platform Default</td>
* </tr>
* </tbody>
* </table>
*
* <h3><a id="templateResolution">Template Resolution</a></h3>
*
* The plugin attempts to open the provided template (<code>${template}</code>) in the following
* ways, failing the build if none of these attempts is successful.
*
* <ol>
* <li>Classpath Resource: <code>classpath://${template}</code></li>
* <li>Absolute Path: <code>file://${template}</code></li>
* <li>Relative Path from Project: <code>file://${basedir}/${template}</code></li>
* </ol>
*
* <h3>Property Replacement</h3>
*
* Maven-style properties (e.g. <code>${foo.bar}</code>) are replaced by their property values
* as resolved in the Maven project. The plugin will recognize the following values for replacement:
*
* <dl>
* <dt>Environment Variables</dt>
* <dd>Properties set in the Maven execution environment, typically available as <code>env.*</code>.</dd>
*
* <dt>JVM System Properties</dt>
* <dd>Properties auto-configured by the JVM (e.g. <code>java.runtime.version</code>, <code>os.arch</code>, etc.)</dd>
*
* <dt>POM Properties</dt>
* <dd>All values defined within the <code><properties></code> section of the POM and any active profiles.</dd>
*
* <dt>Command Line Properties</dt>
* <dd>Properties passed to Maven on the command line as <code>-Dkey=value</code>.</dd>
* </dl>
*
* Additionally, the plugin exposes the following Project Model elements for replacement.
*
* <ul>
* <li>project.groupId</li>
* <li>project.artifactId</li>
* <li>project.version</li>
* <li>project.name</li>
* </ul>
*
* @author Gordon Shankman
*/
@Mojo(
name="generate-resource",
defaultPhase=LifecyclePhase.GENERATE_RESOURCES,
threadSafe=true
)
public class TemplatedResGenMojo extends AbstractMojo {
/**
* The default, system charset.
*/
private static final Charset SYSTEM_ENCODING = Charset.defaultCharset();
/**
* The replacement pattern: ${*}
*/
private static final Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{([-a-zA-Z0-9_.]*)\\}");
/**
* The Maven Project.
*/
@Parameter(defaultValue = "${project}", required = true, readonly = true)
private MavenProject project;
/**
* The Maven Session.
*/
@Parameter(defaultValue="${session}", required=true, readonly=true)
private MavenSession session;
/**
* The path to the template. Can be specified by -Dresgen.template.
*/
@Parameter(property = "template", required = true, defaultValue = "${resgen.template}")
private String template;
/**
* The output directory. Defaults to project.build.outputDirectory.
*/
@Parameter(property = "outputDir", defaultValue = "${project.build.outputDirectory}")
private File outputDir;
/**
* The output file name. Can be specified by -Dresgen.outputFile.
*/
@Parameter(property = "outputFile", required = true, defaultValue = "${resgen.outputFile}")
private String outputFileName;
/**
* The template encoding. Can be specified by -Dresgen.encoding if both template and output encoding are the same.
*/
@Parameter(property = "templateEncoding", defaultValue = "${resgen.encoding}")
private String templateEncoding;
/**
* The output encoding. Can be specified by -Dresgen.encoding if both template and output encoding are the same.
*/
@Parameter(property = "outputEncoding", defaultValue = "${resgen.encoding}")
private String outputEncoding;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
Charset templateCharset = SYSTEM_ENCODING;
boolean resolvedTemplateCharset = false;
if (templateEncoding != null) {
try {
templateCharset = Charset.forName(templateEncoding);
resolvedTemplateCharset = true;
} catch (IllegalArgumentException iae) {
getLog().warn(String.format("Invalid 'templateEncoding' [%s] provided. Using system default: %s",
templateEncoding, SYSTEM_ENCODING.displayName()));
}
} else {
getLog().warn(String.format("No 'templateEncoding' provided. Using system default: %s", SYSTEM_ENCODING.displayName()));
}
Charset outputCharset = templateCharset;
if (outputEncoding != null) {
try {
outputCharset = Charset.forName(outputEncoding);
} catch (IllegalArgumentException iae) {
getLog().warn(String.format("Invalid 'outputEncoding' [%s] provided. Using %s: %s", outputEncoding,
(resolvedTemplateCharset ? "'templateEncoding'" : "system default"), templateCharset.displayName()));
}
} else if (resolvedTemplateCharset) {
getLog().info(String.format("No 'outputEncoding' provided. Using 'templateEncoding': %s", templateEncoding));
} else {
getLog().warn(String.format("No 'outputEncoding' provided. Using system default: %s", SYSTEM_ENCODING.displayName()));
}
Properties props = new Properties();
props.putAll(session.getSystemProperties());
props.putAll(session.getUserProperties());
props.putAll(project.getProperties());
props.putAll(genProjectMetadataProps());
try (
BufferedReader reader = openTemplate(templateCharset);
BufferedWriter writer = openOutputResource(outputCharset);
)
{
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
Matcher matcher = PROPERTY_PATTERN.matcher(line);
StringBuffer outBuffer = new StringBuffer("");
while (matcher.find()) {
String key = matcher.group(1);
String replaceValue = props.getProperty(matcher.group(1), "");
getLog().debug(String.format("Replacing ${%s} with %s", key, replaceValue));
matcher.appendReplacement(outBuffer, replaceValue);
}
matcher.appendTail(outBuffer);
writer.append(outBuffer.toString());
writer.newLine();
}
} catch (IOException ioe) {
throw new MojoFailureException(String.format("Error generating target resource [%s].", outputFileName), ioe);
}
}
private BufferedReader openTemplate(final Charset charset) throws MojoFailureException {
getLog().debug(String.format("Opening template [%s] as classpath resource.", template));
InputStream inTemplate = getClass().getClassLoader().getResourceAsStream(template);
if (inTemplate == null) {
getLog().debug(String.format("Opening template [%s] as system resource.", template));
inTemplate = ClassLoader.getSystemResourceAsStream(template);
}
if (inTemplate == null) {
getLog().debug(String.format("Opening template [%s] as file.", template));
inTemplate = openTemplateFile(new File(template));
}
if (inTemplate == null) {
File projTemplate = new File(project.getBasedir(), template);
getLog().debug(String.format("Opening template as file relative to project directory: %s", projTemplate.getPath()));
inTemplate = openTemplateFile(projTemplate);
}
if (inTemplate == null) {
throw new MojoFailureException(String.format("Unable to open template [%s].", template));
}
return new BufferedReader(new InputStreamReader(inTemplate, charset));
}
private InputStream openTemplateFile(final File file) {
try {
return new FileInputStream(file);
} catch (FileNotFoundException | SecurityException ex) {
return null;
}
}
private BufferedWriter openOutputResource(final Charset charset) throws MojoFailureException {
File resolvedOutputFile = new File(outputDir, outputFileName);
File resolvedOutputDir = resolvedOutputFile.getParentFile();
getLog().debug(String.format("Ensuring full path to output file [%s] exists.", resolvedOutputFile.getPath()));
if (!(resolvedOutputDir.exists() || resolvedOutputDir.mkdirs())) {
throw new MojoFailureException(String.format("Unable to create output path: %s", resolvedOutputDir.getPath()));
}
try {
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resolvedOutputFile), charset));
} catch (FileNotFoundException | SecurityException ex) {
throw new MojoFailureException(String.format("Unable to open output file [%s].", resolvedOutputFile.getPath()), ex);
}
}
private Map<String, String> genProjectMetadataProps() {
Model projectModel = project.getModel();
Map<String, String> props = new HashMap<String, String>();
props.put("project.name", projectModel.getName());
props.put("project.groupId", projectModel.getGroupId());
props.put("project.artifactId", projectModel.getArtifactId());
props.put("project.version", projectModel.getVersion());
return props;
}
}
|
package de.gpue.gotissues.controllers;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import de.gpue.gotissues.bo.Contribution;
import de.gpue.gotissues.bo.Contributor;
import de.gpue.gotissues.bo.Issue;
import de.gpue.gotissues.repo.ContributionRepository;
import de.gpue.gotissues.repo.ContributorRepository;
import de.gpue.gotissues.repo.IssueRepository;
import de.gpue.gotissues.util.MailUtil;
@RestController
@RequestMapping(value = "/api")
public class GotIssuesRestController {
private static final String WATCHED = "watched@";
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
"dd.MM.yyyy");
public static final int PAGE_SIZE = 20;
private static final String ASSIGNED = "assigned@";
private static final String NO_PWD = "********";
@Autowired
private IssueRepository issues;
@Autowired
private ContributorRepository contributors;
@Autowired
private ContributionRepository contributions;
@Autowired
private PasswordEncoder encoder;
@Value("${gotissues.notifier.mail}")
private String notifierMail = "";
private final Log log = LogFactory.getLog(getClass());
@RequestMapping("/issues")
public List<Issue> getIssues(
@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "search", defaultValue = "") String search) {
List<Issue> il = getIssues(search != null ? search : "");
if (page == null || page <= 1)
page = 1;
return page == null ? il : il.subList(
Math.min(il.size(), PAGE_SIZE * (page - 1)),
Math.min(il.size(), PAGE_SIZE * page));
}
@Cacheable("default")
private List<Issue> getIssues(String search) {
Set<Issue> found = new HashSet<Issue>();
String searchArr[] = search.split("\\s");
for (String s : searchArr) {
found.addAll(issues.findByTitleContainingOrDescriptionContaining(
search, search));
contributions.findByContentContaining(s).forEach(
c -> found.add(c.getIssue()));
if (s.startsWith(WATCHED)) {
String cn = s.substring(WATCHED.length());
Contributor c = cn.length() == 0 ? getMe() : contributors
.findOne(cn);
if (c != null)
found.addAll(issues.findByWatchers(c));
} else if (s.startsWith(ASSIGNED)) {
String cn = s.substring(ASSIGNED.length());
Contributor c = cn.length() == 0 ? getMe() : contributors
.findOne(cn);
if (c != null)
found.addAll(issues.findByAssignees(c));
} else {
Contributor c = contributors.findOne(s);
contributions.findByContributorOrderByCreatedDesc(c).forEach(
ct -> found.add(ct.getIssue()));
}
}
List<Issue> result = new ArrayList<Issue>(found);
result.sort(new Comparator<Issue>() {
@Override
public int compare(Issue o1, Issue o2) {
return o2.getLastChanged().compareTo(o1.getLastChanged());
}
});
return orderChildren(result);
}
private List<Issue> orderChildren(List<Issue> todo) {
List<Issue> result = new LinkedList<>();
while (!todo.isEmpty()) {
Issue head = todo.remove(0);
result.add(head);
List<Issue> children = issues
.findByParentOrderByLastChangedDesc(head);
todo.removeAll(children);
result.removeAll(children);
todo.addAll(0, children);
}
return result;
}
@RequestMapping("/issues/{i}")
public Issue getIssue(@PathVariable("i") Long id) {
return issues.findOne(id);
}
@RequestMapping(value = "/issues:add", method = { RequestMethod.GET,
RequestMethod.POST })
@CacheEvict("default")
public Issue addIssue(
@RequestParam("title") String title,
@RequestParam(value = "description", defaultValue = "") String description,
@RequestParam(value = "parent", required = false) Long parent,
@RequestParam(value = "assignees[]", required = false) List<String> assignees,
@RequestParam(value = "deadline", required = false) String deadline)
throws ParseException {
final Issue i = new Issue(title, description, new Date(),
contributors.findOne(getMe().getUsername()),
parent != null ? getIssue(parent) : null);
if (deadline != null && deadline != "")
i.setDeadline(DATE_FORMAT.parse(deadline));
if (assignees != null) {
i.setAssignees(new HashSet<>());
assignees.forEach(a -> i.getAssignees()
.add(contributors.findOne(a)));
}
Issue ir = issues.save(i);
contribute(getMe().getName() + " created a new issue: " + ir,
"<h4>Issue created: " + title + "</h4>" + description
+ "<h4>Assignees:</h4>" + assignees(assignees),
ir.getId(), getMe().getName(), false, 3);
return ir;
}
@SuppressWarnings("unchecked")
@RequestMapping(value = "/issues/{i}:alter", method = { RequestMethod.GET,
RequestMethod.POST })
@CacheEvict("default")
public Issue alterIssue(
@PathVariable("i") Long id,
@RequestParam(value = "title", required = false) String title,
@RequestParam(value = "description", required = false) String description,
@RequestParam(value = "deadline", required = false) String deadline,
@RequestParam(value = "assignees[]", required = false) List<String> assignees) {
Issue i = issues.findOne(id);
if (title == null && description == null)
return i;
Assert.isTrue(i.isOpen(), "Issue is closed!");
StringBuffer content = new StringBuffer("<ul>");
if (title != null && !title.equals(i.getTitle())) {
content.append("<li><strong>New title: </strong>" + title + "</li>");
i.setTitle(title);
}
if (description != null && !description.equals(i.getDescription())) {
content.append("<li><strong>New description: </strong>"
+ description + "</li>");
i.setDescription(description);
}
if (deadline != null) {
Date dlObj = null;
try {
dlObj = DATE_FORMAT.parse(deadline);
} catch (ParseException e) {
e.printStackTrace();
}
if (i.getDeadline() == null) {
if (dlObj != null) {
content.append("<li>strong>New deadline: </strong>"
+ deadline + "</li>");
i.setDeadline(dlObj);
}
} else {
if (dlObj == null) {
content.append("<li><strong>Removed deadline </strong>"
+ deadline + "</li>");
} else {
content.append("<li><strong>Shifted deadline from </strong>"
+ DATE_FORMAT.format(i.getDeadline())
+ " to "
+ deadline + "</li>");
}
}
}
if (assignees != null) {
Set<String> oldCl = i.getAssignees().stream().map(a -> a.getName())
.collect(Collectors.toSet());
List<String> addCl = (List<String>) CollectionUtils
.subtract(assignees, oldCl).stream().map(e -> "" + e)
.collect(Collectors.toList());
List<String> remCl = (List<String>) CollectionUtils
.subtract(oldCl, assignees).stream().map(e -> "" + e)
.collect(Collectors.toList());
if (!addCl.isEmpty())
content.append("<li><strong>Newly assigned:</strong>"
+ assignees(addCl) + "</li>");
if (!remCl.isEmpty())
content.append("<li><strong>Removed assignee(s):</strong>"
+ assignees(remCl) + "</li>");
i.setAssignees(assignees.stream().map(s -> contributors.findOne(s))
.collect(Collectors.toSet()));
}
content.append("</ul>");
issues.save(i);
contribute(getMe().getName() + " changed issue " + i,
"<h4>Issue changed:</h4>" + content, id, getMe().getName(),
false, 2);
return i;
}
@RequestMapping(value = "/issues/{i}:delete", method = { RequestMethod.GET,
RequestMethod.POST })
@CacheEvict("default")
public boolean deleteIssue(@PathVariable("i") Long id) {
Assert.isTrue(getMe().isAdmin());
Assert.notNull(id);
Issue issue = issues.findOne(id);
for (Issue c : issues.findByParentOrderByLastChangedDesc(issue)) {
deleteIssue(c.getId());
}
for (Contribution c : contributions
.findByIssueOrderByCreatedDesc(issue)) {
contributions.delete(c.getId());
}
issues.delete(id);
return true;
}
private String assignees(List<String> assignees) {
if (assignees == null || assignees.isEmpty())
return "none";
StringBuilder b = new StringBuilder();
b.append("<ul>");
assignees.forEach(a -> b.append("<li><a href=\"/contributor/" + a
+ "\">" + a + "</a></li>"));
b.append("</ul>");
return b.toString();
}
@RequestMapping(value = "/issues/{i}:close", method = { RequestMethod.GET,
RequestMethod.POST })
public Issue closeIssue(@PathVariable("i") Long id) {
Issue i = issues.findOne(id);
contribute(getMe() + " closed issue " + i, "<h4>Issue closed.</h4>",
id, getMe().getName(), false, 1);
i.setOpen(false);
issues.save(i);
issues.findByParentOrderByLastChangedDesc(i).forEach(
ic -> closeIssue(ic.getId()));
return i;
}
@RequestMapping(value = "/issues/{i}:open", method = { RequestMethod.GET,
RequestMethod.POST })
public Issue openIssue(@PathVariable("i") Long id) {
Issue i = issues.findOne(id);
i.setOpen(true);
issues.save(i);
contribute(getMe() + " re-opened issue " + i,
"<h4>Issue re-opened.</h4>", id, getMe().getName(), false, 1);
if (i.getParent() != null)
openIssue(i.getParent().getId());
return i;
}
@RequestMapping("/issues/{i}:watch")
public Issue watchIssue(@PathVariable("i") Long id) {
Issue i = issues.findOne(id);
if (i.getWatchers() == null)
i.setWatchers(new HashSet<Contributor>());
i.getWatchers().add(getMe());
issues.save(i);
return i;
}
@RequestMapping("/issues/{i}:unwatch")
public Issue unwatchIssue(@PathVariable("i") Long id) {
Issue i = issues.findOne(id);
if (i.getWatchers() == null)
i.setWatchers(new HashSet<Contributor>());
i.getWatchers().remove(getMe());
issues.save(i);
return i;
}
@RequestMapping("/issues:count")
public int countIssues() {
return issues.count();
}
@RequestMapping(value = "/issues/{i}:contribute", method = {
RequestMethod.GET, RequestMethod.POST })
private Contribution contribute(
@RequestParam(value = "content", defaultValue = "") String content,
@RequestParam("issue") Long issue) {
return contribute(getMe().getName() + " contributed to " + issue,
content, issue, getMe().getName(), true, 3);
}
@RequestMapping(value = "/contributions/{id}:delete", method = {
RequestMethod.GET, RequestMethod.POST })
public boolean deleteContribution(@PathVariable("id") Long id) {
Assert.isTrue(getMe().isAdmin());
Assert.notNull(id);
contributions.delete(id);
return true;
}
@CacheEvict("default")
private Contribution contribute(String mailSubject, String content,
Long issue, String contributor, Boolean revisable, int points) {
Contribution c = new Contribution(content, new Date(), getIssue(issue),
getContributor(contributor), revisable, points);
Assert.isTrue(c.getIssue().isOpen(), "Issue is closed!");
for (Object or : CollectionUtils.union(c.getIssue().getAssignees(), c
.getIssue().getWatchers())) {
Contributor r = (Contributor) or;
try {
MailUtil.sendHTMLMail(notifierMail, r.getMail(), mailSubject,
content);
} catch (Exception e) {
e.printStackTrace();
}
}
c = contributions.save(c);
c.getContributor().setLastContribution(c.getCreated());
contributors.save(c.getContributor());
Issue update = c.getIssue();
while (update != null) {
update.setLastChanged(c.getCreated());
issues.save(update);
update = update.getParent();
}
return c;
}
@RequestMapping("/issues/{i}/contributions")
public List<Contribution> getContributionsByIssue(
@PathVariable("i") Long id,
@RequestParam(value = "page", required = false) Integer page) {
if (page != null) {
return contributions.findByIssueOrderByCreatedDesc(getIssue(id),
new PageRequest(page - 1, PAGE_SIZE)).getContent();
} else {
return contributions.findByIssueOrderByCreatedDesc(getIssue(id));
}
}
@RequestMapping("/contributors")
public List<Contributor> getContributors() {
return contributors.findAll();
}
public static class ChartDataSet {
private String label;
private int value;
private String color;
private String highlight;
public ChartDataSet(String label, int value, String color,
String highlight) {
this.label = label;
this.value = value;
this.color = color;
this.highlight = highlight;
}
public String getLabel() {
return label;
}
public int getValue() {
return value;
}
public String getColor() {
return color;
}
public String getHighlight() {
return highlight;
}
}
public static class ContributorStats {
private String contributor;
private int points;
private List<ChartDataSet> data;
public ContributorStats(String contributor, int points,
List<ChartDataSet> data) {
this.contributor = contributor;
this.points = points;
this.data = data;
}
public String getContributor() {
return contributor;
}
public int getPoints() {
return points;
}
public List<ChartDataSet> getData() {
return data;
}
}
@RequestMapping("/stats")
public List<ContributorStats> getStats(
@RequestParam(value = "contributor", required = false) String cName,
@RequestParam(value = "start", required = false) Long startLong) {
List<Contributor> cl = new LinkedList<>();
List<ContributorStats> result = new LinkedList<>();
if (cName != null) {
cl.add(getContributor(cName));
} else {
cl.addAll(getContributors());
}
for (Contributor c : cl) {
List<ChartDataSet> cds = new LinkedList<>();
Date start = startLong == null ? new Date(0L) : new Date(
System.currentTimeMillis() + startLong);
Integer points = contributions.getPoints(c, start);
int intime = issues.countByAssigneesAndDeadlineAfter(c, new Date());
int overdue = issues.countByAssigneesAndDeadlineBefore(c,
new Date());
int assigned = issues.countByAssignees(c);
cds.add(new ChartDataSet("in time", intime, "Green", "lightgreen"));
cds.add(new ChartDataSet("overdue", overdue, "Red", "Orange"));
cds.add(new ChartDataSet("undated", assigned, "DodgerBlue",
"LightSkyBlue"));
result.add(new ContributorStats(c.getName(), points == null ? 0
: points, cds));
}
Collections.sort(result, new Comparator<ContributorStats>() {
@Override
public int compare(ContributorStats s1, ContributorStats s2) {
return s2.getPoints() - s1.getPoints();
}
});
return result;
}
@RequestMapping(value = "/contributors:add", method = { RequestMethod.GET,
RequestMethod.POST })
public Contributor addContributor(
@RequestParam("username") String name,
@RequestParam(value = "fullname", required = false) String fullname,
@RequestParam("password") String password,
@RequestParam("mail") String mail) {
Assert.isTrue(getMe().isAdmin(), "Only admin can do this!");
Contributor c = new Contributor(name, fullname, mail,
encoder.encode(password));
contributors.save(c);
return getContributor(name);
}
@RequestMapping(value = "/contributors/{c}:alter", method = {
RequestMethod.GET, RequestMethod.POST })
@CacheEvict("default")
public Contributor alterContributor(
@PathVariable("c") String c,
@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "fullname", required = false) String fullname,
@RequestParam(value = "password", required = false) String password,
@RequestParam(value = "mail", required = false) String mail) {
Assert.isTrue(getMe().isAdmin() && getMe().getName().equals(name),
"Only admin or the contributor himself can do this!");
Contributor co = contributors.findOne(c);
if (name != null)
co.setName(name);
if (password != null && !password.equals(NO_PWD))
co.setPassword(encoder.encode(password));
if (mail != null)
co.setMail(mail);
if (fullname != null)
co.setFullName(fullname);
co = contributors.save(co);
return getContributor(co.getName());
}
@RequestMapping(value = "/contributors/{c}:enable", method = {
RequestMethod.GET, RequestMethod.POST })
public Contributor enableContributor(@PathVariable("c") String c,
@RequestParam(value = "enabled") boolean enabled) {
Contributor co = contributors.findOne(c);
co.setEnabled(enabled);
contributors.save(co);
return getContributor(c);
}
@RequestMapping(value = "/contributors/{c}:grant", method = {
RequestMethod.GET, RequestMethod.POST })
public Contributor grantAdmin(@PathVariable("c") String c,
@RequestParam(value = "admin") boolean admin) {
Contributor co = contributors.findOne(c);
co.setAdmin(admin);
contributors.save(co);
return getContributor(c);
}
@RequestMapping("/contributors/{c}/watched")
public List<Issue> getWatchedIssues(@PathVariable("c") String c) {
return issues.findByWatchers(getContributor(c));
}
@RequestMapping("/contributors/{c}/assigned")
public List<Issue> getAssignedIssues(@PathVariable("c") String c) {
return issues.findByAssignees(getContributor(c));
}
@RequestMapping("/contributors/{c}/contributions")
public List<Contribution> getContributionsByContributor(
@PathVariable("c") String c,
@RequestParam(value = "page", required = false) Integer page) {
if (page != null) {
return contributions.findByContributorOrderByCreatedDesc(
getContributor(c), new PageRequest(page - 1, PAGE_SIZE))
.getContent();
} else {
return contributions
.findByContributorOrderByCreatedDesc(getContributor(c));
}
}
@RequestMapping("/contributors/{c}")
public Contributor getContributor(@PathVariable("c") String c) {
Contributor co = contributors.findOne(c);
return co;
}
@RequestMapping("/contributors:me")
public Contributor getMe() {
Object o = SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
return getContributor(o.toString());
}
}
|
package edu.isi.karma.controller.history;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.isi.karma.controller.command.Command;
import edu.isi.karma.controller.command.Command.CommandTag;
import edu.isi.karma.controller.history.HistoryJsonUtil.ClientJsonKeys;
import edu.isi.karma.controller.history.HistoryJsonUtil.ParameterType;
import edu.isi.karma.rep.HNode;
import edu.isi.karma.rep.Workspace;
import edu.isi.karma.util.JSONUtil;
public class CommandHistoryWriter {
private final ArrayList<Command> history;
private Workspace workspace;
public enum HistoryArguments {
worksheetId, commandName, inputParameters, hNodeId, tags
}
public CommandHistoryWriter(ArrayList<Command> history, Workspace workspace) {
this.history = history;
this.workspace = workspace;
}
public void writeHistoryPerWorksheet() throws JSONException {
HashMap<String, List<Command>> comMap = new HashMap<String, List<Command>>();
for(Command command : history) {
if(command.isSavedInHistory() && (command.hasTag(CommandTag.Modeling)
|| command.hasTag(CommandTag.Transformation))) {
JSONArray json = new JSONArray(command.getInputParameterJson());
String worksheetId = HistoryJsonUtil.getStringValue(HistoryArguments.worksheetId.name(), json);
String worksheetName = workspace.getWorksheet(worksheetId).getTitle();
if(comMap.get(worksheetName) == null)
comMap.put(worksheetName, new ArrayList<Command>());
comMap.get(worksheetName).add(command);
}
}
for(String wkName : comMap.keySet()) {
List<Command> comms = comMap.get(wkName);
JSONArray commArr = new JSONArray();
for(Command comm : comms) {
JSONObject commObj = new JSONObject();
commObj.put(HistoryArguments.commandName.name(), comm.getCommandName());
// Populate the tags
JSONArray tagsArr = new JSONArray();
for (CommandTag tag : comm.getTags())
tagsArr.put(tag.name());
commObj.put(HistoryArguments.tags.name(), tagsArr);
JSONArray inputArr = new JSONArray(comm.getInputParameterJson());
for (int i = 0; i < inputArr.length(); i++) {
JSONObject inpP = inputArr.getJSONObject(i);
/*** Check the input parameter type and accordingly make changes ***/
if(HistoryJsonUtil.getParameterType(inpP) == ParameterType.hNodeId) {
String hNodeId = inpP.getString(ClientJsonKeys.value.name());
HNode node = workspace.getFactory().getHNode(hNodeId);
JSONArray hNodeRepresentation = node.getJSONArrayRepresentation(workspace.getFactory());
inpP.put(ClientJsonKeys.value.name(), hNodeRepresentation);
} else if (HistoryJsonUtil.getParameterType(inpP) == ParameterType.worksheetId) {
inpP.put(ClientJsonKeys.value.name(), "W");
} else {
// do nothing
}
}
commObj.put(HistoryArguments.inputParameters.name(), inputArr);
commArr.put(commObj);
}
JSONUtil.writeJsonFile(commArr, HistoryJsonUtil.constructWorksheetHistoryJsonFilePath(wkName,
workspace.getCommandPreferencesId()));
}
}
}
|
package edu.neu.ccs.pyramid.feature_extraction;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import edu.neu.ccs.pyramid.elasticsearch.ESIndex;
import org.elasticsearch.action.search.SearchResponse;
import java.util.*;
import java.util.concurrent.ExecutionException;
public class PhraseDetector {
private int minDf=10;
private ESIndex index;
//keep phraseInfos explored so far
//todo can be optimized, for bad phrases, don't need to keep the actual search response
//todo this only use slop 0
private LoadingCache<String, PhraseInfo> phraseInfoCache;
//todo only look into the training set?
public PhraseDetector(ESIndex index, String[] validationIds) {
this.index = index;
this.phraseInfoCache = CacheBuilder.newBuilder().maximumSize(1000000)
.build(new CacheLoader<String, PhraseInfo>() {
@Override
public PhraseInfo load(String phrase) throws Exception {
PhraseInfo phraseInfo = new PhraseInfo(phrase);
SearchResponse searchResponse = index.matchPhrase(index.getBodyField(),
phrase,validationIds,0);
phraseInfo.setSearchResponse(searchResponse);
return phraseInfo;
}
});
}
public PhraseDetector setMinDf(int minDf) {
this.minDf = minDf;
return this;
}
public Set<PhraseInfo> getPhraseInfos(Map<Integer, String> termVector, Set<String> seeds){
Set<PhraseInfo> phrases = new HashSet<>();
for (Map.Entry<Integer,String> entry: termVector.entrySet()){
int pos = entry.getKey();
String term = entry.getValue();
if (seeds.contains(term)){
phrases.addAll(this.getPhraseInfos(termVector,pos));
}
}
return phrases;
}
/**
*
* @param termVector
* @param pos
* @return
*/
public Set<PhraseInfo> getPhraseInfos(Map<Integer, String> termVector, int pos){
Set<PhraseInfo> phrases = new HashSet<>();
List<PhraseInfo> leftPhrases = exploreLeft(termVector,pos);
List<PhraseInfo> rightPhrases = exploreRight(termVector, pos);
List<PhraseInfo> connected = connect(leftPhrases,rightPhrases);
phrases.addAll(leftPhrases);
phrases.addAll(rightPhrases);
phrases.addAll(connected);
return phrases;
}
/**
* phrases ending with current term
* @param termVector
* @param pos
* @return
*/
public List<PhraseInfo> exploreLeft(Map<Integer, String> termVector, int pos){
List<PhraseInfo> phraseInfos = new ArrayList<>();
String center = termVector.get(pos);
String phrase = center;
int currentLeft = pos - 1;
while(true){
if(!termVector.containsKey(currentLeft)){
break;
}
String leftTerm = termVector.get(currentLeft);
String currentPhrase = leftTerm.concat(" ").concat(phrase);
PhraseInfo phraseInfo = null;
try {
phraseInfo = this.phraseInfoCache.get(currentPhrase);
} catch (ExecutionException e) {
e.printStackTrace();
}
if (phraseInfo.getSearchResponse().getHits().totalHits()<this.minDf){
break;
}
phraseInfos.add(phraseInfo);
phrase = currentPhrase;
currentLeft -= 1;
}
return phraseInfos;
}
/**
* phrases starting with current term
* @param termVector
* @param pos
* @return
*/
public List<PhraseInfo> exploreRight(Map<Integer, String> termVector, int pos){
List<PhraseInfo> phraseInfos = new ArrayList<>();
String center = termVector.get(pos);
String phrase = center;
int currentRight = pos + 1;
while(true){
if(!termVector.containsKey(currentRight)){
break;
}
String rightTerm = termVector.get(currentRight);
String currentPhrase = phrase.concat(" ").concat(rightTerm);
PhraseInfo phraseInfo = null;
try {
phraseInfo = this.phraseInfoCache.get(currentPhrase);
} catch (ExecutionException e) {
e.printStackTrace();
}
if (phraseInfo.getSearchResponse().getHits().totalHits()<this.minDf){
break;
}
phraseInfos.add(phraseInfo);
phrase = currentPhrase;
currentRight += 1;
}
return phraseInfos;
}
public List<PhraseInfo> connect(List<PhraseInfo> leftList, List<PhraseInfo> rightList){
List<PhraseInfo> allConnected = new ArrayList<>();
int numLeft = leftList.size();
int numRight = rightList.size();
boolean[][] valid = new boolean[numLeft][numRight];
for (int i=0;i<numLeft;i++){
PhraseInfo left = leftList.get(i);
for (int j=0;j<numRight;j++){
//just try it
if (i==0){
PhraseInfo right = rightList.get(j);
String connectedString = connect(left.getPhrase(),right.getPhrase());
PhraseInfo connected = null;
try {
connected = this.phraseInfoCache.get(connectedString);
} catch (ExecutionException e) {
e.printStackTrace();
}
if (connected.getSearchResponse().getHits().totalHits()<this.minDf){
//skip j
break;
}
allConnected.add(connected);
valid[i][j] = true;
} else {
//look at the row above it
if (!valid[i-1][j]){
break;
}
PhraseInfo right = rightList.get(j);
String connectedString = connect(left.getPhrase(),right.getPhrase());
PhraseInfo connected = null;
try {
connected = this.phraseInfoCache.get(connectedString);
} catch (ExecutionException e) {
e.printStackTrace();
}
if (connected.getSearchResponse().getHits().totalHits()<this.minDf){
//skip j
break;
}
allConnected.add(connected);
valid[i][j] = true;
}
}
}
return allConnected;
}
static String connect(String left, String right){
String[] leftSplit = left.split(" ");
String[] rightSplit = right.split(" ");
if (!leftSplit[leftSplit.length-1].equals(rightSplit[0])){
throw new IllegalArgumentException("don't share the same term, cannot connect");
}
int pivotLength = rightSplit[0].length();
String connected = "";
connected = connected.concat(left);
connected = connected.concat(right.substring(pivotLength));
return connected;
}
}
|
package eu.socialsensor.framework.common.domain.feeds;
import java.util.Date;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import eu.socialsensor.framework.common.domain.Feed;
public class URLFeed extends Feed{
@Expose
@SerializedName(value = "url")
private String url = null;
public URLFeed(String url, Date since, String id) {
super(since, Feed.FeedType.URL);
this.url = url;
this.id = id;
}
public String getURL() {
return this.url;
}
public void setURL(String url) {
this.url = url;
}
}
|
package fr.univ.nantes.alma.accecs.generator;
import fr.univ.nantes.alma.accecs.model.Machine;
import fr.univ.nantes.alma.accecs.model.Property;
import fr.univ.nantes.alma.accecs.model.Variable;
import org.jtwig.JtwigModel;
import org.jtwig.JtwigTemplate;
import java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Logger;
public class MachineGenerator implements IMachineGenerator {
private static final Logger LOGGER = Logger.getLogger(MachineGenerator.class.getName());
public void generate(Machine machine, File templateFile, OutputStream outputStream) {
JtwigTemplate template = JtwigTemplate.fileTemplate(templateFile);
JtwigModel model = JtwigModel.newModel();
Collection<String> variablesInput = new ArrayList<String>();
Collection<String> variablesOutput = new ArrayList<String>();
Collection<String> variablesControl = new ArrayList<String>();
Collection<String> variablesInternal = new ArrayList<String>();
Collection<String> invariants = new ArrayList<String>();
Collection<String> initialisations = new ArrayList<String>();
Collection<String> properties = new ArrayList<String>();
for (Variable variable : machine.getVariables()) {
switch (variable.getCategory()) {
case INPUT:
variablesInput.add(variable.getName());
break;
case OUTPUT:
variablesOutput.add(variable.getName());
break;
case CONTROL:
variablesControl.add(variable.getName());
break;
case INTERNAL:
variablesInternal.add(variable.getName());
break;
}
invariants.add(variable.getName()+" : "+variable.getType());
if (variable.hasBounds()) {
invariants.add(variable.getName()+" : "+variable.getLowerBound()+".."+variable.getUpperBound());
}
initialisations.add(variable.getName()+" := "+variable.getDefaultValue());
}
for (Property property : machine.getProperties()) {
properties.add(property.getExpression());
}
model.with("name", machine.getName());
model.with("variablesInput", variablesInput);
model.with("variablesOutput", variablesOutput);
model.with("variablesControl", variablesControl);
model.with("variablesInternal", variablesInternal);
model.with("invariants", invariants);
model.with("initialisations", initialisations);
model.with("properties", properties);
template.render(model, outputStream);
}
}
|
package io.jcp.service.impl;
import io.jcp.bean.Callback;
import io.jcp.listener.TaskLifecycleListener;
import io.jcp.service.QueryExecutorService;
import io.jcp.service.QueryManagerService;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
public final class ConcurrentQueryManagerServiceImpl<T, H>
implements QueryManagerService<T, H> {
private final ThreadPoolExecutor threadPool;
private final Collection<TaskLifecycleListener<T>> taskLifecycleListeners;
private final QueryExecutorService<T, H> executorService;
private final AtomicLong submittedTask;
private final AtomicLong inProgressTask;
private final AtomicBoolean shuttingDown;
public ConcurrentQueryManagerServiceImpl(
ThreadPoolExecutor threadPool, Collection<TaskLifecycleListener<T>> taskLifecycleListeners,
QueryExecutorService<T, H> executorService
) {
this.threadPool = threadPool;
this.taskLifecycleListeners = taskLifecycleListeners;
this.executorService = executorService;
this.submittedTask = new AtomicLong();
this.inProgressTask = new AtomicLong();
this.shuttingDown = new AtomicBoolean(false);
}
@Override
public void submit(T query, Optional<Callback<T, H>> callback) {
if (this.shuttingDown.get()) {
throw new IllegalStateException("service is in shutdown state. submissions are blocked");
}
this.threadPool.submit(() -> {
this.submittedTask.decrementAndGet();
this.inProgressTask.incrementAndGet();
try {
executorService.exec(query, callback);
taskLifecycleListeners.forEach(l -> l.onExec(query));
} finally {
this.inProgressTask.decrementAndGet();
if (this.inProgressTask.get() == 0 && this.shuttingDown.get()) {
synchronized (this.shuttingDown) {
this.shuttingDown.notifyAll();
}
}
}
});
taskLifecycleListeners.forEach(l -> l.onSubmit(query));
this.submittedTask.incrementAndGet();
}
@Override
public H exec(T task) throws InterruptedException {
Semaphore semaphore = new Semaphore(1);
Set<H> result = new HashSet<>(1);
Callback<T, H> callback = (t, p) -> {
if (p.isPresent()) {
result.add(p.get());
}
semaphore.release();
};
semaphore.acquire();
submit(task, Optional.of(callback));
semaphore.acquire();
semaphore.release();
return result.iterator().next();
}
@Override
public long countSubmitted() {
return submittedTask.get();
}
@Override
public long countInProgress() {
return inProgressTask.get();
}
@Override
public void shutdown() throws InterruptedException {
if (this.shuttingDown.get()) {
throw new IllegalStateException("already is in shutdown state");
}
this.shuttingDown.set(true);
if (countInProgress() + countSubmitted() == 0) {
return;
}
synchronized (this.shuttingDown) {
this.shuttingDown.wait();
}
}
}
|
package joachimrussig.heatstressrouting.osmdata;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.lang3.tuple.Pair;
import org.openstreetmap.osmosis.core.domain.v0_6.Bound;
import org.openstreetmap.osmosis.core.domain.v0_6.Entity;
import org.openstreetmap.osmosis.core.task.v0_6.RunnableSource;
import org.openstreetmap.osmosis.xml.common.CompressionMethod;
import org.openstreetmap.osmosis.xml.v0_6.XmlReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.graphhopper.util.StopWatch;
import crosby.binary.osmosis.OsmosisReader;
public class OSMFileReader {
private static final Logger logger = LoggerFactory
.getLogger(OSMFileReader.class);
/**
* Creates a new {@code OSMFileReader}.
*/
public OSMFileReader() {
}
/**
* Reads the OSM file specified by {@code file} and returns a
* {@link OSMData} object.
*
* @param file
* OSM file to read
* @return the content of the OSM file as {@code OSMData} object
* @throws IOException
* if an error occoured while reading {@code file}
*/
public OSMData read(File file) throws IOException {
Pair<MultiValuedMap<Long, Entity>, Bound> osmData = readOsmFile(file);
return new OSMData(osmData.getLeft(), osmData.getRight());
}
public static Pair<MultiValuedMap<Long, Entity>, Bound> readOsmFile(
File file) throws FileNotFoundException {
CollectorSink collectorSink = new CollectorSink();
logger.debug("OSM File: " + file.getName() + " (exists = "
+ file.exists() + ")");
boolean pbf = false;
CompressionMethod compression = CompressionMethod.None;
if (file.getName().endsWith(".pbf")) {
pbf = true;
} else if (file.getName().endsWith(".gz")) {
compression = CompressionMethod.GZip;
} else if (file.getName().endsWith(".bz2")) {
compression = CompressionMethod.BZip2;
}
logger.debug(
"pbf = " + pbf + "; compression = " + compression.toString());
RunnableSource reader;
if (pbf) {
reader = new OsmosisReader(new FileInputStream(file));
} else {
reader = new XmlReader(file, false, compression);
}
reader.setSink(collectorSink);
logger.info("Start reading ...");
StopWatch sw = new StopWatch().start();
reader.run();
logger.info("done (" + sw.stop().getTime() + " ms )");
return Pair.of(collectorSink.getEntities(),
collectorSink.getBoundingBox());
}
}
|
package me.palazzomichi.telegram.telejam.util;
import me.palazzomichi.telegram.telejam.Bot;
import me.palazzomichi.telegram.telejam.objects.Message;
import me.palazzomichi.telegram.telejam.objects.TextMessage;
import me.palazzomichi.telegram.telejam.text.Text;
import java.util.HashMap;
import java.util.Map;
/**
* Utility class that handles commands.
* Override the {@link #getCommand(TextMessage)} method to change the
* syntax of commands or to perform checks before the command execution.
*/
public class CommandRegistry implements MessageHandler, CommandHandler {
protected final Bot bot;
private Map<String, CommandHandler> commands;
/**
* Creates a command registry.
*
* @param bot the bot that receives commands
*/
public CommandRegistry(Bot bot) {
this.bot = bot;
commands = new HashMap<>();
}
@Override
public final void onCommand(Command command, TextMessage message) throws Throwable {
CommandHandler handler = getCommandHandler(command.getName());
if (handler != null) {
handler.onCommand(command, message);
}
}
@Override
public final void onMessage(Message message) throws Throwable {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
Command command = getCommand(textMessage);
if (command != null) {
onCommand(command, textMessage);
}
}
}
/**
* Returns the {@link Command} contained in the specified message,
* or <code>null</code> if the message is not a command.
*
* @param message the message
* @return the command contained in the specified message,
* or <code>null</code> if the message is not a command.
* @throws Throwable if an error occurs
*/
public Command getCommand(TextMessage message) throws Throwable {
if (!message.isCommand()) {
return null;
}
Text text = message.getText();
String name = text.getBotCommands().get(0);
Text args = text.subSequence(name.length() + 1).trim();
return new Command(name, args);
}
/**
* Returns the command with ne given name or alias, otherwise <code>null</code>.
*
* @param name the name of the command
* @return the command with ne given name or alias, otherwise <code>null</code>
*/
public final CommandHandler getCommandHandler(String name) {
return commands.get(removeSuffix(name, "@" + bot.getUsername()).toLowerCase());
}
private String removeSuffix(String s, String suffix) {
if (s.endsWith(suffix)) {
return s.substring(0, s.length() - suffix.length());
}
return s;
}
/**
* Registers a command.
*
* @param command the command to register
* @param name the name of the command
*/
public final void registerCommand(CommandHandler command, String name) {
commands.put(name.toLowerCase(), command);
}
/**
* Registers a command.
*
* @param command the command to register
* @param name the name of the command
* @param aliases the aliases of the command
*/
public final void registerCommand(CommandHandler command, String name, String... aliases) {
registerCommand(command, name);
for (String alias : aliases) {
registerCommand(command, alias);
}
}
/**
* Unregisters a command with the given name or alias.
*
* @param name the command name or alias
*/
public final void unregisterCommand(String name) {
commands.remove(name.toLowerCase());
}
/**
* Unregisters a command.
*
* @param command the command to unregister
*/
public final void unregisterCommand(CommandHandler command) {
commands.values().remove(command);
}
}
|
package net.sf.jabref.gui.groups;
import javax.swing.undo.AbstractUndoableEdit;
import net.sf.jabref.gui.undo.NamedCompound;
import net.sf.jabref.gui.undo.UndoableFieldChange;
import net.sf.jabref.logic.groups.EntriesGroupChange;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.model.FieldChange;
public class UndoableChangeEntriesOfGroup {
public static AbstractUndoableEdit getUndoableEdit(GroupTreeNodeViewModel node, EntriesGroupChange change) {
if(change.getOldEntries().size() != change.getNewEntries().size()) {
return new UndoableChangeAssignment(node, change.getOldEntries(), change.getNewEntries());
}
boolean hasEntryChanges = false;
NamedCompound entryChangeCompound = new NamedCompound(Localization.lang("change entries of group"));
for(FieldChange fieldChange : change.getEntryChanges()) {
hasEntryChanges = true;
entryChangeCompound.addEdit(new UndoableFieldChange(fieldChange));
}
if (hasEntryChanges) {
entryChangeCompound.end();
return entryChangeCompound;
}
return null;
}
}
|
package org.ambraproject.wombat.service;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import org.ambraproject.wombat.model.NlmPerson;
import org.ambraproject.wombat.model.Reference;
import org.ambraproject.wombat.util.NodeListAdapter;
import org.ambraproject.wombat.util.ParseXmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.management.modelmbean.XMLParseException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class ParseReferenceService {
private static final Logger log = LoggerFactory.getLogger(ParseReferenceService.class);
private static final Pattern YEAR_FALLBACK = Pattern.compile("\\d{4,}");
private static final Pattern VOL_NUM_RE = Pattern.compile("(\\d{1,})");
private static final String WESTERN_NAME_STYLE = "western";
private static final String EASTERN_NAME_STYLE = "eastern";
private static final Joiner NAME_JOINER = Joiner.on(' ').skipNulls();
private static enum CitationElement {
ELEMENT_CITATION("element-citation"),
MIXED_CITATION("mixed-citation"),
NLM_CITATION("nlm-citation"); //deprecated
String value;
CitationElement(String citationElement) {
this.value = citationElement;
}
public String getValue() {
return value;
}
}
/**
* Helper interface to build journal links from citation DOIs.
*/
@FunctionalInterface
public interface DoiToJournalLinkService {
/**
* @param doi
* @return a fully qualified link to an internal journal article page, or null if an external doi
*/
public String getLink(String doi) throws IOException;
}
/**
* Builds a list of Reference objects for each <ref></ref> element
*
* @param refElement a <ref></ref> node which can contain (label?, (element-citation | mixed-citation | nlm-citation)+)
* @return list of Reference objects
*/
public List<Reference> buildReferences(Element refElement, DoiToJournalLinkService linkService)
throws XMLParseException, IOException {
List<Node> citationElements = null;
for (CitationElement elementType : CitationElement.values()) {
NodeList nodes = refElement.getElementsByTagName(elementType.getValue());
if (!ParseXmlUtil.isNullOrEmpty(nodes)) {
citationElements = NodeListAdapter.wrap(nodes);
break;
}
}
List<Reference> references = new ArrayList<>();
// a <ref></ref> element can have one or more of citation elements
for (Node citationNode : citationElements) {
if (citationNode.getNodeType() != Node.ELEMENT_NODE) {
throw new XMLParseException("<element-citation>, <mixed-citation>, <nlm-citation> is not an element.");
}
Element element = (Element) citationNode;
String unstructuredReference = null;
String uri = null;
String doi = null;
String year = ParseXmlUtil.getElementSingleValue(element, "year");
String volume = ParseXmlUtil.getElementSingleValue(element, "volume");
String title = buildTitle(element);
if (Strings.isNullOrEmpty(title)) {
unstructuredReference = getUnstructuredCitation(element);
}
NodeList extLinkList = element.getElementsByTagName("ext-link");
if (!ParseXmlUtil.isNullOrEmpty(extLinkList)) {
Element extLink = (Element) extLinkList.item(0);
// use the ext-link as doi, only if ext-link previous text is "doi:" or "doi"
boolean useDoi = false;
Node previousNode = extLink.getPreviousSibling();
if (previousNode != null) {
String previousText = extLink.getPreviousSibling().getTextContent();
if (!Strings.isNullOrEmpty(previousText)) {
previousText = previousText.trim();
if (previousText.equalsIgnoreCase("doi:") || previousText.equalsIgnoreCase("doi")) {
useDoi = true;
}
}
}
String linkType = ParseXmlUtil.getElementAttributeValue(extLink, "ext-link-type");
if (linkType.equals("uri")) {
uri = ParseXmlUtil.getElementAttributeValue(extLink, "xlink:href");
// TODO: add a validation check for the doi and add it to the meta-tags
if (useDoi) {
doi = extLink.getFirstChild() == null ? null : extLink.getFirstChild().getNodeValue();
}
}
}
PageRange pages = buildPages(element);
String fullArticleLink = null;
if (doi != null) {
fullArticleLink = linkService.getLink(doi);
}
Reference reference = Reference.build()
.setJournal(parseJournal(element))
.setFullArticleLink(fullArticleLink)
.setTitle(title)
.setChapterTitle(buildChapterTitle(element))
.setUnStructuredReference(unstructuredReference)
.setAuthors(parseAuthors(element))
.setCollabAuthors(parseCollabAuthors(element))
.setYear(parseYear(year))
.setVolume(volume)
.setVolumeNumber(parseVolumeNumber(volume))
.setIssue(ParseXmlUtil.getElementSingleValue(element, "issue"))
.setPublisherName(ParseXmlUtil.getElementSingleValue(element, "publisher-name"))
.setIsbn(ParseXmlUtil.getElementSingleValue(element, "isbn"))
.setUri(uri)
.setDoi(doi)
.setfPage(pages.firstPage)
.setlPage(pages.lastPage)
.build();
references.add(reference);
}
return references;
}
/**
* Sets the journal title property of a reference appropriately based on the XML.
*/
private String parseJournal(Element citationElement) {
String type = ParseXmlUtil.getElementAttributeValue(citationElement, "publication-type");
if (Strings.isNullOrEmpty(type)) {
return null;
}
// pmc2obj-v3.xslt lines 730-739
if (Reference.PublicationType.JOURNAL.getValue().equals(type)) {
return ParseXmlUtil.getElementSingleValue(citationElement, "source");
}
return null;
}
/**
* @return the value of the title property, retrieved from the XML
*/
private String buildTitle(Element citationElement) {
NodeList titleNode = citationElement.getElementsByTagName("article-title");
if (ParseXmlUtil.isNullOrEmpty(titleNode)) {
titleNode = citationElement.getElementsByTagName("source");
}
// unstructured citation
if (ParseXmlUtil.isNullOrEmpty(titleNode)) {
return null;
}
String title = ParseXmlUtil.getElementMixedContent(new StringBuilder(), titleNode.item(0)).toString();
return (title == null) ? null : ParseXmlUtil.standardizeWhitespace(title);
}
/**
* @return the text within <mixed-citation></mixed-citation> with no structure
*/
private String getUnstructuredCitation(Element citationElement) {
String unstructuredCitation = null;
if (citationElement.getTagName().equals(CitationElement.MIXED_CITATION.getValue())
&& citationElement.getFirstChild().getNodeType() == Node.TEXT_NODE) {
unstructuredCitation = ParseXmlUtil.getElementMixedContent(new StringBuilder(), citationElement).toString();
}
return (unstructuredCitation == null) ? null : ParseXmlUtil.standardizeWhitespace(unstructuredCitation);
}
/**
* @return book chapter title
*/
private String buildChapterTitle(Element citationElement) {
NodeList chapterTitleNode = citationElement.getElementsByTagName("chapter-title");
if (ParseXmlUtil.isNullOrEmpty(chapterTitleNode)) {
return null;
}
String chapterTitle = ParseXmlUtil.getElementMixedContent(new StringBuilder(),
chapterTitleNode.item(0)).toString();
return (chapterTitle == null) ? null : ParseXmlUtil.standardizeWhitespace(chapterTitle);
}
private List<NlmPerson> parseAuthors(Element citationElement) {
List<Node> personGroupElement = NodeListAdapter.wrap(citationElement.getElementsByTagName("person-group"));
List<NlmPerson> personGroup = new ArrayList<>();
if (!ParseXmlUtil.isNullOrEmpty(personGroupElement)) {
String type;
for (Node pgNode : personGroupElement) {
Element pgElement = (Element) pgNode;
List<Node> nameNodes = NodeListAdapter.wrap(pgElement.getElementsByTagName("name"));
type = ParseXmlUtil.getElementAttributeValue(pgElement, "person-group-type");
if (!Strings.isNullOrEmpty(type) && type.equals("author")) {
personGroup = nameNodes.stream().map(node -> parsePersonName((Element) node)).collect
(Collectors.toList());
}
}
} else {
List<Node> nameNodes = NodeListAdapter.wrap(citationElement.getElementsByTagName("name"));
int editorStartIndex = getEditorStartIndex(nameNodes);
List<Node> authorNodes = editorStartIndex == -1 ? nameNodes : nameNodes.subList(0, editorStartIndex);
personGroup = authorNodes.stream()
.map(node -> parsePersonName((Element) node))
.collect(Collectors.toList());
}
return personGroup;
}
private NlmPerson parsePersonName(Element nameElement) {
String nameStyle = ParseXmlUtil.getElementAttributeValue(nameElement, "name-style");
String surname = ParseXmlUtil.getElementSingleValue(nameElement, "surname");
String givenNames = ParseXmlUtil.getElementSingleValue(nameElement, "given-names");
String suffix = ParseXmlUtil.getElementSingleValue(nameElement, "suffix");
if (surname == null) {
throw new XmlContentException("Required surname is omitted from node: " + nameElement.getNodeName());
}
String[] fullNameParts;
if (WESTERN_NAME_STYLE.equals(nameStyle) || Strings.isNullOrEmpty(nameStyle)) {
fullNameParts = new String[]{givenNames, surname, suffix};
} else if (EASTERN_NAME_STYLE.equals(nameStyle)) {
fullNameParts = new String[]{surname, givenNames, suffix};
} else {
throw new XmlContentException("Invalid name-style: " + nameStyle);
}
String fullName = NAME_JOINER.join(fullNameParts);
givenNames = Strings.nullToEmpty(givenNames);
suffix = Strings.nullToEmpty(suffix);
return NlmPerson.builder()
.setFullName(fullName)
.setGivenNames(givenNames)
.setSurname(surname)
.setSuffix(suffix)
.build();
}
private int getEditorStartIndex(List<Node> nameNodes) {
// this is a very very very ugly hack for <mixed-citation> element with the following format
// <name name-style="western">
// <surname>s1</surname>
// <given-names>g1</given-names>
// </name> ...
// <chapter-title>Some tite</chapter-title>. In:
// <name name-style="western">
// <surname>s2</surname>
// <given-names>g2</given-names>
// </name>, editors, ...
for (int i = 0; i < nameNodes.size(); i++) {
Node previousNode = nameNodes.get(i).getPreviousSibling();
if (previousNode != null && previousNode.getNodeType() == Node.TEXT_NODE && previousNode.getNodeValue()
.contains("In")) {
return i;
}
}
return -1;
}
private List<String> parseCollabAuthors(Element citationElement) {
List<Node> collabNodes = NodeListAdapter.wrap(citationElement.getElementsByTagName("collab"));
return collabNodes.stream()
.map(collabNode -> collabNode.getFirstChild() != null ? collabNode.getFirstChild().getTextContent() : "")
.collect(Collectors.toList());
}
private Integer parseYear(String displayYear) {
if (displayYear == null) {
return null;
}
try {
return Integer.valueOf(displayYear);
} catch (NumberFormatException e) {
// Test data suggests this is normal input. TODO: Report a warning to the client?
return parseYearFallback(displayYear);
}
}
/**
* As a fallback for parsing the display year into an integer, treat an uninterrupted sequence of four or more digits
* as the year.
*
* @param displayYear the display year given as text in the article XML
* @return the first sequence of four or more digits as a number, if possible; else, {@code null}
*/
private Integer parseYearFallback(String displayYear) {
Matcher matcher = YEAR_FALLBACK.matcher(displayYear);
if (!matcher.find()) {
return null; // displayYear contains no sequence of four digits
}
String displayYearSub = matcher.group();
if (matcher.find()) {
// Legacy behavior was to concatenate all such matches into one number.
log.warn("Matched more than one year-like digit string: using {}; ignoring {}", displayYearSub, matcher.group());
}
try {
return Integer.valueOf(displayYearSub);
} catch (NumberFormatException e) {
return null; // in case so many digits were matched that the number overflows
}
}
static Integer parseVolumeNumber(String volume) {
if (Strings.isNullOrEmpty(volume)) {
return null;
}
// pmc2obj-v3.xslt lines 742-753. Note that there is currently a bug in this
// function, however--it returns 801 for the string "80(1)", instead of 80!
Matcher match = VOL_NUM_RE.matcher(volume);
if (match.find()) {
return Integer.parseInt(match.group());
} else {
return null;
}
}
private static class PageRange {
private final String firstPage;
private final String lastPage;
private PageRange(String firstPage, String lastPage) {
this.firstPage = firstPage;
this.lastPage = lastPage;
}
}
/**
* @return the value of the first and last page of the reference
*/
private PageRange buildPages(Element citationElement) {
String fPage = ParseXmlUtil.getElementSingleValue(citationElement, "fpage");
String lPage = ParseXmlUtil.getElementSingleValue(citationElement, "lpage");
if (Strings.isNullOrEmpty(fPage) && Strings.isNullOrEmpty(lPage)) {
String range = ParseXmlUtil.getElementSingleValue(citationElement, "page-range");
if (!Strings.isNullOrEmpty(range)) {
int index = range.indexOf("-");
if (index > 0) {
fPage = range.substring(0, index);
lPage = range.substring(index + 1);
}
}
}
return new PageRange(fPage, lPage);
}
}
|
package org.jboss.loom.migrators._ext;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.control.CompilationFailedException;
import org.jboss.loom.conf.GlobalConfiguration;
import org.jboss.loom.ex.MigrationException;
import org.jboss.loom.ex.MigrationExceptions;
import org.jboss.loom.migrators._ext.MigratorDefinition.JaxbClassDef;
import org.jboss.loom.spi.IConfigFragment;
import org.jboss.loom.utils.ClassUtils;
import org.jboss.loom.utils.Utils;
import org.jboss.loom.utils.XmlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Loads migrators externalized to *.mig.xml descriptors and *.groovy JAXB beans.
*
* @author Ondrej Zizka, ozizka at redhat.com
*/
public class ExternalMigratorsLoader {
private static final Logger log = LoggerFactory.getLogger( ExternalMigratorsLoader.class );
// Migrator descriptors.
private List<MigratorDefinition> descriptors;
// Map of JAXB class name -> class - not to lead them multiple times.
private Map<String, Class<? extends IConfigFragment>> fragmentJaxbClasses = new HashMap();
// Map of migragor class name -> class
private Map<String, Class<? extends DefinitionBasedMigrator>> migratorsClasses = new HashMap();
/**
* Reads migrator descriptors from *.mig.xml in the given dir and returns them.
*
* 1) Reads the definitions from the XML files.
* 2) Loads the Groovy classes referenced in these definitions.
* 3) Creates the classes of the Migrators.
* 4) Instantiates the classes and returns the list of instances.
*/
public Map<Class<? extends DefinitionBasedMigrator>, DefinitionBasedMigrator> loadMigrators( File dir, GlobalConfiguration globConf ) throws MigrationException {
// Read the definitions from the XML files.
this.descriptors = loadMigratorDefinitions( dir, globConf );
// Load the Groovy classes referenced in these definitions.
//this.fragmentJaxbClasses = loadJaxbClasses( this.descriptors );
// Create the classes of the Migrators.
//this.migratorsClasses = createMigratorsClasses();
// Instantiates the classes and returns the list of instances.
Map<Class<? extends DefinitionBasedMigrator>, DefinitionBasedMigrator> migs = instantiateMigratorsFromDefinitions( this.descriptors, this.fragmentJaxbClasses, globConf );
return migs;
}
/**
* Reads migrator descriptors from *.mig.xml in the given dir and returns them.
*/
public static List<MigratorDefinition> loadMigratorDefinitions( File dir, GlobalConfiguration gc ) throws MigrationException {
List<MigratorDefinition> retDefs = new LinkedList();
List<Exception> problems = new LinkedList();
// For each *.mig.xml file...
for( File xmlFile : FileUtils.listFiles( dir, new String[]{"mig.xml"}, true ) ){
try{
List<MigratorDefinition> defs = XmlUtils.unmarshallBeans( xmlFile, "/migration/migrator", MigratorDefinition.class );
retDefs.addAll( defs );
// Validate
for( MigratorDefinition def : defs ) {
try { Utils.validate( def ); }
catch( MigrationException ex ){ problems.add( ex ); }
}
}
catch( Exception ex ){
problems.add(ex);
}
}
String msg = "Errors occured when reading migrator descriptors from " + dir + ": ";
MigrationExceptions.wrapExceptions( problems, null );
return retDefs;
}
/**
* Loads the Groovy classes referenced in these definitions.
*/
private static Map<String, Class<? extends IConfigFragment>> loadJaxbClasses(
MigratorDefinition desc ) throws MigrationException
{
Map<String, Class<? extends IConfigFragment>> jaxbClasses = new HashMap();
List<Exception> problems = new LinkedList();
// JAXB class...
for( JaxbClassDef jaxbClsBean : desc.jaxbBeansClasses ) {
try {
// Look up in the map: "TestJaxbBean" -> class
String className = StringUtils.substringAfter( jaxbClsBean.file.getName(), "." );
Class cls = jaxbClasses.get( className );
if( cls == null ){
// Use the directory where the definition XML file is from.
log.debug(" Loading JAXB class from dir " + desc.getOrigin() );
//File dir = new File( desc.getLocation().getSystemId() ).getParentFile();
File dir = desc.getOrigin().getFile().getParentFile();
final File groovyFile = new File( dir, jaxbClsBean.file.getPath() );
log.debug(" Loading JAXB class from " + groovyFile );
cls = loadGroovyClass( groovyFile );
if( ! IConfigFragment.class.isAssignableFrom( cls ) ){
problems.add( new MigrationException("Groovy class from '"+groovyFile.getPath()+
"' doesn't implement " + IConfigFragment.class.getSimpleName() + ": " + cls.getName()));
continue;
}
jaxbClasses.put( className, cls );
}
//mig.addJaxbClass( cls );
}
catch( Exception ex ){
problems.add(ex);
}
}
MigrationExceptions.wrapExceptions( problems, "Failed loading JAXB classes. ");
return jaxbClasses;
}// loadJaxbClasses()
/**
* Processes the definitions - loads the used classes and creates the migrator objects.
*/
public static Map<Class<? extends DefinitionBasedMigrator>, DefinitionBasedMigrator> instantiateMigratorsFromDefinitions (
List<MigratorDefinition> defs,
Map<String, Class<? extends IConfigFragment>> fragClasses,
GlobalConfiguration globConf
) throws MigrationException
{
//List<Class<? extends DefinitionBasedMigrator>> migClasses = new LinkedList();
Map<Class<? extends DefinitionBasedMigrator>, DefinitionBasedMigrator> migrators = new HashMap();
List<Exception> problems = new LinkedList();
// For each <migrator ...> definition...
for( MigratorDefinition migDef : defs ) {
log.debug("Instantiating " + migDef);
try {
// JAXB classes.
Map<String, Class<? extends IConfigFragment>> jaxbClasses = loadJaxbClasses( migDef );
// Migrator class.
Class<? extends DefinitionBasedMigrator> migClass = MigratorSubclassMaker.createClass( migDef.name );
//migClasses.add( migClass );
// Instance.
//final DefinitionBasedMigrator mig = DefinitionBasedMigrator.from( desc, gc );
DefinitionBasedMigrator mig = MigratorSubclassMaker.instantiate( migClass, migDef, globConf );
migrators.put( migClass, mig );
} catch( Exception ex ) {
problems.add( ex );
}
}
MigrationExceptions.wrapExceptions( problems, "Failed processing migrator definitions. ");
return migrators;
}
/**
* Loads a groovy class from given file.
*/
private static Class loadGroovyClass( File file ) throws MigrationException {
try {
GroovyClassLoader gcl = new GroovyClassLoader( ExternalMigratorsLoader.class.getClassLoader() );
// Try to add this class' directory on classpath. For the purposes of test runs. Should be conditional?
}
|
package org.jfrog.hudson.pipeline.executors;
import hudson.model.Run;
import hudson.model.TaskListener;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jfrog.build.api.builder.PromotionBuilder;
import org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient;
import org.jfrog.hudson.ArtifactoryServer;
import org.jfrog.hudson.CredentialsConfig;
import org.jfrog.hudson.pipeline.ArtifactoryConfigurator;
import org.jfrog.hudson.pipeline.types.PromotionConfig;
import org.jfrog.hudson.release.PromotionUtils;
import org.jfrog.hudson.util.CredentialManager;
import java.io.IOException;
public class PromotionExecutor {
private final ArtifactoryServer server;
private final TaskListener listener;
private final PromotionConfig promotionConfig;
private final StepContext context;
private Run build;
public PromotionExecutor(ArtifactoryServer server, Run build, TaskListener listener, StepContext context,
PromotionConfig promotionConfig) {
this.server = server;
this.build = build;
this.listener = listener;
this.context = context;
this.promotionConfig = promotionConfig;
}
public void execution() throws IOException {
ArtifactoryConfigurator configurator = new ArtifactoryConfigurator(server);
CredentialsConfig deployerConfig = CredentialManager.getPreferredDeployer(configurator, server);
ArtifactoryBuildInfoClient client = server.createArtifactoryClient(deployerConfig.provideUsername(build.getParent()), deployerConfig.providePassword(build.getParent()),
server.createProxyConfiguration(Jenkins.getInstance().proxy));
PromotionBuilder promotionBuilder = new PromotionBuilder()
.status(promotionConfig.getStatus())
.comment(promotionConfig.getComment())
.targetRepo(promotionConfig.getTargetRepo())
.sourceRepo(promotionConfig.getSourceRepo())
.dependencies(promotionConfig.isIncludeDependencies())
.copy(promotionConfig.isCopy())
.failFast(promotionConfig.isFailFast());
logInfo();
boolean status = PromotionUtils.promoteAndCheckResponse(promotionBuilder, client, listener,
promotionConfig.getBuildName(), promotionConfig.getBuildNumber());
if (!status) {
context.onFailure(new Exception("Build promotion failed"));
}
}
private void logInfo() {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("Promoting '").append(promotionConfig.getBuildName()).append("' ");
strBuilder.append("#").append(promotionConfig.getBuildNumber());
strBuilder.append(" to '").append(promotionConfig.getTargetRepo()).append("'");
if (StringUtils.isNotEmpty(promotionConfig.getSourceRepo())) {
strBuilder.append(" from '").append(promotionConfig.getSourceRepo()).append("'");
}
if (StringUtils.isNotEmpty(promotionConfig.getStatus())) {
strBuilder.append(", with status: '").append(promotionConfig.getStatus()).append("'");
}
if (StringUtils.isNotEmpty(promotionConfig.getComment())) {
strBuilder.append(", with comment: '").append(promotionConfig.getComment()).append("'");
}
if (promotionConfig.isIncludeDependencies()) {
strBuilder.append(", including dependencies");
}
if (promotionConfig.isCopy()) {
strBuilder.append(", using copy");
}
if (promotionConfig.isFailFast()) {
strBuilder.append(", failing on first error");
}
listener.getLogger().println(strBuilder.append(".").toString());
}
}
|
package reborncore.common.powerSystem.tesla;
import net.darkhax.tesla.capability.TeslaStorage;
import net.darkhax.tesla.lib.TeslaUtils;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import reborncore.common.RebornCoreConfig;
import reborncore.common.powerSystem.TilePowerAcceptor;
public class TeslaPowerManager implements ITeslaPowerManager {
AdvancedTeslaContainer container;
@Override
public void readFromNBT(NBTTagCompound compound, TilePowerAcceptor powerAcceptor) {
// this.container = new AdvancedTeslaContainer(null, compound.getTag("TeslaContainer"), powerAcceptor);
}
@Override
public void writeToNBT(NBTTagCompound compound, TilePowerAcceptor powerAcceptor) {
// compound.setTag("TeslaContainer", this.container.writeNBT(null));
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing, TilePowerAcceptor powerAcceptor) {
if (capability == TeslaStorage.TESLA_HANDLER_CAPABILITY)
return (T) this.container;
return null;
}
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing, TilePowerAcceptor powerAcceptor) {
if (capability == TeslaStorage.TESLA_HANDLER_CAPABILITY)
return true;
return false;
}
@Override
public void update(TilePowerAcceptor powerAcceptor) {
if(powerAcceptor.canProvideEnergy(null)){
TeslaUtils.distributePowerEqually(powerAcceptor.getWorld(), powerAcceptor.getPos(), (long) powerAcceptor.getMaxOutput(), false);
}
}
@Override
public void created(TilePowerAcceptor powerAcceptor) {
this.container = new AdvancedTeslaContainer(powerAcceptor);
}
@Override
public String getDisplayableTeslaCount(long tesla) {
return TeslaUtils.getDisplayableTeslaCount(tesla / RebornCoreConfig.euPerRF);
}
public static ITeslaPowerManager getPowerManager(){
return new TeslaPowerManager();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.